Programs & Examples On #Statement modifiers

What is the difference between the | and || or operators?

One is a "bitwise or".

10011b | 01000b => 11011b

The other is a logic or.

true or false => true

Including all the jars in a directory within the Java classpath

Using Java 6 or later, the classpath option supports wildcards. Note the following:

  • Use straight quotes (")
  • Use *, not *.jar

Windows

java -cp "Test.jar;lib/*" my.package.MainClass

Unix

java -cp "Test.jar:lib/*" my.package.MainClass

This is similar to Windows, but uses : instead of ;. If you cannot use wildcards, bash allows the following syntax (where lib is the directory containing all the Java archive files):

java -cp "$(printf %s: lib/*.jar)"

(Note that using a classpath is incompatible with the -jar option. See also: Execute jar file with multiple classpath libraries from command prompt)

Understanding Wildcards

From the Classpath document:

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo, use either foo;foo/* or foo/*;foo. The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo, or vice versa.

Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo, not in foo/bar, foo/baz, etc.

The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required then the JAR files can be enumerated explicitly in the class path.

Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar, b.jar, and c.jar, then the class path foo/* is expanded into foo/a.jar;foo/b.jar;foo/c.jar, and that string would be the value of the system property java.class.path.

The CLASSPATH environment variable is not treated any differently from the -classpath (or -cp) command-line option. That is, wildcards are honored in all these cases. However, class path wildcards are not honored in the Class-Path jar-manifest header.

Note: due to a known bug in java 8, the windows examples must use a backslash preceding entries with a trailing asterisk: https://bugs.openjdk.java.net/browse/JDK-8131329

How to get Django and ReactJS to work together?

I don't have experience with Django but the concepts from front-end to back-end and front-end framework to framework are the same.

  1. React will consume your Django REST API. Front-ends and back-ends aren't connected in any way. React will make HTTP requests to your REST API in order to fetch and set data.
  2. React, with the help of Webpack (module bundler) & Babel (transpiler), will bundle and transpile your Javascript into single or multiple files that will be placed in the entry HTML page. Learn Webpack, Babel, Javascript and React and Redux (a state container). I believe you won't use Django templating but instead allow React to render the front-end.
  3. As this page is rendered, React will consume the API to fetch data so React can render it. Your understanding of HTTP requests, Javascript (ES6), Promises, Middleware and React is essential here.

Here are a few things I've found on the web that should help (based on a quick Google search):

Hope this steers you in the right direction! Good luck! Hopefully others who specialize in Django can add to my response.

How to merge two arrays in JavaScript and de-duplicate items

You can use loadash unionWith - _.unionWith([arrays], [comparator])

This method is like _.union except that it accepts comparator which is invoked to compare elements of arrays. Result values are chosen from the first array in which the value occurs. The comparator is invoked with two arguments: (arrVal, othVal).

_x000D_
_x000D_
var array1 = ["Vijendra","Singh"];_x000D_
var array2 = ["Singh", "Shakya"];_x000D_
 _x000D_
var array3 = _.unionWith(array1, array2, _.isEqual);_x000D_
console.log(array3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

How to disable margin-collapsing?

One neat trick to disable margin collapsing that has no visual impact, as far as I know, is setting the padding of the parent to 0.05px:

.parentClass {
    padding: 0.05px;
}

The padding is no longer 0 so collapsing won't occur anymore but at the same time the padding is small enough that visually it will round down to 0.

If some other padding is desired, then apply padding only to the "direction" in which margin collapsing is not desired, for example padding-top: 0.05px;.

Working example:

_x000D_
_x000D_
.noCollapse {_x000D_
  padding: 0.05px;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  background-color: red;_x000D_
  width: 150px;_x000D_
}_x000D_
_x000D_
.children {_x000D_
  margin-top: 50px;_x000D_
_x000D_
  background-color: lime;      _x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<h3>Border collapsing</h3>_x000D_
<div class="parent">_x000D_
  <div class="children">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>No border collapsing</h3>_x000D_
<div class="parent noCollapse">_x000D_
  <div class="children">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit: changed the value from 0.1 to 0.05. As Chris Morgan mentioned in a comment bellow, and from this small test, it seems that indeed Firefox takes the 0.1px padding into consideration. Though, 0.05px seemes to do the trick.

Best Practices for securing a REST API / web service

I'm kind of surprised SSL with client certificates hasn't been mentioned yet. Granted, this approach is only really useful if you can count on the community of users being identified by certificates. But a number of governments/companies do issue them to their users. The user doesn't have to worry about creating yet another username/password combination, and the identity is established on each and every connection so communication with the server can be entirely stateless, no user sessions required. (Not to imply that any/all of the other solutions mentioned require sessions)

How to copy file from host to container using Dockerfile

I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue

COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory

I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.

Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"

Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/

Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build

Step 4: docker image created Successfully with logs

Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe

Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

I think the only cookie you need is JSESSIONID=xxx..

Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.

What is HEAD in Git?

In addition to all definitions, the thing that stuck in my mind was, when you make a commit, GIT creates a commit object within the repository. Commit objects should have a parent ( or multiple parents if it is a merge commit). Now, how does git know the parent of the current commit? So HEAD is a pointer to the (reference of the) last commit which will become the parent of the current commit.

SQL LIKE condition to check for integer?

PostgreSQL supports regular expressions matching.

So, your example would look like

SELECT * FROM books WHERE title ~ '^\d+ ?' 

This will match a title starting with one or more digits and an optional space

First letter capitalization for EditText

use this code to only First letter capitalization for EditText

MainActivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:tag="true">
    </EditText>

</RelativeLayout>

MainActivity.java

EditText et = findViewById(R.id.et);
        et.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
                if (et.getText().toString().length() == 1 && et.getTag().toString().equals("true"))
                {
                    et.setTag("false");
                    et.setText(et.getText().toString().toUpperCase());
                    et.setSelection(et.getText().toString().length());
                }
                if(et.getText().toString().length() == 0)
                {
                    et.setTag("true");
                }
            }

            public void afterTextChanged(Editable editable) {

            }
        });

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Mod of negative number is melting my brain

You're expecting a behaviour that is contrary to the documented behaviour of the % operator in c# - possibly because you're expecting it to work in a way that it works in another language you are more used to. The documentation on c# states (emphasis mine):

For the operands of integer types, the result of a % b is the value produced by a - (a / b) * b. The sign of the non-zero remainder is the same as that of the left-hand operand

The value you want can be calculated with one extra step:

int GetArrayIndex(int i, int arrayLength){
    int mod = i % arrayLength;
    return (mod>=0) : mod ? mod + arrayLength;
}

fopen deprecated warning

It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files. For example:

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>

The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add _CRT_SECURE_NO_DEPRECATE to Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions.

What is the standard Python docstring format?

I suggest using Vladimir Keleshev's pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.

pep257 will report divergence you make from the standard and is called like pylint and pep8.

Angular 2: How to style host element of the component?

In your Component you can add .class to your host element if you would have some general styles that you want to apply.

export class MyComponent{
     @HostBinding('class') classes = 'classA classB';

How to force a UIViewController to Portrait orientation in iOS 6

I disagree from @aprato answer, because the UIViewController rotation methods are declared in categories themselves, thus resulting in undefined behavior if you override then in another category. Its safer to override them in a UINavigationController (or UITabBarController) subclass

Also, this does not cover the scenario where you push / present / pop from a Landscape view into a portrait only VC or vice-versa. To solve this tough issue (never addressed by Apple), you should:

In iOS <= 4 and iOS >= 6:

UIViewController *vc = [[UIViewController alloc]init];
[self presentModalViewController:vc animated:NO];
[self dismissModalViewControllerAnimated:NO];
[vc release];

In iOS 5:

UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *view = [window.subviews objectAtIndex:0];
[view removeFromSuperview];
[window addSubview:view];

These will REALLY force UIKit to re-evaluate all your shouldAutorotate , supportedInterfaceOrientations, etc.

How do I change the value of a global variable inside of a function

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.

If the name of the local value has the same name as the global value, use the window object

See this jsfiddle

_x000D_
_x000D_
x = 1;_x000D_
y = 2;_x000D_
z = 3;_x000D_
_x000D_
function a(y) {_x000D_
  // y is local to the function, because it is a function parameter_x000D_
  console.log('local y: should be 10:', y); // local y through function parameter_x000D_
  y = 3; // will only overwrite local y, not 'global' y_x000D_
  console.log('local y: should be 3:', y); // local y_x000D_
  // global value could be accessed by referencing through window object_x000D_
  console.log('global y: should be 2:', window.y) // global y, different from local y ()_x000D_
_x000D_
  var x; // makes x a local variable_x000D_
  x = 4; // only overwrites local x_x000D_
  console.log('local x: should be 4:', x); // local x_x000D_
  _x000D_
  z = 5; // overwrites global z, because there is no local z_x000D_
  console.log('local z: should be 5:', z); // local z, same as global_x000D_
  console.log('global z: should be 5 5:', window.z, z) // global z, same as z, because z is not local_x000D_
}_x000D_
a(10);_x000D_
console.log('global x: should be 1:', x); // global x_x000D_
console.log('global y: should be 2:', y); // global y_x000D_
console.log('global z: should be 5:', z); // global z, overwritten in function a
_x000D_
_x000D_
_x000D_

Edit

With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)

MySQL error - #1062 - Duplicate entry ' ' for key 2

In addition to Sabeen's answer:

The first column id is your primary key.
Don't insert '' into the primary key, but insert null instead.

INSERT INTO users
  (`id`,`title`,`firstname`,`lastname`,`company`,`address`,`city`,`county`
   ,`postcode`,`phone`,`mobile`,`category`,`email`,`password`,`userlevel`) 
VALUES     
  (null,'','John','Doe','company','Streeet','city','county'
  ,'postcode','phone','','category','[email protected]','','');

If it's an autoincrement key this will fix your problem.
If not make id an autoincrement key, and always insert null into it to trigger an autoincrement.

MySQL has a setting to autoincrement keys only on null insert or on both inserts of 0 and null. Don't count on this setting, because your code may break if you change server.
If you insert null your code will always work.

See: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Zooming MKMapView to fit annotation pins?

@"I'm not sure if this is because of some other factors in my implementation, but I find that showAnnotations doesn't do as close a zoom/fit of the annotations as the manual implementation does, so I've stuck with the manual one. – Ted Avery Apr 17 at 0:35"

I had the same problem, but then I tried doing showAnnotations twice (like below), and for some reason, it worked.

[mapView showAnnotations:yourAnnotationArray animated:YES]; [mapView showAnnotations:yourAnnotationArray animated:YES];

Delete a database in phpMyAdmin

Follow the following steps to delete database in PhpMyAdmin.

  1. Select your database.
  2. Choose the "Operations" tab.
  3. On this page under remove database, you will find a "Drop the database (DROP)"

Hope this helps.

Linux Command History with date and time

Try this:

> HISTTIMEFORMAT="%d/%m/%y %T "

> history

You can adjust the format to your liking, of course.

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

Referring to SimpleDataFormat JavaDoc:

Letter | Date or Time Component | Presentation | Examples
---------------------------------------------------------
   H   |  Hour in day (0-23)    |    Number    |    0
   h   |  Hour in am/pm (1-12)  |    Number    |    12

How to check if a string contains only numbers?

http://msdn.microsoft.com/en-us/library/f02979c7(v=VS.90).aspx

You can pass nothing if you don't need the returned integer like so

if integer.TryParse(number,nothing) then

How can I delete multiple lines in vi?

You can delete multiple(range) lines if you know the line numbers:

:[start_line_no],[end_line_no]d

Note: d stands for delete

where,
start_line_no is the beginning line no you want to delete and end_line_no is the ending line no you want to delete. The lines between the start and end, including start and end will be deleted.

Eg:

:45,101d

The lines between 45 and 101 including 45 and 101 will be deleted.

Restoring MySQL database from physical files

From the answer of @Vicent, I already restore MySQL database as below:

Step 1. Shutdown Mysql server

Step 2. Copy database in your database folder (in linux, the default location is /var/lib/mysql). Keep same name of the database, and same name of database in mysql mode.

sudo cp -rf   /mnt/ubuntu_426/var/lib/mysql/database1 /var/lib/mysql/

Step 3: Change own and change mode the folder:

sudo chown -R mysql:mysql /var/lib/mysql/database1
sudo chmod -R 660 /var/lib/mysql/database1
sudo chown  mysql:mysql /var/lib/mysql/database1 
sudo chmod 700 /var/lib/mysql/database1

Step 4: Copy ibdata1 in your database folder

sudo cp /mnt/ubuntu_426/var/lib/mysql/ibdata1 /var/lib/mysql/

sudo chown mysql:mysql /var/lib/mysql/ibdata1

Step 5: copy ib_logfile0 and ib_logfile1 files in your database folder.

sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile0 /var/lib/mysql/

sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile1 /var/lib/mysql/

Remember change own and change root of those files:

sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile0

sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile1

or

sudo chown -R mysql:mysql /var/lib/mysql

Step 6 (Optional): My site has configuration to store files in a specific location, then I copy those to corresponding location, exactly.

Step 7: Start your Mysql server. Everything come back and enjoy it.

That is it.

See more info at: https://biolinh.wordpress.com/2017/04/01/restoring-mysql-database-from-physical-files-debianubuntu/

What is the difference between atomic / volatile / synchronized?

volatile:

volatile is a keyword. volatile forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.

AtomicXXX:

AtomicXXX classes support lock-free thread-safe programming on single variables. These AtomicXXX classes (like AtomicInteger) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.

When to use: Multiple threads can read and modify data.

synchronized:

synchronized is keyword used to guard a method or code block. By making method as synchronized has two effects:

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

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

When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations

AtomicXXX is equivalent of volatile + synchronized even though the implementation is different. AmtomicXXX extends volatile variables + compareAndSet methods but does not use synchronization.

Related SE questions:

Difference between volatile and synchronized in Java

Volatile boolean vs AtomicBoolean

Good articles to read: ( Above content is taken from these documentation pages)

https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

How to have a a razor action link open in a new tab?

If your goal is to use the ActionLink helper and open a new tab:

@Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })

@Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

Parameter "stratify" from method "train_test_split" (scikit Learn)

Scikit-Learn is just telling you it doesn't recognise the argument "stratify", not that you're using it incorrectly. This is because the parameter was added in version 0.17 as indicated in the documentation you quoted.

So you just need to update Scikit-Learn.

How to ignore certain files in Git

You can also use .gitattributes (instead of .gitignore) to exclude entire filetypes. The file is pretty self-explanatory, but I'm pasting the contents here for reference. Pay attention to the last line (*.class binary):

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
*.gif binary
*.ico binary
*.mo binary
*.pdf binary
*.phar binary
*.class binary

IIS: Where can I find the IIS logs?

The 100% correct answer for the default location of the log files is...

%SystemDrive%\inetpub\logs\LogFiles

Yes you can enter this into the explorer address bar it'll work.

To be 100% sure, you need to look at the logging for the web site in IIS.

https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85

i.e.

  1. Open IIS Manager.
  2. Select the site or server in the Connections pane,
  3. Double-click Logging.
  4. The location of log files for the site can be found within the Directory field

EDIT: As pointed out by Andy in the comments below you need to ensure when installing IIS that you elected to enable HTTP logging, otherwise HTTP logging won't be available.

Enable HTTP Logging

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

How can I download HTML source in C#

You can get it with:

var html = new System.Net.WebClient().DownloadString(siteUrl)

What are some resources for getting started in operating system development?

I found Robert Love's Linux Kernel Development quite interesting. It tells you about how the different subsystems in the Linux kernel works in a very down-to-earth way. Since the source is available Linux is a prime candidate for something to hack on.

Get a list of dates between two dates using a function

Declare @date1 date = '2016-01-01'
              ,@date2 date = '2016-03-31'
              ,@date_index date
Declare @calender table (D date)
SET @date_index = @date1
WHILE @date_index<=@date2
BEGIN
INSERT INTO @calender
SELECT @date_index

SET @date_index = dateadd(day,1,@date_index)

IF @date_index>@date2
Break
ELSE
Continue
END

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

Set position / size of UI element as percentage of screen size

For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:

Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
btn.setHeight((int)(display.getHeight()*0.68));

Accessing a local website from another computer inside the local network in IIS 7

Add two bindings to your website, one for local access and another for LAN access like so:

Open IIS and select your local website (that you want to access from your local network) from the left panel:

Connections > server (user-pc) > sites > local site

Open Bindings on the right panel under Actions tab add these bindings:

  1. Local:

    Type: http
    Ip Address: All Unassigned
    Port: 80
    Host name: samplesite.local
    
  2. LAN:

    Type: http
    Ip Address: <Network address of the hosting machine ex. 192.168.0.10>
    Port: 80
    Host name: <Leave it blank>
    

Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.

NOTE:

if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):

192.168.0.10 samplesite.local

How to get a complete list of ticker symbols from Yahoo Finance?

One workaround I had for this was to iterate over the sectors(which at the time you could do...I haven't tested that recently).

You wind up getting blocked eventually when you do it that way though, since YQL gets throttled per day.

Use the CSV API whenever possible to avoid this.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

I found the solution here in this link.

You just have to place below code in your Android application class. And that is enough. Don't need to do any changes in your Retrofit settings. It saved my day.

public class MyApplication extends Application {
@Override
public void onCreate() {
    super.onCreate();
    try {
      // Google Play will install latest OpenSSL 
      ProviderInstaller.installIfNeeded(getApplicationContext());
      SSLContext sslContext;
      sslContext = SSLContext.getInstance("TLSv1.2");
      sslContext.init(null, null, null);
      sslContext.createSSLEngine();
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
        | NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
        }
    }
}

Hope this will be of help. Thank you.

How to write DataFrame to postgres table?

This is how I did it.

It may be faster because it is using execute_batch:

# df is the dataframe
if len(df) > 0:
    df_columns = list(df)
    # create (col1,col2,...)
    columns = ",".join(df_columns)

    # create VALUES('%s', '%s",...) one '%s' per column
    values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

    #create INSERT INTO table (columns) VALUES('%s',...)
    insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

    cur = conn.cursor()
    psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
    conn.commit()
    cur.close()

Compute row average in pandas

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

Get the closest number out of an array

Another variant here we have circular range connecting head to toe and accepts only min value to given input. This had helped me get char code values for one of the encryption algorithm.

function closestNumberInCircularRange(codes, charCode) {
  return codes.reduce((p_code, c_code)=>{
    if(((Math.abs(p_code-charCode) > Math.abs(c_code-charCode)) || p_code > charCode) && c_code < charCode){
      return c_code;
    }else if(p_code < charCode){
      return p_code;
    }else if(p_code > charCode && c_code > charCode){
      return Math.max.apply(Math, [p_code, c_code]);
    }
    return p_code;
  });
}

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

How do I pass the this context to a function?

Another basic example:

NOT working:

var img = new Image;
img.onload = function() {
   this.myGlobalFunction(img);
};
img.src = reader.result;

Working:

var img = new Image;
img.onload = function() {
   this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;

So basically: just add .bind(this) to your function

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

When to catch java.lang.Error?

Never. You can never be sure that the application is able to execute the next line of code. If you get an OutOfMemoryError, you have no guarantee that you will be able to do anything reliably. Catch RuntimeException and checked Exceptions, but never Errors.

http://pmd.sourceforge.net/rules/strictexception.html

Convert a PHP script into a stand-alone windows executable

My experience in this matter tells me , most of these software work good with small projects .
But what about big projects? e.g: Zend Framework 2 and some things like that.
Some of them need browser to run and this is difficult to tell customer "please type http://localhost/" in your browser address bar !!

I create a simple project to do this : PHPPy

This is not complete way for create stand alone executable file for running php projects but helps you to do this.
I couldn't compile python file with PyInstaller or Py2exe to .exe file , hope you can.
You don't need uniformserver executable files.

Getting and removing the first character of a string

Another alternative is to use capturing sub-expressions with the regular expression functions regmatches and regexec.

# the original example
x <- 'hello stackoverflow'

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))

This returns the entire string, the first character, and the "popped" result in a list of length 1.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). That is, it contains the super set of the desired elements as well as the full string.


Adding sapply will allow this method to work for a character vector of length > 1.

# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))

This returns a list with the matched full string as the first element and the matching subexpressions captured by () as the following elements. So in the regular expression '(^.)(.*)', (^.) matches the first character and (.*) matches the remaining characters.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

[[2]]
[1] "right back" "r"          "ight back" 

[[3]]
[1] "at yah" "a"      "t yah" 

Now, we can use the trusty sapply + [ method to pull out the desired substrings.

myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back"          "t yah"

How do Python functions handle the types of the parameters that you pass in?

You don't specify a type. The method will only fail (at runtime) if it tries to access attributes that are not defined on the parameters that are passed in.

So this simple function:

def no_op(param1, param2):
    pass

... will not fail no matter what two args are passed in.

However, this function:

def call_quack(param1, param2):
    param1.quack()
    param2.quack()

... will fail at runtime if param1 and param2 do not both have callable attributes named quack.

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.

You might want to try:

salesAmount = float(raw_input("Insert sale amount here\n"))

cat, grep and cut - translated to python

You need to have better understanding of the python language and its standard library to translate the expression

cat "$filename": Reads the file cat "$filename" and dumps the content to stdout

|: pipe redirects the stdout from previous command and feeds it to the stdin of the next command

grep "something": Searches the regular expressionsomething plain text data file (if specified) or in the stdin and returns the matching lines.

cut -d'"' -f2: Splits the string with the specific delimiter and indexes/splices particular fields from the resultant list

Python Equivalent

cat "$filename"  | with open("$filename",'r') as fin:        | Read the file Sequentially
                 |     for line in fin:                      |   
-----------------------------------------------------------------------------------
grep 'something' | import re                                 | The python version returns
                 | line = re.findall(r'something', line)[0]  | a list of matches. We are only
                 |                                           | interested in the zero group
-----------------------------------------------------------------------------------
cut -d'"' -f2    | line = line.split('"')[1]                 | Splits the string and selects
                 |                                           | the second field (which is
                 |                                           | index 1 in python)

Combining

import re
with open("filename") as origin_file:
    for line in origin_file:
        line = re.findall(r'something', line)
        if line:
           line = line[0].split('"')[1]
        print line

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

IN-clause in HQL or Java Persistence Query Language

Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:

String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);

For Hibernate's, you'll need to use the setParameterList:

String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);

How to use PHP with Visual Studio

I don't understand how other answers don't answer the original question about how to use PHP (not very consistent with the title).
PHP files or PHP code embedded in HTML code start always with the tag <?php and ends with ?>.

You can embed PHP code inside HTML like this (you have to save the file using .php extension to let PHP server recognize and process it, ie: index.php):

<body>
   <?php echo "<div>Hello World!</div>" ?>
</body>

or you can use a whole php file, ie: test.php:

<?php    
$mycontent = "Hello World!";
echo "<div>$mycontent</div>";
?> // is not mandatory to put this at the end of the file

there's no document.ready in PHP, the scripts are processed when they are invoked from the browser or from another PHP file.

Should image size be defined in the img tag height/width attributes or in CSS?

I'm going to go against the grain here and state that the principle of separating content from layout (which would justify the answers that suggest using CSS) does not always apply to image height and width.

Each image has an innate, original height and width that can be derived from the image data. In the framework of content vs layout, I would say that this derived height and width information is content, not layout, and should therefore be rendered as HTML as element attributes.

This is much like the alt text, which can also be said to be derived from the image. This also supports the idea that an arbitrary user agent (e.g. a speech browser) should have that information in order to relate it to the user. At the least, the aspect ratio could prove useful ("image has a width of 15 and a height of 200"). Such user agents wouldn't necessarily process any CSS.

The spec says that the width and height attributes can also be used to override the height and width conveyed in the actual image file. I am not suggesting they be used for this. To override height and width, I believe CSS (inline, embedded or external) is the best approach.

So depending on what you want to do, you would specify one and/or the other. I think ideally, the original height and width would always be specified as HTML element attributes, while styling information should optionally be conveyed in CSS.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Updated for Xcode 7. Adds String extension:

Use:

var chuck: String = "Hello Chuck Norris"
chuck[6...11] // => Chuck

Implementation:

extension String {

    /**
     Subscript to allow for quick String substrings ["Hello"][0...1] = "He"
     */
    subscript (r: Range<Int>) -> String {
        get {
            let start = self.startIndex.advancedBy(r.startIndex)
            let end = self.startIndex.advancedBy(r.endIndex - 1)
            return self.substringWithRange(start..<end)
        }
    }

}

