Programs & Examples On #Input language

Does mobile Google Chrome support browser extensions?

You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.

I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.

To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.

edit

Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.

I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...

and it works in chrome whatever platform I am currently logged on to.

What is the difference between buffer and cache memory in Linux?

Buffer contains metadata which helps improve write performance

Cache contains the file content itself (sometimes yet to write to disk) which improves read performance

When do you use POST and when do you use GET?

One practical difference is that browsers and webservers have a limit on the number of characters that can exist in a URL. It's different from application to application, but it's certainly possible to hit it if you've got textareas in your forms.

Another gotcha with GETs - they get indexed by search engines and other automatic systems. Google once had a product that would pre-fetch links on the page you were viewing, so they'd be faster to load if you clicked those links. It caused major havoc on sites that had links like delete.php?id=1 - people lost their entire sites.

How to save a Seaborn plot into a file

You should just be able to use the savefig method of sns_plot directly.

sns_plot.savefig("output.png")

For clarity with your code if you did want to access the matplotlib figure that sns_plot resides in then you can get it directly with

fig = sns_plot.fig

In this case there is no get_figure method as your code assumes.

Fundamental difference between Hashing and Encryption algorithms

You already got some good answers, but I guess you could see it like this: ENCRYPTION: Encryption has to be decryptable if you have the right key.

Example: Like when you send an e-mail. You might not want everyone in the world to know what you are writing to the person receiving the e-mail, but the person who receives the e-mail would probably want to be able to read it.

HASHES: hashes work similar like encryption, but it should not be able to reverse it at all.

Example: Like when you put a key in a locked door(the kinds that locks when you close them). You do not care how the lock works in detail, just as long as it unlocks itself when you use the key. If there is trouble you probably cannot fix it, instead get a new lock.(like forgetting passwords on every login, at least I do it all the time and it is a common area to use hashing).

... and I guess you could call that rainbow-algorithm a locksmith in this case.

Hope things clear up =)

Difference between "on-heap" and "off-heap"

The heap is the place in memory where your dynamically allocated objects live. If you used new then it's on the heap. That's as opposed to stack space, which is where the function stack lives. If you have a local variable then that reference is on the stack. Java's heap is subject to garbage collection and the objects are usable directly.

EHCache's off-heap storage takes your regular object off the heap, serializes it, and stores it as bytes in a chunk of memory that EHCache manages. It's like storing it to disk but it's still in RAM. The objects are not directly usable in this state, they have to be deserialized first. Also not subject to garbage collection.

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

Importing Excel files into R, xlsx or xls

I would definitely try the read.xls function in the gdata package, which is considerably more mature than the xlsx package. It may require Perl ...

What does "subject" mean in certificate?

The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).

As RFC 5280 says:

The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.

X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.

The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".

In the context of the article you're linking to, the subject would be the user/owner of the cert.

Import SQL file into mysql

In Windows OS the following commands works for me.

mysql>Use <DatabaseName>
mysql>SOURCE C:/data/ScriptFile.sql;

No single quotes or double quotes around file name. Path would contain '/' instead of '\'.

How to use refs in React with Typescript

I always do this, in that case to grab a ref

let input: HTMLInputElement = ReactDOM.findDOMNode<HTMLInputElement>(this.refs.input);

Make Iframe to fit 100% of container's remaining height

You can do this by measuring the body size on load/resize events and setting the height to the (full height - banner height).

Note that currently in IE8 Beta2 you can't do this onresize as that event is currently broken in IE8 Beta2.

Error 0x80005000 and DirectoryServices

I had the same error - in my case it was extra slash in path argument that made the difference.

BAD:

DirectoryEntry directoryEntry = 
    new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com/", 
                       userName, password);

GOOD:

DirectoryEntry directoryEntry = 
    new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com", 
                       userName, password);

How to convert a huge list-of-vector to a matrix more efficiently?

You can also use,

output <- as.matrix(as.data.frame(z))

The memory usage is very similar to

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Which can be verified, with mem_changed() from library(pryr).

Use chrome as browser in C#?

I don't know of any full Chrome component, but you could use WebKit, which is the rendering engine that Chrome uses. The Mono project made WebKit Sharp, which might work for you.

Register 32 bit COM DLL to 64 bit Windows 7

The problem is likely you try to register a 32-bit library with 64-bit version of regsvr32. See this KB article - you need to run regsvr32 from windows\SysWOW64 for 32-bit libraries.

Mysql where id is in array

$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");

NB: the syntax is:

SELECT * FROM table WHERE column IN('value1','value2','value3')

Change Screen Orientation programmatically using a Button

Use this to set the orientation of the screen:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

or

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

and don't forget to add this to your manifest:

android:configChanges = "orientation"

Convert Unicode data to int in python

int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).

Do this instead:

limit = int(limit)

Or when definiting limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])

Trying to embed newline in a variable in bash

Try echo $'a\nb'.

If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:

var=$'a\nb\nc'
echo "$var"

Or, to fix your example program literally:

var="a b c"
for i in $var; do
    p="`echo -e "$p\\n$i"`"
done
echo "$p"

Getting data-* attribute for onclick event for an html element

here is an example

 <a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>

    $('.facultySelecter').click(function() {        
    var unhide = $(this).data("faculty");
    });

this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get

Returning a file to View/Download in ASP.NET MVC

To view file (txt for example):

return File("~/TextFileInRootDir.txt", MediaTypeNames.Text.Plain);

To download file (txt for example):

return File("~/TextFileInRootDir.txt", MediaTypeNames.Text.Plain, "TextFile.txt");

note: to download file we should pass fileDownloadName argument

How to solve error message: "Failed to map the path '/'."

I Think this is because of IIS is unable to find the root folder. i.e wwwroot. Restarting the IIS wont be helpful in some scenarios. if the root path has changed, you should bring it back to %SystemDrive%\inetpub\wwwroot

by right clicking sites node in IIS and changing physical path to the above one.

and make sure that your application pool is asp.net v4.0 and running in integrated mode

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Aus_lacy's post gave me the idea of trying related methods, of which join does work:

In [196]:

hl.name = 'hl'
Out[196]:
'hl'
In [199]:

df.join(hl).head(4)
Out[199]:
high    low loc_h   loc_l   hl
2014-01-01 17:00:00 1.376235    1.375945    1.376235    1.375945    1.376090
2014-01-01 17:01:00 1.376005    1.375775    NaN NaN NaN
2014-01-01 17:02:00 1.375795    1.375445    NaN 1.375445    1.375445
2014-01-01 17:03:00 1.375625    1.375515    NaN NaN NaN

Some insight into why concat works on the example but not this data would be nice though!

Moment.js - how do I get the number of years since a date, not rounded up?

There appears to be a difference function that accepts time intervals to use as well as an option to not round the result. So, something like

Math.floor(moment(new Date()).diff(moment("02/26/1978","MM/DD/YYYY"),'years',true)))

I haven't tried this, and I'm not completely familiar with moment, but it seems like this should get what you want (without having to reset the month).

DB2 Date format

select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1

result: 20160510

Java Equivalent of C# async/await?

As it was mentioned, there is no direct equivalent, but very close approximation could be created with Java bytecode modifications (for both async/await-like instructions and underlying continuations implementation).

I'm working right now on a project that implements async/await on top of JavaFlow continuation library, please check https://github.com/vsilaev/java-async-await

No Maven mojo is created yet, but you may run examples with supplied Java agent. Here is how async/await code looks like:

public class AsyncAwaitNioFileChannelDemo {

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

    ...
    final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo();
    final CompletionStage<String> result = demo.processFile("./.project");
    System.out.println("Returned to caller " + LocalTime.now());
    ...
}


public @async CompletionStage<String> processFile(final String fileName) throws IOException {
    final Path path = Paths.get(new File(fileName).toURI());
    try (
            final AsyncFileChannel file = new AsyncFileChannel(
                path, Collections.singleton(StandardOpenOption.READ), null
            );              
            final FileLock lock = await(file.lockAll(true))
        ) {

        System.out.println("In process, shared lock: " + lock);
        final ByteBuffer buffer = ByteBuffer.allocateDirect((int)file.size());

        await( file.read(buffer, 0L) );
        System.out.println("In process, bytes read: " + buffer);
        buffer.rewind();

        final String result = processBytes(buffer);

        return asyncResult(result);

    } catch (final IOException ex) {
        ex.printStackTrace(System.out);
        throw ex;
    }
}

@async is the annotation that flags a method as asynchronously executable, await() is a function that waits on CompletableFuture using continuations and a call to "return asyncResult(someValue)" is what finalizes associated CompletableFuture/Continuation

As with C#, control flow is preserved and exception handling may be done in regular manner (try/catch like in sequentially executed code)

How to get PHP $_GET array?

You could make id a series of comma-seperated values, like this:

index.php?id=1,2,3&name=john

Then, within your PHP code, explode it into an array:

$values = explode(",", $_GET["id"]);
print count($values) . " values passed.";

This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:

index.php?id[]=1&id[]=2&id[]=3&name=john

But that clearly would be much more verbose.

Can a relative sitemap url be used in a robots.txt?

According to the official documentation on sitemaps.org it needs to be a full URL:

You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:

Sitemap: http://www.example.com/sitemap.xml

Best way to determine user's locale within browser

Combining the multiple ways browsers are using to store the user's language, you get this function :

const getNavigatorLanguage = () => {
  if (navigator.languages && navigator.languages.length) {
    return navigator.languages[0];
  } else {
    return navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
  }
}

We first check the navigator.languages array for its first element.
Then we get either navigator.userLanguage or navigator.language.
If this fails we get navigator.browserLanguage.
Finally, we set it to 'en' if everything else failed.


And here's the sexy one-liner :

