Programs & Examples On #Sharepoint documents

JAVA_HOME does not point to the JDK

I had a similar problem and it turned out the issue was having both versions 6 & 7 of OpenJDK. The answer comes from r-senior on ubuntu forums (http://ubuntuforums.org/showthread.php?t=1977619) --- just uninstall version 6:

sudo apt-get remove openjdk-6-*

make sure that JAVA_HOME and CLASSPATH aren't set to anything since that isn't actually the problem.

How to have multiple conditions for one if statement in python

Darian Moody has a nice solution to this challenge in his blog post:

a = 1
b = 2
c = True

rules = [a == 1,
         b == 2,
         c == True]

if all(rules):
    print("Success!")

The all() method returns True when all elements in the given iterable are true. If not, it returns False.

You can read a little more about it in the python docs here and more information and examples here.

(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)

Passing parameters to addTarget:action:forControlEvents

There is another one way, in which you can get indexPath of the cell where your button was pressed:

using usual action selector like:

 UIButton *btn = ....;
    [btn addTarget:self action:@selector(yourFunction:) forControlEvents:UIControlEventTouchUpInside];

and then in in yourFunction:

   - (void) yourFunction:(id)sender {

    UIButton *button = sender;
    CGPoint center = button.center;
    CGPoint rootViewPoint = [button.superview convertPoint:center toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
    //the rest of your code goes here
    ..
}

since you get an indexPath it becames much simplier.

cURL POST command line on WINDOWS RESTful service

Alternative solution: A More Userfriendly solution than command line:

If you are looking for a user friendly way to send and request data using HTTP Methods other than simple GET's probably you are looking for a chrome extention just like this one http://goo.gl/rVW22f called AVANCED REST CLIENT

For guys looking to stay with command-line i recommend cygwin:

I ended up installing cygwin with CURL which allow us to Get that Linux feeling - on Windows!

Using Cygwin command line this issues have stopped and most important, the request syntax used on 1. worked fine.

Useful links:

Where i was downloading the curl for windows command line?

For more information on how to install and get curl working with cygwin just go here

I hope it helps someone because i spent all morning on this.

How to check if one DateTime is greater than the other in C#

You can use the overloaded < or > operators.

For example:

DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...

Convert a string to a datetime

Nobody mentioned this, but in some cases the other method fails to recognize the datetime...

You can try this instead, which will convert the specified string representation of a date and time to an equivalent date and time value

string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
MessageBox.Show(oDate.Day + " " + oDate.Month + "  " + oDate.Year );

"Stack overflow in line 0" on Internet Explorer

This is problem with Java and Flash Player. Install the latest Java and Flash Player, and the problem will be resolved. If not, then install Mozilla Firefox, it will auto install the updates required.

Python loop for inside lambda

Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

x = lambda x: sys.stdout.write("\n".join(x) + "\n")

How to call javascript function from code-behind

This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.

ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg", 
    "$(document).ready(function(){EnableControls();
    alert('Overrides successfully Updated.');
    DisableControls();});", 
true);

In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

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

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

MongoDB vs Firebase

I will answer this question in terms of AngularFire, Firebase's library for Angular.

  1. Tl;dr: superpowers. :-)

  2. AngularFire's three-way data binding. Angular binds the view and the $scope, i.e., what your users do in the view automagically updates in the local variables, and when your JavaScript updates a local variable the view automagically updates. With Firebase the cloud database also updates automagically. You don't need to write $http.get or $http.put requests, the data just updates.

  3. Five-way data binding, and seven-way, nine-way, etc. I made a tic-tac-toe game using AngularFire. Two players can play together, with the two views updating the two $scopes and the cloud database. You could make a game with three or more players, all sharing one Firebase database.

  4. AngularFire's OAuth2 library makes authorization easy with Facebook, GitHub, Google, Twitter, tokens, and passwords.

  5. Double security. You can set up your Angular routes to require authorization, and set up rules in Firebase about who can read and write data.

  6. There's no back end. You don't need to make a server with Node and Express. Running your own server can be a lot of work, require knowing about security, require that someone do something if the server goes down, etc.

  7. Fast. If your server is in San Francisco and the client is in San Jose, fine. But for a client in Bangalore connecting to your server will be slower. Firebase is deployed around the world for fast connections everywhere.

mkdir's "-p" option

-p|--parent will be used if you are trying to create a directory with top-down approach. That will create the parent directory then child and so on iff none exists.

-p, --parents no error if existing, make parent directories as needed

About rlidwka it means giving full or administrative access. Found it here https://itservices.stanford.edu/service/afs/intro/permissions/unix.

How to put comments in Django templates

As answer by Miles, {% comment %}...{% endcomment %} is used for multi-line comments, but you can also comment out text on the same line like this:

{# some text #}

Extract number from string with Oracle function

If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

What are the advantages of NumPy over regular Python lists?

All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:

  1. Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.

  2. The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory

  3. Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences

How to get the title of HTML page with JavaScript?

Put in the URL bar and then click enter:

javascript:alert(document.title);

You can select and copy the text from the alert depending on the website and the web browser you are using.

How can I convert radians to degrees with Python?

-fix- because you want to change from radians to degrees, it is actually rad=deg * math.pi /180 and not deg*180/math.pi

import math
x=1                # in deg
x = x*math.pi/180  # convert to rad
y = math.cos(x)    # calculate in rad

print y

in 1 line it can be like this

y=math.cos(1*math.pi/180)

How do I divide so I get a decimal value?

I mean it's quite simple. Set it as a double. So lets say

double answer = 3.0/2.0;
System.out.print(answer);

No Multiline Lambda in Python: Why not?

because a lambda function is supposed to be one-lined, as its the simplest form of a function, an entrance, then return

How to get text box value in JavaScript

+1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.

i am getting only "software".

id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:

<input type="text" name="txtJob" value=software engineer>

dll missing in JDBC

For easy fix follow these steps:

  1. goto: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
  2. Download the JDBC file and extract to your preferred location
  3. open the auth folder matching your OS x64 or x86
  4. copy sqljdbc_auth.dll file
  5. paste in: C:\Program Files\Java\jdk_version\bin

restart either eclipse or netbeans

How can I go back/route-back on vue-router?

Use router.back() directly to go back/route-back programmatic on vue-router.

How to list files and folder in a dir (PHP)

Have a look at building a simple directory browser using php RecursiveDirectoryIterator

Also, as you mentioned you want to list you can also look at some ready made libraries that create file/folder explorers e.g.:

Prevent div from moving while resizing the page

hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body> in a fixed width <div style="margin: 0 auto; width: 900px> to achieve what you have done with the body {margin: 0 10% 0 10%}

Choosing the best concurrency list in Java

had better be List

The only List implementation in java.util.concurrent is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.

That said, are you sure you need it to be a List? There are a lot more options for concurrent Queues and Maps (and you can make Sets from Maps), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.

For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:

How to run a SQL query on an Excel table?

I suggest you to have a look at the MySQL csv storage engine which essentially allows you to load any csv file (easily created from excel) into the database, once you have that, you can use any SQL command you want.

It's worth to have a look at it.

Object passed as parameter to another class, by value or reference?

"Objects" are NEVER passed in C# -- "objects" are not values in the language. The only types in the language are primitive types, struct types, etc. and reference types. No "object types".

The types Object, MyClass, etc. are reference types. Their values are "references" -- pointers to objects. Objects can only be manipulated through references -- when you do new on them, you get a reference, the . operator operates on a reference; etc. There is no way to get a variable whose value "is" an object, because there are no object types.

All types, including reference types, can be passed by value or by reference. A parameter is passed by reference if it has a keyword like ref or out. The SetObject method's obj parameter (which is of a reference type) does not have such a keyword, so it is passed by value -- the reference is passed by value.

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

What about using App-V? http://www.microsoft.com/systemcenter/appv/default.mspx

In particular Dynamic Application Virtualization http://www.microsoft.com/systemcenter/appv/dynamic.mspx

It virtualizes at the application level. It is useful when running incompatible software on the same OS instance.

Java, return if trimmed String in List contains String

You need to iterate your list and call String#trim for searching:

String search = "A";
for(String str: myList) {
    if(str.trim().contains(search))
       return true;
}
return false;

OR if you want to perform ignore case search, then use:

search = search.toLowerCase(); // outside loop

// inside the loop
if(str.trim().toLowerCase().contains(search))

What to gitignore from the .idea folder?

https://www.gitignore.io/api/jetbrains

Created by https://www.gitignore.io/api/jetbrains

### JetBrains ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml

# Gradle:
.idea/gradle.xml
.idea/libraries

# Mongo Explorer plugin:
.idea/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### JetBrains Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml 
# *.ipr 

Get a random boolean in python?

I like

 np.random.rand() > .5

How to find files recursively by file type and copy them to a directory while in ssh?

Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;

Just to sum up!

How do you use global variables or constant values in Ruby?

One of the reasons why the global variable needs a prefix (called a "sigil") is because in Ruby, unlike in C, you don't have to declare your variables before assigning to them. The sigil is used as a way to be explicit about the scope of the variable.

Without a specific prefix for globals, given a statement pointNew = offset + point inside your draw method then offset refers to a local variable inside the method (and results in a NameError in this case). The same for @ used to refer to instance variables and @@ for class variables.

In other languages that use explicit declarations such as C, Java etc. the placement of the declaration is used to control the scope.

Find out free space on tablespace

The following query will help to find out free space of tablespaces in MB:

select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

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

Best way to check if MySQL results returned in PHP?

What is more logical then testing the TYPE of the result variable before processing? It is either of type 'boolean' or 'resource'. When you use a boolean for parameter with mysqli_num_rows, a warning will be generated because the function expects a resource.

$result = mysqli_query($dbs, $sql);

if(gettype($result)=='boolean'){ // test for boolean
    if($result){  // returned TRUE, e.g. in case of a DELETE sql  
        echo "SQL succeeded"; 
    } else { // returned FALSE
        echo "Error: " . mysqli_error($dbs);
    } 
} else { // must be a resource
    if(mysqli_num_rows($result)){

       // process the data    

    }
    mysqli_free_result($result);  
 }

how to convert a string to a bool

I used the below code to convert a string to boolean.

Convert.ToBoolean(Convert.ToInt32(myString));

Javascript onclick hide div

If you want to close it you can either hide it or remove it from the page. To hide it you would do some javascript like:

this.parentNode.style.display = 'none';

To remove it you use removeChild

this.parentNode.parentNode.removeChild(this.parentNode);

If you had a library like jQuery included then hiding or removing the div would be slightly easier:

$(this).parent().hide();
$(this).parent().remove();

One other thing, as your img is in an anchor the onclick event on the anchor is going to fire as well. As the href is set to # then the page will scroll back to the top of the page. Generally it is good practice that if you want a link to do something other than go to its href you should set the onclick event to return false;

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

After reading the documentation of VideoCapture. I figured out that you can tell VideoCapture, which frame to process next time we call VideoCapture.read() (or VideoCapture.grab()).

The problem is that when you want to read() a frame which is not ready, the VideoCapture object stuck on that frame and never proceed. So you have to force it to start again from the previous frame.

Here is the code

import cv2

cap = cv2.VideoCapture("./out.mp4")
while not cap.isOpened():
    cap = cv2.VideoCapture("./out.mp4")
    cv2.waitKey(1000)
    print "Wait for the header"

pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
    flag, frame = cap.read()
    if flag:
        # The frame is ready and already captured
        cv2.imshow('video', frame)
        pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
        print str(pos_frame)+" frames"
    else:
        # The next frame is not ready, so we try to read it again
        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
        print "frame is not ready"
        # It is better to wait for a while for the next frame to be ready
        cv2.waitKey(1000)

    if cv2.waitKey(10) == 27:
        break
    if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
        # If the number of captured frames is equal to the total number of frames,
        # we stop
        break

How to generate .angular-cli.json file in Angular Cli?

If you copy paste your project the .angular-cli.json you wil not find this file try to create a new file with the same name and add the code and it wil work.

Is it possible to use Java 8 for Android development?

Native Java 8 arrives on android! Finally!

remove the Retrolambda plugin and retrolambda block from each module's build.gradle file:

To disable Jack and switch to the default toolchain, simply remove the jackOptions block from your module’s build.gradle file

To start using supported Java 8 language features, update the Android plugin to 3.0.0 (or higher)

Starting with Android Studio 3.0 , Java 8 language features are now natively supported by android:

  • Lambda expressions
  • Method references
  • Type annotations (currently type annotation information is not available at runtime but only on compile time);
  • Repeating annotations
  • Default and static interface methods (on API level 24 or higher, no instant run support tho);

Also from min API level 24 the following Java 8 API are available:

  • java.util.stream
  • java.util.function
  • java.lang.FunctionalInterface
  • java.lang.annotation.Repeatable
  • java.lang.reflect.AnnotatedElement.getAnnotationsByType(Class)
  • java.lang.reflect.Method.isDefault()

Add these lines to your application module’s build.gradle to inform the project of the language level:

 android {
   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
   }

Disable Support for Java 8 Language Features by adding the following to your gradle.properties file:

android.enableDesugar=false

You’re done! You can now use native java8!

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

This will maybe give you a hint on what went wrong.

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BigDecimal bdTest = new BigDecimal(0.745);
        BigDecimal bdTest1 = new BigDecimal("0.745");
        bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
        bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("bdTest:" + bdTest); // prints "bdTest:0.74"
        System.out.println("bdTest1:" + bdTest1); // prints "bdTest:0.75"
    }
}