How do I add a new class to an element dynamically?

why @Marco Berrocl get a negative feedback and his answer is totally right what about using a library to make some animation so i need to call the class in hover to element not copy the code from the library and this will make me slow.

so i think hover not the answer and he should use jquery or javascript in many cases

Count occurrences of a char in a string using Bash

also check this out, for example we wanna count t

echo "test" | awk -v RS='t' 'END{print NR-1}'

or in python

python -c 'print "this is for test".count("t")'

or even better, we can make our script dynamic with awk

echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""

in this case output is like this :

e 1
s 1
t 2

python max function using 'key' and lambda expression

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

How to show a GUI message box from a bash script in linux?

Zenity is really the exact tool that I think that you are looking for.

or

zenity --help

Checking if a worksheet-based checkbox is checked

Try: Controls("Check Box 1") = True

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

How can we redirect a Java program console output to multiple files?

Go to run as and choose Run Configurations -> Common and in the Standard Input and Output you can choose a File also.

iOS 7: UITableView shows under status bar

I was facing this issue in ios 11 but layout was correct for ios 8 - 10.3.3 . For my case I set a Vertical Space Constraint to Superview.Top Margin instead of Superview.Top which works for ios 8 - 11.

enter image description here

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():

unset($arr[1]);

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

SQL query for finding records where count > 1