const getNavigatorLanguage = () => (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';

Xcode 7.2 no matching provisioning profiles found

I updated to Xcode v7.3.1 and it solved the issue.

How can I determine installed SQL Server instances and their versions?

I know this thread is a bit old, but I came across this thread before I found the answer I was looking for and thought I'd share. If you are using SQLExpress (or localdb) there is a simpler way to find your instance names. At a command line type:

> sqllocaldb i

This will list the instance names you have installed locally. So your full server name should include (localdb)\ in front of the instance name to connect. Also, sqllocaldb allows you to create new instances or delete them as well as configure them. See: SqlLocalDB Utility.

Good Hash Function for Strings

If it's a security thing, you could use Java crypto:

import java.security.MessageDigest;

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(stringToHash.getBytes());
String stringHash = new String(messageDigest.digest());

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

How can I group data with an Angular filter?

Update

I initially wrote this answer because the old version of the solution suggested by Ariel M. when combined with other $filters triggered an "Infite $diggest Loop Error" (infdig). Fortunately this issue has been solved in the latest version of the angular.filter.

I suggested the following implementation, that didn't have that issue:

angular.module("sbrpr.filters", [])
.filter('groupBy', function () {
  var results={};
    return function (data, key) {
        if (!(data && key)) return;
        var result;
        if(!this.$id){
            result={};
        }else{
            var scopeId = this.$id;
            if(!results[scopeId]){
                results[scopeId]={};
                this.$on("$destroy", function() {
                    delete results[scopeId];
                });
            }
            result = results[scopeId];
        }

        for(var groupKey in result)
          result[groupKey].splice(0,result[groupKey].length);

        for (var i=0; i<data.length; i++) {
            if (!result[data[i][key]])
                result[data[i][key]]=[];
            result[data[i][key]].push(data[i]);
        }

        var keys = Object.keys(result);
        for(var k=0; k<keys.length; k++){
          if(result[keys[k]].length===0)
            delete result[keys[k]];
        }
        return result;
    };
});

However, this implementation will only work with versions prior to Angular 1.3. (I will update this answer shortly providing a solution that works with all versions.)

I've actually wrote a post about the steps that I took to develop this $filter, the problems that I encountered and the things that I learned from it.

Execute multiple command lines with the same process using .NET

I prefer to do it by using a BAT file.

With BAT file you have more control and can do whatever you want.

string batFileName = path + @"\" + Guid.NewGuid() + ".bat";

using (StreamWriter batFile = new StreamWriter(batFileName))
{
    batFile.WriteLine($"YOUR COMMAND");
    batFile.WriteLine($"YOUR COMMAND");
    batFile.WriteLine($"YOUR COMMAND");
}

ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c " + batFileName);
processStartInfo.UseShellExecute = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;

Process p = new Process();
p.StartInfo = processStartInfo;
p.Start();
p.WaitForExit();

File.Delete(batFileName);

Best approach to converting Boolean object to string in java

If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:

Boolean.TRUE.toString();
Boolean.FALSE.toString();

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

html table span entire width?

There might be a margin style that your table is inheriting. Try setting the margin of the table to 0:

<table border="1" width="100%" ID="Table2" style="margin: 0px;">
<tr>
  <td>100</td>
</tr>
</table>

Tool to convert java to c# code

Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.

OWIN Security - How to Implement OAuth2 Refresh Tokens

Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:

private string ComputeHash(Guid input)
{
    byte[] source = input.ToByteArray();

    var encoder = new SHA256Managed();
    byte[] encoded = encoder.ComputeHash(source);

    return Convert.ToBase64String(encoded);
}

In CreateAsync:

var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());

ReceiveAsync:

public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    Guid token;

    if (Guid.TryParse(context.Token, out token))
    {
        AuthenticationTicket ticket;

        if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

'NOT LIKE' in an SQL query

You need to specify the column in both expressions.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

What is an Intent in Android?

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

For more details see these links :

1). http://developer.android.com/reference/android/content/Intent.html

2) http://developer.android.com/guide/topics/intents/intents-filters.html

3). http://www.vogella.de/articles/AndroidIntent/article.html

there are many more articles are available.

How to set focus to a button widget programmatically?

Try this:

btn.requestFocusFromTouch();

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL 
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
   insert into table(fieldValue) values('')
   select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')

Checking if element exists with Python Selenium

Solution without try&catch and without new imports:

if len(driver.find_elements_by_id('blah')) > 0: #pay attention: find_element*s*
    driver.find_element_by_id('blah').click #pay attention: find_element

Running MSBuild fails to read SDKToolsPath

I suspect the targets file is overriding the tools path, I had a quick look in this file and is sets the SDKToolsPath to $TargetFrameworkSDKToolsDirectory under some of the targets in there. I don't think you should need to set these in the environment anyway, but they may need fixing in your project files.

Note that according to this page http://nant.sourceforge.net/ Nant does not support .Net 4.0, could this be the real problem?

Sorry, I know this doesn't really answer your question:(

How to convert a normal Git repository to a bare one?

In short: replace the contents of repo with the contents of repo/.git, then tell the repository that it is now a bare repository.

To do this, execute the following commands:

cd repo
mv .git ../repo.git # renaming just for clarity
cd ..
rm -fr repo
cd repo.git
git config --bool core.bare true

Note that this is different from doing a git clone --bare to a new location (see below).

Set Content-Type to application/json in jsp file

Try this piece of code, it should work too

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>

How to auto-size an iFrame?

My workaround is to set the iframe the height/width well over any anticipated source page size in CSS & the background property to transparent.

In the iframe set allow-transparency to true and scrolling to no.

The only thing visible will be whatever source file you use. It works in IE8, Firefox 3, & Safari.

How to force deletion of a python object?

  1. Add an exit handler that closes all the bars.
  2. __del__() gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.
  3. If __init__() raises an exception then the object is assumed to be incomplete and __del__() won't be invoked.

Can't find AVD or SDK manager in Eclipse

Unfortunately I ended up having to re-install eclipse. but first (In Linux)(not sure of folder in Windows) do:

sudo rm -R /usr/share/eclipse/

What is the difference between PUT, POST and PATCH?

The below definition is from the real world example.

Example Overview
For every client data, we are storing an identifier to find that client data and we will send back that identifier to that client for reference.

  1. POST

    • If the Client sends data without any identifier using the POST method then we will store it and assign a new identifier.
    • If the Client again sends the same data without any identifier using the POST method, then we will store it and assign a new identifier.
    • Note: Duplication is allowed here
  2. PUT

    • If the Client Sends data with an identifier then we will check whether that identifier exists. If the identifier exists we will update data else we will create it and assign a new identifier.
  3. PATCH

    • If the Client Sends data with an identifier then we will check whether that identifier exists. If the identifier exists we will update data else we will throw an exception.

Note: On Put Method, We are not throwing an exception if an identifier is not found. But in Patch method, we are throwing an exception if the identifier is not found.

Do let me know if you have any queries on the above.

How do I align spans or divs horizontally?

You can use

.floatybox {
     display: inline-block;
     width: 123px;
}

If you only need to support browsers that have support for inline blocks. Inline blocks can have width, but are inline, like button elements.

Oh, and you might wnat to add vertical-align: top on the elements to make sure things line up

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

What regex will match every character except comma ',' or semi-colon ';'?

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

Class constructor type in typescript?

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

class Zoo<T extends Animal> {
    constructor(public readonly AnimalClass: new () => T) {
    }
}

This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.

const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.

Facebook API "This app is in development mode"

for testing purposes only you could Go to your facebook developer dashboard. create your app then in the top left corner open the apps dropdown menu and click create test app take the app ID and use instead.

image

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

<project>

    <!-- ... -->

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Python virtualenv questions

Yes basically this is what virtualenv do , and this is what the activate command is for, from the doc here:

activate script

In a newly created virtualenv there will be a bin/activate shell script, or a Scripts/activate.bat batch file on Windows.

This will change your $PATH to point to the virtualenv bin/ directory. Unlike workingenv, this is all it does; it's a convenience. But if you use the complete path like /path/to/env/bin/python script.py you do not need to activate the environment first. You have to use source because it changes the environment in-place. After activating an environment you can use the function deactivate to undo the changes.

The activate script will also modify your shell prompt to indicate which environment is currently active.

so you should just use activate command which will do all that for you:

> \path\to\env\bin\activate.bat

How to set "value" to input web element using selenium?

As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");

What is the cleanest way to ssh and run multiple commands in Bash?

I see two ways:

First you make a control socket like this:

 ssh -oControlMaster=yes -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip>

and run your commands

 ssh -oControlMaster=no -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip> -t <yourcommand>

This way you can write an ssh command without actually reconnecting to the server.

The second would be to dynamically generate the script, scping it and running.

How can I test a change made to Jenkinsfile locally?

For simplicity, you can create a Jenkinsfile at the root of the git repository, similar to the below example 'Jenkinsfile' based on the groovy syntax of the declarative pipeline.