The problem is, that your input (a double x=0.745;) can not represent 0.745 exactly. It actually saves a value slightly lower. For BigDecimals, this is already below 0.745, so it rounds down...

Try not to use the BigDecimal(double/float) constructors.

Best Practice: Software Versioning

As Mahesh says: I would use x.y.z kind of versioning

x - major release y - minor release z - build number

you may want to add a datetime, maybe instead of z.

You increment the minor release when you have another release. The major release will probably stay 0 or 1, you change that when you really make major changes (often when your software is at a point where its not backwards compatible with previous releases, or you changed your entire framework)

Getting execute permission to xp_cmdshell

Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):

use YourDatabase
go
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
go
alter role [db_datareader] add member [YourDomain\YourUser]
go

Checking if my Windows application is running

The recommended way is to use a Mutex. You can check out a sample here : http://www.codeproject.com/KB/cs/singleinstance.aspx

In specific the code:


        /// 
        /// check if given exe alread running or not
        /// 
        /// returns true if already running
        private static bool IsAlreadyRunning()
        {
            string strLoc = Assembly.GetExecutingAssembly().Location;
            FileSystemInfo fileInfo = new FileInfo(strLoc);
            string sExeName = fileInfo.Name;
            bool bCreatedNew;

            Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
            if (bCreatedNew)
                mutex.ReleaseMutex();

            return !bCreatedNew;
        }

pyplot scatter plot marker size

If the size of the circles corresponds to the square of the parameter in s=parameter, then assign a square root to each element you append to your size array, like this: s=[1, 1.414, 1.73, 2.0, 2.24] such that when it takes these values and returns them, their relative size increase will be the square root of the squared progression, which returns a linear progression.

If I were to square each one as it gets output to the plot: output=[1, 2, 3, 4, 5]. Try list interpretation: s=[numpy.sqrt(i) for i in s]

Python Matplotlib figure title overlaps axes label when using twiny

Forget using plt.title and place the text directly with plt.text. An over-exaggerated example is given below:

import pylab as plt

fig = plt.figure(figsize=(5,10))

figure_title = "Normal title"
ax1  = plt.subplot(1,2,1)

plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])

figure_title = "Raised title"
ax2  = plt.subplot(1,2,2)

plt.text(0.5, 1.08, figure_title,
         horizontalalignment='center',
         fontsize=20,
         transform = ax2.transAxes)
plt.plot([1,2,3],[1,4,9])

plt.show()

enter image description here

How to loop over files in directory and change path and add suffix to filename

for file in Data/*.txt
do
    for ((i = 0; i < 3; i++))
    do
        name=${file##*/}
        base=${name%.txt}
        ./MyProgram.exe "$file" Logs/"${base}_Log$i.txt"
    done
done

The name=${file##*/} substitution (shell parameter expansion) removes the leading pathname up to the last /.

The base=${name%.txt} substitution removes the trailing .txt. It's a bit trickier if the extensions can vary.

Changing cursor to waiting in javascript/jquery

The following is my preferred way, and will change the cursor everytime a page is about to change i.e. beforeunload

$(window).on('beforeunload', function(){
   $('*').css("cursor", "progress");
});

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

How to return only the Date from a SQL Server DateTime datatype

SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 101))

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

When do items in HTML5 local storage expire?

If someone using jStorage Plugin of jQuery the it can be add expiry with setTTL function if jStorage plugin

$.jStorage.set('myLocalVar', "some value");
$.jStorage.setTTL("myLocalVar", 24*60*60*1000); // 24 Hr.

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How to check certificate name and alias in keystore files?

In a bash-like environment you can use:

keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo

This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep.

how to set the background image fit to browser using html

You can achieved what you want by creating a .css file and link to your <head> tag just after the </title> (closing title tag).

Hi-Resolution image will be good to use, around 2112x1584 pixels but consider the file size because it will matter for the page load time.

On the opening of your <body> tag, just delete the background property as it will be declared through the .css file.

When your image is ready, put this code to your .css file

body {
background-image: url(imagePAth/Indian_wallpapers_205.jpg); /*You will specify your image path here.*/

-moz-background-size: cover;
-webkit-background-size: cover;
background-size: cover;
background-position: top center !important;
background-repeat: no-repeat !important;
background-attachment: fixed;
}

When your .css file is done, you can link it to the <head> tag. It will look something like this: <link rel="stylesheet" type="text/css" href="yourCSSpath/yourCSSname.css" />

That's how i make a background image to fit the browser screen.

Failed to load AppCompat ActionBar with unknown error in android studio

Use this one:

implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
implementation 'com.android.support:design:26.0.0-beta1'

instead of

implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
implementation 'com.android.support:design:26.0.0-beta2'

In my case it removed the rendering problem.

maven compilation failure

It COULD be due to insufficient heap memory.

It sounds strange, but try it, it might just work:

export MAVEN_OPTS='-Xms384M -Xmx512M -XX:MaxPermSize=256M'

Source: https://groups.google.com/group/neo4j/msg/e208be9ee1c101d7)

Convert HTML to PDF in .NET

Here is a wrapper for wkhtmltopdf.dll by pruiz

And a wrapper for wkhtmltopdf.exe by Codaxy
- also on nuget.

C# Public Enums in Classes

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

XDocument or XmlDocument

Also, note that XDocument is supported in Xbox 360 and Windows Phone OS 7.0. If you target them, develop for XDocument or migrate from XmlDocument.

How to change the author and committer name and e-mail of multiple commits in Git?

For a single commit:

git commit --amend --author="Author Name <[email protected]>"

(extracted from asmeurer's answer)

assembly to compare two numbers

input password program
.modle small
.stack 100h
.data
s pasword db 34
input pasword db "enter pasword","$"
valid db ?
invalid db?
.code
mov ax, @ data 
mov db, ax
mov ah,09h
mov dx, offest s pasword
int 21h
mov ah, 01h
cmp al, s pasword
je v
jmp nv
v:
mov ah, 09h
mov dx, offset valid 
int 21h
nv:
mov ah, 09h
mov dx, offset invalid 
int 21h
mov ah, 04ch 
int 21
end 

array filter in python?

No, there is no build in function in python to do this, because simply:

set(A)- set(subset_of_A)

will provide you the answer.

Send email with PHP from html form on submit with the same script

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

Html.EditorFor Set Default Value

Here's what I've found:

@Html.TextBoxFor(c => c.Propertyname, new { @Value = "5" })

works with a capital V, not a lower case v (the assumption being value is a keyword used in setters typically) Lower vs upper value

@Html.EditorFor(c => c.Propertyname, new { @Value = "5" })

does not work

Your code ends up looking like this though

<input Value="5" id="Propertyname" name="Propertyname" type="text" value="" />

Value vs. value. Not sure I'd be too fond of that.

Why not just check in the controller action if the proprety has a value or not and if it doesn't just set it there in your view model to your defaulted value and let it bind so as to avoid all this monkey work in the view?

Node.js version on the command line? (not the REPL)

One cool tip if you are using the Atom editor.

$ apm -v
apm  1.12.5
npm  3.10.5
node 4.4.5
python 2.7.12
git 2.7.4

It will return you not only the node version but also few other things.

Header set Access-Control-Allow-Origin in .htaccess doesn't work

This should work:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

What is the color code for transparency in CSS?

jus add two zeroes (00) before your color code you will get the transparent of that color

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

AppFabric installation failed because installer MSI returned with error code : 1603

I had the same problem today. I've found this link, where you can try 3 solutions. First solution helped for me.

Microsoft ANSWER for this issue

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

@laryx-decidua: I think you are only seeing the 18.x instant client releases that are in the ol7_oci_included repo. The 19.x instant client RPMs, at the moment, are only in the ol7_oracle_instantclient repo. Easiest way to access that repo is:

yum install oracle-release-el7

How to check Oracle patches are installed?

I understand the original post is for Oracle 10 but this is for reference by anyone else who finds it via Google.

Under Oracle 12c, I found that that my registry$history is empty. This works instead:

select * from registry$sqlpatch;

How can I echo a newline in a batch file?

If anybody comes here because they are looking to echo a blank line from a MINGW make makefile, I used

@cmd /c echo.

simply using echo. causes the dreaded process_begin: CreateProcess(NULL, echo., ...) failed. error message.

I hope this helps at least one other person out there :)

How to Find App Pool Recycles in Event Log

It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)

Format output string, right alignment

To do it by using f-string and with control of the number of trailing digits:

print(f'A number -> {my_number:>20.5f}')