Try this query:

SELECT column_name
  FROM table_name
 GROUP BY column_name
HAVING COUNT(column_name) = 1;

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

How to sort rows of HTML table that are called from MySQL

It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY. I would like to suggest javascript alternatives.

In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)

Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22 you will get 1, 11, 2, 22.

You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table> in HTML5 has sortable attribute, but apparently it's not implemented yet.

What is the difference between a string and a byte string?

The Python languages includes str and bytes as standard "Built-in Types". In other words, they are both classes. I don't think it's worthwhile trying to rationalize why Python has been implemented this way.

Having said that, str and bytes are very similar to one another. Both share most of the same methods. The following methods are unique to the str class:

casefold
encode
format
format_map
isdecimal
isidentifier
isnumeric
isprintable

The following methods are unique to the bytes class:

decode
fromhex
hex

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

Following the steps in the accepted answer didn't work for me. I followed the steps in this guide with an image running 5.0.0, and it got the job done. It's a step-wise process just like the accepted answer for adding Google Play support to genymotion images.

The most important differences are that in the guide I linked to, they mention that installing Google Play Services on images running higher than 5.0.0 may not work, and they say to change the ADB tool connection settings in the Genymotion desktop application's settings window to: Use custom Android SDK tools. Also, the gapps zips seem to be different.

The guide also uses GIFs to illustrate the steps in the process, so it leaves much less room for doubt.

Link to gapps zip for Android 5.0 used in the guide -- requires Genymotion 2.4.0+

Link to ARM Translation Installer v1.1 used in the guide -- this is provided for convenience. it doesn't seem any different than the one provided in the accepted answer at first glance

Anaconda vs. miniconda

Miniconda gives you the Python interpreter itself, along with a command-line tool called conda which operates as a cross-platform package manager geared toward Python packages, similar in spirit to the apt or yum tools that Linux users might be familiar with.

Anaconda includes both Python and conda, and additionally bundles a suite of other pre-installed packages geared toward scientific computing. Because of the size of this bundle, expect the installation to consume several gigabytes of disk space.

Source: Jake VanderPlas's Python Data Science Handbook

How can I get the line number which threw exception?

If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

try
{
    throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
}

Note that this will only work if there is a pdb file available for the assembly.

Create an array of strings

As already mentioned by Amro, the most concise way to do this is using cell arrays. However, Budo touched on the new string class introduced in version R2016b of MATLAB. Using this new object, you can very easily create an array of strings in a loop as follows:

for i = 1:10
  Names(i) = string('Sample Text');
end

What should I set JAVA_HOME environment variable on macOS X 10.6?

Create file ~/.mavenrc

then paste this into the file

export JAVA_HOME=$(/usr/libexec/java_home)

test

mvn -v

Can I remove the URL from my print css, so the web address doesn't print?

@media print 
{
  a[href]:after { content: none !important; }
  img[src]:after { content: none !important; }
}

If statement within Where clause

CASE might help you out:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

CSS @font-face not working with Firefox, but working with Chrome and IE

I had exactly this problem running ff4 on a mac. I had a local development server running and my @font-face declaration worked fine. I migrated to live and FF would 'flash' the correct type on first page load, but when navigating deeper the typeface defaulted to the browser stylesheet.

I found the solution lay in adding the following declaration to .htaccess

<FilesMatch "\.(ttf|otf|eot)$">
    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>

found via

Leave only two decimal places after the dot

Try this:

double result = Math.Round(24.576938593,2);
MessageBox.Show(result.ToString());

Output: 24.57

rails bundle clean

If you are using RVM you can install your gems into gemsets. That way when you want to perform a full cleanup you can simply remove the gemset, which in turn removes all the gems installed in it. Your other option is to simply uninstall your unused gems and re-run your bundle install command.

Since bundler is meant to be a project-per-project gem versioning tool it does not provide a bundle clean command. Doing so would mean the possibility of removing gems associated with other projects as well, which would not be desirable. That means that bundler is probably the wrong tool to use to manage your gem directory. My personal recommendation would be to use RVM gemsets to sandbox your gems in certain projects or ruby versions.

Why is `input` in Python 3 throwing NameError: name... is not defined

If we setaside the syntax error of print, then the way to use input in multiple scenarios are -

If using python 2.x :

then for evaluated input use "input"
example: number = input("enter a number")

and for string use "raw_input"
example: name = raw_input("enter your name")

If using python 3.x :

then for evaluated result use "eval" and "input"
example: number = eval(input("enter a number"))

for string use "input"
example: name = input("enter your name")

sudo: npm: command not found

For MAC users, the follow steps worked for me.

If you get Error for Brew, Here's the command you need to type first in the terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Then run following commands:
$ brew update
$ brew uninstall node
$ brew install node
$ brew postinstall 