pipeline {

    agent any

    stages {
        stage('Build the Project') {
            steps {
                git 'https://github.com/jaikrgupta/CarthageAPI-1.0.git'
                echo pwd()
                sh 'ls -alrt'
                sh 'pip install -r requirements.txt'
                sh 'python app.py &'
                echo "Build stage gets finished here"
            }
        }
        stage('Test') {
            steps {
                sh 'chmod 777 ./scripts/test-script.sh'
                sh './scripts/test-script.sh'
                sh 'cat ./test-reports/test_script.log'
                echo "Test stage gets finished here"
            }
        }
}

https://github.com/jaikrgupta/CarthageAPI-1.0.git

You can now set up a new item in Jenkins as a Pipeline job. Select the Definition as Pipeline script from SCM and Git for the SCM option. Paste the project's git repo link in the Repository URL and Jenkinsfile in the script name box. Then click on the lightweight checkout option and save the project. So whenever you pushed a commit to the git repo, you can always test the changes running the Build Now every time in Jenkins.

Please follow the instructions in the below visuals for easy setup a Jenkins Pipeline's job.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

How to style UITextview to like Rounded Rect text field?

I know there are already a lot of answers to this one, but I didn't really find any of them sufficient (at least in Swift). I wanted a solution that provided the same exact border as a UITextField (not an approximated one that looks sort of like it looks right now, but one that looks exactly like it and will always look exactly like it). I needed to use a UITextField to back the UITextView for the background, but didn't want to have to create that separately every time.

The solution below is a UITextView that supplies it's own UITextField for the border. This is a trimmed down version of my full solution (which adds "placeholder" support to the UITextView in a similar way) and was posted here: https://stackoverflow.com/a/36561236/1227119

// This class implements a UITextView that has a UITextField behind it, where the 
// UITextField provides the border.
//
class TextView : UITextView, UITextViewDelegate
{
    var textField = TextField();

    required init?(coder: NSCoder)
    {
        fatalError("This class doesn't support NSCoding.")
    }

    override init(frame: CGRect, textContainer: NSTextContainer?)
    {
        super.init(frame: frame, textContainer: textContainer);

        self.delegate = self;

        // Create a background TextField with clear (invisible) text and disabled
        self.textField.borderStyle = UITextBorderStyle.RoundedRect;
        self.textField.textColor = UIColor.clearColor();
        self.textField.userInteractionEnabled = false;

        self.addSubview(textField);
        self.sendSubviewToBack(textField);
    }

    convenience init()
    {
        self.init(frame: CGRectZero, textContainer: nil)
    }

    override func layoutSubviews()
    {
        super.layoutSubviews()
        // Do not scroll the background textView
        self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
    }

    // UITextViewDelegate - Note: If you replace delegate, your delegate must call this
    func scrollViewDidScroll(scrollView: UIScrollView)
    {
        // Do not scroll the background textView
        self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
    }        
}

Is there a better way to compare dictionary values

Not sure if this helps but in my app I had to check if a dictionary has changed.

Doing this will not work since basically it's still the same object:

val={'A':1,'B':2}
old_val=val

val['A']=10
if old_val != val:
  print('changed')

Using copy/deepcopy works:

import copy
val={'A':1,'B':2}
old_val=copy.deepcopy(val)

val['A']=10
if old_val != val:
  print('changed')

How do I add an existing directory tree to a project in Visual Studio?

Visual Studio 2017 and newer support a new lightweight .csproj format which has come to be known as "SDK format". One of several advantages of this format is that instead of containing a list of files and folders which are included, files are wildcard included by default. Therefore, with this new format, your files and folders - added in Explorer or on the command line - will get picked up automatically!

The SDK format .csproj file currently works with the following project types:

  • Class library projects

  • Console apps

  • ASP.NET Core web apps

  • .NET Core projects of any type

To use the new format, create a new .NET Core or .NET Standard project. Because the templates haven't been updated for the full .NET Framework even in Visual Studio 2019, to create a .NET class library choose the .NET Standard Library template, and then edit the project file to target the framework version of your choice (the new style project format can be edited inside Visual Studio - just right click the project in the Solution Explorer and select "Edit project file"). For example:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>
</Project>

Further reading:

reading from app.config file

ConfigurationSettings.AppSettings is deprecated, see here:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings.aspx

That said, it should still work.

Just a suggestion, but have you confirmed that your application configuration is the one your executable is using?

Try attaching a debugger and checking the following value:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

And then opening the configuration file and verifying the section is there as you expected.

How to do SELECT MAX in Django?

Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.

You can give the field name when calling that function:

max_rated_entry = YourModel.objects.latest('rating')
return max_rated_entry.details

Or you can already give that field name in your models meta data:

from django.db import models

class YourModel(models.Model):
    #your class definition
    class Meta:
        get_latest_by = 'rating'

Now you can call 'latest()' without any parameters:

max_rated_entry = YourModel.objects.latest()
return max_rated_entry.details

Invert match with regexp

You can also do this (in python) by using re.split, and splitting based on your regular expression, thus returning all the parts that don't match the regex, splitting based on what doesn't match a regularexpression

Getting value from a cell from a gridview on RowDataBound event

Regarding the index selection style of the columns i suggest you do the following. i ran into this problem but i was going to set values dynamically using an API so what i did was this : keep in mind .CastTo<T> is simply ((T)e.Row.DataItem)

and you have to call DataBind() in order to see the changes in the grid. this way you wont run into issues if you decide to add a column to the grid.

 protected void gvdata_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if(e.Row.RowType == DataControlRowType.DataRow)
            {
                var number = e.Row.DataItem.CastTo<DataRowView>().Row["number"];
                e.Row.DataItem.CastTo<DataRowView>().Row["ActivationDate"] = DateTime.Parse(userData.basic_info.creation_date).ToShortDateString();
                e.Row.DataItem.CastTo<DataRowView>().Row["ExpirationDate"] = DateTime.Parse(userData.basic_info.nearest_exp_date).ToShortDateString();
                e.Row.DataItem.CastTo<DataRowView>().Row["Remainder"] = Convert.ToDecimal(userData.basic_info.credit).ToStringWithSeparator();

                e.Row.DataBind();
            }
        }

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

The fastest, easiest way to do this is to use the --exec argument of git rebase:

git rebase -i -p --exec 'git commit --amend --reset-author --no-edit'

This will create a todo-list that looks like this:

pick ef11092 Blah blah blah
exec git commit --amend --reset-author --no-edit
pick 52d6391 Blah bloh bloo
exec git commit --amend --reset-author --no-edit
pick 30ebbfe Blah bluh bleh
exec git commit --amend --reset-author --no-edit
...

and this will work all automatically, which works when you have hundreds of commits.

Plot a horizontal line using matplotlib

You are correct, I think the [0,len(xs)] is throwing you off. You'll want to reuse the original x-axis variable xs and plot that with another numpy array of the same length that has your variable in it.

annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')

#####horizontal line
horiz_line_data = np.array([40 for i in xrange(len(xs))])
plt.plot(xs, horiz_line_data, 'r--') 
###########plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()

Hopefully that fixes the problem!

SQLite UPSERT / UPDATE OR INSERT

This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.

INSERT INTO players (user_name, age)
  VALUES('steven', 32) 
  ON CONFLICT(user_name) 
  DO UPDATE SET age=excluded.age;

Note: For those having to use a version of SQLite earlier than 3.24.0, please reference this answer below (posted by me, @MarqueIV).

However if you do have the option to upgrade, you are strongly encouraged to do so as unlike my solution, the one posted here achieves the desired behavior in a single statement. Plus you get all the other features, improvements and bug fixes that usually come with a more recent release.

Multidimensional Array [][] vs [,]

double[,] is a 2d array (matrix) while double[][] is an array of arrays (jagged arrays) and the syntax is:

double[][] ServicePoint = new double[10][];

How to check command line parameter in ".bat" file?

In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

... the /I switch, if specified, says to do case insensitive string compares.

it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

IF /I "%1"=="-b" GOTO SPECIFIC

How to make a TextBox accept only alphabetic characters?

        if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
        { 
        }
        else
        {
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
            MessageBox.Show("Enter only Alphabets");


        }

Please Try this

Transferring files over SSH

You need to specify both source and destination, and if you want to copy directories you should look at the -r option.

So to recursively copy /home/user/whatever from remote server to your current directory:

scp -pr user@remoteserver:whatever .

Show hide fragment in android

I may be way way too late but it could help someone in the future.
This answer is a modification to mangu23 answer
I only added a for loop to avoid repetition and to easily add more fragments without boilerplate code.

We first need a list of the fragments that should be displayed

public class MainActivity extends AppCompatActivity{
    //...
    List<Fragment> fragmentList = new ArrayList<>();
}

Then we need to fill it with our fragments

@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    HomeFragment homeFragment = new HomeFragment();
    MessagesFragment messagesFragment = new MessagesFragment();
    UserFragment userFragment = new UserFragment();
    FavoriteFragment favoriteFragment = new FavoriteFragment();
    MapFragment mapFragment = new MapFragment();

    fragmentList.add(homeFragment);
    fragmentList.add(messagesFragment);
    fragmentList.add(userFragment);
    fragmentList.add(favoriteFragment);
    fragmentList.add(mapFragment);
}

And we need a way to know which fragment were selected from the list, so we need getFragmentIndex function

private int getFragmentIndex(Fragment fragment) {
    int index = -1;
    for (int i = 0; i < fragmentList.size(); i++) {
        if (fragment.hashCode() == fragmentList.get(i).hashCode()){
            return i;
        }
    }
    return index;
}

And finally, the displayFragment method will like this:

private void displayFragment(Fragment fragment) {
        int index = getFragmentIndex(fragment);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragment.isAdded()) { // if the fragment is already in container
            transaction.show(fragment);
        } else { // fragment needs to be added to frame container
            transaction.add(R.id.placeholder, fragment);
        }
        // hiding the other fragments
        for (int i = 0; i < fragmentList.size(); i++) {
            if (fragmentList.get(i).isAdded() && i != index) {
                transaction.hide(fragmentList.get(i));
            }
        }
        transaction.commit();
    }

In this way, we can call displayFragment(homeFragment) for example.
This will automatically show the HomeFragment and hide any other fragment in the list.
This solution allows you to append more fragments to the fragmentList without having to repeat the if statements in the old displayFragment version.
I hope someone will find this useful.

c++ boost split string

My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:

-----------test2-------test3

What happened is the machine actually printed this:

test-------test2-------test3\r-------

That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).

Ascii/Hex convert in bash

$> printf "%x%x\n" "'A" "'a"
4161

Relative instead of Absolute paths in Excel VBA

I think the problem is that opening the file without a path will only work if your "current directory" is set correctly.

Try typing "Debug.Print CurDir" in the Immediate Window - that should show the location for your default files as set in Tools...Options.

I'm not sure I'm completely happy with it, perhaps because it's somewhat of a legacy VB command, but you could do this:

ChDir ThisWorkbook.Path