__init__ and arguments in Python

The fact that your method does not use the self argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Linux command: How to 'find' only text files?

Although it is an old question, I think this info bellow will add to the quality of the answers here.

When ignoring files with the executable bit set, I just use this command:

find . ! -perm -111

To keep it from recursively enter into other directories:

find . -maxdepth 1 ! -perm -111

No need for pipes to mix lots of commands, just the powerful plain find command.

  • Disclaimer: it is not exactly what OP asked, because it doesn't check if the file is binary or not. It will, for example, filter out bash script files, that are text themselves but have the executable bit set.

That said, I hope this is useful to anyone.

Get the current time in C

LONG VERSION

src: https://en.wikipedia.org/wiki/C_date_and_time_functions

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

int main(void)
{
    time_t current_time;
    char* c_time_string;

    /* Obtain current time. */
    current_time = time(NULL);

    if (current_time == ((time_t)-1))
    {
        (void) fprintf(stderr, "Failure to obtain the current time.\n");
        exit(EXIT_FAILURE);
    }

    /* Convert to local time format. */
    c_time_string = ctime(&current_time);

    if (c_time_string == NULL)
    {
        (void) fprintf(stderr, "Failure to convert the current time.\n");
        exit(EXIT_FAILURE);
    }

    /* Print to stdout. ctime() has already added a terminating newline character. */
    (void) printf("Current time is %s", c_time_string);
    exit(EXIT_SUCCESS);
}

The output is:

Current time is Thu Sep 15 21:18:23 2016

SHORT VERSION:

#include <stdio.h>
#include <time.h>