How to HTML encode/escape a string? Is there a built-in?

Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.

CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo &quot;bar&quot; &lt;baz&gt;"

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

How to adjust text font size to fit textview

I had the same problem and wrote a class that seems to work for me. Basically, I used a static layout to draw the text in a separate canvas and remeasure until I find a font size that fits. You can see the class posted in the topic below. I hope it helps.

Auto Scale TextView Text to Fit within Bounds

Python-Requests close http connection

please use response.close() to close to avoid "too many open files" error

for example:

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

How to "crop" a rectangular image into a square with CSS?

Either use a div with square dimensions with the image inside with the .testimg class:

.test {
width: 307px;
height: 307px;
overflow:hidden
}

.testimg {
    margin-left: -76px

}

or a square div with a background of the image.

.test2 {
width: 307px;
height: 307px;
    background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%
}

Here's some examples: http://jsfiddle.net/QqCLC/1/

UPDATED SO THE IMAGE CENTRES

_x000D_
_x000D_
.test {_x000D_
  width: 307px;_x000D_
  height: 307px;_x000D_
  overflow: hidden_x000D_
}_x000D_
_x000D_
.testimg {_x000D_
  margin-left: -76px_x000D_
}_x000D_
_x000D_
.test2 {_x000D_
  width: 307px;_x000D_
  height: 307px;_x000D_
  background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%_x000D_
}
_x000D_
<div class="test"><img src="http://i.stack.imgur.com/GA6bB.png" width="460" height="307" class="testimg" /></div>_x000D_
_x000D_
<div class="test2"></div>
_x000D_
_x000D_
_x000D_

passing 2 $index values within nested ng-repeat

When you are dealing with objects, you want to ignore simple id's as much as convenient.

If you change the click line to this, I think you will be well on your way:

<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">

Also, I think you may need to change

class="tutorial_title {{tutorial.active}}"

to something like

ng-class="tutorial_title {{tutorial.active}}"

See http://docs.angularjs.org/misc/faq and look for ng-class.

"SSL certificate verify failed" using pip to install packages

In Windows 10 / search the drive you have installed the conda or it should be in C:\Users\name\AppData\Roaming\pipright with your mouse right click and select edit with notepad leave the [global] and replace what ever you have in there with blow code, Ctrl+s and rerun the code. it should work.

trusted-host = pypi.python.org pypi.org files.pythonhosted.org

How to display activity indicator in middle of the iphone screen?

If you want to center the spinner using AutoLayout, do:

UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[activityView startAnimating];
[self.view addSubview:activityView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
                                                      attribute:NSLayoutAttributeCenterX
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterX
                                                     multiplier:1.0
                                                       constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
                                                      attribute:NSLayoutAttributeCenterY
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterY
                                                     multiplier:1.0
                                                       constant:0.0]];

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I am using wildfly 10 for javaee container . I had experienced "Target Unreachable, 'entity' returned null" issue. Thanks for suggestions by BalusC but the my issue out of the solutions explained. Accidentally using "import com.sun.istack.logging.Logger;" instead of "import org.jboss.logging.Logger;" caused CDI implemented JSF EL. Hope it helps to improve solution .

Assign an initial value to radio button as checked

Im a bit late to the party and I know the OP said html, but if you needed to do this in MVC you can set true in the third param.

eg:

    <p>Option One :@Html.RadioButton("options", "option1", true})</p>
    // true will set it checked

     <p>Option Two :@Html.RadioButton("options", "option2"})</p>
     //nothing will leave it unchecked

When should I use cross apply over inner join?

cross apply sometimes enables you to do things that you cannot do with inner join.

Example (a syntax error):

select F.* from sys.objects O  
inner join dbo.myTableFun(O.name) F   
on F.schema_id= O.schema_id

This is a syntax error, because, when used with inner join, table functions can only take variables or constants as parameters. (I.e., the table function parameter cannot depend on another table's column.)

However:

select F.* from sys.objects O  
cross apply ( select * from dbo.myTableFun(O.name) ) F  
where F.schema_id= O.schema_id

This is legal.

Edit: Or alternatively, shorter syntax: (by ErikE)

select F.* from sys.objects O  
cross apply dbo.myTableFun(O.name) F
where F.schema_id= O.schema_id

Edit:

Note: Informix 12.10 xC2+ has Lateral Derived Tables and Postgresql (9.3+) has Lateral Subqueries which can be used to a similar effect.

Convert String to Double - VB

Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
    ' text is convertible to Double, and value contains the Double value now
Else
    ' Cannot convert text to Double
End If

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You must add this code in global.aspx:

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Force re-download of release dependency using Maven

Just delete ~/.m2/repository...../actual_path where the invalid LOC is coming as it forces to re-download the deleted jar files. Dont delete the whole repository folder instead delete the specific folder from where the error is coming.

How to perform a sum of an int[] array

Here is an efficient way to solve this question using For loops in Java

 public static void main(String[] args) {

    int [] numbers = { 1, 2, 3, 4 };
    int size = numbers.length;

    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }

    System.out.println(sum);
}

Swift extract regex matches

Swift 4 without NSString.

extension String {
    func matches(regex: String) -> [String] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) else { return [] }
        let matches  = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count))
        return matches.map { match in
            return String(self[Range(match.range, in: self)!])
        }
    }
}

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

To make a batch file for its current directory and sub directories:

cd %~dp0
attrib -h -r -s /s /d /l *.*

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.

You can use JavaScript/Canvas to do the job but it is still experimental.

How to set focus on input field?

Not to resurrect a zombie or plug my own directive (ok that's exactly what I'm doing):

https://github.com/hiebj/ng-focus-if

http://plnkr.co/edit/MJS3zRk079Mu72o5A9l6?p=preview

<input focus-if />

(function() {
    'use strict';
    angular
        .module('focus-if', [])
        .directive('focusIf', focusIf);

    function focusIf($timeout) {
        function link($scope, $element, $attrs) {
            var dom = $element[0];
            if ($attrs.focusIf) {
                $scope.$watch($attrs.focusIf, focus);
            } else {
                focus(true);
            }
            function focus(condition) {
                if (condition) {
                    $timeout(function() {
                        dom.focus();
                    }, $scope.$eval($attrs.focusDelay) || 0);
                }
            }
        }
        return {
            restrict: 'A',
            link: link
        };
    }
})();

Set markers for individual points on a line in Matplotlib

Specify the keyword args linestyle and/or marker in your call to plot.

For example, using a dashed line and blue circle markers:

plt.plot(range(10), linestyle='--', marker='o', color='b')

A shortcut call for the same thing:

plt.plot(range(10), '--bo')

example1

Here is a list of the possible line and marker styles:

================    ===============================
character           description
================    ===============================
   -                solid line style
   --               dashed line style
   -.               dash-dot line style
   :                dotted line style
   .                point marker
   ,                pixel marker
   o                circle marker
   v                triangle_down marker
   ^                triangle_up marker
   <                triangle_left marker
   >                triangle_right marker
   1                tri_down marker
   2                tri_up marker
   3                tri_left marker
   4                tri_right marker
   s                square marker
   p                pentagon marker
   *                star marker
   h                hexagon1 marker
   H                hexagon2 marker
   +                plus marker
   x                x marker
   D                diamond marker
   d                thin_diamond marker
   |                vline marker
   _                hline marker
================    ===============================

edit: with an example of marking an arbitrary subset of points, as requested in the comments:

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(-np.pi, np.pi, 30)
ys = np.sin(xs)
markers_on = [12, 17, 18, 19]
plt.plot(xs, ys, '-gD', markevery=markers_on)
plt.show()

example2

This last example using the markevery kwarg is possible in since 1.4+, due to the merge of this feature branch. If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot. See the edit history for more details.

Convert Little Endian to Big Endian

"I swap each bytes right?" -> yes, to convert between little and big endian, you just give the bytes the opposite order. But at first realize few things:

  • size of uint32_t is 32bits, which is 4 bytes, which is 8 HEX digits
  • mask 0xf retrieves the 4 least significant bits, to retrieve 8 bits, you need 0xff

so in case you want to swap the order of 4 bytes with that kind of masks, you could:

uint32_t res = 0;
b0 = (num & 0xff) << 24;        ; least significant to most significant
b1 = (num & 0xff00) << 8;       ; 2nd least sig. to 2nd most sig.
b2 = (num & 0xff0000) >> 8;     ; 2nd most sig. to 2nd least sig.
b3 = (num & 0xff000000) >> 24;  ; most sig. to least sig.
res = b0 | b1 | b2 | b3 ;

Writing data into CSV file in C#

Handling Commas

For handling commas inside of values when using string.Format(...), the following has worked for me:

var newLine = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                              first,
                              second,
                              third                                    
                              );
csv.AppendLine(newLine);

So to combine it with Johan's answer, it'd look like this:

//before your loop
var csv = new StringBuilder();

//in your loop
  var first = reader[0].ToString();
  var second = image.ToString();
  //Suggestion made by KyleMit
  var newLine = string.Format("\"{0}\",\"{1}\"", first, second);
  csv.AppendLine(newLine);  

//after your loop
File.WriteAllText(filePath, csv.ToString());

Returning CSV File

If you simply wanted to return the file instead of writing it to a location, this is an example of how I accomplished it:

From a Stored Procedure

public FileContentResults DownloadCSV()
{
  // I have a stored procedure that queries the information I need
  SqlConnection thisConnection = new SqlConnection("Data Source=sv12sql;User ID=UI_Readonly;Password=SuperSecure;Initial Catalog=DB_Name;Integrated Security=false");
  SqlCommand queryCommand = new SqlCommand("spc_GetInfoINeed", thisConnection);
  queryCommand.CommandType = CommandType.StoredProcedure;

  StringBuilder sbRtn = new StringBuilder();

  // If you want headers for your file
  var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                             "Name",
                             "Address",
                             "Phone Number"
                            );
  sbRtn.AppendLine(header);

  // Open Database Connection
  thisConnection.Open();
  using (SqlDataReader rdr = queryCommand.ExecuteReader())
  {
    while (rdr.Read())
    {
      // rdr["COLUMN NAME"].ToString();
      var queryResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                                        rdr["Name"].ToString(),
                                        rdr["Address"}.ToString(),
                                        rdr["Phone Number"].ToString()
                                       );
      sbRtn.AppendLine(queryResults);
    }
  }
  thisConnection.Close();

  return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