I think I'd prefer to use ThisWorkbook.Path to construct a path to the HTML file. I'm a big fan of the FileSystemObject in the Scripting Runtime (which always seems to be installed), so I'd be happier to do something like this (after setting a reference to Microsoft Scripting Runtime):

Const HTML_FILE_NAME As String = "my_input.html"

With New FileSystemObject
    With .OpenTextFile(.BuildPath(ThisWorkbook.Path, HTML_FILE_NAME), ForReading)
        ' Now we have a TextStream object that we can use to read the file
    End With
End With

How do I convert from int to Long in Java?

use

new Long(your_integer);

or

Long.valueOf(your_integer);

How to add a linked source folder in Android Studio?

The right answer is:

android {
    ....
    ....

    sourceSets {
        main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
    }
}

Furthermore, if your external source directory is not under src/main, you could use a relative path like this:

sourceSets {
    main.java.srcDirs += 'src/main/../../../<YOUR DIRECTORY>'
}

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
{
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
        }
    }
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}

Rails: Can't verify CSRF token authenticity when making a POST request

Since Rails 5 you can also create a new class with ::API instead of ::Base:

class ApiController < ActionController::API
end

What does "<>" mean in Oracle

not equals. See here for a list of conditions

Make $JAVA_HOME easily changable in Ubuntu

You need to put variable definition in the ~/.bashrc file.

From bash man page:

When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist.

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

Many languages have variables, which are of a specific type and have a value. Python does not have variables; it has objects, and you use names to refer to these objects.

In other languages, when you say:

a = 1

then a (typically integer) variable changes its contents to the value 1.

In Python,

a = 1

means “use the name a to refer to the object 1”. You can do the following in an interactive Python session:

>>> type(1)
<type 'int'>

The function type is called with the object 1; since every object knows its type, it's easy for type to find out said type and return it.

Likewise, whenever you define a function

def funcname(param1, param2):

the function receives two objects, and names them param1 and param2, regardless of their types. If you want to make sure the objects received are of a specific type, code your function as if they are of the needed type(s) and catch the exceptions that are thrown if they aren't. The exceptions thrown are typically TypeError (you used an invalid operation) and AttributeError (you tried to access an inexistent member (methods are members too) ).

ASP.NET MVC Razor pass model to layout

Seems like you have modeled your viewmodels a bit wrong if you have this problem.

Personally I would never type a layout page. But if you want to do that you should have a base viewmodel that your other viewmodels inherits from and type your layout to the base viewmodel and you pages to the specific once.

What does 'const static' mean in C and C++?

That line of code can actually appear in several different contexts and alghough it behaves approximately the same, there are small differences.

Namespace Scope

// foo.h
static const int i = 0;

'i' will be visible in every translation unit that includes the header. However, unless you actually use the address of the object (for example. '&i'), I'm pretty sure that the compiler will treat 'i' simply as a type safe 0. Where two more more translation units take the '&i' then the address will be different for each translation unit.

// foo.cc
static const int i = 0;

'i' has internal linkage, and so cannot be referred to from outside of this translation unit. However, again unless you use its address it will most likely be treated as a type-safe 0.

One thing worth pointing out, is that the following declaration:

const int i1 = 0;

is exactly the same as static const int i = 0. A variable in a namespace declared with const and not explicitly declared with extern is implicitly static. If you think about this, it was the intention of the C++ committee to allow const variables to be declared in header files without always needing the static keyword to avoid breaking the ODR.

Class Scope

class A {
public:
  static const int i = 0;
};

In the above example, the standard explicitly specifies that 'i' does not need to be defined if its address is not required. In other words if you only use 'i' as a type-safe 0 then the compiler will not define it. One difference between the class and namespace versions is that the address of 'i' (if used in two ore more translation units) will be the same for the class member. Where the address is used, you must have a definition for it:

// a.h
class A {
public:
  static const int i = 0;
};

// a.cc
#include "a.h"
const int A::i;            // Definition so that we can take the address

Convert UTC Epoch to local date

I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:

var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);

d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)

VBA copy cells value and format

Instead of setting the value directly you can try using copy/paste, so instead of:

Worksheets(2).Cells(a, 15) = Worksheets(1).Cells(i, 3).Value

Try this:

Worksheets(1).Cells(i, 3).Copy
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteFormats
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteValues

To just set the font to bold you can keep your existing assignment and add this:

If Worksheets(1).Cells(i, 3).Font.Bold = True Then
  Worksheets(2).Cells(a, 15).Font.Bold = True
End If

AngularJS - ng-if check string empty value

If by "empty" you mean undefined, it is the way ng-expressions are interpreted. Then, you could use :

<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>

What's NSLocalizedString equivalent in Swift?

Localization with default language:

extension String {
func localized() -> String {
       let defaultLanguage = "en"
       let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
       let bundle = Bundle(path: path!)

       return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
    }
}

jdk7 32 bit windows version to download

As detailed in the Oracle Java SE Support Roadmap