int main(int argc, char *argv[]) {
    time_t current_time;
    time(&current_time);
    printf("%s", ctime(&current_time));

The output is:

Current time is Thu Jan 28 15:22:31 2021

Install numpy on python3.3 - Install pip for python3

I'm on Ubuntu 15.04. This seemed to work:

$ sudo pip3 install numpy

On RHEL this worked:

$ sudo python3 -m pip install numpy

Observable Finally on Subscribe

The current "pipable" variant of this operator is called finalize() (since RxJS 6). The older and now deprecated "patch" operator was called finally() (until RxJS 5.5).

I think finalize() operator is actually correct. You say:

do that logic only when I subscribe, and after the stream has ended

which is not a problem I think. You can have a single source and use finalize() before subscribing to it if you want. This way you're not required to always use finalize():

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

This prints to console:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

Jan 2019: Updated for RxJS 6

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

os.walk without digging into directories below

If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.

ie:

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        dirs[:] = [d for d in dirs if is_good(d)]
        for f in files:
            do_stuff()

Note - be careful to mutate the list, rather than just rebind it. Obviously os.walk doesn't know about the external rebinding.

Setting up an MS-Access DB for multi-user access

Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:

  1. No Locks
  2. All Records
  3. Edited Record

You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.

Transactions shouldn't be a problem if you use them correctly.

Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.

See other answers for Oracle comparison.

How to configure SMTP settings in web.config

Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:

  1. Open IIS Manager
  2. Connect to your server if needed
  3. Select the server node; you should see an SMTP option on the right in the ASP.NET section
  4. Double-click the SMTP icon.
  5. Select the "Deliver e-mail to SMTP server" option and enter your server name, credentials, etc.

No grammar constraints (DTD or XML schema) detected for the document

I can't really say why you get the "No grammar constraints..." warning, but I can provoke it in Eclipse by completely removing the DOCTYPE declaration. When I put the declaration back and validate again, I get this error message:

The content of element type "template" must match "(description+,variation?,variation-field?,allow-multiple-variation?,class-pattern?,getter-setter?,allowed-file-extensions?,template-body+).

And that is correct, I believe (the "number-required-classes" element is not allowed).

Is it possible to get multiple values from a subquery?

you can use cross apply:

select
    a.x,
    bb.y,
    bb.z
from
    a
    cross apply
    (   select b.y, b.z
        from b
        where b.v = a.v
    ) bb

If there will be no row from b to mach row from a then cross apply wont return row. If you need such a rows then use outer apply

If you need to find only one specific row for each of row from a, try:

    cross apply
    (   select top 1 b.y, b.z
        from b
        where b.v = a.v
        order by b.order
    ) bb

Maven project.build.directory

Aside from @Verhás István answer (which I like), I was expecting a one-liner for the question:

${project.reporting.outputDirectory} resolves to target/site in your project.

How do I restrict a float value to only two places after the decimal point in C?

Always use the printf family of functions for this. Even if you want to get the value as a float, you're best off using snprintf to get the rounded value as a string and then parsing it back with atof:

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

double dround(double val, int dp) {
    int charsNeeded = 1 + snprintf(NULL, 0, "%.*f", dp, val);
    char *buffer = malloc(charsNeeded);
    snprintf(buffer, charsNeeded, "%.*f", dp, val);
    double result = atof(buffer);
    free(buffer);
    return result;
}

I say this because the approach shown by the currently top-voted answer and several others here - multiplying by 100, rounding to the nearest integer, and then dividing by 100 again - is flawed in two ways:

  • For some values, it will round in the wrong direction because the multiplication by 100 changes the decimal digit determining the rounding direction from a 4 to a 5 or vice versa, due to the imprecision of floating point numbers
  • For some values, multiplying and then dividing by 100 doesn't round-trip, meaning that even if no rounding takes place the end result will be wrong

To illustrate the first kind of error - the rounding direction sometimes being wrong - try running this program:

int main(void) {
    // This number is EXACTLY representable as a double
    double x = 0.01499999999999999944488848768742172978818416595458984375;

    printf("x: %.50f\n", x);

    double res1 = dround(x, 2);
    double res2 = round(100 * x) / 100;

    printf("Rounded with snprintf: %.50f\n", res1);
    printf("Rounded with round, then divided: %.50f\n", res2);
}

You'll see this output:

x: 0.01499999999999999944488848768742172978818416595459
Rounded with snprintf: 0.01000000000000000020816681711721685132943093776703
Rounded with round, then divided: 0.02000000000000000041633363423443370265886187553406

Note that the value we started with was less than 0.015, and so the mathematically correct answer when rounding it to 2 decimal places is 0.01. Of course, 0.01 is not exactly representable as a double, but we expect our result to be the double nearest to 0.01. Using snprintf gives us that result, but using round(100 * x) / 100 gives us 0.02, which is wrong. Why? Because 100 * x gives us exactly 1.5 as the result. Multiplying by 100 thus changes the correct direction to round in.

To illustrate the second kind of error - the result sometimes being wrong due to * 100 and / 100 not truly being inverses of each other - we can do a similar exercise with a very big number:

int main(void) {
    double x = 8631192423766613.0;

    printf("x: %.1f\n", x);

    double res1 = dround(x, 2);
    double res2 = round(100 * x) / 100;

    printf("Rounded with snprintf: %.1f\n", res1);
    printf("Rounded with round, then divided: %.1f\n", res2);
}

Our number now doesn't even have a fractional part; it's an integer value, just stored with type double. So the result after rounding it should be the same number we started with, right?

If you run the program above, you'll see:

x: 8631192423766613.0
Rounded with snprintf: 8631192423766613.0
Rounded with round, then divided: 8631192423766612.0

Oops. Our snprintf method returns the right result again, but the multiply-then-round-then-divide approach fails. That's because the mathematically correct value of 8631192423766613.0 * 100, 863119242376661300.0, is not exactly representable as a double; the closest value is 863119242376661248.0. When you divide that back by 100, you get 8631192423766612.0 - a different number to the one you started with.

Hopefully that's a sufficient demonstration that using roundf for rounding to a number of decimal places is broken, and that you should use snprintf instead. If that feels like a horrible hack to you, perhaps you'll be reassured by the knowledge that it's basically what CPython does.

How to show/hide JPanels in a JFrame?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Style1.java
 *
 * Created on May 5, 2011, 6:31:16 AM
 */
package Test;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Sameera
 */
public class Style2 extends javax.swing.JFrame {

    /** Creates new form Style1 */
    public Style2() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        cmd_SH = new javax.swing.JButton();
        pnl_2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        cmd_SH.setText("Hide");
        cmd_SH.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmd_SHActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(558, Short.MAX_VALUE)
                .addComponent(cmd_SH)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(236, Short.MAX_VALUE)
                .addComponent(cmd_SH)
                .addContainerGap())
        );

        pnl_2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout pnl_2Layout = new javax.swing.GroupLayout(pnl_2);
        pnl_2.setLayout(pnl_2Layout);
        pnl_2Layout.setHorizontalGroup(
            pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 621, Short.MAX_VALUE)
        );
        pnl_2Layout.setVerticalGroup(
            pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 270, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnl_2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pnl_2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void cmd_SHActionPerformed(java.awt.event.ActionEvent evt) {                                       


        System.out.println(evt.getActionCommand());
        if (evt.getActionCommand().equals("Hide")) {
            pnl_2.setVisible(false);
            cmd_SH.setText("Show");
            this.setSize(643, 294);
            this.pack();


        }
        if (evt.getActionCommand().equals("Show")) {
            pnl_2.setVisible(true);
            cmd_SH.setText("Hide");
            this.setSize(643, 583);
            this.pack();    
        }
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Style1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton cmd_SH;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel pnl_2;
    // End of variables declaration
}

How to send a JSON object over Request with Android?

public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
    JSONArray array;
    @Override
    protected JSONArray doInBackground(Void... params) {

        try {
            commonurl cu = new commonurl();
            String u = cu.geturl("tempshowusermain.php");
            URL url =new URL(u);
          //  URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("lid",lid);


            DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.write(jsonObject.toString().getBytes("UTF-8"));

            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                StringBuffer stringBuffer = new StringBuffer();
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                object =  new JSONObject(stringBuffer.toString());
             //   array = new JSONArray(stringBuffer.toString());
                array = object.getJSONArray("response");

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return array;


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();



    }

    @Override
    protected void onPostExecute(JSONArray array) {
        super.onPostExecute(array);
        try {
            for (int x = 0; x < array.length(); x++) {

                object = array.getJSONObject(x);
                ComonUserView commUserView=new ComonUserView();//  commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
                //pidArray.add(jsonObject2.getString("pid").toString());

                commUserView.setLid(object.get("lid").toString());
                commUserView.setUname(object.get("uname").toString());
                commUserView.setAboutme(object.get("aboutme").toString());
                commUserView.setHeight(object.get("height").toString());
                commUserView.setAge(object.get("age").toString());
                commUserView.setWeight(object.get("weight").toString());
                commUserView.setBodytype(object.get("bodytype").toString());
                commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
                commUserView.setImagepath(object.get("imagepath").toString());
                commUserView.setDistance(object.get("distance").toString());
                commUserView.setLookingfor(object.get("lookingfor").toString());
                commUserView.setStatus(object.get("status").toString());

                cm.add(commUserView);
            }
            custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
          gridusername.setAdapter(custuserprof);
            //  listusername.setAdapter(custuserprof);
            } catch (Exception e) {

                e.printStackTrace();
        }
    }

PHP: Split string into array, like explode with no delimiter

Try this:

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

The above example will output:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

How to restrict SSH users to a predefined set of commands after login?

ssh follows the rsh tradition by using the user's shell program from the password file to execute commands.

This means that we can solve this without involving ssh configuration in any way.

If you don't want the user to be able to have shell access, then simply replace that user's shell with a script. If you look in /etc/passwd you will see that there is a field which assigns a shell command interpreter to each user. The script is used as the shell both for their interactive login ssh user@host as well as for commands ssh user@host command arg ....

Here is an example. I created a user foo whose shell is a script. The script prints the message my arguments are: followed by its arguments (each on a separate line and in angle brackets) and terminates. In the log in case, there are no arguments. Here is what happens:

webserver:~# ssh foo@localhost
foo@localhost's password:
Linux webserver [ snip ]
[ snip ]
my arguments are:
Connection to localhost closed.

If the user tries to run a command, it looks like this:

webserver:~# ssh foo@localhost cat /etc/passwd
foo@localhost's password:
my arguments are:
<-c>
<cat /etc/passwd>

Our "shell" receives a -c style invocation, with the entire command as one argument, just the same way that /bin/sh would receive it.

So as you can see, what we can do now is develop the script further so that it recognizes the case when it has been invoked with a -c argument, and then parses the string (say by pattern matching). Those strings which are allowed can be passed to the real shell by recursively invoking /bin/bash -c <string>. The reject case can print an error message and terminate (including the case when -c is missing).

You have to be careful how you write this. I recommend writing only positive matches which allow only very specific things, and disallow everything else.

Note: if you are root, you can still log into this account by overriding the shell in the su command, like this su -s /bin/bash foo. (Substitute shell of choice.) Non-root cannot do this.

Here is an example script: restrict the user into only using ssh for git access to repositories under /git.

#!/bin/sh

if [ $# -ne 2 ] || [ "$1" != "-c" ] ; then
  printf "interactive login not permitted\n"
  exit 1
fi

set -- $2

if [ $# != 2 ] ; then
  printf "wrong number of arguments\n"
  exit 1
fi

case "$1" in
  ( git-upload-pack | git-receive-pack )
    ;; # continue execution
  ( * )
    printf "command not allowed\n"
    exit 1
    ;;
esac

# Canonicalize the path name: we don't want escape out of
# git via ../ path components.

gitpath=$(readlink -f "$2")  # GNU Coreutils specific

case "$gitpath" in
  ( /git/* )
     ;; # continue execution
  ( * )
    printf "access denied outside of /git\n"
    exit 1
    ;;
esac

if ! [ -e "$gitpath" ] ; then
   printf "that git repo doesn't exist\n"
   exit 1
fi

"$1" "$gitpath"

Of course, we are trusting that these Git programs git-upload-pack and git-receive-pack don't have holes or escape hatches that will give users access to the system.

That is inherent in this kind of restriction scheme. The user is authenticated to execute code in a certain security domain, and we are kludging in a restriction to limit that domain to a subdomain. For instance if you allow a user to run the vim command on a specific file to edit it, the user can just get a shell with :!sh[Enter].

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

Difference between "this" and"super" keywords in Java

From your question, I take it that you are really asking about the use of this and super in constructor chaining; e.g.

public class A extends B {
    public A(...) {
        this(...);
        ...
    }
}

versus

public class A extends B {
    public A(...) {
        super(...);
        ...
    }
}

The difference is simple:

  • The this form chains to a constructor in the current class; i.e. in the A class.

  • The super form chains to a constructor in the immediate superclass; i.e. in the B class.

How to reset sequence in postgres and fill id column with new data?

Inspired by the other answers here, I created an SQL function to do a sequence migration. The function moves a primary key sequence to a new contiguous sequence starting with any value (>= 1) either inside or outside the existing sequence range.

I explain here how I used this function in a migration of two databases with the same schema but different values into one database.

First, the function (which prints the generated SQL commands so that it is clear what is actually happening):

CREATE OR REPLACE FUNCTION migrate_pkey_sequence
  ( arg_table      text
  , arg_column     text
  , arg_sequence   text
  , arg_next_value bigint  -- Must be >= 1
  )
RETURNS int AS $$
DECLARE
  result int;
  curr_value bigint = arg_next_value - 1;
  update_column1 text := format
    ( 'UPDATE %I SET %I = nextval(%L) + %s'
    , arg_table
    , arg_column
    , arg_sequence
    , curr_value
    );
  alter_sequence text := format
    ( 'ALTER SEQUENCE %I RESTART WITH %s'
    , arg_sequence
    , arg_next_value
    );
  update_column2 text := format
    ( 'UPDATE %I SET %I = DEFAULT'
    , arg_table
    , arg_column
    );
  select_max_column text := format
    ( 'SELECT coalesce(max(%I), %s) + 1 AS nextval FROM %I'
    , arg_column
    , curr_value
    , arg_table
    );
BEGIN
  -- Print the SQL command before executing it.
  RAISE INFO '%', update_column1;
  EXECUTE update_column1;
  RAISE INFO '%', alter_sequence;
  EXECUTE alter_sequence;
  RAISE INFO '%', update_column2;
  EXECUTE update_column2;
  EXECUTE select_max_column INTO result;
  RETURN result;
END $$ LANGUAGE plpgsql;

The function migrate_pkey_sequence takes the following arguments:

  1. arg_table: table name (e.g. 'example')
  2. arg_column: primary key column name (e.g. 'id')
  3. arg_sequence: sequence name (e.g. 'example_id_seq')
  4. arg_next_value: next value for the column after migration

It performs the following operations:

  1. Move the primary key values to a free range. I assume that nextval('example_id_seq') follows max(id) and that the sequence starts with 1. This also handles the case where arg_next_value > max(id).
  2. Move the primary key values to the contiguous range starting with arg_next_value. The order of key values are preserved but holes in the range are not preserved.
  3. Print the next value that would follow in the sequence. This is useful if you want to migrate the columns of another table and merge with this one.

To demonstrate, we use a sequence and table defined as follows (e.g. using psql):

# CREATE SEQUENCE example_id_seq
  START WITH 1
  INCREMENT BY 1
  NO MINVALUE
  NO MAXVALUE
  CACHE 1;
# CREATE TABLE example
  ( id bigint NOT NULL DEFAULT nextval('example_id_seq'::regclass)
  );

Then, we insert some values (starting, for example, at 3):

# ALTER SEQUENCE example_id_seq RESTART WITH 3;
# INSERT INTO example VALUES (DEFAULT), (DEFAULT), (DEFAULT);
-- id: 3, 4, 5

Finally, we migrate the example.id values to start with 1.

# SELECT migrate_pkey_sequence('example', 'id', 'example_id_seq', 1);
INFO:  00000: UPDATE example SET id = nextval('example_id_seq') + 0
INFO:  00000: ALTER SEQUENCE example_id_seq RESTART WITH 1
INFO:  00000: UPDATE example SET id = DEFAULT
 migrate_pkey_sequence
-----------------------
                     4
(1 row)

The result:

# SELECT * FROM example;
 id
----
  1
  2
  3
(3 rows)

Understanding ASP.NET Eval() and Bind()

For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind.

Imagine for example a GridView with a ItemTemplate and EditItemTemplate. If you use Bind or Eval in the ItemTemplate, there will be no difference. If you use Eval in the EditItemTemplate, the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.


UPDATE: I've come up with this example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Data binding demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView 
            ID="grdTest" 
            runat="server" 
            AutoGenerateEditButton="true" 
            AutoGenerateColumns="false" 
            DataSourceID="mySource">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox 
                            ID="edtName" 
                            runat="server" 
                            Text='<%# Bind("Name") %>' 
                        />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

    <asp:ObjectDataSource 
        ID="mySource" 
        runat="server"
        SelectMethod="Select" 
        UpdateMethod="Update" 
        TypeName="MyCompany.CustomDataSource" />
</body>
</html>

And here's the definition of a custom class that serves as object data source:

public class CustomDataSource
{
    public class Model
    {
        public string Name { get; set; }
    }

    public IEnumerable<Model> Select()
    {
        return new[] 
        {
            new Model { Name = "some value" }
        };
    }

    public void Update(string Name)
    {
        // This method will be called if you used Bind for the TextBox
        // and you will be able to get the new name and update the
        // data source accordingly
    }

    public void Update()
    {
        // This method will be called if you used Eval for the TextBox
        // and you will not be able to get the new name that the user
        // entered
    }
}

How to automatically reload a page after a given period of inactivity

Using LocalStorage to keep track of the last time of activity, we can write the reload function as follows

function reloadPage(expiryDurationMins) {
    const lastInteraction = window.localStorage.getItem('lastinteraction')
    if (!lastInteraction) return // no interaction recorded since page load
    const inactiveDurationMins = (Date.now() - Number(lastInteraction)) / 60000
    const pageExpired = inactiveDurationMins >= expiryDurationMins
    if (pageExpired) window.location.reload()
}

Then we create an arrow function which saves the last time of interaction in milliseconds(String)

const saveLastInteraction = () => window.localStorage.setItem('last', Date.now().toString())

We will need to listen to the beforeunload event in the browser to clear our lastinteraction record so we don't get stuck in an infinite reload loop.

window.addEventListener('beforeunload', () => window.localStorage.removeItem('lastinteraction'))

The user activity events we will need to monitor would be mousemove and keypress. We store the last interaction time when the user moves the mouse or presses a key on the keyboard

window.addEventListener('mousemove', saveLastInteraction)
window.addEventListener('keypress', saveLastInteraction)

To set up our final listener, we will use the load event. On page load, we use the setInterval function to check if the page has expired after a certain period.

const expiryDurationMins = 1

window.addEventListener('load', setInterval.bind(null, reloadPage.bind(null, expiryDurationMins), 1000))

Google Maps: Auto close open InfoWindows?

Declare a variable for active window

var activeInfoWindow; 

and bind this code in marker listener

 marker.addListener('click', function () {
    if (activeInfoWindow) { activeInfoWindow.close();}
    infowindow.open(map, marker);
    activeInfoWindow = infowindow;
});

How to create multidimensional array

Create uninitialized multidimensional array:

function MultiArray(a) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]);
  return [...Array(a[0])].map(() => MultiArray(a.slice(1)));
}

Create initialized multidimensional array:

function MultiArrayInit(a, init) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]).fill(init);
  return [...Array(a[0])].map(() => MultiArrayInit(a.slice(1), init));
}

Usage:

MultiArray([3,4,5]);  // -> Creates an array of [3][4][5] of empty cells

MultiArrayInit([3,4,5], 1);  // -> Creates an array of [3][4][5] of 1s

One line if-condition-assignment

You can definitely use num1 = (20 if someBoolValue else num1) if you want.

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Java: How to convert String[] to List or Set

Collections.addAll provides the shortest (one-line) receipt

Having

String[] array = {"foo", "bar", "baz"}; 
Set<String> set = new HashSet<>();

You can do as below

Collections.addAll(set, array); 

PHP's array_map including keys

$array = [
  'category1' => 'first category',
  'category2' => 'second category',
];
 
$new = array_map(function($key, $value) {
  return "{$key} => {$value}";
}, array_keys($array), $array);

How can I get a random number in Kotlin?

Below in Kotlin worked well for me:

(fromNumber.rangeTo(toNumber)).random()

Range of the numbers starts with variable fromNumber and ends with variable toNumber. fromNumber and toNumber will also be included in the random numbers generated out of this.

How to highlight a selected row in ngRepeat?

I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.

<ul ng-repeat="vote in votes" ...>
    <li data-choice="selected" data-value="vote.id">...</li>
</ul>

Solution: http://jsfiddle.net/brandonmilleraz/5fr9V/

How to delete last character from a string using jQuery?

@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

//-----------------------------------------
// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

Getting the SQL from a Django QuerySet

You print the queryset's query attribute.

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"

How to control the width and height of the default Alert Dialog in Android?

This works as well by adding .getWindow().setLayout(width, height) after show()

alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
              })
            .setNegativeButton("No",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            }).show().getWindow().setLayout(600,500);

Check if a given key already exists in a dictionary

For additional info on speed execution of the accepted answer's proposed methods (10m loops):

  • 'key' in mydict elapsed time 1.07 sec
  • mydict.get('key') elapsed time 1.84 sec
  • mydefaultdict['key'] elapsed time 1.07 sec

Therefore using in or defaultdict are recommended against get.

Struct Constructor in C++?

Yes it possible to have constructor in structure here is one example:

#include<iostream.h> 
struct a {
  int x;
  a(){x=100;}
};

int main() {
  struct a a1;
  getch();
}

How to get numbers after decimal point?

You can use this:

number = 5.55
int(str(number).split('.')[1])

How to call a RESTful web service from Android?

This is an sample restclient class

public class RestClient
{
    public enum RequestMethod
    {
        GET,
        POST
    }
    public int responseCode=0;
    public String message;
    public String response;
    public void Execute(RequestMethod method,String url,ArrayList<NameValuePair> headers,ArrayList<NameValuePair> params) throws Exception
    {
        switch (method)
        {
            case GET:
            {
                // add parameters
                String combinedParams = "";
                if (params!=null)
                {
                    combinedParams += "?";
                    for (NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if (combinedParams.length() > 1)
                            combinedParams += "&" + paramString;
                        else
                            combinedParams += paramString;
                    }
                }
                HttpGet request = new HttpGet(url + combinedParams);
                // add headers
                if (headers!=null)
                {
                    headers=addCommonHeaderField(headers);
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }
                executeRequest(request, url);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);
                // add headers
                if (headers!=null)
                {
                    headers=addCommonHeaderField(headers);
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }
                if (params!=null)
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                executeRequest(request, url);
                break;
            }
        }
    }
    private ArrayList<NameValuePair> addCommonHeaderField(ArrayList<NameValuePair> _header)
    {
        _header.add(new BasicNameValuePair("Content-Type","application/x-www-form-urlencoded"));
        return _header;
    }
    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse;
        try
        {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();
            HttpEntity entity = httpResponse.getEntity();

            if (entity != null)
            {
                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
                instream.close();
            }
        }
        catch (Exception e)
        { }
    }

    private static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
        }
        catch (IOException e)
        { }
        return sb.toString();
    }
}

Why Does OAuth v2 Have Both Access and Refresh Tokens?

The link to discussion, provided by Catchdave, has another valid point (original, dead link) made by Dick Hardt, which I believe is worth to be mentioned here in addition to what's been written above:

My recollection of refresh tokens was for security and revocation. <...>

revocation: if the access token is self contained, authorization can be revoked by not issuing new access tokens. A resource does not need to query the authorization server to see if the access token is valid.This simplifies access token validation and makes it easier to scale and support multiple authorization servers. There is a window of time when an access token is valid, but authorization is revoked.

Indeed, in the situation where Resource Server and Authorization Server is the same entity, and where the connection between user and either of them is (usually) equally secure, there is not much sense to keep refresh token separate from the access token.

Although, as mentioned in the quote, another role of refresh tokens is to ensure the access token can be revoked at any time by the User (via the web-interface in their profiles, for example) while keeping the system scalable at the same time.

Generally, tokens can either be random identifiers pointing to the specific record in the Server's database, or they can contain all information in themselves (certainly, this information have to be signed, with MAC, for example).

How the system with long-lived access tokens should work

The server allows the Client to get access to User's data within a pre-defined set of scopes by issuing a token. As we want to keep the token revocable, we must store in the database the token along with the flag "revoked" being set or unset (otherwise, how would you do that with self-contained token?) Database can contain as much as len(users) x len(registered clients) x len(scopes combination) records. Every API request then must hit the database. Although it's quite trivial to make queries to such database performing O(1), the single point of failure itself can have negative impact on the scalability and performance of the system.

How the system with long-lived refresh token and short-lived access token should work

Here we issue two keys: random refresh token with the corresponding record in the database, and signed self-contained access token, containing among others the expiration timestamp field.

As the access token is self-contained, we don't have to hit the database at all to check its validity. All we have to do is to decode the token and to validate the signature and the timestamp.

Nonetheless, we still have to keep the database of refresh tokens, but the number of requests to this database is generally defined by the lifespan of the access token (the longer the lifespan, the lower the access rate).

In order to revoke the access of Client from a particular User, we should mark the corresponding refresh token as "revoked" (or remove it completely) and stop issuing new access tokens. It's obvious though that there is a window during which the refresh token has been revoked, but its access token may still be valid.

Tradeoffs

Refresh tokens partially eliminate the SPoF (Single Point of Failure) of Access Token database, yet they have some obvious drawbacks.

  1. The "window". A timeframe between events "user revokes the access" and "access is guaranteed to be revoked".

  2. The complication of the Client logic.

    without refresh token

    • send API request with access token
    • if access token is invalid, fail and ask user to re-authenticate

    with refresh token

    • send API request with access token
    • If access token is invalid, try to update it using refresh token
    • if refresh request passes, update the access token and re-send the initial API request
    • If refresh request fails, ask user to re-authenticate

I hope this answer does make sense and helps somebody to make more thoughtful decision. I'd like to note also that some well-known OAuth2 providers, including github and foursquare adopt protocol without refresh tokens, and seem happy with that.

jquery how to use multiple ajax calls one after the end of the other

I consider the following to be more pragmatic since it does not sequence the ajax calls but that is surely a matter of taste.

function check_ajax_call_count()
{
    if ( window.ajax_call_count==window.ajax_calls_completed )
    {
        // do whatever needs to be done after the last ajax call finished
    }
}
window.ajax_call_count = 0;
window.ajax_calls_completed = 10;
setInterval(check_ajax_call_count,100);

Now you can iterate window.ajax_call_count inside the success part of your ajax requests until it reaches the specified number of calls send (window.ajax_calls_completed).

How to add browse file button to Windows Form using C#

OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}

In this code you can put your address in a text box.

fileReader.readAsBinaryString to upload files

Use fileReader.readAsDataURL( fileObject ), this will encode it to base64, which you can safely upload to your server.

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

If you are using AWS (Amazon Web Services) Micro version, then it is a memory issue. When I ran

mysql

from the terminal it would say

ERROR 2002 (HY000): Can't connect to local MySQL server through socket /var/run/mysqld/mysqld.sock' (111)

So I tried the following and it would just fail.

service mysqld restart

After much searching, I found out that you have to create a swap file for MySQL to have enough memory. Instructions are listed: http://www.prowebdev.us/2012/05/amazon-ec2-linux-micro-swap-space.html.

Then, I was able to restart mysqld.

Android get image from gallery into ImageView

This is the easiest way to get image from gallery and crop ass well

step 1: StartActivity for result

imageUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            intent.setType("image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("scale", true);
            intent.putExtra("outputX", 256);
            intent.putExtra("outputY", 256);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 1);

            }
    });

step 2:Handle the result

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {
        return;
    }
    if (requestCode == 1) {
        final Bundle extras = data.getExtras();
        if (extras != null) {
            //Get image
            Bitmap ProfilePic = extras.getParcelable("data");
            imageUser.setImageBitmap(ProfilePic);
            TextView t=(TextView)findViewById(R.id.textoverimage);
            t.setText("image Selected");
        }
    }


}

Empty set literal?

Just to extend the accepted answer:

From version 2.7 and 3.1 python has got set literal {} in form of usage {1,2,3}, but {} itself still used for empty dict.

Python 2.7 (first line is invalid in Python <2.7)

>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>

Python 3.x

>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>

More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes

Disabling tab focus on form elements

You have to disable or enable the individual elements. This is how I did it:

$(':input').keydown(function(e){
     var allowTab = true; 
     var id = $(this).attr('name');

     // insert your form fields here -- (:'') is required after
     var inputArr = {username:'', email:'', password:'', address:''}

     // allow or disable the fields in inputArr by changing true / false
     if(id in inputArr) allowTab = false; 

     if(e.keyCode==9 && allowTab==false) e.preventDefault();
});

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.

So, you should:

  1. Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

  2. Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".

  3. Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.

So your route should like this:

// Map this rule first
RouteTable.Routes.MapRoute(
     "WithActionApi",
     "api/{controller}/{action}/{id}"
 );

RouteTable.Routes.MapRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);

And your controller:

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
    return "object of id id";
}        

[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
    return new string[] { "byCategory1", "byCategory2" };
}

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

How to mention C:\Program Files in batchfile

While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.

Do following steps:

1. Type c: then press enter

2. cd program files

3. cd "choose your own folder name"

then continue as you wish.

This way you can create batch file and you can mention program files folder.

How to remove files that are listed in the .gitignore but still on the repository?

You can remove them from the repository manually:

git rm --cached file1 file2 dir/file3

Or, if you have a lot of files:

git rm --cached `git ls-files -i --exclude-from=.gitignore`

But this doesn't seem to work in Git Bash on Windows. It produces an error message. The following works better:

git ls-files -i --exclude-from=.gitignore | xargs git rm --cached  

Regarding rewriting the whole history without these files, I highly doubt there's an automatic way to do it.
And we all know that rewriting the history is bad, don't we? :)

Ternary operator (?:) in Bash

This is much like Vladimir's fine answer. If your "ternary" is a case of "if true, string, if false, empty", then you can simply do:

$ c="it was five"
$ b=3
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a

$ b=5
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a
it was five

How to update nested state properties in React

I know it is an old question but still wanted to share how i achieved this. Assuming state in constructor looks like this:

  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      user: {
        email: ""
      },
      organization: {
        name: ""
      }
    };

    this.handleChange = this.handleChange.bind(this);
  }

My handleChange function is like this:

  handleChange(e) {
    const names = e.target.name.split(".");
    const value = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    this.setState((state) => {
      state[names[0]][names[1]] = value;
      return {[names[0]]: state[names[0]]};
    });
  }

And make sure you name inputs accordingly:

<input
   type="text"
   name="user.email"
   onChange={this.handleChange}
   value={this.state.user.firstName}
   placeholder="Email Address"
/>

<input
   type="text"
   name="organization.name"
   onChange={this.handleChange}
   value={this.state.organization.name}
   placeholder="Organization Name"
/>

What is Express.js?

1) What is Express.js?

Express.js is a Node.js framework. It's the most popular framework as of now (the most starred on NPM).

Enter image description here.

It's built around configuration and granular simplicity of Connect middleware. Some people compare Express.js to Ruby Sinatra vs. the bulky and opinionated Ruby on Rails.

2) What is the purpose of it with Node.js?

That you don't have to repeat same code over and over again. Node.js is a low-level I/O mechanism which has an HTTP module. If you just use an HTTP module, a lot of work like parsing the payload, cookies, storing sessions (in memory or in Redis), selecting the right route pattern based on regular expressions will have to be re-implemented. With Express.js, it is just there for you to use.

3) Why do we actually need Express.js? How it is useful for us to use with Node.js?

The first answer should answer your question. If no, then try to write a small REST API server in plain Node.js (that is, using only core modules) and then in Express.js. The latter will take you 5-10x less time and lines of code.

What is Redis? Does it come with Express.js?

Redis is a fast persistent key-value storage. You can optionally use it for storing sessions with Express.js, but you don't need to. By default, Express.js has memory storage for sessions. Redis also can be use for queueing jobs, for example, email jobs.

Check out my tutorial on REST API server with Express.js.

MVC but not by itself

Express.js is not an model-view-controller framework by itself. You need to bring your own object-relational mapping libraries such as Mongoose for MongoDB, Sequelize (http://sequelizejs.com) for SQL databases, Waterline (https://github.com/balderdashy/waterline) for many databases into the stack.

Alternatives

Other Node.js frameworks to consider (https://www.quora.com/Node-js/Which-Node-js-framework-is-best-for-building-a-RESTful-API):

UPDATE: I put together this resource that aid people in choosing Node.js frameworks: http://nodeframework.com

UPDATE2: We added some GitHub stats to nodeframework.com so now you can compare the level of social proof (GitHub stars) for 30+ frameworks on one page.

enter image description here

Full-stack:

Just REST API:

Ruby on Rails like:

Sinatra like:

Other:

Middleware:

Static site generators:

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

No Application Encryption Key Has Been Specified

  1. Copy .env.example to .env:

    cp -a .env.example .env

  2. Generate a key:

    php artisan key:generate

  3. Only then run:

    php artisan serve

How can I convert NSDictionary to NSData and vice versa?

In Swift 2 you can do it in this way:

var dictionary: NSDictionary = ...

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary

In Swift 3:

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

How do I serialize a C# anonymous type to a JSON string?

The fastest way I found was this:

var obj = new {Id = thing.Id, Name = thing.Name, Age = 30};
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(obj);

Namespace: System.Web.Script.Serialization.JavaScriptSerializer

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Using Thread.sleep(2000); is an unconditional wait. If your test loads faster you will still have to wait. So in principle using implicitlyWait is the better solution.

However, I don't see why implicitlyWait does not work in your case. Did you measure if the findElement actually takes two seconds before throwing an exception. If so, can you try to use WebDriver's conditional wait as described in this answer?

Detect Safari using jQuery

For checking Safari I used this:

$.browser.safari = ($.browser.webkit && !(/chrome/.test(navigator.userAgent.toLowerCase())));
if ($.browser.safari) {
    alert('this is safari');
}

It works correctly.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?

  • Check the other server's network configuration in SQL Server.
  • Check the other machines FIREWALL. SQL Server does not open ports automatically, so the windows firewall normally blocks access..

Which loop is faster, while or for?

I also tried to benchmark the different kinds of loop in C#. I used the same code as Shane, but I also tried with a do-while and found it to be the fastest. This is the code:

using System;
using System.Diagnostics;


public class Program
{
    public static void Main()
    {
        int max = 9999999;
        Stopwatch stopWatch = new Stopwatch();

        Console.WriteLine("Do While Loop: ");
        stopWatch.Start();
        DoWhileLoop(max);
        stopWatch.Stop();
        DisplayElapsedTime(stopWatch.Elapsed);
        Console.WriteLine("");
        Console.WriteLine("");

        Console.WriteLine("While Loop: ");
        stopWatch.Start();
        WhileLoop(max);
        stopWatch.Stop();
        DisplayElapsedTime(stopWatch.Elapsed);
        Console.WriteLine("");
        Console.WriteLine("");

        Console.WriteLine("For Loop: ");
        stopWatch.Start();
        ForLoop(max);
        stopWatch.Stop();
        DisplayElapsedTime(stopWatch.Elapsed);
    }

    private static void DoWhileLoop(int max)
    {
        int i = 0;
        do
        {
            //Performe Some Operation. By removing Speed increases
            var j = 10 + 10;
            j += 25;
            i++;
        } while (i <= max);
    }

    private static void WhileLoop(int max)
    {
        int i = 0;
        while (i <= max)
        {
            //Performe Some Operation. By removing Speed increases
            var j = 10 + 10;
            j += 25;
            i++;
        };
    }

    private static void ForLoop(int max)
    {
        for (int i = 0; i <= max; i++)
        {
            //Performe Some Operation. By removing Speed increases
            var j = 10 + 10;
            j += 25;
        }
    }

    private static void DisplayElapsedTime(TimeSpan ts)
    {
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
        Console.WriteLine(elapsedTime, "RunTime");
    }
}

and these are the results of a live demo on DotNetFiddle:

Do While Loop:
00:00:00.06

While Loop:
00:00:00.13

For Loop:
00:00:00.27

Modify SVG fill color when being served as Background-Image

This is my favorite method, but your browser support must be very progressive. With the mask property you create a mask that is applied to an element. Everywhere the mask is opaque, or solid, the underlying image shows through. Where it’s transparent, the underlying image is masked out, or hidden. The syntax for a CSS mask-image is similar to background-image.look at the codepenmask

Compiling/Executing a C# Source File in Command Prompt

You can compile a C# program :

c: > csc Hello.cs

You can run the program

c: > Hello

Google Recaptcha v3 example demo

I process POST on PHP from an angular ajax call. I also like to see the SCORE from google.

This works well for me...

$postData = json_decode(file_get_contents('php://input'), true); //get data sent via post
$captcha = $postData['g-recaptcha-response'];

header('Content-Type: application/json');
if($captcha === ''){
    //Do something with error
    echo '{ "status" : "bad", "score" : "none"}';
} else {
    $secret   = 'your-secret-key';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
        echo '{ "status" : "bad", "score" : "none"}';
    }else if ($response->success==true && $response->score <= 0.5) {
        echo '{ "status" : "bad", "score" : "'.$response->score.'"}';
    }else {
        echo '{ "status" : "ok", "score" : "'.$response->score.'"}';
    }
}

On HTML

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">

On js

$scope.grabCaptchaV3=function(){
    var params = {
                     method: 'POST',
                     url: 'api/recaptcha.php',
                     headers: {
                       'Content-Type': undefined
                     },
                     data:   {'g-recaptcha-response' : myCaptcha }
     }
     $http(params).then(function(result){ 
                console.log(result.data);
     }, function(response){
                console.log(response.statusText);
     }); 
}

how to place last div into right top corner of parent div? (css)

Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.

enter image description here

HTML sample:

<body>
    <ul class="nav-tabs">
        <li><a  id="btn-tab-business" class="btn-tab nav-tab-selected"  onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
        <li><a  id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
        <li><a  id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
    </ul>
</body>

CSS sample:

.nav-tabs{
  position: relative;
  padding-bottom: 50px;
}
.nav-tabs li {
  display: inline-block;  
  position: absolute;
  list-style: none;
}
.nav-tabs li:first-child{
  top: 0px;
  left: 0px;
}
.nav-tabs li:last-child{
  top: 0px;
  right: 0px;
}
.nav-tabs li:nth-child(2){
  top: 0px;
  left: 50%;
  transform: translate(-50%, 0%);
}

Remove scroll bar track from ScrollView in Android

By using below, solved the problem

android:scrollbarThumbVertical="@null"

How to indent a few lines in Markdown markup?

There's no way to do that in markdown's native features. However markdown allows inline HTML, so writing

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This will appear with six space characters in front of it

will produce:

      This will appear with six space characters in front of it

If you have control over CSS on the page, you could also use a tag and style it, either inline or with CSS rules.

Either way, markdown is not meant as a tool for layout, it is meant to simplify the process of writing for the web, so if you find yourself stretching its feature set to do what you need, you might look at whether or not you're using the right tool here. Check out Gruber's docs:

http://daringfireball.net/projects/markdown/syntax#html

Filter rows which contain a certain string

This answer similar to others, but using preferred stringr::str_detect and dplyr rownames_to_column.

library(tidyverse)

mtcars %>% 
  rownames_to_column("type") %>% 
  filter(stringr::str_detect(type, 'Toyota|Mazda') )

#>             type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1      Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> 2  Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> 3 Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#> 4  Toyota Corona 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1

Created on 2018-06-26 by the reprex package (v0.2.0).

Why should we include ttf, eot, woff, svg,... in a font-face

Answer in 2019:

Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format

(svg and eot are dead formats, ttf and otf are full system fonts, and should not be used for web purposes)

Original answer from 2012:

In short, font-face is very old, but only recently has been supported by more than IE.

  • eot is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.

  • ttf and otf are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.

  • Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.

  • Then, woff gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.

  • 2019 edit A few years later, woff2 gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.

If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)

@font-face {
  font-family: 'MyWebFont';
  src:  url('myfont.woff2') format('woff2'),
        url('myfont.woff') format('woff');
}

Support for woff can be checked at http://caniuse.com/woff
Support for woff2 can be checked at http://caniuse.com/woff2

Why is list initialization (using curly braces) better than the alternatives?

There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.

struct Foo {
    Foo() {}

    Foo(std::initializer_list<Foo>) {
        std::cout << "initializer list" << std::endl;
    }

    Foo(const Foo&) {
        std::cout << "copy ctor" << std::endl;
    }
};

int main() {
    Foo a;
    Foo b(a); // copy ctor
    Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}

Assuming you don't encounter such classes there is little reason not to use the intializer list.

SQL SELECT WHERE field contains words

If you just want to find a match.

SELECT * FROM MyTable WHERE INSTR('word1 word2 word3',Column1)<>0

SQL Server :

CHARINDEX(Column1, 'word1 word2 word3', 1)<>0

To get exact match. Example (';a;ab;ac;',';b;') will not get a match.

SELECT * FROM MyTable WHERE INSTR(';word1;word2;word3;',';'||Column1||';')<>0

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Try this:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider NuGet -Force

Set-PSRepository PSGallery -InstallationPolicy Trusted

REST / SOAP endpoints for a WCF service

This is what i did to make it work. Make sure you put
webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.

[ServiceContract]
public interface ITestService
{

    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
    string GetData();
}

public class TestService : ITestService
{
    public string GetJsonData()
    {
        return "I am good...";
    }
}

Inside service model

   <service name="TechCity.Business.TestService">

    <endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
      bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
    <endpoint address="mex"
              contract="IMetadataExchange" binding="mexHttpBinding"/>
    <endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
              name="Http" contract="TechCity.Interfaces.ITestService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8739/test" />
      </baseAddresses>
    </host>
  </service>

EndPoint Behaviour

  <endpointBehaviors>
    <behavior name="jsonBehavior">
      <webHttp automaticFormatSelectionEnabled="true"  />
      <!-- use JSON serialization -->
    </behavior>
  </endpointBehaviors>

invalid_grant trying to get oAuth token from google

I ran into this same problem despite specifying the "offline" access_type in my request as per bonkydog's answer. Long story short I found that the solution described here worked for me:

https://groups.google.com/forum/#!topic/google-analytics-data-export-api/4uNaJtquxCs

In essence, when you add an OAuth2 Client in your Google API's console Google will give you a "Client ID" and an "Email address" (assuming you select "webapp" as your client type). And despite Google's misleading naming conventions, they expect you to send the "Email address" as the value of the client_id parameter when you access their OAuth2 API's.

This applies when calling both of these URL's:

Note that the call to the first URL will succeed if you call it with your "Client ID" instead of your "Email address". However using the code returned from that request will not work when attempting to get a bearer token from the second URL. Instead you will get an 'Error 400' and an "invalid_grant" message.

Make the image go behind the text and keep it in center using CSS

There are two ways to handle this.

  • Background Image
  • Using z-index property of CSS

The background image is probably easier. You need a fixed width somewhere.

.background-image {
    width: 400px;
    background: url(background.png) 50% 50%;
}
<form><div class="background-image"></div></form>

Hashing a file in Python

I would propose simply:

def get_digest(file_path):
    h = hashlib.sha256()

    with open(file_path, 'rb') as file:
        while True:
            # Reading is buffered, so we can read smaller chunks.
            chunk = file.read(h.block_size)
            if not chunk:
                break
            h.update(chunk)

    return h.hexdigest()

All other answers here seem to complicate too much. Python is already buffering when reading (in ideal manner, or you configure that buffering if you have more information about underlying storage) and so it is better to read in chunks the hash function finds ideal which makes it faster or at lest less CPU intensive to compute the hash function. So instead of disabling buffering and trying to emulate it yourself, you use Python buffering and control what you should be controlling: what the consumer of your data finds ideal, hash block size.

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

Add days Oracle SQL

In a more general way you can use "INTERVAL". Here some examples:

1) add a day

select sysdate + INTERVAL '1' DAY from dual;

2) add 20 days

select sysdate + INTERVAL '20' DAY from dual;

2) add some minutes

select sysdate + INTERVAL '15' MINUTE from dual;

How to initialize a nested struct?

If you don't want to go with separate struct definition for nested struct and you don't like second method suggested by @OneOfOne you can use this third method:

package main
import "fmt"
type Configuration struct {
    Val   string
    Proxy struct {
        Address string
        Port    string
    }
}

func main() {
    c := &Configuration{
        Val: "test",
    }

    c.Proxy.Address = `127.0.0.1`
    c.Proxy.Port = `8080`
}

You can check it here: https://play.golang.org/p/WoSYCxzCF2

What is the best way to know if all the variables in a Class are null?

"Best" is such a subjective term :-)

I would just use the method of checking each individual variable. If your class already has a lot of these, the increase in size is not going to be that much if you do something like:

public Boolean anyUnset() {
    if (  id == null) return true;
    if (name == null) return true;
    return false;
}

Provided you keep everything in the same order, code changes (and automated checking with a script if you're paranoid) will be relatively painless.

Alternatively (assuming they're all strings), you could basically put these values into a map of some sort (eg, HashMap) and just keep a list of the key names for that list. That way, you could iterate through the list of keys, checking that the values are set correctly.

Spring boot - Not a managed type

Configure the location of entities using @EntityScan in Spring Boot entry point class.

Update on Sept 2016: For Spring Boot 1.4+:
use org.springframework.boot.autoconfigure.domain.EntityScan
instead of org.springframework.boot.orm.jpa.EntityScan, as ...boot.orm.jpa.EntityScan is deprecated as of Spring Boot 1.4

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

A key is just a normal index. A way over simplification is to think of it like a card catalog at a library. It points MySQL in the right direction.

A unique key is also used for improved searching speed, but it has the constraint that there can be no duplicated items (there are no two x and y where x is not y and x == y).

The manual explains it as follows:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.

A primary key is a 'special' unique key. It basically is a unique key, except that it's used to identify something.

The manual explains how indexes are used in general: here.

In MSSQL, the concepts are similar. There are indexes, unique constraints and primary keys.

Untested, but I believe the MSSQL equivalent is:

CREATE TABLE tmp (
  id int NOT NULL PRIMARY KEY IDENTITY,
  uid varchar(255) NOT NULL CONSTRAINT uid_unique UNIQUE,
  name varchar(255) NOT NULL,
  tag int NOT NULL DEFAULT 0,
  description varchar(255),
);

CREATE INDEX idx_name ON tmp (name);
CREATE INDEX idx_tag ON tmp (tag);

Edit: the code above is tested to be correct; however, I suspect that there's a much better syntax for doing it. Been a while since I've used SQL server, and apparently I've forgotten quite a bit :).

find all the name using mysql query which start with the letter 'a'

I would go for substr() functionality in MySql.

Basically, this function takes account of three parameters i.e. substr(str,pos,len)

http://www.w3resource.com/mysql/string-functions/mysql-substr-function.php

SELECT * FROM artists 
WHERE lower(substr(name,1,1)) in ('a','b','c');

Python NameError: name is not defined

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

Make function definition in a python file order independent

How do I center a window onscreen in C#?

In Windows Forms:

this.StartPosition = FormStartPosition.CenterScreen;

In WPF:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

That's all you have to do...

row-level trigger vs statement-level trigger

You may want trigger action to execute once after the client executes a statement that modifies a million rows (statement-level trigger). Or, you may want to trigger the action once for every row that is modified (row-level trigger).

EXAMPLE: Let's say you have a trigger that will make sure all high school seniors graduate. That is, when a senior's grade is 12, and we increase it to 13, we want to set the grade to NULL.

For a statement level trigger, you'd say, after the increase-grade statement runs, check the whole table once to update any nows with grade 13 to NULL.

For a row-level trigger, you'd say, after every row that is updated, update the new row's grade to NULL if it is 13.

A statement-level trigger would look like this:

create trigger stmt_level_trigger
after update on Highschooler
begin
    update Highschooler
    set grade = NULL
    where grade = 13;
end;

and a row-level trigger would look like this:

create trigger row_level_trigger
after update on Highschooler
for each row
when New.grade = 13
begin
    update Highschooler
    set grade = NULL
    where New.ID = Highschooler.ID;
end;

Note that SQLite doesn't support statement-level triggers, so in SQLite, the FOR EACH ROW is optional.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Angular JS update input field after change

You just need to correct the format of your html

<form>
    <li>Number 1: <input type="text" ng-model="one"/> </li>
    <li>Number 2: <input type="text" ng-model="two"/> </li>
        <li>Total <input type="text" value="{{total()}}"/>  </li>      
    {{total()}}

</form>

http://jsfiddle.net/YUza7/105/

Uninstall Node.JS using Linux command line?

If you have yum you could do:

yum remove nodesource-release* nodejs

yum clean all

And after that check if its deleted:

rpm -qa 'node|npm'

Sum up a column from a specific row down

This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:

=sum(c6:c1048576)

For more robust solutions, see the other answers.

Iterate through Nested JavaScript Objects

You can get through every object in the list and get which value you want. Just pass an object as first parameter in the function call and object property which you want as second parameter. Change object with your object.

_x000D_
_x000D_
const treeData = [{_x000D_
        "jssType": "fieldset",_x000D_
        "jssSelectLabel": "Fieldset (with legend)",_x000D_
        "jssSelectGroup": "jssItem",_x000D_
        "jsName": "fieldset-715",_x000D_
        "jssLabel": "Legend",_x000D_
        "jssIcon": "typcn typcn-folder",_x000D_
        "expanded": true,_x000D_
        "children": [{_x000D_
                "jssType": "list-ol",_x000D_
                "jssSelectLabel": "List - ol",_x000D_
                "jssSelectGroup": "jssItem",_x000D_
                "jsName": "list-ol-147",_x000D_
                "jssLabel": "",_x000D_
                "jssIcon": "dashicons dashicons-editor-ol",_x000D_
                "noChildren": false,_x000D_
                "expanded": true,_x000D_
                "children": [{_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-752",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "text",_x000D_
                            "jssSelectLabel": "Text (short text)",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "text-422",_x000D_
                            "jssLabel": "Your Name (required)",_x000D_
                            "jsRequired": true,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "akismet_author_email",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Akismet - this field requires author's email address",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsAkismetAuthor": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-sort-alphabetically",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    },_x000D_
                    {_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-538",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "email",_x000D_
                            "jssSelectLabel": "Email",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "email-842",_x000D_
                            "jssLabel": "Email Address (required)",_x000D_
                            "jsRequired": true,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "akismet_author_email",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Akismet - this field requires author's email address",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsAkismetAuthorEmail": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-mail",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    },_x000D_
                    {_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-855",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "textarea",_x000D_
                            "jssSelectLabel": "Textarea (long text)",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "textarea-217",_x000D_
                            "jssLabel": "Your Message",_x000D_
                            "jsRequired": false,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-document-text",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    }_x000D_
                ]_x000D_
            },_x000D_
            {_x000D_
                "jssType": "paragraph",_x000D_
                "jssSelectLabel": "Paragraph - p",_x000D_
                "jssSelectGroup": "jssItem",_x000D_
                "jsName": "paragraph-993",_x000D_
                "jssContent": "* Required",_x000D_
                "jssIcon": "dashicons dashicons-editor-paragraph",_x000D_
                "noChildren": true_x000D_
            }_x000D_
        ]_x000D_
        _x000D_
    },_x000D_
    {_x000D_
        "jssType": "submit",_x000D_
        "jssSelectLabel": "Submit",_x000D_
        "jssSelectGroup": "jsTag",_x000D_
        "jsName": "submit-704",_x000D_
        "jssLabel": "Send",_x000D_
        "jsValues": "",_x000D_
        "jsRequired": false,_x000D_
        "jsIdAttribute": "",_x000D_
        "jsClassAttribute": "",_x000D_
        "jssIcon": "typcn typcn-mail",_x000D_
        "noChildren": true_x000D_
    },_x000D_
    _x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function findObjectByLabel(obj, label) {_x000D_
       for(var elements in obj){_x000D_
           if (elements === label){_x000D_
                console.log(obj[elements]);_x000D_
           }_x000D_
            if(typeof obj[elements] === 'object'){_x000D_
            findObjectByLabel(obj[elements], 'jssType');_x000D_
           }_x000D_
          _x000D_
       }_x000D_
};_x000D_
_x000D_
 findObjectByLabel(treeData, 'jssType');
_x000D_
_x000D_
_x000D_

How might I force a floating DIV to match the height of another floating DIV?

This code will let you have a variable number of rows (with a variable number of DIVs on each row) and it will make all of the DIVs on each row match the height of its tallest neighbour:

If we assumed all the DIVs, that are floating, are inside a container with the id "divContainer", then you could use the following:

$(document).ready(function() {

var currentTallest = 0;
var currentRowStart = 0;
var rowDivs = new Array();

$('div#divContainer div').each(function(index) {

    if(currentRowStart != $(this).position().top) {

        // we just came to a new row.  Set all the heights on the completed row
        for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);

        // set the variables for the new row
        rowDivs.length = 0; // empty the array
        currentRowStart = $(this).position().top;
        currentTallest = $(this).height();
        rowDivs.push($(this));

    } else {

        // another div on the current row.  Add it to the list and check if it's taller
        rowDivs.push($(this));
        currentTallest = (currentTallest < $(this).height()) ? ($(this).height()) : (currentTallest);

    }
    // do the last row
    for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);

});
});

How to round up with excel VBA round()?

I find the following function sufficient:

'
' Round Up to the given number of digits
'
Function RoundUp(x As Double, digits As Integer) As Double

    If x = Round(x, digits) Then
        RoundUp = x
    Else
        RoundUp = Round(x + 0.5 / (10 ^ digits), digits)
    End If

End Function

Will using 'var' affect performance?

For the following method:

   private static void StringVsVarILOutput()
    {
        var string1 = new String(new char[9]);

        string string2 = new String(new char[9]);
    }

The IL Output is this:

        {
          .method private hidebysig static void  StringVsVarILOutput() cil managed
          // Code size       28 (0x1c)
          .maxstack  2
          .locals init ([0] string string1,
                   [1] string string2)
          IL_0000:  nop
          IL_0001:  ldc.i4.s   9
          IL_0003:  newarr     [mscorlib]System.Char
          IL_0008:  newobj     instance void [mscorlib]System.String::.ctor(char[])
          IL_000d:  stloc.0
          IL_000e:  ldc.i4.s   9
          IL_0010:  newarr     [mscorlib]System.Char
          IL_0015:  newobj     instance void [mscorlib]System.String::.ctor(char[])
          IL_001a:  stloc.1
          IL_001b:  ret
        } // end of method Program::StringVsVarILOutput

Getting the thread ID from a thread

According to MSDN:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

So basically, the Thread object does not necessarily correspond to an OS thread - which is why it doesn't have the native ID exposed.

How can I drop a table if there is a foreign key constraint in SQL Server?

1-firstly, drop the foreign key constraint after that drop the tables.

2-you can drop all foreign key via executing the following query:

DECLARE @SQL varchar(4000)=''
SELECT @SQL = 
@SQL + 'ALTER TABLE ' + s.name+'.'+t.name + ' DROP CONSTRAINT [' + RTRIM(f.name) +'];' + CHAR(13)
FROM sys.Tables t
INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id
INNER JOIN sys.schemas     s ON s.schema_id = f.schema_id

--EXEC (@SQL)

PRINT @SQL

if you execute the printed results @SQL, the foreign keys will be dropped.

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

Calculating sum of repeated elements in AngularJS ng-repeat

Huy Nguyen's answer is almost there. To make it work, add:

ng-repeat="_ in [ products ]"

...to the line with ng-init. The list always has a single item, so Angular will repeat the block exactly once.

Zybnek's demo using filtering can be made to work by adding:

ng-repeat="_ in [ [ products, search ] ]"

See http://plnkr.co/edit/dLSntiy8EyahZ0upDpgy?p=preview.

CSS-moving text from left to right

I like using the following to prevent things being outside my div elements. It helps with CSS rollovers too.

.marquee{
    overflow:hidden;
}

this will hide anything that moves/is outside of the div which will prevent the browser expanding and causing a scroll bar to appear.

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

Best way to get identity of inserted row?

From MSDN

@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.

@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.

  • IDENT_CURRENT is a function which takes a table as a argument.
  • @@IDENTITY may return confusing result when you have an trigger on the table
  • SCOPE_IDENTITY is your hero most of the time.

Parsing boolean values with argparse

class FlagAction(argparse.Action):
    # From http://bugs.python.org/issue8538

    def __init__(self, option_strings, dest, default=None,
                 required=False, help=None, metavar=None,
                 positive_prefixes=['--'], negative_prefixes=['--no-']):
        self.positive_strings = set()
        self.negative_strings = set()
        for string in option_strings:
            assert re.match(r'--[A-z]+', string)
            suffix = string[2:]
            for positive_prefix in positive_prefixes:
                self.positive_strings.add(positive_prefix + suffix)
            for negative_prefix in negative_prefixes:
                self.negative_strings.add(negative_prefix + suffix)
        strings = list(self.positive_strings | self.negative_strings)
        super(FlagAction, self).__init__(option_strings=strings, dest=dest,
                                         nargs=0, const=None, default=default, type=bool, choices=None,
                                         required=required, help=help, metavar=metavar)

    def __call__(self, parser, namespace, values, option_string=None):
        if option_string in self.positive_strings:
            setattr(namespace, self.dest, True)
        else:
            setattr(namespace, self.dest, False)

Getting Python error "from: can't read /var/mail/Bio"

for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.

The property 'Id' is part of the object's key information and cannot be modified

For me the issue was caused by the lack of a Primary Key to my table, after setting a PK for the table the problem was gone

How to use LINQ Distinct() with multiple fields

the solution to your problem looks like this:

public class Category {
  public long CategoryId { get; set; }
  public string CategoryName { get; set; }
} 

...

public class CategoryEqualityComparer : IEqualityComparer<Category>
{
   public bool Equals(Category x, Category y)
     => x.CategoryId.Equals(y.CategoryId)
          && x.CategoryName .Equals(y.CategoryName, 
 StringComparison.OrdinalIgnoreCase);

   public int GetHashCode(Mapping obj)
     => obj == null 
         ? 0
         : obj.CategoryId.GetHashCode()
           ^ obj.CategoryName.GetHashCode();
}

...

 var distinctCategories = product
     .Select(_ => 
        new Category {
           CategoryId = _.CategoryId, 
           CategoryName = _.CategoryName
        })
     .Distinct(new CategoryEqualityComparer())
     .ToList();

Android studio Gradle build speed up

There is a newer version of gradle (ver 2.4).

You can set this for your project(s) by opening up 'Project Structure' dialog from File menu,

Project Structure -> Project -> Gradle version

and set it to '2.4'.
You can read more about boosting performance at this link.

ListView with Add and Delete Buttons in each Row in android

You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > 

<TextView
    android:id="@+id/list_item_string"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:paddingLeft="8dp"
    android:textSize="18sp"
    android:textStyle="bold" /> 

<Button
    android:id="@+id/delete_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:text="Delete" /> 

<Button
    android:id="@+id/add_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/delete_btn"
    android:layout_centerVertical="true"
    android:layout_marginRight="10dp"
    android:text="Add" />

</RelativeLayout>

Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.

public class MyCustomAdapter extends BaseAdapter implements ListAdapter { 
private ArrayList<String> list = new ArrayList<String>(); 
private Context context; 



public MyCustomAdapter(ArrayList<String> list, Context context) { 
    this.list = list; 
    this.context = context; 
} 

@Override
public int getCount() { 
    return list.size(); 
} 

@Override
public Object getItem(int pos) { 
    return list.get(pos); 
} 

@Override
public long getItemId(int pos) { 
    return list.get(pos).getId();
    //just return 0 if your list items do not have an Id variable.
} 

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
        view = inflater.inflate(R.layout.my_custom_list_layout, null);
    } 

    //Handle TextView and display string from your list
    TextView listItemText = (TextView)view.findViewById(R.id.list_item_string); 
    listItemText.setText(list.get(position)); 

    //Handle buttons and add onClickListeners
    Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
    Button addBtn = (Button)view.findViewById(R.id.add_btn);

    deleteBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            list.remove(position); //or some other task
            notifyDataSetChanged();
        }
    });
    addBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            notifyDataSetChanged();
        }
    });

    return view; 
} 
}

Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.

public class MyActivity extends Activity { 

@Override
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my_activity); 

    //generate list
    ArrayList<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");

    //instantiate custom adapter
    MyCustomAdapter adapter = new MyCustomAdapter(list, this);

    //handle listview and assign adapter
    ListView lView = (ListView)findViewById(R.id.my_listview);
    lView.setAdapter(adapter);
}

Hope this helps!

Firebase FCM notifications click_action payload

Update:

So just to verify, it is not currently possible to set the click_action parameter via the Firebase Console.


So I've been trying to do this in the Firebase Notifications Console with no luck. Since I can't seem to find anywhere to place the click_action value in the console, what I mainly did to test this out is to add a custom key/value pair in the Notification (Advance Options > Custom Data):

Key: click_action
Value: <your_preferred_value>

then tried calling RemoteMessage.getNotification().getClickAction() in onMessageReceived() to see if it was retrieving the correct value, but it always returns null. So next I tried calling RemoteMessage.getData().get(< specified_key >) and was able to retrieve the value I added.

NOTE: I am not entirely sure if that is okay to be used as a workaround, or if it's against best practice. I would suggest using your own app server but your post is specific to the Firebase Console.

The way the client app and the notification behaves still depends on how you program it. With that said, I think you can use the above as a workaround, using the value retrieved from the getData(), then having the Notification call this or that. Hope this helps somehow. Cheers! :D

Generate 'n' unique random numbers within a range

If you just need sampling without replacement:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sample takes a population and a sample size k and returns k random members of the population.

If you have to control for the case where k is larger than len(population), you need to be prepared to catch a ValueError:

>>> try:
...   random.sample(range(1, 2), 3)
... except ValueError:
...   print('Sample size exceeded population size.')
... 
Sample size exceeded population size

Error: could not find function "%>%"

One needs to install magrittr as follows

install.packages("magrittr")

Then, in one's script, don't forget to add on top

library(magrittr)

For the meaning of the operator %>% you might want to consider this question: What does %>% function mean in R?

Note that the same operator would also work with the library dplyr, as it imports from magrittr.

dplyr used to have a similar operator (%.%), which is now deprecated. Here we can read about the differences between %.% (deprecated operator from the library dplyr) and %>% (operator from magrittr, that is also available in dplyr)

How do I change a tab background color when using TabLayout?

What finally worked for me is similar to what @????DJ suggested, but the tabBackground should be in the layout file and not inside the style, so it looks like:

res/layout/somefile.xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

and the selector res/drawable/tab_color_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>

"Object doesn't support property or method 'find'" in IE

The Array.find method support for Microsoft's browsers started with Edge.

The W3Schools compatibility table states that the support started on version 12, while the Can I Use compatibility table says that the support was unknown between version 12 and 14, being officially supported starting at version 15.