From a List

/* To help illustrate */
public static List<Person> list = new List<Person>();

/* To help illustrate */
public class Person
{
  public string name;
  public string address;
  public string phoneNumber;
}

/* The important part */
public FileContentResults DownloadCSV()
{
  StringBuilder sbRtn = new StringBuilder();

  // If you want headers for your file
  var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                             "Name",
                             "Address",
                             "Phone Number"
                            );
  sbRtn.AppendLine(header);

  foreach (var item in list)
  {
      var listResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                                        item.name,
                                        item.address,
                                        item.phoneNumber
                                       );
      sbRtn.AppendLine(listResults);
    }
  }

  return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

Hopefully this is helpful.

Is there a command to undo git init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

How to update array value javascript?

If you want to reassign an element in an array, you can do the following:

var blah = ['Jan', 'Fed', 'Apr'];

console.log(blah);

function reassign(array, index, newValue) {
    array[index] = newValue;
    return array;
}

reassign(blah, [2], 'Mar');

Oracle DB: How can I write query ignoring case?

You could also use Regular Expressions:

SELECT * FROM TABLE WHERE REGEXP_LIKE (TABLE.NAME,'IgNoReCaSe','i');

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

Sqlite convert string to date

As Sqlite doesn't have a date type you will need to do string comparison to achieve this. For that to work you need to reverse the order - eg from dd/MM/yyyy to yyyyMMdd, using something like

where substr(column,7)||substr(column,4,2)||substr(column,1,2) 
      between '20101101' and '20101130'

Loop through each cell in a range of cells when given a Range object

You could use Range.Rows, Range.Columns or Range.Cells. Each of these collections contain Range objects.

Here's how you could modify Dick's example so as to work with Rows:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Rows
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

And Columns:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCol In rRng.Columns
        For Each rCell In rCol.Rows
            Debug.Print rCell.Address, rCell.Value
        Next rCell
    Next rCol

End Sub

load json into variable

<input  class="pull-right" id="currSpecID" name="currSpecID" value="">

   $.get("http://localhost:8080/HIS_API/rest/MriSpecimen/getMaxSpecimenID", function(data, status){
       alert("Data: " + data + "\nStatus: " + status);
    $("#currSpecID").val(data);
    });

enter image description here enter image description here

Vertical Align Center in Bootstrap 4

.jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Java Enum Methods - return opposite direction enum

For a small enum like this, I find the most readable solution to be:

public enum Direction {

    NORTH {
        @Override
        public Direction getOppositeDirection() {
            return SOUTH;
        }
    }, 
    SOUTH {
        @Override
        public Direction getOppositeDirection() {
            return NORTH;
        }
    },
    EAST {
        @Override
        public Direction getOppositeDirection() {
            return WEST;
        }
    },
    WEST {
        @Override
        public Direction getOppositeDirection() {
            return EAST;
        }
    };


    public abstract Direction getOppositeDirection();

}

Get string between two strings in a string

getStringBetween(startStr, endStr, fullStr) {
    string startIndex = fullStr.indexOf(startStr);
    string endIndex= fullStr.indexOf(endStr);
    return fullStr.substring(startIndex + startStr.length, endIndex);
}

Redirect within component Angular 2

@kit's answer is okay, but remember to add ROUTER_PROVIDERS to providers in the component. Then you can redirect to another page within ngOnInit method:

import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'

@Component({
    selector: 'loginForm',
    templateUrl: 'login.html',
    providers: [ROUTER_PROVIDERS]
})

export class LoginComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
        this.router.navigate(['./SomewhereElse']);
    }

}

How do I pass a string into subprocess.Popen (using the stdin argument)?

I am using python3 and found out that you need to encode your string before you can pass it into stdin:

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode())
print(out)

Singleton: How should it be used

Answer:

Use a Singleton if:

  • You need to have one and only one object of a type in system

Do not use a Singleton if:

  • You want to save memory
  • You want to try something new
  • You want to show off how much you know
  • Because everyone else is doing it (See cargo cult programmer in wikipedia)
  • In user interface widgets
  • It is supposed to be a cache
  • In strings
  • In Sessions
  • I can go all day long

How to create the best singleton:

  • The smaller, the better. I am a minimalist
  • Make sure it is thread safe
  • Make sure it is never null
  • Make sure it is created only once
  • Lazy or system initialization? Up to your requirements
  • Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
  • Provide a destructor or somehow figure out how to dispose resources
  • Use little memory

using sql count in a case statement

select sum(rsp_ind = 0) as `New`,
       sum(rsp_ind = 1) as `Accepted` 
from tb_a

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

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

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

How to style an asp.net menu with CSS

The thing to look at is what HTML is being spit out by the control. In this case it puts out a table to create the menu. The hover style is set on the TD and once you select a menu item the control posts back and adds the selected style to the A tag of the link within the TD.

So you have two different items that are being manipulated here. One is a TD element and another is an A element. So, you have to make your CSS work accordingly. If I add the below CSS to a page with the menu then I get the expected behavior of the background color changing in either case. You may be doing some different CSS manipulation that may or may not apply to those elements.

<style>
    .StaticHoverStyle
    {
        background: #000000;
    }

    .StaticSelectedStyle
    {
        background: blue;
    }
</style>

Jetty: HTTP ERROR: 503/ Service Unavailable

2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker

Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.

"Parser Error Message: Could not load type" in Global.asax

"BUILD -> CONFIGURATION MANAGER and -- ahem -- check the box next to my project to ensure it actually gets built." That and going to the project folder in windows explorer, pressing options and unchecking the "Read only" checkbox helped.

How to Set Focus on Input Field using JQuery

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
    $('input[name="aa"'+n+']').focus();
}

int array to string

You can simply use String.Join function, and as separator use string.Empty because it uses StringBuilder internally.

string result = string.Join(string.Empty, new []{0,1,2,3,0,1});

E.g.: If you use semicolon as separator, the result would be 0;1;2;3;0;1.

It actually works with null separator, and second parameter can be enumerable of any objects, like:

string result = string.Join(null, new object[]{0,1,2,3,0,"A",DateTime.Now});

View not attached to window manager crash

For Dialog created in a Fragment, I use the following code:

ProgressDialog myDialog = new ProgressDialog(getActivity());
myDialog.setOwnerActivity(getActivity());
...
Activity activity = myDialog.getOwnerActivity();
if( activity!=null && !activity.isFinishing()) {
    myDialog.dismiss();
}

I use this pattern to deal with the case when a Fragment may be detached from the Activity.

Apache default VirtualHost

Obligatory - none of the previous answers worked for me. I inherited a strange combination of IP address-based virtual hosts and * vhosts (not assigned/catch all IP addresses) based virtual hosts in this Apache configuration messed up by ISPConfig.

I wanted Apache to serve not configured hosts with the same page.

I had: not configured hosts went to the first vhost after 000-default.conf. No matter I had *:80 catch all defined as the first vhost, instead of default Apache would load first defined site:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
</VirtualHost>

Although it's not completely valid configuration, what finally worked was adding an IP address-based virtualhost without ServerName/ServerAlias defined:

<VirtualHost 192.168.10.10:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
</VirtualHost>

<VirtualHost 192.168.10.10:443>
  ServerAdmin webmaster@localhost
  DocumentRoot /var/www/html
  SSLEngine On
  ...
</VirtualHost>

$ apachectl -S outputs IP address-based vhosts first, and * based vhosts later, and finally my default site is loaded before real site:

AH00548: NameVirtualHost has no effect and will be removed in the next release /etc/apache2/sites-enabled/000-default.conf:50
192.168.10.10:80        is a NameVirtualHost
         default server server.tld (/etc/apache2/sites-enabled/000-default.conf:34)
         port 80 namevhost server.tld (/etc/apache2/sites-enabled/000-default.conf:34)
         port 80 namevhost some-site.tld (/etc/apache2/sites-enabled/100-some-site.tld.vhost:7)

...

46.23.86.103:443       is a NameVirtualHost
         default server server.tld (/etc/apache2/sites-enabled/000-default.conf:38)
         port 443 namevhost server.tld (/etc/apache2/sites-enabled/000-default.conf:38)
         port 443 namevhost some-site.tld (/etc/apache2/sites-enabled/100-some-site.tld.vhost:182)

...

*:80                   is a NameVirtualHost
         default server server.tld (/etc/apache2/sites-enabled/000-default.conf:1)
         port 80 namevhost server.tld (/etc/apache2/sites-enabled/000-default.conf:1)

Word of notice - in a configuration like this, * vhosts won't work, so you need to apply IP addresses to all vhosts.

"Too many characters in character literal error"

I believe you can do this using a Unicode encoding, but I doubt this is what you really want.

The == is the unicode value 2A76 so I belive you can do this:

char c = '\u2A76';

I can't test this at the moment but I'd be interested to know if that works for you.

You will need to dig around for the others. Here is a unicode table if you want to look:

http://www.tamasoft.co.jp/en/general-info/unicode.html

Regular expression that matches valid IPv6 addresses

In Scala use the well known Apache Commons validators.

http://mvnrepository.com/artifact/commons-validator/commons-validator/1.4.1

libraryDependencies += "commons-validator" % "commons-validator" % "1.4.1"


import org.apache.commons.validator.routines._

/**
 * Validates if the passed ip is a valid IPv4 or IPv6 address.
 *
 * @param ip The IP address to validate.
 * @return True if the passed IP address is valid, false otherwise.
 */  
 def ip(ip: String) = InetAddressValidator.getInstance().isValid(ip)

Following the test's of the method ip(ip: String):

"The `ip` validator" should {
  "return false if the IPv4 is invalid" in {
    ip("123") must beFalse
    ip("255.255.255.256") must beFalse
    ip("127.1") must beFalse
    ip("30.168.1.255.1") must beFalse
    ip("-1.2.3.4") must beFalse
  }

  "return true if the IPv4 is valid" in {
    ip("255.255.255.255") must beTrue
    ip("127.0.0.1") must beTrue
    ip("0.0.0.0") must beTrue
  }

  //IPv6
  //@see: http://www.ronnutter.com/ipv6-cheatsheet-on-identifying-valid-ipv6-addresses/
  "return false if the IPv6 is invalid" in {
    ip("1200::AB00:1234::2552:7777:1313") must beFalse
  }

  "return true if the IPv6 is valid" in {
    ip("1200:0000:AB00:1234:0000:2552:7777:1313") must beTrue
    ip("21DA:D3:0:2F3B:2AA:FF:FE28:9C5A") must beTrue
  }
}

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