After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive

Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe (64-bit is named jdk-7u80-windows-x64.exe.

Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget to grab the file without signing in.

wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"

Combining two lists and removing duplicates, without removing duplicates in original list

You can bring this down to one single line of code if you use numpy:

a = [1,2,3,4,5,6,7]
b = [2,4,7,8,9,10,11,12]

sorted(np.unique(a+b))

>>> [1,2,3,4,5,6,7,8,9,10,11,12]

mysqld: Can't change dir to data. Server doesn't start

What I did (Windows 10) for a new installation:

  1. Start cmd in admin mode (run as administrator by hitting windows key, typing cmd, right clicking on it and selecting "Run as Administrator"

  2. Change into "MySQL Server X.Y" directory (for me the full path is C:\Program Files\MySQL\MySQL Server 5.7")

  3. using notepad create a my.ini with a mysqld section that points at your data directory

    [mysqld]
    datadir="X:\Your Directory Path and Name"
    
  4. created the directory identified in my.ini above.

  5. change into bin Directory under server directory and execute: mysqld --initialize

  6. Once complete, started the service and it came up fine.

Node.js Logging

Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.

The fix is to change logger.trace to logger.error in the body of errorLogger.

diff to output only the file names

The approach of running diff -qr old/ new/ has one major drawback: it may miss files in newly created directories. E.g. in the example below the file data/pages/playground/playground.txt is not in the output of diff -qr old/ new/ whereas the directory data/pages/playground/ is (search for playground.txt in your browser to quickly compare). I also posted the following solution on Unix & Linux Stack Exchange, but I'll copy it here as well:

To create a list of new or modified files programmatically the best solution I could come up with is using rsync, sort, and uniq:

(rsync -rcn --out-format="%n" old/ new/ && rsync -rcn --out-format="%n" new/ old/) | sort | uniq

Let me explain with this example: we want to compare two dokuwiki releases to see which files were changed and which ones were newly created.

We fetch the tars with wget and extract them into the directories old/ and new/:

wget http://download.dokuwiki.org/src/dokuwiki/dokuwiki-2014-09-29d.tgz
wget http://download.dokuwiki.org/src/dokuwiki/dokuwiki-2014-09-29.tgz
mkdir old && tar xzf dokuwiki-2014-09-29.tgz -C old --strip-components=1
mkdir new && tar xzf dokuwiki-2014-09-29d.tgz -C new --strip-components=1

Running rsync one way might miss newly created files as the comparison of rsync and diff shows here:

rsync -rcn --out-format="%n" old/ new/

yields the following output:

VERSION
doku.php
conf/mime.conf
inc/auth.php
inc/lang/no/lang.php
lib/plugins/acl/remote.php
lib/plugins/authplain/auth.php
lib/plugins/usermanager/admin.php

Running rsync only in one direction misses the newly created files and the other way round would miss deleted files, compare the output of diff:

diff -qr old/ new/

yields the following output:

Files old/VERSION and new/VERSION differ
Files old/conf/mime.conf and new/conf/mime.conf differ
Only in new/data/pages: playground
Files old/doku.php and new/doku.php differ
Files old/inc/auth.php and new/inc/auth.php differ
Files old/inc/lang/no/lang.php and new/inc/lang/no/lang.php differ
Files old/lib/plugins/acl/remote.php and new/lib/plugins/acl/remote.php differ
Files old/lib/plugins/authplain/auth.php and new/lib/plugins/authplain/auth.php differ
Files old/lib/plugins/usermanager/admin.php and new/lib/plugins/usermanager/admin.php differ

Running rsync both ways and sorting the output to remove duplicates reveals that the directory data/pages/playground/ and the file data/pages/playground/playground.txt were missed initially:

(rsync -rcn --out-format="%n" old/ new/ && rsync -rcn --out-format="%n" new/ old/) | sort | uniq

yields the following output:

VERSION
conf/mime.conf
data/pages/playground/
data/pages/playground/playground.txt
doku.php
inc/auth.php
inc/lang/no/lang.php
lib/plugins/acl/remote.php
lib/plugins/authplain/auth.php
lib/plugins/usermanager/admin.php

rsync is run with theses arguments:

  • -r to "recurse into directories",
  • -c to also compare files of identical size and only "skip based on checksum, not mod-time & size",
  • -n to "perform a trial run with no changes made", and
  • --out-format="%n" to "output updates using the specified FORMAT", which is "%n" here for the file name only

The output (list of files) of rsync in both directions is combined and sorted using sort, and this sorted list is then condensed by removing all duplicates with uniq

Python, print all floats to 2 decimal places in output

If what you want is to have the print operation automatically change floats to only show 2 decimal places, consider writing a function to replace 'print'. For instance:

def fp(*args):  # fp means 'floating print'
    tmps = []
    for arg in args:
        if type(arg) is float: arg = round(arg, 2)  # transform only floats
        tmps.append(str(arg))
    print(" ".join(tmps)

Use fp() in place of print ...

fp("PI is", 3.14159) ... instead of ... print "PI is", 3.14159

How do I properly compare strings in C?

Ok a few things: gets is unsafe and should be replaced with fgets(input, sizeof(input), stdin) so that you don't get a buffer overflow.

Next, to compare strings, you must use strcmp, where a return value of 0 indicates that the two strings match. Using the equality operators (ie. !=) compares the address of the two strings, as opposed to the individual chars inside them.

And also note that, while in this example it won't cause a problem, fgets stores the newline character, '\n' in the buffers also; gets() does not. If you compared the user input from fgets() to a string literal such as "abc" it would never match (unless the buffer was too small so that the '\n' wouldn't fit in it).

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

How to change a particular element of a C++ STL vector

I prefer

l.at(4)= -1;

while [4] is your index

The model backing the <Database> context has changed since the database was created

Now it's:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<YourDbContext>(null);
    base.OnModelCreating(modelBuilder);
}

in your YourDbContext.cs file.

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

Clear back stack using fragments

I got this working this way:

public void showHome() {
    getHandler().post(new Runnable() {
        @Override
        public void run() {
            final FragmentManager fm = getSupportFragmentManager();
            while (fm.getBackStackEntryCount() > 0) {
                fm.popBackStackImmediate();
            }
        }
    });
}

Format cell color based on value in another sheet and cell

I'm using Excel 2003 -

The problem with using conditional formatting here is that you can't reference another worksheet or workbook in your conditions. What you can to do is set some column on sheet 1 equal to the appropriate column on sheet 2 (in your example =Sheet2!B6). I used Column F in my example below. Then you can use conditional formatting. Select the cell at Sheet 1, row , column 1 and then go to the conditional formatting menu. Choose "Formula Is" from the drop down and set the condition to "=$F$6=4". Click on the format button and then choose the Patterns tab. Choose the color you want and you're done.

You can use the format painter tool to apply conditional formatting to other cells, but be aware that by default Excel uses absolute references in the conditions. If you want them to be relative you'll need to remove the dollar signs from the condition.

You can have up to 3 conditions applied to a cell (use the add >> button at the bottom of the Conditional formatting dialog) so if the last row is fixed (for example, you know that it will always be row 10) you can use it as a condition to set the background color to none. Assuming that the last value you care about is in row 10 then (still assuming that you've set column F on sheet1 to the corresponding cells on sheet 2) then set the 1st condition to Formula Is =$F$10="" and the pattern to None. Make it the first condition and it will override any following conflicting statements.

How to get the full URL of a Drupal page?

This is what I found to be useful

global $base_root;
$base_root . request_uri();

Returns query strings and it's what's used in core: page_set_cache()

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

Multiple glibc libraries on a single host

It is very possible to have multiple versions of glibc on the same system (we do that every day).

However, you need to know that glibc consists of many pieces (200+ shared libraries) which all must match. One of the pieces is ld-linux.so.2, and it must match libc.so.6, or you'll see the errors you are seeing.

The absolute path to ld-linux.so.2 is hard-coded into the executable at link time, and can not be easily changed after the link is done (Update: can be done with patchelf; see this answer below).

To build an executable that will work with the new glibc, do this:

g++ main.o -o myapp ... \
   -Wl,--rpath=/path/to/newglibc \
   -Wl,--dynamic-linker=/path/to/newglibc/ld-linux.so.2

The -rpath linker option will make the runtime loader search for libraries in /path/to/newglibc (so you wouldn't have to set LD_LIBRARY_PATH before running it), and the -dynamic-linker option will "bake" path to correct ld-linux.so.2 into the application.

If you can't relink the myapp application (e.g. because it is a third-party binary), not all is lost, but it gets trickier. One solution is to set a proper chroot environment for it. Another possibility is to use rtldi and a binary editor. Update: or you can use patchelf.

How do I space out the child elements of a StackPanel?

Another nice approach can be seen here: http://blogs.microsoft.co.il/blogs/eladkatz/archive/2011/05/29/what-is-the-easiest-way-to-set-spacing-between-items-in-stackpanel.aspx Link is broken -> this is webarchive of this link.

It shows how to create an attached behavior, so that syntax like this would work:

<StackPanel local:MarginSetter.Margin="5">
   <TextBox Text="hello" />
   <Button Content="hello" />
   <Button Content="hello" />
</StackPanel>

This is the easiest & fastest way to set Margin to several children of a panel, even if they are not of the same type. (I.e. Buttons, TextBoxes, ComboBoxes, etc.)

Display Adobe pdf inside a div

You cannot, and here is the simple answer.

Every media asset poured into the browser is identified by a mime type name. A browser then makes processing determinations upon that mime type name. If it is image/gif or image/jpeg the browser processes the asset as an image. If it is text/css or text/javascript it is processed as a code asset unless the asset is addressed independent of HTML. PDF is identified as application/pdf. When browsers see application/pdf they immediately switch processing to a plugin software capable of processing that media type. If you attempt to push media of type application/pdf into a div the browser will likely throw an error to the user. Typically files of type application/pdf are linked to directly so that the processing software an intercept the request and process the media independent of the browser.

How to convert an enum type variable to a string?

For C99 there is P99_DECLARE_ENUM in P99 that lets you simply declare enum like this:

P99_DECLARE_ENUM(color, red, green, blue);

and then use color_getname(A) to obtain a string with the color name.

Right pad a string with variable number of spaces

This is based on Jim's answer,

SELECT
    @field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
   ,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad

Advantages

  • More Straight Forward
  • Slightly Cleaner (IMO)
  • Faster (Maybe?)
  • Easily Modified to either double pad for displaying in non-fixed width fonts or split padding left and right to center

Disadvantages

  • Doesn't handle LEN(@field_text) > @pad_length

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Not really answer to the question, but one-liners for foldl and foldr:

a = [8,3,4]

## Foldl
reduce(lambda x,y: x**y, a)
#68719476736

## Foldr
reduce(lambda x,y: y**x, a[::-1])
#14134776518227074636666380005943348126619871175004951664972849610340958208L

Git Commit Messages: 50/72 Formatting

Is the maximum recommended title length really 50?

I have believed this for years, but as I just noticed the documentation of "git commit" actually states

$ git help commit | grep -C 1 50
      Though not required, it’s a good idea to begin the commit message with
      a single short (less than 50 character) line summarizing the change,
      followed by a blank line and then a more thorough description. The text

$  git version
git version 2.11.0

One could argue that "less then 50" can only mean "no longer than 49".

HTML table headers always visible at top of window when viewing a large table

It's frustrating that what works great in one browser doesn't work in others. The following works in Firefox, but not in Chrome or IE:

<table width="80%">

 <thead>

 <tr>
  <th>Column 1</th>
  <th>Column 2</th>
  <th>Column 3</th>
 </tr>

 </thead>

 <tbody style="height:50px; overflow:auto">

  <tr>
    <td>Cell A1</td>
    <td>Cell B1</td>
    <td>Cell C1</td>
  </tr>

  <tr>
    <td>Cell A2</td>
    <td>Cell B2</td>
    <td>Cell C2</td>
  </tr>

  <tr>
    <td>Cell A3</td>
    <td>Cell B3</td>
    <td>Cell C3</td>
  </tr>

 </tbody>

</table>

Get Android Device Name

Try this code. You get android device name.

public static String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(manufacturer)) {
        return model;
    }
    return manufacturer + " " + model;
}

How to use if-else logic in Java 8 stream forEach

I think it's possible in Java 9:

animalMap.entrySet().stream()
                .forEach(
                        pair -> Optional.ofNullable(pair.getValue())
                                .ifPresentOrElse(v -> myMap.put(pair.getKey(), v), v -> myList.add(pair.getKey())))
                );

Need the ifPresentOrElse for it to work though. (I think a for loop looks better.)

What's your most controversial programming opinion?

JavaScript is a "messy" language but god help me I love it.

Heap space out of memory

If you are using a lot of memory and facing memory leaks, then you might want to check if you are using a large number of ArrayLists or HashMaps with many elements each.

An ArrayList is implemented as a dynamic array. The source code from Sun/Oracle shows that when a new element is inserted into a full ArrayList, a new array of 1.5 times the size of the original array is created, and the elements copied over. What this means is that you could be wasting up to 50% of the space in each ArrayList you use, unless you call its trimToSize method. Or better still, if you know the number of elements you are going to insert before hand, then call the constructor with the initial capacity as its argument.

I did not examine the source code for HashMap very carefully, but at a first glance it appears that the array length in each HashMap must be a power of two, making it another implementation of a dynamic array. Note that HashSet is essentially a wrapper around HashMap.

How to sort Map values by key in Java?

Just use TreeMap

new TreeMap<String, String>(unsortMap);

Be aware that the TreeMap is sorted according to the natural ordering of its 'keys'

How can I use ":" as an AWK field separator?

If you want to do it programatically, you can use the FS variable:

echo "1: " | awk 'BEGIN { FS=":" } /1/ { print $1 }'

Note that if you change it in the main loop rather than the BEGIN loop, it takes affect for the next line read in, since the current line has already been split.

Very simple log4j2 XML configuration file using Console and File appender

Here is my simplistic log4j2.xml that prints to console and writes to a daily rolling file:

// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);


// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">target/cucumber-logs</Property>
        <Property name="rollingFileName">cucumber</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
        </Console>
        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <OnStartupTriggeringPolicy />
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

TimeBasedTriggeringPolicy

interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.

modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.

Source: https://logging.apache.org/log4j/2.x/manual/appenders.html

Output:

[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000

A new log file will be created daily with previous day automatically renamed to:

cucumber_yyyy-MM-dd.log

In a Maven project, you would put the log4j2.xml in src/main/resources or src/test/resources.

How to add text at the end of each line in Vim?

This will do it to every line in the file:

:%s/$/,/

If you want to do a subset of lines instead of the whole file, you can specify them in place of the %.

One way is to do a visual select and then type the :. It will fill in :'<,'> for you, then you type the rest of it (Notice you only need to add s/$/,/)

:'<,'>s/$/,/

C subscripted value is neither array nor pointer nor vector when assigning an array element value

the second subscript operator is invalid here. You passed a int * pointer into function, which is a 1-d array. So only one subscript operator can be used on it.

Solution : you can pass int ** pointer into funciton

Using Linq select list inside list

list.Where(m => m.application == "applicationName" && 
           m.users.Any(u => u.surname=="surname"));

if you want to filter users as TimSchmelter commented, you can use

list.Where(m => m.application == "applicationName")
    .Select(m => new Model
    {
        application = m.application,
        users = m.users.Where(u => u.surname=="surname").ToList()
    });

How to close a GUI when I push a JButton?

By using System.exit(0); you would close the entire process. Is that what you wanted or did you intend to close only the GUI window and allow the process to continue running?

The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked:

this.dispose();

If you are using the NetBeans GUI designer, the easiest way to add this actionListener is to enter the GUI editor window and double click the JButton component. Doing this will automatically create an actionListener and actionEvent, which can be modified manually by you.

Effective method to hide email from spam bots

There is a open licence PHP script that outputs javascript which encodes the mail: http://www.maurits.vdschee.nl/php_hide_email/. You can then easily call the php function with the specific mail as an argument.

Fatal error: Class 'ZipArchive' not found in

For the ZipArchive class to be present, PHP needs to have the zip extension installed.

See this page for installation instructions (both Linux and Windows).

How to create a CPU spike with a bash command

I went through the Internet to find something like it and found this very handy cpu hammer script.

#!/bin/sh

# unixfoo.blogspot.com

if [ $1 ]; then
    NUM_PROC=$1
else
    NUM_PROC=10
fi

for i in `seq 0 $((NUM_PROC-1))`; do
    awk 'BEGIN {for(i=0;i<10000;i++)for(j=0;j<10000;j++);}' &
done

disable all form elements inside div

If your form inside div simply contains form inputting elements, then this simple query will disable every element inside form tag:

<div id="myForm">
    <form action="">
    ...
    </form>
</div>

However, it will also disable other than inputting elements in form, as it's effects will only be seen on input type elements, therefore suitable majorly for every type of forms!

$('#myForm *').attr('disabled','disabled');

GitHub: How to make a fork of public repository private?

Just go to https://github.com/new/import .

GitHub Import

In the section "Your old repository's clone URL" paste the repo URL you want and in "Privacy" select Private.

SQL Server: Make all UPPER case to Proper Case/Title Case

If you can enable the CLR in SQL Server (requires 2005 or later) then you could create a CLR function that uses the TextInfo.ToTitleCase built-in function which would allow you to create a culture-aware way of doing this in only a few lines of code.

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

C++ Structure Initialization

I found this way of doing it for global variables, that does not require to modify the original structure definition :

struct address {
             int street_no;
             char *street_name;
             char *city;
             char *prov;
             char *postal_code;
           };

then declare the variable of a new type inherited from the original struct type and use the constructor for fields initialisation :

struct temp_address : address { temp_address() { 
    city = "Hamilton"; 
    prov = "Ontario"; 
} } temp_address;

Not quite as elegant as the C style though ...

For a local variable it requires an additional memset(this, 0, sizeof(*this)) at the beginning of the constructor, so it's clearly not worse it and @gui13 's answer is more appropriate.

(Note that 'temp_address' is a variable of type 'temp_address', however this new type inherit from 'address' and can be used in every place where 'address' is expected, so it's OK.)

How to use jQuery Plugin with Angular 4?

ngOnInit() {
     const $ = window["$"];
     $('.flexslider').flexslider({
        animation: 'slide',
        start: function (slider) {
          $('body').removeClass('loading')
        }
     })
}

Detect enter press in JTextField

Add an event for KeyPressed.

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
  if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
      // Enter was pressed. Your code goes here.
   }
} 

How do you get total amount of RAM the computer has?

/*The simplest way to get/display total physical memory in VB.net (Tested)

public sub get_total_physical_mem()

    dim total_physical_memory as integer

    total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))
    MsgBox("Total Physical Memory" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + "Mb" )
end sub
*/


//The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)

public void get_total_physical_mem()
{
    int total_physical_memory = 0;

    total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) /  (1024 * 1024));
    Interaction.MsgBox("Total Physical Memory" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + "Mb");
}