For Bootstrap 3 for collapse, if you don't specify data-target on the anchor and rely on href to determine the target, the event will be prevented. If you use data-target you'll need to prevent the event yourself.

<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#demo">Collapse This</button>

<div id="demo" class="collapse"> 
<p>Lorem ipsum dolor sit amet</p>
</div>

How to fetch the dropdown values from database and display in jsp

  1. Make the database connection and retrieve the query result.
  2. Traverse through the result and display the query results.

The example code below demonstrates this in detail.

<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library

<%

String label = request.getParameter("label"); // retrieving a variable from a previous page

Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null) 
{
    System.out.println("Connection successful");
}

ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult

%>

<form name="demo form" method="post">

    <table>
        <tr>
            <td>
                Label Name:
            </td>

            <td>
                <input type="text" name="label" value="<%=rs.getString("labelname")%>">
            </td>

            <td>
                <select name="label">
                <option value="">SELECT</option>

                <% while (rs.next()) {%>

                    <option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
                    </option>

                <%}%>
                </select>
            </td>
        </tr>
    </table>

</form>

//The function:

public static ResultSet func(Connection dbc, String x)
{
    ResultSet rs = null;
    String sql;
    PreparedStatement pst;
    try
    {
        sql = "select lname from demo where label like '" + x + "'";
        pst = dbc.prepareStatement(sql);
        rs = pst.executeQuery();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        String sqlMessage = e.getMessage();
    }
    return rs;
}

I have tried to make this example as detailed as possible. Do ask if you have any queries.

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

java: ArrayList - how can I check if an index exists?

Regarding your update (which probably should be another question). You should use an array of these objects instead an ArrayList, so you can simply check the value for null:

Object[] array = new Object[MAX_ENTRIES];
..
if ( array[ 8 ] == null ) {
   // not available
}
else {
   // do something
}

Best-Practice

If you don't have hundred of entries in your array you should consider organizing it as a class to get rid of the magic numbers 3,8 etc.

Control flow using exception is bad practice.

Django download a file

Simple using html like this downloads the file mentioned using static keyword

<a href="{% static 'bt.docx' %}" class="btn btn-secondary px-4 py-2 btn-sm">Download CV</a>

Ignore duplicates when producing map using streams

For anyone else getting this issue but without duplicate keys in the map being streamed, make sure your keyMapper function isn't returning null values.

It's very annoying to track this down because the error will say "Duplicate key 1" when 1 is actually the value of the entry instead of the key.

In my case, my keyMapper function tried to look up values in a different map, but due to a typo in the strings was returning null values.

final Map<String, String> doop = new HashMap<>();
doop.put("a", "1");
doop.put("b", "2");

final Map<String, String> lookup = new HashMap<>();
doop.put("c", "e");
doop.put("d", "f");

doop.entrySet().stream().collect(Collectors.toMap(e -> lookup.get(e.getKey()), e -> e.getValue()));

1052: Column 'id' in field list is ambiguous

The simplest solution is a join with USING instead of ON. That way, the database "knows" that both id columns are actually the same, and won't nitpick on that:

SELECT id, name, section
  FROM tbl_names
  JOIN tbl_section USING (id)

If id is the only common column name in tbl_names and tbl_section, you can even use a NATURAL JOIN:

SELECT id, name, section
  FROM tbl_names
  NATURAL JOIN tbl_section

See also: https://dev.mysql.com/doc/refman/5.7/en/join.html

ggplot2 plot without axes, legends, etc

Late to the party, but might be of interest...

I find a combination of labs and guides specification useful in many cases:

You want nothing but a grid and a background:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  labs(x = NULL, y = NULL) + 
  guides(x = "none", y = "none")

enter image description here

You want to only suppress the tick-mark label of one or both axes:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  guides(x = "none", y = "none")

enter image description here

How to use wget in php?

<?php
function wget($address,$filename)
{
  file_put_contents($filename,file_get_contents($address));
}
?>

use:

<?php
wget(URL, FileName);
?>

jQuery send string as POST parameters

Try like this:

$.ajax({
    type: 'POST',
    // make sure you respect the same origin policy with this url:
    // http://en.wikipedia.org/wiki/Same_origin_policy
    url: 'http://nakolesah.ru/',
    data: { 
        'foo': 'bar', 
        'ca$libri': 'no$libri' // <-- the $ sign in the parameter name seems unusual, I would avoid it
    },
    success: function(msg){
        alert('wow' + msg);
    }
});

How to implement a simple scenario the OO way

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:

books

  • id
  • book specific info
  • etc

chapters

  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

How do I find out if the GPS of an Android device is enabled

This method will use the LocationManager service.

Source Link

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

In order to make that working I had to set:

compile ("com.android.support:support-v4:22.2.0")
compile ("com.android.support:appcompat-v7:22.2.0")
compile ("com.android.support:support-annotations:22.2.0")
compile ("com.android.support:recyclerview-v7:22.2.0")
compile ("com.android.support:design:22.2.0")

compile ("com.android.support:design:22.2.0")

Documentation states something different (docs):

com.android.support:support-design:22.0.0

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

write direct password into config>database.php

'password' => env('DB_PASSWORD', '')

Change to

'password' => 'your password',

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How can I share Jupyter notebooks with non-programmers?

One more way to achieve this goal would be using JupyterHub.

With JupyterHub you can create a multi-user Hub which spawns, manages, and proxies multiple instances of the single-user Jupyter notebook server. Due to its flexibility and customization options, JupyterHub can be used to serve notebooks to a class of students, a corporate data science group, or a scientific research group.

enter image description here

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

How often should you use git-gc?

You can do it without any interruption, with the new (Git 2.0 Q2 2014) setting gc.autodetach.

See commit 4c4ac4d and commit 9f673f9 (Nguy?n Thái Ng?c Duy, aka pclouds):

gc --auto takes time and can block the user temporarily (but not any less annoyingly).
Make it run in background on systems that support it.
The only thing lost with running in background is printouts. But gc output is not really interesting.
You can keep it in foreground by changing gc.autodetach.


Since that 2.0 release, there was a bug though: git 2.7 (Q4 2015) will make sure to not lose the error message.
See commit 329e6e8 (19 Sep 2015) by Nguy?n Thái Ng?c Duy (pclouds).
(Merged by Junio C Hamano -- gitster -- in commit 076c827, 15 Oct 2015)

gc: save log from daemonized gc --auto and print it next time

While commit 9f673f9 (gc: config option for running --auto in background - 2014-02-08) helps reduce some complaints about 'gc --auto' hogging the terminal, it creates another set of problems.

The latest in this set is, as the result of daemonizing, stderr is closed and all warnings are lost. This warning at the end of cmd_gc() is particularly important because it tells the user how to avoid "gc --auto" running repeatedly.
Because stderr is closed, the user does not know, naturally they complain about 'gc --auto' wasting CPU.

Daemonized gc now saves stderr to $GIT_DIR/gc.log.
Following gc --auto will not run and gc.log printed out until the user removes gc.log
.

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html

What can I use for good quality code coverage for C#/.NET?

TestCocoon is also pretty nice. It is in active development and has a user community:

  • Open source (GPL 3)
  • Supports C/C++/C# cross platform (Linux, Windows, and Mac)
  • CoverageScanner - Instrumentation during the Generation
  • CoverageBrowser - View, Analysis and Management of Code Coverage Result

However, TestCocoon is no longer developed and its creators are now producing a commercial software for C/C++.

Ignoring NaNs with str.contains

import folium
import pandas

data= pandas.read_csv("maps.txt")

lat = list(data["latitude"])
lon = list(data["longitude"])

map= folium.Map(location=[31.5204, 74.3587], zoom_start=6, tiles="Mapbox Bright")

fg = folium.FeatureGroup(name="My Map")

for lt, ln in zip(lat, lon):
c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))

child = fg.add_child(folium.Marker(location=[31.5204, 74.5387], popup="Welcome to Lahore", icon= folium.Icon(color='green')))

map.add_child(fg)

map.save("Lahore.html")


Traceback (most recent call last):
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\check2.py", line 14, in <module>
    c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\map.py", line 647, in __init__
    self.location = _validate_coordinates(location)
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\utilities.py", line 48, in _validate_coordinates
    'got:\n{!r}'.format(coordinates))
ValueError: Location values cannot contain NaNs, got:
[nan, nan]

how to get the cookies from a php curl into a variable

If you use CURLOPT_COOKIE_FILE and CURLOPT_COOKIE_JAR curl will read/write the cookies from/to a file. You can, after curl is done with it, read and/or modify it however you want.

Change span text?

Replace whatever is in the address bar with this:

javascript:document.getElementById('serverTime').innerHTML='[text here]';

Example.

How to remove Left property when position: absolute?

left:auto;

This will default the left back to the browser default.


So if you have your Markup/CSS as:

<div class="myClass"></div>

.myClass
{
  position:absolute;
  left:0;
}

When setting RTL, you could change to:

<div class="myClass rtl"></div>

.myClass
{
  position:absolute;
  left:0;
}
.myClass.rtl
{
  left:auto;
  right:0;
}

Refused to load the script because it violates the following Content Security Policy directive

Adding the meta tag to ignore this policy was not helping us, because our webserver was injecting the Content-Security-Policy header in the response.

In our case we are using Ngnix as the web server for a Tomcat 9 Java-based application. From the web server, it is directing the browser not to allow inline scripts, so for a temporary testing we have turned off Content-Security-Policy by commenting.

How to turn it off in ngnix

  • By default, ngnix ssl.conf file will have this adding a header to the response:

    #> grep 'Content-Security' -ir /etc/nginx/global/ssl.conf add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'none'; script-src 'self'; img-src 'self'; style-src 'self'; base-uri 'self'; form-action 'self';";

  • If you just comment this line and restart ngnix, it should not be adding the header to the response.

If you are concerned about security or in production please do not follow this, use these steps as only for testing purpose and moving on.

Convert seconds to HH-MM-SS with JavaScript?

I know this is kinda old, but...