HttpClient does not exist in .net 4.0: what can I do?

read this...

Portable HttpClient for .NET Framework and Windows Phone

see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

Spring Security redirect to previous page after successful login

You can use a Custom SuccessHandler extending SimpleUrlAuthenticationSuccessHandler for redirecting users to different URLs when login according to their assigned roles.

CustomSuccessHandler class provides custom redirect functionality:

package com.mycompany.uomrmsweb.configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        String url="";

        Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();

        List<String> roles = new ArrayList<String>();

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isStaff(roles)) {
            url = "/staff";
        } else if (isAdmin(roles)) {
            url = "/admin";
        } else if (isStudent(roles)) {
            url = "/student";
        }else if (isUser(roles)) {
            url = "/home";
        } else {
            url="/Access_Denied";
        }

        return url;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

    private boolean isUser(List<String> roles) {
        if (roles.contains("ROLE_USER")) {
            return true;
        }
        return false;
    }

    private boolean isStudent(List<String> roles) {
        if (roles.contains("ROLE_Student")) {
            return true;
        }
        return false;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
            return true;
        }
        return false;
    }

    private boolean isStaff(List<String> roles) {
        if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
            return true;
        }
        return false;
    }
}

Extending Spring SimpleUrlAuthenticationSuccessHandler class and overriding handle() method which simply invokes a redirect using configured RedirectStrategy [default in this case] with the URL returned by the user defined determineTargetUrl() method. This method extracts the Roles of currently logged in user from Authentication object and then construct appropriate URL based on there roles. Finally RedirectStrategy , which is responsible for all redirections within Spring Security framework , redirects the request to specified URL.

Registering CustomSuccessHandler using SecurityConfiguration class:

package com.mycompany.uomrmsweb.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/", "/home").access("hasRole('USER')")
        .antMatchers("/admin/**").access("hasRole('SystemAdmin') or hasRole('ExaminationsStaff')")
        .antMatchers("/staff/**").access("hasRole('AcademicStaff') or hasRole('UniversityAdmin')")
        .antMatchers("/student/**").access("hasRole('Student')")  
                    .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
        .usernameParameter("username").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }
}

successHandler is the class responsible for eventual redirection based on any custom logic, which in this case will be to redirect the user [to student/admin/staff ] based on his role [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff].

Giving UIView rounded corners

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 50, 200, 200)];

view.layer.backgroundColor = [UIColor whiteColor].CGColor;
view.layer.cornerRadius = 20.0;
view.layer.frame = CGRectInset(v.layer.frame, 20, 20);

view.layer.shadowOffset = CGSizeMake(1, 0);
view.layer.shadowColor = [[UIColor blackColor] CGColor];
view.layer.shadowRadius = 5;
view.layer.shadowOpacity = .25;

[self.view addSubview:view];
[view release];

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

svn : how to create a branch from certain revision of trunk

Try below one:

svn copy http://svn.example.com/repos/calc/trunk@rev-no 
       http://svn.example.com/repos/calc/branches/my-calc-branch 
  -m "Creating a private branch of /calc/trunk."  --parents

No slash "\" between the svn URLs.

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Self-Signed Certificate Authorities pip / conda

After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:

NEVER disable all SSL verification!

This creates a bad security culture. Don't be that person.

tl;dr

pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify

# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt

But where do we get ca-bundle.crt?


Get an up to date CA Bundle

cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox

https://curl.haxx.se/docs/caextract.html

I recommend you open up this cacert.pem file in a text editor as we will need to add our self-signed CA to this file.

Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:

----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----

https://support.ssl.com/Knowledgebase/Article/View/19/0/der-vs-crt-vs-cer-vs-pem-certificates-and-how-to-convert-them


Getting our Self Signed Certificate

Below are a few options on how to get our self signed certificate:

  • Via OpenSSL CLI
  • Via Browser
  • Via Python Scripting

Get our Self-Signed Certificate by OpenSSL CLI

https://unix.stackexchange.com/questions/451207/how-to-trust-self-signed-certificate-in-curl-command-line/468360#468360

echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem

Get our Self-Signed Certificate Authority via Browser

Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.

Copy the contents of this exported file and paste it at the end of your cacerts.pem file.

For consistency rename this file cacerts.pem --> ca-bundle.crt and place it somewhere easy like:

# Windows
%USERPROFILE%\certs\ca-bundle.crt

# or *nix
$HOME/certs/cabundle.crt

Get our Self-Signed Certificate Authority via Python

Thanks to all the brilliant answers in:

How to get response SSL certificate from requests in python?

I have put together the following to attempt to take it a step further.

https://github.com/neozenith/get-ca-py


Finally

Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.

pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt

OR

pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt

THEN

pip config list
conda config --show ssl_verify

# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'

References

'NOT NULL constraint failed' after adding to models.py

if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.

Spring default behavior for lazy-init

For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:

In the configuration class:

@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {

    @Bean
    @Lazy
    public Demo demo() {
        return new Demo();
    }
}

For component scanning and auto-wiring:

@Component
@Lazy
public class Demo {
    ....
    ....
}

@Component
public class B {

    @Autowired
    @Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
    private Demo demo;

    .......
 }

comma separated string of selected values in mysql

Try this

SELECT CONCAT('"',GROUP_CONCAT(id),'"') FROM table_level 
where parent_id=4 group by parent_id;

Result will be

 "5,6,9,10,12,14,15,17,18,779"

Sum columns with null values in oracle

Without group by SUM(NVL(regular, 0) + NVL(overtime, 0)) will thrown an error and to avoid this we can simply use NVL(regular, 0) + NVL(overtime, 0)

Android Studio Gradle Already disposed Module

I figured out this problem by:

  1. ./gradlew clean
  2. Restart Android Studio

Where does this come from: -*- coding: utf-8 -*-

# -*- coding: utf-8 -*- is a Python 2 thing. In Python 3+, the default encoding of source files is already UTF-8 and that line is useless.

See: Should I use encoding declaration in Python 3?

pyupgrade is a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object.

How to remove all numbers from string?

Regex

   $words = preg_replace('#[0-9 ]*#', '', $words);

Log4net rolling daily filename with date in the file name

I've tried all the answers, but there was always something missing and not functioning as expected for me.

Then I experimented a bit with the hints given in each answer and was successful with the following setting:

<appender name="RollingActivityLog" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="C:\temp\LOG4NET_Sample_Activity.log" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <staticLogFileName value="false" />
  <preserveLogFileNameExtension value="true" />
  <datePattern value="-yyyyMMdd" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level - %message%newline" />
  </layout>
</appender>

The issue with other combinations of parameters was that the latest file didn't have the time pattern, or that the time pattern was appended as .log20171215 which created a new file time (and a new file type!) each day - or both issues appeared.

Now with this setting you are getting files like this one:

LOG4NET_Sample_Activity-20171215.log

which is what I wanted.


To summarize:

  • Don't put the date pattern in the <file value=... attribute, just define it in the datePattern.

  • Make sure you have the preserveLogFileNameExtension value attribute set to true.

  • Make sure you have the staticLogFileName value set to false.

  • Set the rollingStyle attribute value to Date.

Php, wait 5 seconds before executing an action

i use this

    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            // Code Here
            $i = -1;
        }
    }

you can use

function WaitForSec($sec){
    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            return 1;
            $i = -1;
        }
    }
}

and run code =>

WaitForSec(your_sec);

Example :

WaitForSec(5);

OR you can use sleep

Example :

sleep(5);

Script Tag - async & defer

Faced same kind of problem and now clearly understood how both will works.Hope this reference link will be helpful...

Async

When you add the async attribute to your script tag, the fol­low­ing will happen.

<script src="myfile1.js" async></script>
<script src="myfile2.js" async></script>
  1. Make par­al­lel requests to fetch the files.
  2. Con­tinue pars­ing the doc­u­ment as if it was never interrupted.
  3. Exe­cute the indi­vid­ual scripts the moment the files are downloaded.

Defer

Defer is very sim­i­lar to async with one major dif­fer­er­ence. Here’s what hap­pens when a browser encoun­ters a script with the defer attribute.

<script src="myfile1.js" defer></script>
<script src="myfile2.js" defer></script>
  1. Make par­al­lel requests to fetch the indi­vid­ual files.
  2. Con­tinue pars­ing the doc­u­ment as if it was never interrupted.
  3. Fin­ish pars­ing the doc­u­ment even if the script files have downloaded.
  4. Exe­cute each script in the order they were encoun­tered in the document.

Reference :Difference between Async and Defer

Adding quotes to a string in VBScript

I usually do this:

Const Q = """"

Dim a, g
a = "xyz"  
g = "abcd " & Q & a & Q

If you need to wrap strings in quotes more often in your code and find the above approach noisy or unreadable, you can also wrap it in a function:

a = "xyz"  
g = "abcd " & Q(a)

Function Q(s)
  Q = """" & s & """"
End Function

c# foreach (property in object)... Is there a simple way of doing this?

You can loop through all non-indexed properties of an object like this:

var s = new MyObject();
foreach (var p in s.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) {
    Console.WriteLine(p.GetValue(s, null));
}

Since GetProperties() returns indexers as well as simple properties, you need an additional filter before calling GetValue to know that it is safe to pass null as the second parameter.

You may need to modify the filter further in order to weed out write-only and otherwise inaccessible properties.

How to send an email with Python?

I'd like to help you with sending emails by advising the yagmail package (I'm the maintainer, sorry for the advertising, but I feel it can really help!).

The whole code for you would be:

import yagmail
yag = yagmail.SMTP(FROM, 'pass')
yag.send(TO, SUBJECT, TEXT)

Note that I provide defaults for all arguments, for example if you want to send to yourself, you can omit TO, if you don't want a subject, you can omit it also.

Furthermore, the goal is also to make it really easy to attach html code or images (and other files).

Where you put contents you can do something like:

contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',
            'You can also find an audio file attached.', '/local/path/song.mp3']

Wow, how easy it is to send attachments! This would take like 20 lines without yagmail ;)

Also, if you set it up once, you'll never have to enter the password again (and have it safely stored). In your case you can do something like:

import yagmail
yagmail.SMTP().send(contents = contents)

which is much more concise!

I'd invite you to have a look at the github or install it directly with pip install yagmail.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think that it's around 2GB. While the answer by Pete Kirkham is very interesting and probably holds truth, I have allocated upwards of 3GB without error, however it did not use 3GB in practice. That might explain why you were able to allocate 2.5 GB on 2GB RAM with no swap space. In practice, it wasn't using 2.5GB.

Getting the WordPress Post ID of current post

You can get id through below Code...Its Simple and Fast

 <?php $post_id = get_the_ID();
   echo $post_id;
   ?>

Seaborn plots not showing up

I come to this question quite regularly and it always takes me a while to find what I search:

import seaborn as sns
import matplotlib.pyplot as plt

plt.show()  # <--- This is what you are looking for

Please note: In Python 2, you can also use sns.plt.show(), but not in Python 3.

Complete Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Visualize C_0.99 for all languages except the 10 with most characters."""

import seaborn as sns
import matplotlib.pyplot as plt

l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
     55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
     58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
     61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
     62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
     65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
     67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
     70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
     74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
     80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
     87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
     92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
     109, 110, 110, 113, 113, 115, 116, 118, 119, 121]

sns.distplot(l, kde=True, rug=False)

plt.show()

Gives

enter image description here

How to get an object's property's value by property name?

Here is an alternative way to get an object's property value:

write-host $(get-something).SomeProp

PHP - Get bool to echo false when false

var_export provides the desired functionality.

This will always print a value rather than printing nothing for null or false. var_export prints a PHP representation of the argument it's passed, the output could be copy/pasted back into PHP.

var_export(true);    // true
var_export(false);   // false
var_export(1);       // 1
var_export(0);       // 0
var_export(null);    // NULL
var_export('true');  // 'true'   <-- note the quotes
var_export('false'); // 'false'

If you want to print strings "true" or "false", you can cast to a boolean as below, but beware of the peculiarities:

var_export((bool) true);   // true
var_export((bool) false);  // false
var_export((bool) 1);      // true
var_export((bool) 0);      // false
var_export((bool) '');     // false
var_export((bool) 'true'); // true
var_export((bool) null);   // false

// !! CAREFUL WITH CASTING !!
var_export((bool) 'false'); // true
var_export((bool) '0');     // false

Array inside a JavaScript Object?

In regards to multiple arrays in an object. For instance, you want to record modules for different courses

var course = {
    InfoTech:["Information Systems","Internet Programming","Software Eng"],
    BusComm:["Commercial Law","Accounting","Financial Mng"],
    Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);

How to customize Bootstrap 3 tab color

On the selector .nav-tabs > li > a:hover add !important to the background-color.

_x000D_
_x000D_
.nav-tabs{_x000D_
  background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
    background-color:#303136;_x000D_
    color:#fff;_x000D_
    padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
  border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
  background-color: #303136 !important;_x000D_
    border: medium none;_x000D_
    border-radius: 0;_x000D_
    color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
    <li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
    <li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
    <div id="search" class="tab-pane fade in active">_x000D_
        Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
        butcher voluptate nisi qui._x000D_
    </div>_x000D_
    <div id="advanced" class="tab-pane fade">_x000D_
        Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Detect click outside element

I am using this package : https://www.npmjs.com/package/vue-click-outside

It works fine for me

HTML :

<div class="__card-content" v-click-outside="hide" v-if="cardContentVisible">
    <div class="card-header">
        <input class="subject-input" placeholder="Subject" name=""/>
    </div>
    <div class="card-body">
        <textarea class="conversation-textarea" placeholder="Start a conversation"></textarea>
    </div>
</div>

My script codes :

import ClickOutside from 'vue-click-outside'
export default
{
    data(){
        return {
            cardContentVisible:false
        }
    },
    created()
    {
    },
    methods:
        {
            openCardContent()
            {
                this.cardContentVisible = true;
            }, hide () {
            this.cardContentVisible = false
                }
        },
    directives: {
            ClickOutside
    }
}

Change location of log4j.properties

In Eclipse you can set a VM argument to:

-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}

Node.js on multi-core machines

You may run your node.js application on multiple cores by using the cluster module on combination with os module which may be used to detect how many CPUs you have.

For example let's imagine that you have a server module that runs simple http server on the backend and you want to run it for several CPUs:

_x000D_
_x000D_
// Dependencies._x000D_
const server = require('./lib/server'); // This is our custom server module._x000D_
const cluster = require('cluster');_x000D_
const os = require('os');_x000D_
_x000D_
 // If we're on the master thread start the forks._x000D_
if (cluster.isMaster) {_x000D_
  // Fork the process._x000D_
  for (let i = 0; i < os.cpus().length; i++) {_x000D_
    cluster.fork();_x000D_
  }_x000D_
} else {_x000D_
  // If we're not on the master thread start the server._x000D_
  server.init();_x000D_
}
_x000D_
_x000D_
_x000D_

Why java.security.NoSuchProviderException No such provider: BC?

Im not very familiar with the Android sdk, but it seems that the android-sdk comes with the BouncyCastle provider already added to the security.

What you will have to do in the PC environment is just add it manually,

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

if you have access to the policy file, just add an entry like:

security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider 

Notice the .5 it is equal to a sequential number of the already added providers.

How To Upload Files on GitHub

If you want to upload a folder or a file to Github

1- Create a repository on the Github

2- make: git remote add origin "Your Link" as it is described on the Github

3- Then use git push -u origin master.

4- You have to enter your username and Password.

5- After the authentication, the transfer will start