ES2015:

var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}

It will output:

toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

How do I make a semi transparent background?

div.main{
     width:100%;
     height:550px;
     background: url('https://images.unsplash.com/photo-1503135935062-
     b7d1f5a0690f?ixlib=rb-enter code here0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=cf4d0c234ecaecd14f51a2343cc89b6c&dpr=1&auto=format&fit=crop&w=376&h=564&q=60&cs=tinysrgb') no-repeat;
     background-position:center;
     background-size:cover 
}
 div.main>div{
     width:100px;
     height:320px;
     background:transparent;
     background-attachment:fixed;
     border-top:25px solid orange;
     border-left:120px solid orange;
     border-bottom:25px solid orange;
     border-right:10px solid orange;
     margin-left:150px 
}

enter image description here

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

Iterating through a string word by word

Using nltk.

from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)

You may use TweetTokenizer for parsing casual text with emoticons and such.

Returning a value from thread?

I came across this thread when also trying to obtain the return value of a method that gets executed within a Thread. I thought I would post my solution that works.

This solution uses an class to store both the method to be executed (indirectly) and stores the returning value. The class can be used for any function and any return type. You just instantiate the object using the return value type and then pass the function to call via a lambda (or delegate).


C# 3.0 Implementation


public class ThreadedMethod<T>
{

    private T mResult;
    public T Result 
    {
        get { return mResult; }
        private set { mResult = value; }
    }

    public ThreadedMethod()
    {
    }

    //If supporting .net 3.5
    public void ExecuteMethod(Func<T> func)
    {
        Result = func.Invoke();
    }

    //If supporting only 2.0 use this and 
    //comment out the other overload
    public void ExecuteMethod(Delegate d)
    {
        Result = (T)d.DynamicInvoke();
    }
}

To use this code you can use a Lambda (or a delegate). Here is the example using lambdas:

ThreadedMethod<bool> threadedMethod = new ThreadedMethod<bool>();
Thread workerThread = new Thread((unused) => 
                            threadedMethod.ExecuteMethod(() => 
                                SomeMethod()));
workerThread.Start();
workerThread.Join();
if (threadedMethod.Result == false) 
{
    //do something about it...
}

VB.NET 2008 Implementation


Anyone using VB.NET 2008 can't use lambdas with non-value returning methods. This affects the ThreadedMethod class, so we'll make ExecuteMethod return the value of the function. This doesn't hurt anything.

Public Class ThreadedMethod(Of T)

    Private mResult As T
    Public Property Result() As T
        Get
            Return mResult
        End Get
        Private Set(ByVal value As T)
            mResult = value
        End Set
    End Property

    Sub New()
    End Sub

    'If supporting .net 3.5'
    Function ExecuteMethod(ByVal func As Func(Of T)) As T
        Result = func.Invoke()
        Return Result
    End Function

    'If supporting only 2.0 use this and' 
    'comment out the other overload'
    Function ExecuteMethod(ByVal d As [Delegate]) As T
        Result = DirectCast(d.DynamicInvoke(), T)
        Return Result
    End Function

End Class

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.

Oracle - How to generate script from sql developer

This worked for me:

  • In SQL Developer, right click the object that you want to generate a script for. i.e. the table name
  • Select Quick DLL > Save To File
  • This will then write the create statement to an external sql file.

Note, you can also highlight multiple objects at the same time, so you could generate one script that contains create statements for all tables within the database.

Use css gradient over background image

Ok, I solved it by adding the url for the background image at the end of the line.

Here's my working code:

_x000D_
_x000D_
.css {_x000D_
  background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
_x000D_
_x000D_

Deleting specific rows from DataTable

the easy way use this in button :

 var table = $('#example1').DataTable();
 table.row($(`#yesmediasec-${id}`).closest('tr')).remove( ).draw();

example1 = id table . yesmediasec = id of the button in the row

use it and every thing will be ok

Can you break from a Groovy "each" closure?

I agree with other answers not to use an exception to break an each. I also do not prefer to create an extra closure eachWithBreak, instead of this I prefer a modern approach: let's use the each to iterate over the collection, as requested, but refine the collection to contain only those elements to be iterated, for example with findAll:

collection.findAll { !endCondition }.each { doSomething() }

For example, if we what to break when the counter == 3 we can write this code (already suggested):

(0..5)
    .findAll { it < 3  }
    .each { println it }

This will output

0
1
2

So far so good, but you will notice a small discrepancy though. Our end condition, negation of counter == 3 is not quite correct because !(counter==3) is not equivalent with it < 3. This is necessary to make the code work since findAll does not actually break the loop but continues until the end.

To emulate a real situation, let's say we have this code:

for (n in 0..5) {
    if (n == 3)
        break
    println n
}

but we want to use each, so let's rewrite it using a function to simulate a break condition:

def breakWhen(nr) { nr == 3 }
(0..5)
    .findAll { !breakWhen(it) }
    .each { println it }

with the output:

0
1
2
4
5

now you see the problem with findAll. This does not stop, but ignores that element where the condition is not met.

To solve this issues, we need an extra variable to remember when the breaking condition become true. After this moment, findAll must ignore all remaining elements.

This is how it should look like:

def breakWhen(nr) { nr == 3 }
def loop = true
(0..5)
    .findAll {
        if (breakWhen(it))
            loop = false
        !breakWhen(it) && loop
    } .each {
        println it
    }

with the output:

0
1
2

That's what we want!

Step-by-step debugging with IPython

Developing New Code

Debugging inside IPython

  1. Use Jupyter/IPython cell execution to speed up experiment iterations
  2. Use %%debug for step through

Cell Example:

%%debug
...: for n in range(4):
...:    n>2

Debugging Existing Code

IPython inside debugging

  1. Debugging a broken unit test: pytest ... --pdbcls=IPython.terminal.debugger:TerminalPdb --pdb
  2. Debugging outside of test case: breakpoint(), python -m ipdb, etc.
  3. IPython.embed() for full IPython functionality where needed while in the debugger

Thoughts on Python

I agree with the OP that many things MATLAB does nicely Python still does not have and really should since just about everything in the language favors development speed over production speed. Maybe someday I will contribute more than trivial bug fixes to CPython.

https://github.com/ipython/ipython/commit/f042f3fea7560afcb518a1940daa46a72fbcfa68

See also Is it possible to run commands in IPython with debugging?

Check variable equality against a list of values

You can write if(foo in L(10,20,30)) if you define L to be

var L = function()
{
    var obj = {};
    for(var i=0; i<arguments.length; i++)
        obj[arguments[i]] = null;

    return obj;
};

Turn off warnings and errors on PHP and MySQL

Prepend functions with the '@' symbol to suppress certain errors, as opposed to turning off all error reporting.

More information: http://php.net/manual/en/language.operators.errorcontrol.php

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

@fsockopen();

Function to get yesterday's date in Javascript in format DD/MM/YYYY

Try this:

function getYesterdaysDate() {
    var date = new Date();
    date.setDate(date.getDate()-1);
    return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}

How to find top three highest salary in emp table in oracle?

select top 3 * from emp  order by sal desc

Why do people hate SQL cursors so much?

Cursors make people overly apply a procedural mindset to a set-based environment.

And they are SLOW!!!

From SQLTeam:

Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row. In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.

Benefits of using the conditional ?: (ternary) operator

I'd recommend limiting the use of the ternary(?:) operator to simple single line assignment if/else logic. Something resembling this pattern:

if(<boolCondition>) {
    <variable> = <value>;
}
else {
    <variable> = <anotherValue>;
}

Could be easily converted to:

<variable> = <boolCondition> ? <value> : <anotherValue>;

I would avoid using the ternary operator in situations that require if/else if/else, nested if/else, or if/else branch logic that results in the evaluation of multiple lines. Applying the ternary operator in these situations would likely result in unreadable, confusing, and unmanageable code. Hope this helps.

Python: Get relative path from comparing two absolute paths

os.path.relpath:

Return a relative filepath to path either from the current directory or from an optional start point.

>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'../log'

So, if relative path starts with '..' - it means that the second path is not descendant of the first path.

In Python3 you can use PurePath.relative_to:

Python 3.5.1 (default, Jan 22 2016, 08:54:32)
>>> from pathlib import Path

>>> Path('/usr/var/log').relative_to('/usr/var/log/')
PosixPath('.')

>>> Path('/usr/var/log').relative_to('/usr/var/')
PosixPath('log')

>>> Path('/usr/var/log').relative_to('/etc/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/usr/var/log' does not start with '/etc'

Specifying colClasses in the read.csv

I know OP asked about the utils::read.csv function, but let me provide an answer for these that come here searching how to do it using readr::read_csv from the tidyverse.

read_csv ("test.csv", col_names=FALSE, col_types = cols (.default = "c", time = "i"))

This should set the default type for all columns as character, while time would be parsed as integer.

How to check for an active Internet connection on iOS or macOS?

Apple provides a sample app which does exactly this:

Reachability

Stop MySQL service windows

I'm on XP. I've installed MySQL-5.6.10 manually from .zip, no Windows auto-installer provided by MySQL site. The /bin directory of my MySQL is in my PATH. So I start the server with mysqld --console command, like this:

C:\Documents and Settings\User>mysqld --console
2013-04-12 14:39:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_times
tamp server option (see documentation for more details).

From now on it is running. And that cmd window is occupied. I open and use another one.

I've tried to use the answers from above but none of them can stop the server. Only errors are throw. So I stop the server with mysqladmin -u root shutdown on the other cmd window or with Ctrl + C on the cmd window it is running in. The latter works not so good as the former, sometimes I have to click Ctrl + C twice or more.

The log of the shutdown process is like this:

2013-04-12 17:55:29 3968 [Note] Giving 0 client threads a chance to die gracefully
2013-04-12 17:55:29 3968 [Note] Event Scheduler: Purging the queue. 0 events
2013-04-12 17:55:29 3968 [Note] Shutting down slave threads
2013-04-12 17:55:29 3968 [Note] Forcefully disconnecting 0 remaining clients
2013-04-12 17:55:29 3968 [Note] Binlog end
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'partition'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INSERTED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_METRICS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCKS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_TRX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'InnoDB'
2013-04-12 17:55:29 3968 [Note] InnoDB: FTS optimize thread exiting.
2013-04-12 17:55:29 3968 [Note] InnoDB: Starting shutdown...
2013-04-12 17:55:30 3968 [Note] InnoDB: Shutdown completed; log sequence number 1719777
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'BLACKHOLE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'ARCHIVE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MRG_MYISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MyISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MEMORY'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'CSV'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'sha256_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_old_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_native_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'binlog'
2013-04-12 17:55:30 3968 [Note] mysqld: Shutdown complete

And I still don't know if it is 100% right way to shutdown the server, but it works :)

Does Java SE 8 have Pairs or Tuples?

Sadly, Java 8 did not introduce pairs or tuples. You can always use org.apache.commons.lang3.tuple of course (which personally I do use in combination with Java 8) or you can create your own wrappers. Or use Maps. Or stuff like that, as is explained in the accepted answer to that question you linked to.


UPDATE: JDK 14 is introducing records as a preview feature. These aren't tuples, but can be used to save many of the same problems. In your specific example from above, that could look something like this:

public class Jdk14Example {
    record CountForIndex(int index, long count) {}

    public static void main(String[] args) {
        boolean [][] directed_acyclic_graph = new boolean[][]{
                {false,  true, false,  true, false,  true},
                {false, false, false,  true, false,  true},
                {false, false, false,  true, false,  true},
                {false, false, false, false, false,  true},
                {false, false, false, false, false,  true},
                {false, false, false, false, false, false}
        };

        System.out.println(
                IntStream.range(0, directed_acyclic_graph.length)
                        .parallel()
                        .mapToObj(i -> {
                            long count = IntStream.range(0, directed_acyclic_graph[i].length)
                                            .filter(j -> directed_acyclic_graph[j][i])
                                            .count();
                            return new CountForIndex(i, count);
                        }
                        )
                        .filter(n -> n.count == 0)
                        .collect(() -> new ArrayList<CountForIndex>(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))
        );
    }
}

When compiled and run with JDK 14 (at the time of writing, this an early access build) using the --enable-preview flag, you get the following result:

[CountForIndex[index=0, count=0], CountForIndex[index=2, count=0], CountForIndex[index=4, count=0]]

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

A little late to game but thought I would add my 2 cents...

To avoid adding the extra mark-up of an inner span you could change the <h1> display property from block to inline (catch is you would have ensure the elements after the <h1> are block elements.

HTML

<h1>  
The Last Will and Testament of
Eric Jones</h1> 
<p>Some other text</p>

CSS

h1{
    display:inline;
    background-color:green;
    color:#fff;
}

Result
enter image description here
JSFIDDLE http://jsfiddle.net/J7VBV/

How to set a primary key in MongoDB?

In mongodb _id field is reserved for primary key. Mongodb use an internal ObjectId value if you don't define it in your object and also create an index to ensure performance.

But you can put your own unique value for _id and Mongodb will use it instead of making one for you. And even if you want to use multiple field as primary key you can use an object:

{ _id : { a : 1, b: 1} }

Just be careful when creating these ids that the order of keys (a and b in the example) matters, if you swap them around, it is considered a different object.

Can't push to GitHub because of large file which I already deleted

Sometimes the file is kept in tracking history, try the following steps:

  1. git commit, If you are seeing create mode with the big file listed, then do:
  2. git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch filename' HEAD. You should see a bunch of Rewrites shown in your console which ends with:

    rm 'filename' and

    the last line Ref was rewritten.

It's done.

Sorting objects by property values

With ES6 arrow functions it will be like this:

//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
  { brand: 'Benz', top_speed: 110 },
  { brand: 'Fiat', top_speed: 90 },
  { brand: 'Aston Martin', top_speed: 70 } ]

Array.prototype.sort() can accept a comparator function (here I used arrow notation, but ordinary functions work the same):

let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)

// [ { brand: 'Aston Martin', top_speed: 70 },
//   { brand: 'Benz', top_speed: 110 },
//   { brand: 'Fiat', top_speed: 90 },
//   { brand: 'Porsche', top_speed: 260 } ]

The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:

let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)