WinForms DataGridView font size

I think it's easiest:

First set any Label as you like (Italic, Bold, Size etc.) And:

yourDataGridView.Font = anyLabel.Font;

Git with SSH on Windows

If Git for windows is installed, run Git Bash shell:

  bash

You can run ssh from within Bash shell (Bash is aware of the path of ssh)

To know the exact path of ssh, run "where" command in Bash shell:

  $ where ssh

you get:

  c:\Program Files\Git\usr\bin\ssh.exe

How to use Macro argument as string literal?

#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian

What is a monad?

[Disclaimer: I am still trying to fully grok monads. The following is just what I have understood so far. If it’s wrong, hopefully someone knowledgeable will call me on the carpet.]

Arnar wrote:

Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.

That’s precisely it. The idea goes like this:

  1. You take some kind of value and wrap it with some additional information. Just like the value is of a certain kind (eg. an integer or a string), so the additional information is of a certain kind.

    E.g., that extra information might be a Maybe or an IO.

  2. Then you have some operators that allow you to operate on the wrapped data while carrying along that additional information. These operators use the additional information to decide how to change the behaviour of the operation on the wrapped value.

    E.g., a Maybe Int can be a Just Int or Nothing. Now, if you add a Maybe Int to a Maybe Int, the operator will check to see if they are both Just Ints inside, and if so, will unwrap the Ints, pass them the addition operator, re-wrap the resulting Int into a new Just Int (which is a valid Maybe Int), and thus return a Maybe Int. But if one of them was a Nothing inside, this operator will just immediately return Nothing, which again is a valid Maybe Int. That way, you can pretend that your Maybe Ints are just normal numbers and perform regular math on them. If you were to get a Nothing, your equations will still produce the right result – without you having to litter checks for Nothing everywhere.

But the example is just what happens for Maybe. If the extra information was an IO, then that special operator defined for IOs would be called instead, and it could do something totally different before performing the addition. (OK, adding two IO Ints together is probably nonsensical – I’m not sure yet.) (Also, if you paid attention to the Maybe example, you have noticed that “wrapping a value with extra stuff” is not always correct. But it’s hard to be exact, correct and precise without being inscrutable.)

Basically, “monad” roughly means “pattern”. But instead of a book full of informally explained and specifically named Patterns, you now have a language construct – syntax and all – that allows you to declare new patterns as things in your program. (The imprecision here is all the patterns have to follow a particular form, so a monad is not quite as generic as a pattern. But I think that’s the closest term that most people know and understand.)

And that is why people find monads so confusing: because they are such a generic concept. To ask what makes something a monad is similarly vague as to ask what makes something a pattern.

But think of the implications of having syntactic support in the language for the idea of a pattern: instead of having to read the Gang of Four book and memorise the construction of a particular pattern, you just write code that implements this pattern in an agnostic, generic way once and then you are done! You can then reuse this pattern, like Visitor or Strategy or Façade or whatever, just by decorating the operations in your code with it, without having to re-implement it over and over!

So that is why people who understand monads find them so useful: it’s not some ivory tower concept that intellectual snobs pride themselves on understanding (OK, that too of course, teehee), but actually makes code simpler.

How can I store the result of a system command in a Perl variable?

Using backtick or qx helps, thanks everybody for the answers. However, I found that if you use backtick or qx, the output contains trailing newline and I need to remove that. So I used chomp.

chomp($host = `hostname`);
chomp($domain = `domainname`);
$fqdn = $host.".".$domain;

More information here: http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html

Batch program to to check if process exists

TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:

@echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
  specific commands to perform if the process was not found
)
exit

There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:

@echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
  specific commands to perform if the process
  was not terminated because it was not found
)
exit

Could not load file or assembly Exception from HRESULT: 0x80131040

What worked for me immediately was:

  • I located bin folder (picture below shows).

  • moved all dll in other folder for safety.

  • then rebuild ed the project.

  • after solved the issue, deleted old dll files.

Open file location

Check if Cell value exists in Column, and then get the value of the NEXT Cell

Use a different function, like VLOOKUP:

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", VLOOKUP(A1,B:C,2,FALSE))

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

POSIX 7 quotes

POSIX 7 specifies both at http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html:

CLOCK_REALTIME:

This clock represents the clock measuring real time for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch.

CLOCK_MONOTONIC (optional feature):

For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime().

clock_settime() gives an important hint: POSIX systems are able to arbitrarily change CLOCK_REALITME with it, so don't rely on it flowing neither continuously nor forward. NTP could be implemented using clock_settime(), and could only affect CLOCK_REALITME.

The Linux kernel implementation seems to take boot time as the epoch for CLOCK_MONOTONIC: Starting point for CLOCK_MONOTONIC

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The IIS inbound rules as shown in the question DO work. I had to clear the browser cache and add the following line in the top of my <head> section of the index.html page:

<base href="/myApplication/app/" />

This is because I have more than one application in localhost and so requests to other partials were being taken to localhost/app/view1 instead of localhost/myApplication/app/view1

Hopefully this helps someone!

mongod command not recognized when trying to connect to a mongodb server

Are you sure that you have specified the correct paths?

You need to be in the right directory, i.e.

C:\Program Files\MongoDB\bin

and the path you are installing into needs to be the correct one

i.e.

mongod --dbpath 
C:\Users\Name\Documents\myWebsites\nodetest1

A folder named "data" must also exist in your project folder.

I got the same error and this worked for me.

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

I had the same issue, and spent quite a bit of time trying to track down the solution. I had Anonymous Authentication set up at two different levels with two different users. Make sure that you're not overwriting your set up at a lower level.

What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for.

The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

how to get domain name from URL

A little late to the party, but:

_x000D_
_x000D_
const urls = [_x000D_
  'www.abc.au.uk',_x000D_
  'https://github.com',_x000D_
  'http://github.ca',_x000D_
  'https://www.google.ru',_x000D_
  'http://www.google.co.uk',_x000D_
  'www.yandex.com',_x000D_
  'yandex.ru',_x000D_
  'yandex'_x000D_
]_x000D_
_x000D_
urls.forEach(url => console.log(url.replace(/.+\/\/|www.|\..+/g, '')))
_x000D_
_x000D_
_x000D_

How do I link a JavaScript file to a HTML file?

Below you have some VALID html5 example document. The type attribute in script tag is not mandatory in HTML5.

You use jquery by $ charater. Put libraries (like jquery) in <head> tag - but your script put allways at the bottom of document (<body> tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src attribute in bottom script tag to include you script file instead of putting direct js code like above.

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Example</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <div>Im the content</div>_x000D_
_x000D_
    <script>_x000D_
        alert( $('div').text() ); // show message with div content_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

See this http://blog.stevenlevithan.com/archives/date-time-format

you can do anything with date.

file : http://stevenlevithan.com/assets/misc/date.format.js

add this to your html code using script tag and to use you can use it as :

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

Create a dictionary with list comprehension

In Python 2.7, it goes like:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

Zip them!

How to send control+c from a bash script?

ctrl+c and kill -INT <pid> are not exactly the same, to emulate ctrl+c we need to first understand the difference.

kill -INT <pid> will send the INT signal to a given process (found with its pid).

ctrl+c is mapped to the intr special character which when received by the terminal should send INT to the foreground process group of that terminal. You can emulate that by targetting the group of your given <pid>. It can be done by prepending a - before the signal in the kill command. Hence the command you want is:

kill -INT -<pid>

You can test it pretty easily with a script:

#!/usr/bin/env ruby

fork {
    trap(:INT) {
        puts 'signal received in child!'
        exit
    }
    sleep 1_000
}

puts "run `kill -INT -#{Process.pid}` in any other terminal window."
Process.wait

Sources:

PostgreSQL: Why psql can't connect to server?

Solved it! Although I don't know what happened, but I just deleted all the stuff and reinstalled it. This is the command I used to delete it sudo apt-get --purge remove postgresql\* and dpkg -l | grep postgres. The latter one is to find all the packets in case it is not clean.

When to use static classes in C#

I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.

I rarely use static classes methods for the same reasons why I rarely use the singleton "design pattern".

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Best /Fastest way to read an Excel Sheet into a DataTable?

This is the way to read from excel oledb

try
{
    System.Data.OleDb.OleDbConnection MyConnection;
    System.Data.DataSet DtSet;
    System.Data.OleDb.OleDbDataAdapter MyCommand;
    string strHeader7 = "";
    strHeader7 = (hdr7) ? "Yes" : "No";
    MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fn + ";Extended Properties=\"Excel 12.0;HDR=" + strHeader7 + ";IMEX=1\"");
    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + wks + "$]", MyConnection);
    MyCommand.TableMappings.Add("Table", "TestTable");
    DtSet = new System.Data.DataSet();
    MyCommand.Fill(DtSet);
    dgv7.DataSource = DtSet.Tables[0];
    MyConnection.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

How to compare dates in datetime fields in Postgresql?

@Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:

SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);

C# Parsing JSON array of objects

string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";

                  string jsonData = jsonData1.Replace("\"", "");


                  DataSet ds = new DataSet();
                  DataTable dt = new DataTable();
       JArray array= JArray.Parse(jsonData);

couldnot parse , if the vaule is a string..

look at name : meals , if name : 1 then it will parse

How to create a Calendar table for 100 years in Sql

This will create you the result in lightning fast.

select top 100000  identity (int ,1,1) as Sequence into Tally from sysobjects , sys.all_columns


select dateadd(dd,sequence,-1) Dates into CalenderTable from tally


delete from CalenderTable where dates < -- mention the mindate you need
delete from CalenderTable where dates >  -- mention the max date you need

Step 1 : Create a sequence table

Step 2 : Use the sequence table to generate the desired dates

Step 3 : Delete unwanted dates

Bash tool to get nth line from a file

To print nth line using sed with a variable as line number:

a=4
sed -e $a'q:d' file

Here the '-e' flag is for adding script to command to be executed.