//[ { brand: 'Aston Martin', top_speed: 70 },
//  { brand: 'Fiat', top_speed: 90 },
//  { brand: 'Benz', top_speed: 110 },
//  { brand: 'Porsche', top_speed: 260 } ]

If you don't mind mutating the orginal array cars.sort(comparatorFunction) will do the trick.

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

Does Ruby have a string.startswith("abc") built in method?

If this is for a non-Rails project, I'd use String#index:

"foobar".index("foo") == 0  # => true

How can two strings be concatenated?

help.search() is a handy function, e.g.

> help.search("concatenate")

will lead you to paste().

LINQ - Full Outer Join

I think there are problems with most of these, including the accepted answer, because they don't work well with Linq over IQueryable either due to doing too many server round trips and too much data returns, or doing too much client execution.

For IEnumerable I don't like Sehe's answer or similar because it has excessive memory use (a simple 10000000 two list test ran Linqpad out of memory on my 32GB machine).

Also, most of the others don't actually implement a proper Full Outer Join because they are using a Union with a Right Join instead of Concat with a Right Anti Semi Join, which not only eliminates the duplicate inner join rows from the result, but any proper duplicates that existed originally in the left or right data.

So here are my extensions that handle all of these issues, generate SQL as well as implementing the join in LINQ to SQL directly, executing on the server, and is faster and with less memory than others on Enumerables:

public static class Ext {
    public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return from left in leftItems
               join right in rightItems on leftKeySelector(left) equals rightKeySelector(right) into temp
               from right in temp.DefaultIfEmpty()
               select resultSelector(left, right);
    }

    public static IEnumerable<TResult> RightOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return from right in rightItems
               join left in leftItems on rightKeySelector(right) equals leftKeySelector(left) into temp
               from left in temp.DefaultIfEmpty()
               select resultSelector(left, right);
    }

    public static IEnumerable<TResult> FullOuterJoinDistinct<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Union(leftItems.RightOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    public static IEnumerable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        var hashLK = new HashSet<TKey>(from l in leftItems select leftKeySelector(l));
        return rightItems.Where(r => !hashLK.Contains(rightKeySelector(r))).Select(r => resultSelector(default(TLeft),r));
    }

    public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector)  where TLeft : class {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    private static Expression<Func<TP, TC, TResult>> CastSMBody<TP, TC, TResult>(LambdaExpression ex, TP unusedP, TC unusedC, TResult unusedRes) => (Expression<Func<TP, TC, TResult>>)ex;

    public static IQueryable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLR = new { left = default(TLeft), rightg = default(IEnumerable<TRight>) };
        var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
        var parmC = Expression.Parameter(typeof(TRight), "c");
        var argLeft = Expression.PropertyOrField(parmP, "left");
        var newleftrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, parmC), parmP, parmC), sampleAnonLR, default(TRight), default(TResult));

        return leftItems.AsQueryable().GroupJoin(rightItems, leftKeySelector, rightKeySelector, (left, rightg) => new { left, rightg }).SelectMany(r => r.rightg.DefaultIfEmpty(), newleftrs);
    }

    public static IQueryable<TResult> RightOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLR = new { leftg = default(IEnumerable<TLeft>), right = default(TRight) };
        var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
        var parmC = Expression.Parameter(typeof(TLeft), "c");
        var argRight = Expression.PropertyOrField(parmP, "right");
        var newrightrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, parmC, argRight), parmP, parmC), sampleAnonLR, default(TLeft), default(TResult));

        return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).SelectMany(l => l.leftg.DefaultIfEmpty(), newrightrs);
    }

    public static IQueryable<TResult> FullOuterJoinDistinct<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Union(leftItems.RightOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    private static Expression<Func<TP, TResult>> CastSBody<TP, TResult>(LambdaExpression ex, TP unusedP, TResult unusedRes) => (Expression<Func<TP, TResult>>)ex;

    public static IQueryable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLgR = new { leftg = default(IEnumerable<TLeft>), right = default(TRight) };
        var parmLgR = Expression.Parameter(sampleAnonLgR.GetType(), "lgr");
        var argLeft = Expression.Constant(default(TLeft), typeof(TLeft));
        var argRight = Expression.PropertyOrField(parmLgR, "right");
        var newrightrs = CastSBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, argRight), parmLgR), sampleAnonLgR, default(TResult));

        return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).Where(lgr => !lgr.leftg.Any()).Select(newrightrs);
    }

    public static IQueryable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }
}

The difference between a Right Anti-Semi-Join is mostly moot with Linq to Objects or in the source, but makes a difference on the server (SQL) side in the final answer, removing an unnecessary JOIN.

The hand coding of Expression to handle merging an Expression<Func<>> into a lambda could be improved with LinqKit, but it would be nice if the language/compiler had added some help for that. The FullOuterJoinDistinct and RightOuterJoin functions are included for completeness, but I did not re-implement FullOuterGroupJoin yet.

I wrote another version of a full outer join for IEnumerable for cases where the key is orderable, which is about 50% faster than combining the left outer join with the right anti semi join, at least on small collections. It goes through each collection after sorting just once.

I also added another answer for a version that works with EF by replacing the Invoke with a custom expansion.

Count number of 1's in binary representation

Below are two simple examples (in C++) among many by which you can do this.

  1. We can simply count set bits (1's) using __builtin_popcount().

    int numOfOnes(int x) { return __builtin_popcount(x); }

  2. Loop through all bits in an integer, check if a bit is set and if it is then increment the count variable.

    int hammingDistance(int x) { int count = 0 for(int i = 0; i < 32; i++) if(x & (1 << i)) count++; return count; }

Hope this helps!

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

SQL Server may be able to suggest the right data type for you (even when it does not choose the right type by default) - clicking the "Suggest Types" button (shown in your screenshot above) allows you to have SQL Server scan the source and suggest a data type for the field that's throwing an error. In my case, choosing to scan 20000 rows to generate the suggestions, and using the resulting suggested data type, fixed the issue.

Make the current commit the only (initial) commit in a Git repository?

Just delete the Github repo and create a new one. By far the fastest, easiest and safest approach. After all, what do you have to gain carrying out all those commands in the accepted solution when all you want is the master branch with a single commit?

AngularJS : ng-click not working

i tried using the same ng-click for two elements with same name showDetail2('abc')

it is working for me . can you check rest of the code which may be breaking you to move further.

here is the sample jsfiddle i tried: