Programs & Examples On #Test first

How to test Spring Data repositories?

With JUnit5 and @DataJpaTest test will look like (kotlin code):

@DataJpaTest
@ExtendWith(value = [SpringExtension::class])
class ActivityJpaTest {

    @Autowired
    lateinit var entityManager: TestEntityManager

    @Autowired
    lateinit var myEntityRepository: MyEntityRepository

    @Test
    fun shouldSaveEntity() {
        // when
        val savedEntity = myEntityRepository.save(MyEntity(1, "test")

        // then 
        Assertions.assertNotNull(entityManager.find(MyEntity::class.java, savedEntity.id))
    }
}

You could use TestEntityManager from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager package in order to validate entity state.

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

Java constructor/method with optional parameters?

You can simulate it with using varargs, however then you should check it for too many arguments.

public void foo(int param1, int ... param2)
{
   int param2_
   if(param2.length == 0)
      param2_ = 2
   else if(para2.length == 1)
      param2_ = param2[0]
   else
      throw new TooManyArgumentsException(); // user provided too many arguments,

   // rest of the code
}

However this approach is not a good way of doing this, therefore it is better to use overloading.

$(this).serialize() -- How to add a value?

While matt b's answer will work, you can also use .serializeArray() to get an array from the form data, modify it, and use jQuery.param() to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.

var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
    type: 'POST',
    url: this.action,
    data: $.param(data),
});

Populate a datagridview with sql query results

String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);

SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;

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

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

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

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

MongoDB: update every document on one field

You can use updateMany() methods of mongodb to update multiple document

Simple query is like this

db.collection.updateMany(filter, update, options)

For more doc of uppdateMany read here

As per your requirement the update code will be like this:

User.updateMany({"created": false}, {"$set":{"created": true}});

here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set

error: expected class-name before ‘{’ token

Replace

#include "Landing.h"

with

class Landing;

If you still get errors, also post Item.h, Flight.h and common.h

EDIT: In response to comment.

You will need to e.g. #include "Landing.h" from Event.cpp in order to actually use the class. You just cannot include it from Event.h

Close window automatically after printing dialog closes

setTimeout(function () { window.print(); }, 500);
        window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }

It's work perfectly for me. Hope it helps

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

How do you post to an iframe?

Depends what you mean by "post data". You can use the HTML target="" attribute on a <form /> tag, so it could be as simple as:

<form action="do_stuff.aspx" method="post" target="my_iframe">
  <input type="submit" value="Do Stuff!">
</form>

<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>

If that's not it, or you're after something more complex, please edit your question to include more detail.

There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.

I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.

default.asp

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <form action="do_stuff.asp" method="post" target="my_frame">
    <input type="text" name="someText" value="Some Text">
    <input type="submit">
  </form>
  <iframe name="my_frame" src="do_stuff.asp">
  </iframe>
  </body>
</html>

do_stuff.asp

<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <% if (Request.Form.Count) { %>
  You typed: <%=Request.Form("someText").Item%>
  <% } else { %>
  (not submitted)
  <% } %>
  </body>
</html>

I would be very interested to hear of any browser that doesn't run these examples correctly.

Creation timestamp and last update timestamp with Hibernate and MySQL

Thanks everyone who helped. After doing some research myself (I'm the guy who asked the question), here is what I found to make sense most:

  • Database column type: the timezone-agnostic number of milliseconds since 1970 represented as decimal(20) because 2^64 has 20 digits and disk space is cheap; let's be straightforward. Also, I will use neither DEFAULT CURRENT_TIMESTAMP, nor triggers. I want no magic in the DB.

  • Java field type: long. The Unix timestamp is well supported across various libs, long has no Y2038 problems, timestamp arithmetic is fast and easy (mainly operator < and operator +, assuming no days/months/years are involved in the calculations). And, most importantly, both primitive longs and java.lang.Longs are immutable—effectively passed by value—unlike java.util.Dates; I'd be really pissed off to find something like foo.getLastUpdate().setTime(System.currentTimeMillis()) when debugging somebody else's code.

  • The ORM framework should be responsible for filling in the data automatically.

  • I haven't tested this yet, but only looking at the docs I assume that @Temporal will do the job; not sure about whether I might use @Version for this purpose. @PrePersist and @PreUpdate are good alternatives to control that manually. Adding that to the layer supertype (common base class) for all entities, is a cute idea provided that you really want timestamping for all of your entities.

Add/delete row from a table

jQuery has a nice function for removing elements from the DOM.

The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."

$(this).closest("tr").remove();

Each delete button could run that very succinct code with a function call.

Batch file to map a drive when the folder name contains spaces

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes 

does not work?

Change Spinner dropdown icon

We can manage it by hiding the icon as i did:

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Spinner android:id="@+id/fragment_filter_sp_users"
             android:layout_width="match_parent"
             android:background="@color/colorTransparent"
             android:layout_height="wrap_content"/>

    <ImageView
            android:layout_gravity="end|bottom"
            android:contentDescription="@null"
            android:layout_marginBottom="@dimen/_5sdp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_arrow_bottom"
    />
</FrameLayout>

Is there a css cross-browser value for "width: -moz-fit-content;"?

width: intrinsic;           /* Safari/WebKit uses a non-standard name */
width: -moz-max-content;    /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */

How to use HTTP_X_FORWARDED_FOR properly?

I like Hrishikesh's answer, to which I only have this to add...because we saw a comma-delimited string coming across when multiple proxies along the way were used, we found it necessary to add an explode and grab the final value, like this:

$IParray=array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));
return end($IParray);

the array_filter is in there to remove empty entries.

C-like structures in Python

https://stackoverflow.com/a/32448434/159695 does not work in Python3.

https://stackoverflow.com/a/35993/159695 works in Python3.

And I extends it to add default values.

class myStruct:
    def __init__(self, **kwds):
        self.x=0
        self.__dict__.update(kwds) # Must be last to accept assigned member variable.
    def __repr__(self):
        args = ['%s=%s' % (k, repr(v)) for (k,v) in vars(self).items()]
        return '%s(%s)' % ( self.__class__.__qualname__, ', '.join(args) )

a=myStruct()
b=myStruct(x=3,y='test')
c=myStruct(x='str')

>>> a
myStruct(x=0)
>>> b
myStruct(x=3, y='test')
>>> c
myStruct(x='str')

How do I find the time difference between two datetime objects in python?

this is to find the difference between current time and 9.30 am

t=datetime.now()-datetime.now().replace(hour=9,minute=30)

Download File Using Javascript/jQuery

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
    document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

In jQuery:

$('a#someID').attr({target: '_blank', 
                    href  : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.

What is wrong with my SQL here? #1089 - Incorrect prefix key

It works for me:

CREATE TABLE `users`(
    `user_id` INT(10) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(255) NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`user_id`)
) ENGINE = MyISAM;       

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

startsWith() and endsWith() functions in PHP

You also can use regular expressions:

function endsWith($haystack, $needle, $case=true) {
  return preg_match("/.*{$needle}$/" . (($case) ? "" : "i"), $haystack);
}

What is the best way to dump entire objects to a log in C#?

You could base something on the ObjectDumper code that ships with the Linq samples.
Have also a look at the answer of this related question to get a sample.

PHP validation/regex for URL

Peter's Regex doesn't look right to me for many reasons. It allows all kinds of special characters in the domain name and doesn't test for much.

Frankie's function looks good to me and you can build a good regex from the components if you don't want a function, like so:

^(http://|https://)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z]{2,6}

Untested but I think that should work.

Also, Owen's answer doesn't look 100% either. I took the domain part of the regex and tested it on a Regex tester tool http://erik.eae.net/playground/regexp/regexp.html

I put the following line:

(\S*?\.\S*?)

in the "regexp" section and the following line:

-hello.com

under the "sample text" section.

The result allowed the minus character through. Because \S means any non-space character.

Note the regex from Frankie handles the minus because it has this part for the first character:

[a-z0-9]

Which won't allow the minus or any other special character.

How can I render Partial views in asp.net mvc 3?

<%= Html.Partial("PartialName", Model) %>

How can I generate a 6 digit unique number?

You can use $uniq = round(microtime(true));

it generates 10 digit base on time which is never be duplicated

Entity framework code-first null foreign key

I prefer this (below):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

How to get the top 10 values in postgresql?

(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)

UNION ALL

(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC    
LIMIT 10)

Creating a new database and new connection in Oracle SQL Developer

This tutorial should help you:

Getting Started with Oracle SQL Developer

See the prerequisites:

  1. Install Oracle SQL Developer. You already have it.
  2. Install the Oracle Database. Download available here.
  3. Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:

    alter user hr identified by hr account unlock;

  4. Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.


Another version from May 2011: Getting Started with Oracle SQL Developer


For more info check this related question:

How to create a new database after initally installing oracle database 11g Express Edition?

How do I check if a string is unicode or ascii?

This may help someone else, I started out testing for the string type of the variable s, but for my application, it made more sense to simply return s as utf-8. The process calling return_utf, then knows what it is dealing with and can handle the string appropriately. The code is not pristine, but I intend for it to be Python version agnostic without a version test or importing six. Please comment with improvements to the sample code below to help other people.

def return_utf(s):
    if isinstance(s, str):
        return s.encode('utf-8')
    if isinstance(s, (int, float, complex)):
        return str(s).encode('utf-8')
    try:
        return s.encode('utf-8')
    except TypeError:
        try:
            return str(s).encode('utf-8')
        except AttributeError:
            return s
    except AttributeError:
        return s
    return s # assume it was already utf-8

How do I align a number like this in C?

As far as I can tell from the question, the amount of padding you want will vary according to the data you have. Accordingly, the only solution to this is to scan the data before printing, to figure out the widest datum, and so find a width value you can pass to printf using the asterix operator, e.g.

loop over data - get correct padding, put into width

printf( "%*d\n", width, datum );

How to hide the Google Invisible reCAPTCHA badge

Note: if you choose to hide the badge, please use
.grecaptcha-badge { visibility: hidden; }

You are allowed to hide the badge as long as you include the reCAPTCHA branding visibly in the user flow. Please include the following text:

This site is protected by reCAPTCHA and the Google
<a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply.

more details here reCaptacha

How to decode JWT Token?

You need the secret string which was used to generate encrypt token. This code works for me:

protected string GetName(string token)
    {
        string secret = "this is a string used for encrypt and decrypt token"; 
        var key = Encoding.ASCII.GetBytes(secret);
        var handler = new JwtSecurityTokenHandler();
        var validations = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        var claims = handler.ValidateToken(token, validations, out var tokenSecure);
        return claims.Identity.Name;
    }

How remove border around image in css?

Try this:

img{border:0;}

You can also limitate the scope and only remove border on some images by doing so:

.myClass img{border:0;}

More information about the border css property can by found here.

Edit: Changed border from 0px to 0. As explained in comments, px is redundant for a unit of 0.

Get Memory Usage in Android

Check the Debug class. http://developer.android.com/reference/android/os/Debug.html i.e. Debug.getNativeHeapAllocatedSize()

It has methods to get the used native heap, which is i.e. used by external bitmaps in your app. For the heap that the app is using internally, you can see that in the DDMS tool that comes with the Android SDK and is also available via Eclipse.

The native heap + the heap as indicated in the DDMS make up the total heap that your app is allocating.

For CPU usage I'm not sure if there's anything available via API/SDK.

How to git-cherry-pick only changes to certain files?

I usually use the -p flag with a git checkout from the other branch which I find easier and more granular than most other methods I have come across.

In principle:

git checkout <other_branch_name> <files/to/grab in/list/separated/by/spaces> -p

example:

git checkout mybranch config/important.yml app/models/important.rb -p

You then get a dialog asking you which changes you want in "blobs" this pretty much works out to every chunk of continuous code change which you can then signal y (Yes) n (No) etc for each chunk of code.

The -p or patch option works for a variety of commands in git including git stash save -p which allows you to choose what you want to stash from your current work

I sometimes use this technique when I have done a lot of work and would like to separate it out and commit in more topic based commits using git add -p and choosing what I want for each commit :)

How to create text file and insert data to that file on Android

I'm using Kotlin here

Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example

var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
 strwrt=FileWriter(File("sdcard/${NamaFile}"))
            strwrt.write(teks)
            strwrt.close()

after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.

How to convert Excel values into buckets?

Here is a solution which:

  • Is self contained
  • Does not require VBA
  • Is not limited in the same way as IF regarding bucket maximums
  • Does not require precise values as LOOKUP does

 

=INDEX({"Small","Medium","Large"},LARGE(IF([INPUT_VALUE]>{0,11,21},{1,2,3}),1))

 

Replace [INPUT_VALUE] with the appropriate cell reference and make sure to press Ctrl+Shift+Enter as this is an array formula.

Each of the array constants can be expanded to be arbitrarily long; as long as the formula does not exceed Excel's maximum of 8,192 characters. The first constant should contain the return values, the second should contain ordered thresholds,and the third should simply be ascending integers.

Will #if RELEASE work like #if DEBUG does in C#?

I've never seen that before...but I have seen:

#if (DEBUG == FALSE)

and

#if (!DEBUG)

That work for ya?

How do I compile a .cpp file on Linux?

Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"

excel plot against a date time x series

[excel 2010] separate the date and time into separate columns and select both as X-Axis and data as graph series see http://www.79783.mrsite.com/USERIMAGES/horizontal_axis_date_and_time2.xlsx

Combine two columns of text in pandas dataframe

df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
df['period'] = df[['Year', 'quarter']].apply(lambda x: ''.join(x), axis=1)

Yields this dataframe

   Year quarter  period
0  2014      q1  2014q1
1  2015      q2  2015q2

This method generalizes to an arbitrary number of string columns by replacing df[['Year', 'quarter']] with any column slice of your dataframe, e.g. df.iloc[:,0:2].apply(lambda x: ''.join(x), axis=1).

You can check more information about apply() method here

How to evaluate a math expression given in string form?

You might have a look at the Symja framework:

ExprEvaluator util = new ExprEvaluator(); 
IExpr result = util.evaluate("10-40");
System.out.println(result.toString()); // -> "-30" 

Take note that definitively more complex expressions can be evaluated:

// D(...) gives the derivative of the function Sin(x)*Cos(x)
IAST function = D(Times(Sin(x), Cos(x)), x);
IExpr result = util.evaluate(function);
// print: Cos(x)^2-Sin(x)^2

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

Append a dictionary to a dictionary

Assuming that you do not want to change orig, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:

from itertools import chain
dest = dict(chain(orig.items(), extra.items()))

Or without itertools:

dest = dict(list(orig.items()) + list(extra.items()))

Note that you only need to pass the result of items() into list() on Python 3, on 2.x dict.items() already returns a list so you can just do dict(orig.items() + extra.items()).

As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:

from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))

How can I get the timezone name in JavaScript?

You can use this script. http://pellepim.bitbucket.org/jstz/

Fork or clone repository here. https://bitbucket.org/pellepim/jstimezonedetect

Once you include the script, you can get the list of timezones in - jstz.olson.timezones variable.

And following code is used to determine client browser's timezone.

var tz = jstz.determine();
tz.name();

Enjoy jstz!

How can I convert a zero-terminated byte array to string?

The following code is looking for '\0', and under the assumptions of the question the array can be considered sorted since all non-'\0' precede all '\0'. This assumption won't hold if the array can contain '\0' within the data.

Find the location of the first zero-byte using a binary search, then slice.

You can find the zero-byte like this:

package main

import "fmt"

func FirstZero(b []byte) int {
    min, max := 0, len(b)
    for {
        if min + 1 == max { return max }
        mid := (min + max) / 2
        if b[mid] == '\000' {
            max = mid
        } else {
            min = mid
        }
    }
    return len(b)
}
func main() {
    b := []byte{1, 2, 3, 0, 0, 0}
    fmt.Println(FirstZero(b))
}

It may be faster just to naively scan the byte array looking for the zero-byte, especially if most of your strings are short.

Android eclipse DDMS - Can't access data/data/ on phone to pull files

If it retures "permission denied" on adb shell -> su...

Go to "Developer Options" -> Root access -> "Apps and ADB"

SQL-Server: The backup set holds a backup of a database other than the existing

system.data.sqlclient.sqlerror:The backup set holds a backup of a database other than the existing 'Dbname' database

I have came across to find soultion

  1. Don't Create a database with the same name or different database name !Important.

  2. right click the database | Tasks > Restore > Database

  3. Under "Source for restore" select "From Device"

  4. Select .bak file

  5. Select the check box for the database in the gridview below

  6. To DataBase: "Here You can type New Database Name" (Ex:DemoDB)

  7. Don't select the Existing Database From DropDownlist

  8. Now Click on Ok Button ,it will create a new Databse and restore all data from your .bak file .

you can get help from this link even

Hope it will help to sort out your issue...

Regex match entire words only

Using \b can yield surprising results. You would be better off figuring out what separates a word from its definition and incorporating that information into your pattern.

#!/usr/bin/perl

use strict; use warnings;

use re 'debug';

my $str = 'S.P.E.C.T.R.E. (Special Executive for Counter-intelligence,
Terrorism, Revenge and Extortion) is a fictional global terrorist
organisation';

my $word = 'S.P.E.C.T.R.E.';

if ( $str =~ /\b(\Q$word\E)\b/ ) {
    print $1, "\n";
}

Output:

Compiling REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b"
Final program:
   1: BOUND (2)
   2: OPEN1 (4)
   4:   EXACT  (9)
   9: CLOSE1 (11)
  11: BOUND (12)
  12: END (0)
anchored "S.P.E.C.T.R.E." at 0 (checking anchored) stclass BOUND minlen 14
Guessing start of match in sv for REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P
.E.C.T.R.E. (Special Executive for Counter-intelligence,"...
Found anchored substr "S.P.E.C.T.R.E." at offset 0...
start_shift: 0 check_at: 0 s: 0 endpos: 1
Does not contradict STCLASS...
Guessed: match at offset 0
Matching REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P.E.C.T.R.E. (Special Exec
utive for Counter-intelligence,"...
   0           |  1:BOUND(2)
   0           |  2:OPEN1(4)
   0           |  4:EXACT (9)
  14      |  9:CLOSE1(11)
  14      | 11:BOUND(12)
                                  failed...
Match failed
Freeing REx: "\b(S\.P\.E\.C\.T\.R\.E\.)\b"

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

Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.

You have four ways of accessing a specific item in a vector:

  • Using the [] operator
  • Using the member function at(...)
  • Using an iterator in combination with a given offset
  • Using std::for_each from the algorithm header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.

In the following examples I will be using the following vector as a lab rat and explaining the first three methods:

static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));

This creates a vector as seen below:

1 2 3 4

First let's look at the [] way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the [] operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:

v[10] = 9;

This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100 instead of 234, which is somewhat connected to that very location where you retrieve an item from you vector.

A much better way is to use at(...). This will automatically check for out of bounds behaviour and break throwing an std::out_of_range. So in the case when we have

v.at(10) = 9;

We will get:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)

The third way is similar to the [] operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:

std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9;  // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...

As you can see we can also do

*(it+10) = 9;

which is again an invalid memory access. This is basically the same as using at(0 + offset) but without the out of bounds error checking.

I would advice using at(...) whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the [] operator.

Cannot delete or update a parent row: a foreign key constraint fails

You need to delete it by order There are dependency in the tables

How to export iTerm2 Profiles

If you have a look at Preferences -> General you will notice at the bottom of the panel, there is a setting Load preferences from a custom folder or URL:. There is a button next to it Save settings to Folder.

So all you need to do is save your settings first and load it after you reinstalled your OS.

If the Save settings to Folder is disabled, select a folder (e.g. empty) in the Load preferences from a custom folder or URL: text box.

In iTerm2 3.3 on OSX the sequence is: iTerm2 menu, Preferences, General tab, Preferences subtab

What is "entropy and information gain"?

As you are reading a book about NLTK it would be interesting you read about MaxEnt Classifier Module http://www.nltk.org/api/nltk.classify.html#module-nltk.classify.maxent

For text mining classification the steps could be: pre-processing (tokenization, steaming, feature selection with Information Gain ...), transformation to numeric (frequency or TF-IDF) (I think that this is the key step to understand when using text as input to a algorithm that only accept numeric) and then classify with MaxEnt, sure this is just an example.

Kill Attached Screen in Linux

You could create a function to kill all existing sessions. take a look at Kill all detached screen sessions

to list all active sessions use screen -r

when listed, select with your mouse the session you are interested in and paste it. like this

screen -r

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

hope this may help you:

SELECT  CAST(LoginTime AS DATE)
         FROM    AuditTrail 

If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month

Objects inside objects in javascript

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};

then:

pause_menu.pause_button.someProperty //evaluates to "prop1"

etc etc.

How to install bcmath module?

ubuntu and php7.1

sudo apt install php7.1-bcmath

ubuntu and php without version specification

sudo apt install php-bcmath

CSS width of a <span> tag

I would use the padding attribute. This will allow you add a set number of pixels to either side of the element without the element loosing its span qualities:

  • It won't become a block
  • It will float as you expect

This method will only add to the padding however, so if you change the length of the content (from Categories to Tags, for example) the size of the content will change and the overall size of the element will change as well. But if you really want to set a rigid size, you should do as mentioned above and use a div.

See the box model for more details about the box model, content, padding, margin, etc.

SQL Server: Get data for only the past year

Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1

Then if you want to restrict this query, you can add some other filter, but always searching in the last year.

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'

Web scraping with Java

If you wish to automate scraping of large amount pages or data, then you could try Gotz ETL.

It is completely model driven like a real ETL tool. Data structure, task workflow and pages to scrape are defined with a set of XML definition files and no coding is required. Query can be written either using Selectors with JSoup or XPath with HtmlUnit.

Is there any way to show a countdown on the lockscreen of iphone?

There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.

I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.

Add JsonArray to JsonObject

Just try below a simple solution:

JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);

whenever my JSON request is like:

{
      "role": "RT",
      "orders": [
        {
          "order_id": "ORDER201908aPq9Gs",
          "cart_id": 164444,
          "affiliate_id": 0,
          "orm_order_status": 9,
          "status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
          "status_date": "2020-04-15",
        }
      ]
    }

SQL Server insert if not exists best practice

Normalizing your operational tables as suggested by Transact Charlie, is a good idea, and will save many headaches and problems over time - but there are such things as interface tables, which support integration with external systems, and reporting tables, which support things like analytical processing; and those types of tables should not necessarily be normalized - in fact, very often it is much, much more convenient and performant for them to not be.

In this case, I think Transact Charlie's proposal for your operational tables is a good one.

But I would add an index (not necessarily unique) to CompetitorName in the Competitors table to support efficient joins on CompetitorName for the purposes of integration (loading of data from external sources), and I would put an interface table into the mix: CompetitionResults.

CompetitionResults should contain whatever data your competition results have in it. The point of an interface table like this one is to make it as quick and easy as possible to truncate and reload it from an Excel sheet or a CSV file, or whatever form you have that data in.

That interface table should not be considered part of the normalized set of operational tables. Then you can join with CompetitionResults as suggested by Richard, to insert records into Competitors that don't already exist, and update the ones that do (for example if you actually have more information about competitors, like their phone number or email address).

One thing I would note - in reality, Competitor Name, it seems to me, is very unlikely to be unique in your data. In 200,000 competitors, you may very well have 2 or more David Smiths, for example. So I would recommend that you collect more information from competitors, such as their phone number or an email address, or something which is more likely to be unique.

Your operational table, Competitors, should just have one column for each data item that contributes to a composite natural key; for example it should have one column for a primary email address. But the interface table should have a slot for old and new values for a primary email address, so that the old value can be use to look up the record in Competitors and update that part of it to the new value.

So CompetitionResults should have some "old" and "new" fields - oldEmail, newEmail, oldPhone, newPhone, etc. That way you can form a composite key, in Competitors, from CompetitorName, Email, and Phone.

Then when you have some competition results, you can truncate and reload your CompetitionResults table from your excel sheet or whatever you have, and run a single, efficient insert to insert all the new competitors into the Competitors table, and single, efficient update to update all the information about the existing competitors from the CompetitionResults. And you can do a single insert to insert new rows into the CompetitionCompetitors table. These things can be done in a ProcessCompetitionResults stored procedure, which could be executed after loading the CompetitionResults table.

That's a sort of rudimentary description of what I've seen done over and over in the real world with Oracle Applications, SAP, PeopleSoft, and a laundry list of other enterprise software suites.

One last comment I'd make is one I've made before on SO: If you create a foreign key that insures that a Competitor exists in the Competitors table before you can add a row with that Competitor in it to CompetitionCompetitors, make sure that foreign key is set to cascade updates and deletes. That way if you need to delete a competitor, you can do it and all the rows associated with that competitor will get automatically deleted. Otherwise, by default, the foreign key will require you to delete all the related rows out of CompetitionCompetitors before it will let you delete a Competitor.

(Some people think non-cascading foreign keys are a good safety precaution, but my experience is that they're just a freaking pain in the butt that are more often than not simply a result of an oversight and they create a bunch of make work for DBA's. Dealing with people accidentally deleting stuff is why you have things like "are you sure" dialogs and various types of regular backups and redundant data sources. It's far, far more common to actually want to delete a competitor, whose data is all messed up for example, than it is to accidentally delete one and then go "Oh no! I didn't mean to do that! And now I don't have their competition results! Aaaahh!" The latter is certainly common enough, so, you do need to be prepared for it, but the former is far more common, so the easiest and best way to prepare for the former, imo, is to just make foreign keys cascade updates and deletes.)

Is it .yaml or .yml?

The nature and even existence of file extensions is platform-dependent (some obscure platforms don't even have them, remember) -- in other systems they're only conventional (UNIX and its ilk), while in still others they have definite semantics and in some cases specific limits on length or character content (Windows, etc.).

Since the maintainers have asked that you use ".yaml", that's as close to an "official" ruling as you can get, but the habit of 8.3 is hard to get out of (and, appallingly, still occasionally relevant in 2013).

Ansible: Store command's stdout in new variable?

There's no need to set a fact.

    - shell: cat "hello"
      register: cat_contents

    - shell: echo "I cat hello"
      when: cat_contents.stdout == "hello"

Adding rows to tbody of a table using jQuery

("#tblEntAttributes tbody")

needs to be

$("#tblEntAttributes tbody").

You are not selecting the element with the correct syntax

Here's an example of both

$(newRowContent).appendTo($("#tblEntAttributes"));

and

$("#tblEntAttributes tbody").append(newRowContent);

working http://jsfiddle.net/xW4NZ/

Detect if user is scrolling

You just said javascript in your tags, so @Wampie Driessen post could helps you.

I want also to contribute, so you can use the following when using jQuery if you need it.

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.wheelDelta< 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Another example:

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});?

Reverse Y-Axis in PyPlot

Use matplotlib.pyplot.axis()

axis([xmin, xmax, ymin, ymax])

So you could add something like this at the end:

plt.axis([min(x_arr), max(x_arr), max(y_arr), 0])

Although you might want padding at each end so that the extreme points don't sit on the border.

Update records using LINQ

Yes. You can use foreach to update the records in linq.There is no performance degrade.

you can verify that the standard Where operator is implemented using the yield construct introduced in C# 2.0.

The use of yield has an interesting benefit which is that the query is not actually evaluated until it is iterated over, either with a foreach statement or by manually using the underlying GetEnumerator and MoveNext methods

For instance,

var query = db.Customers.Where (c => c.Name.StartsWith ("A"));
query = query.Where (c => c.Purchases.Count() >= 2);
var result = query.Select (c => c.Name);

foreach (string name in result)   // Only now is the query executed!
   Console.WriteLine (name);

Exceptional operators are: First, ElementAt, Sum, Average, All, Any, ToArray and ToList force immediate query evaluation.

So no need to scare to use foreach for update the linq result.

In your case code sample given below will be useful to update many properties,

 var persons = (from p in Context.person_account_portfolio where p.person_name == personName select p);

//TO update using foreach

foreach(var person in persons)
{
//update property values
}  

I hope it helps...

Extract a subset of a dataframe based on a condition involving a field

Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:

    bar <- foo[foo[ ,1] == "there", ]

This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).

This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:

    foo[foo[ ,c(1:N)], ]

Or specific columns, as you would expect.

    foo[foo[ ,c(1,5,9)], ]

What's the right way to pass form element state to sibling/parent elements?

  1. The right thing to do is to have the state in the parent component, to avoid ref and what not
  2. An issue is to avoid constantly updating all children when typing into a field
  3. Therefore, each child should be a Component (as in not a PureComponent) and implement shouldComponentUpdate(nextProps, nextState)
  4. This way, when typing into a form field, only that field updates

The code below uses @bound annotations from ES.Next babel-plugin-transform-decorators-legacy of BabelJS 6 and class-properties (the annotation sets this value on member functions similar to bind):

/*
© 2017-present Harald Rudell <[email protected]> (http://www.haraldrudell.com)
All rights reserved.
*/
import React, {Component} from 'react'
import {bound} from 'class-bind'

const m = 'Form'

export default class Parent extends Component {
  state = {one: 'One', two: 'Two'}

  @bound submit(e) {
    e.preventDefault()
    const values = {...this.state}
    console.log(`${m}.submit:`, values)
  }

  @bound fieldUpdate({name, value}) {
    this.setState({[name]: value})
  }

  render() {
    console.log(`${m}.render`)
    const {state, fieldUpdate, submit} = this
    const p = {fieldUpdate}
    return (
      <form onSubmit={submit}> {/* loop removed for clarity */}
        <Child name='one' value={state.one} {...p} />
        <Child name='two' value={state.two} {...p} />
        <input type="submit" />
      </form>
    )
  }
}

class Child extends Component {
  value = this.props.value

  @bound update(e) {
    const {value} = e.target
    const {name, fieldUpdate} = this.props
    fieldUpdate({name, value})
  }

  shouldComponentUpdate(nextProps) {
    const {value} = nextProps
    const doRender = value !== this.value
    if (doRender) this.value = value
    return doRender
  }

  render() {
    console.log(`Child${this.props.name}.render`)
    const {value} = this.props
    const p = {value}
    return <input {...p} onChange={this.update} />
  }
}

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

How do I convert a column of text URLs into active hyperlinks in Excel?

If you don't want to make a macro and as long as you don't mind an additional column, then just create a new column alongside your column of URLs.

In the new column type in the formula =HYPERLINK(A1) (replacing A1 with whatever cell you are interested in). Then copy the formula down the rest of the 200 entries.

NOTE: This solution does not work if the cell A1 contains a string longer than 255 characters. It results in a #VALUE! error

How to check all versions of python installed on osx and centos

Here is a cleaner way to show them (technically without symbolic links):

ls -1 /usr/bin/python* | grep '[2-3].[0-9]$'

Where grep filters the output of ls that that has that numeric pattern at the end ($).

Or using find:

find /usr/bin/python* ! -type l

Which shows all the different (!) of symbolic link type (-type l).

Pythonic way to check if a file exists?

Instead of os.path.isfile, suggested by others, I suggest using os.path.exists, which checks for anything with that name, not just whether it is a regular file.

Thus:

if not os.path.exists(filename):
    file(filename, 'w').close()

Alternatively:

file(filename, 'w+').close()

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.

cor shows only NA or 1 for correlations - Why?

NAs also appear if there are attributes with zero variance (with all elements equal); see for instance:

cor(cbind(a=runif(10),b=rep(1,10)))

which returns:

   a  b
a  1 NA
b NA  1
Warning message:
In cor(cbind(a = runif(10), b = rep(1, 10))) :
  the standard deviation is zero

dll missing in JDBC

Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

java -Djava.library.path=C:\Java\native\libs YourProgram

C:\Java\native\libs should contain sqljdbc_auth.dll

Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

"Full screen" <iframe>

Adding this to your iframe might resolve the issue:

frameborder="0"  seamless="seamless"

Post values from a multiple select

You need to add a name attribute.

Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3.

In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.

Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs

For PHP you can use:

<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">

Table-level backup

A free app named SqlTableZip will get the job done. Basically, you write any query (which, of course can also be [select * from table]) and the app creates a compressed file with all the data, which can be restored later.

Link: http://www.doccolabs.com/products_sqltablezip.html

laravel foreach loop in controller

Is sku just a property of the Product model? If so:

$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();

foreach ($products as $product ) {
  // Access $product->sku here...
}

Or is sku a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.

Angular 2 - innerHTML styling

If you're trying to style dynamically added HTML elements inside an Angular component, this might be helpful:

// inside component class...
    
constructor(private hostRef: ElementRef) { }
    
getContentAttr(): string {
  const attrs = this.hostRef.nativeElement.attributes
  for (let i = 0, l = attrs.length; i < l; i++) {
    if (attrs[i].name.startsWith('_nghost-c')) {
      return `_ngcontent-c${attrs[i].name.substring(9)}`
    }
  }
}
    
ngAfterViewInit() {
  // dynamically add HTML element
  dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}

My guess is that the convention for this attribute is not guaranteed to be stable between versions of Angular, so that one might run into problems with this solution when upgrading to a new version of Angular (although, updating this solution would likely be trivial in that case).

Force "portrait" orientation mode

Note that

android:screenOrientation="portrait"     
android:configChanges="orientation|keyboardHidden"

is added in the manifest file - where the activity is defined.

Java: get greatest common divisor

we can use recursive function for find gcd

public class Test
{
 static int gcd(int a, int b)
    {
        // Everything divides 0 
        if (a == 0 || b == 0)
           return 0;

        // base case
        if (a == b)
            return a;

        // a is greater
        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }

    // Driver method
    public static void main(String[] args) 
    {
        int a = 98, b = 56;
        System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

To make locking reliable you need an atomic operation. Many of the above proposals are not atomic. The proposed lockfile(1) utility looks promising as the man-page mentioned, that its "NFS-resistant". If your OS does not support lockfile(1) and your solution has to work on NFS, you have not many options....

NFSv2 has two atomic operations:

  • symlink
  • rename

With NFSv3 the create call is also atomic.

Directory operations are NOT atomic under NFSv2 and NFSv3 (please refer to the book 'NFS Illustrated' by Brent Callaghan, ISBN 0-201-32570-5; Brent is a NFS-veteran at Sun).

Knowing this, you can implement spin-locks for files and directories (in shell, not PHP):

lock current dir:

while ! ln -s . lock; do :; done

lock a file:

while ! ln -s ${f} ${f}.lock; do :; done

unlock current dir (assumption, the running process really acquired the lock):

mv lock deleteme && rm deleteme

unlock a file (assumption, the running process really acquired the lock):

mv ${f}.lock ${f}.deleteme && rm ${f}.deleteme

Remove is also not atomic, therefore first the rename (which is atomic) and then the remove.

For the symlink and rename calls, both filenames have to reside on the same filesystem. My proposal: use only simple filenames (no paths) and put file and lock into the same directory.

Inline JavaScript onclick function

you can use Self-Executing Anonymous Functions. this code will work:

<a href="#" onClick="(function(){
    alert('Hey i am calling');
    return false;
})();return false;">click here</a>

see JSfiddle

'dict' object has no attribute 'has_key'

I think it is considered "more pythonic" to just use in when determining if a key already exists, as in

if start not in graph:
    return None

npm install -g less does not work: EACCES: permission denied

Run these commands in a terminal window (note: DON'T replace the $USER part... thats a linux command to get your user!):

sudo chown -R $USER ~/.npm
sudo chown -R $USER /usr/lib/node_modules
sudo chown -R $USER /usr/local/lib/node_modules

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

click File -> Invalidate Caches/ Restart doesn't help you anymore
Delete .iml , .idea files & folders from file explorer not inside android studio

1) Open android studio with different/another project

2) import project newly not from recent

3) build the project again

sure it will work

Rails: Check output of path helper from console

You can always check the output of path_helpers in console. Just use the helper with app

app.post_path(3)
#=> "/posts/3"

app.posts_path
#=> "/posts"

app.posts_url
#=> "http://www.example.com/posts"

The server encountered an internal error or misconfiguration and was unable to complete your request

You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)

usually the log file is in

/var/log/apache2/error.log

or

/var/log/httpd/error.log

Git - deleted some files locally, how do I get them from a remote repository

You need to check out a previous version from before you deleted the files. Try git checkout HEAD^ to checkout the last revision.

how to open .mat file without using MATLAB?

If you are using the free software R, you can open the matlab files in Rstudio. Very easy!

Using SSH keys inside docker container

It's a harder problem if you need to use SSH at build time. For example if you're using git clone, or in my case pip and npm to download from a private repository.

The solution I found is to add your keys using the --build-arg flag. Then you can use the new experimental --squash command (added 1.13) to merge the layers so that the keys are no longer available after removal. Here's my solution:

Build command

$ docker build -t example --build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" --squash .

Dockerfile

FROM python:3.6-slim

ARG ssh_prv_key
ARG ssh_pub_key

RUN apt-get update && \
    apt-get install -y \
        git \
        openssh-server \
        libmysqlclient-dev

# Authorize SSH Host
RUN mkdir -p /root/.ssh && \
    chmod 0700 /root/.ssh && \
    ssh-keyscan github.com > /root/.ssh/known_hosts

# Add the keys and set permissions
RUN echo "$ssh_prv_key" > /root/.ssh/id_rsa && \
    echo "$ssh_pub_key" > /root/.ssh/id_rsa.pub && \
    chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/id_rsa.pub

# Avoid cache purge by adding requirements first
ADD ./requirements.txt /app/requirements.txt

WORKDIR /app/

RUN pip install -r requirements.txt

# Remove SSH keys
RUN rm -rf /root/.ssh/

# Add the rest of the files
ADD . .

CMD python manage.py runserver

Update: If you're using Docker 1.13 and have experimental features on you can append --squash to the build command which will merge the layers, removing the SSH keys and hiding them from docker history.

Extracting Nupkg files using command line

With PowerShell 5.1 (PackageManagement module)

Install-Package -Name MyPackage -Source (Get-Location).Path -Destination C:\outputdirectory

Why does corrcoef return a matrix?

Consider using matplotlib.cbook pieces

for example:

import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
     print s

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

If you are facing this issue in case of Sqlite then

. I think this is the problem with version of Sqlite,I had the same problem when I was using this versions of SqLite

Version 2.2.4:

enter image description here

After checking version here enter image description here I changed the version then it worked.

enter image description here

No error after using this

Version 2.1.2:

enter image description here

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

How to add a downloaded .box file to Vagrant?

Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:

{
  "name": "laravel/homestead",
  "versions": [
    {
      "version": "7.0.0",
      "providers": [
        {
          "name": "virtualbox",
          "url": "file:///path/to/box/virtualbox.box"
        }
      ]
    }
  ]
}

Then run vagrant box add command with parameter:

vagrant box add laravel/homestead /path/to/metadata.json

How do I get JSON data from RESTful service using Python?

If you desire to use Python 3, you can use the following:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))

INSERT ... ON DUPLICATE KEY (do nothing)

Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id (it won't trigger row update even though id is assigned to itself).

If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE.

How do you extract a column from a multi-dimensional array?

Despite using zip(*iterable) to transpose a nested list, you can also use the following if the nested lists vary in length:

map(None, *[(1,2,3,), (4,5,), (6,)])

results in:

[(1, 4, 6), (2, 5, None), (3, None, None)]

The first column is thus:

map(None, *[(1,2,3,), (4,5,), (6,)])[0]
#>(1, 4, 6)

How to delete empty folders using windows command prompt?

This is a hybird of the above. It removes ALL files older than X days and removes any empty folders for the given path. To use simply set the days, folderpath and drive

@echo off
SETLOCAL
set days=30
set folderpath=E:\TEST\
set drive=E:

::Delete files
forfiles -p %folderpath% -s -d -%days% -c "cmd /c del /q @path "

::Delete folders
cd %folderpath%
%drive%
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"`

How to clear gradle cache?

Take care with gradle daemon, you have to stop it before clear and re-run gradle.

Stop first daemon:

./gradlew --stop

Clean cache using:

rm -rf ~/.gradle/caches/

Run again you compilation

How can I jump to class/method definition in Atom text editor?

Use atom-ctags as a package for C language with all things you need:

  • Generated ctags for your project. Auto-complete.
  • Go to declaration: Ctrl+Alt+Down and Alt+Click by default.
  • There are customizable options for Click action.

Can an Android App connect directly to an online mysql database

What you want to do is a bad idea. It would require you to embed your username and password in the app. This is a very bad idea as it might be possible to reverse engineer your APK and get the username and password to this publicly facing mysql server which may contain sensitive user data.

I would suggest making a web service to act as a proxy to the mysql server. I assume users need to be logged in, so you could use their username/password to authenticate to the web service.

How do I parse a string with a decimal point to a double?

The trick is to use invariant culture, to parse dot in all cultures.

double.Parse("3.5", System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Display names of all constraints for a table in Oracle SQL

You need to query the data dictionary, specifically the USER_CONS_COLUMNS view to see the table columns and corresponding constraints:

SELECT *
  FROM user_cons_columns
 WHERE table_name = '<your table name>';

FYI, unless you specifically created your table with a lower case name (using double quotes) then the table name will be defaulted to upper case so ensure it is so in your query.

If you then wish to see more information about the constraint itself query the USER_CONSTRAINTS view:

SELECT *
  FROM user_constraints
 WHERE table_name = '<your table name>'
   AND constraint_name = '<your constraint name>';

If the table is held in a schema that is not your default schema then you might need to replace the views with:

all_cons_columns

and

all_constraints

adding to the where clause:

   AND owner = '<schema owner of the table>'

How to compare files from two different branches?

I simply do git diff branch1 branch2 path/to/file

This checks for differences between the files. Changes in branch1 would be in red. Changes in branch2 would be in green.

It's assumed that branch1 is the past and branch2 is the future. You can reverse this by reversing the order of the branches in the diff: git diff branch2 branch1

How to SHA1 hash a string in Android?

Here is the Kotlin version to get SHA encryption string.

import java.security.MessageDigest

object HashUtils {
    fun sha512(input: String) = hashString("SHA-512", input)

    fun sha256(input: String) = hashString("SHA-256", input)

    fun sha1(input: String) = hashString("SHA-1", input)

    /**
     * Supported algorithms on Android:
     *
     * Algorithm    Supported API Levels
     * MD5          1+
     * SHA-1        1+
     * SHA-224      1-8,22+
     * SHA-256      1+
     * SHA-384      1+
     * SHA-512      1+
     */
    private fun hashString(type: String, input: String): String {
        val HEX_CHARS = "0123456789ABCDEF"
        val bytes = MessageDigest
                .getInstance(type)
                .digest(input.toByteArray())
        val result = StringBuilder(bytes.size * 2)

        bytes.forEach {
            val i = it.toInt()
            result.append(HEX_CHARS[i shr 4 and 0x0f])
            result.append(HEX_CHARS[i and 0x0f])
        }

        return result.toString()
    }
}

Its originally posted here: https://www.samclarke.com/kotlin-hash-strings/

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

How to confirm RedHat Enterprise Linux version?

I assume that you've run yum upgrade. That will in general update you to the newest minor release.

Your main resources for determining the version are /etc/redhat_release and lsb_release -a

Dynamically load a function from a DLL

LoadLibrary does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary is called at runtime (remember that C++ is a statically typed language).

You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress.

Example

#include <windows.h>
#include <iostream>

/* Define a function pointer for our imported
 * function.
 * This reads as "introduce the new type f_funci as the type: 
 *                pointer to a function returning an int and 
 *                taking no arguments.
 *
 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)
 * with the exported function. __stdcall is the convention used by the WinAPI
 */
typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // resolve function address here
  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;

  return EXIT_SUCCESS;
}

Also, you should export your function from the DLL correctly. This can be done like this:

int __declspec(dllexport) __stdcall funci() {
   // ...
}

As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.

What are the performance characteristics of sqlite with very large database files?

Besides the usual recommendation:

  1. Drop index for bulk insert.
  2. Batch inserts/updates in large transactions.
  3. Tune your buffer cache/disable journal /w PRAGMAs.
  4. Use a 64bit machine (to be able to use lots of cache™).
  5. [added July 2014] Use common table expression (CTE) instead of running multiple SQL queries! Requires SQLite release 3.8.3.

I have learnt the following from my experience with SQLite3:

  1. For maximum insert speed, don't use schema with any column constraint. (Alter table later as needed You can't add constraints with ALTER TABLE).
  2. Optimize your schema to store what you need. Sometimes this means breaking down tables and/or even compressing/transforming your data before inserting to the database. A great example is to storing IP addresses as (long) integers.
  3. One table per db file - to minimize lock contention. (Use ATTACH DATABASE if you want to have a single connection object.
  4. SQLite can store different types of data in the same column (dynamic typing), use that to your advantage.

Question/comment welcome. ;-)

How to check if internet connection is present in Java?

You can simply write like this

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {

    private static final String HOST = "localhost";

    public static void main(String[] args) throws UnknownHostException {

        boolean isConnected = !HOST.equals(InetAddress.getLocalHost().getHostAddress().toString());

        if (isConnected) System.out.println("Connected");
        else System.out.println("Not connected");

    }
}

How to use external ".js" files

Code like this

 <html>
    <head>
          <script type="text/javascript" src="path/to/script.js"></script>
          <!--other script and also external css included over here-->
    </head>
    <body>
        <form>
            <select name="users" onChange="showUser(this.value)">
               <option value="1">Tom</option>
               <option value="2">Bob</option>
               <option value="3">Joe</option>
            </select>
        </form>
    </body>
    </html>

I hope it will help you.... thanks

How to create a CPU spike with a bash command

I use stress for this kind of thing, you can tell it how many cores to max out.. it allows for stressing memory and disk as well.

Example to stress 2 cores for 60 seconds

stress --cpu 2 --timeout 60

How to add users to Docker container?

The trick is to use useradd instead of its interactive wrapper adduser. I usually create users with:

RUN useradd -ms /bin/bash newuser

which creates a home directory for the user and ensures that bash is the default shell.

You can then add:

USER newuser
WORKDIR /home/newuser

to your dockerfile. Every command afterwards as well as interactive sessions will be executed as user newuser:

docker run -t -i image
newuser@131b7ad86360:~$

You might have to give newuser the permissions to execute the programs you intend to run before invoking the user command.

Using non-privileged users inside containers is a good idea for security reasons. It also has a few drawbacks. Most importantly, people deriving images from your image will have to switch back to root before they can execute commands with superuser privileges.

How do I show multiple recaptchas on a single page?

To add a bit to raphadko's answer: since you have multiple captchas (on one page), you can't use the (universal) g-recaptcha-response POST parameter (because it holds only one captcha's response). Instead, you should use grecaptcha.getResponse(opt_widget_id) call for each captcha. Here's my code (provided each captcha is inside its form):

HTML:

<form ... />

<div id="RecaptchaField1"></div>

<div class="field">
  <input type="hidden" name="grecaptcha" id="grecaptcha" />
</div>

</form>

and

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

JavaScript:

var CaptchaCallback = function(){
    var widgetId;

    $('[id^=RecaptchaField]').each(function(index, el) {

         widgetId = grecaptcha.render(el.id, {'sitekey' : 'your_site_key'});

         $(el).closest("form").submit(function( event ) {

            this.grecaptcha.value = "{\"" + index + "\" => \"" + grecaptcha.getResponse(widgetId) + "\"}"

         });
    });
};

Notice that I apply the event delegation (see refresh DOM after append element ) to all the dynamically modified elements. This binds every individual captha's response to its form submit event.

What is the most appropriate way to store user settings in Android application

As others already pointed out you can use SharedPreferences generally but if you would like to store data encrypted it's a bit inconvenient. Fortunately, there is an easier and quicker way to encrypt data now since there is an implementation of SharedPreferences that encrypts keys and values. You can use EncryptedSharedPreferences in Android JetPack Security.

Just add AndroidX Security into your build.gradle:

implementation 'androidx.security:security-crypto:1.0.0-rc01'

And you can use it like this:

String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);

SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
    "secret_shared_prefs",
    masterKeyAlias,
    context,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);

// use the shared preferences and editor as you normally would
SharedPreferences.Editor editor = sharedPreferences.edit();

See more details: https://android-developers.googleblog.com/2020/02/data-encryption-on-android-with-jetpack.html

Official docs: https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences

Install tkinter for Python

I think you have to install the tkinter onto your code repository directory.

For liunx (Ubuntu or debian), open the terminal. Install the tkinter package by running this command on the terminal.

sudo apt-get install python-tk 

After installing the python-tk package on the terminal, create a new python file. Call it filename.py.

On the first line of the filename.py, import tkinter into the python file.

import tkinter

To create a tkinter with different fields, you can use this tutorial. https://www.delftstack.com/tutorial/tkinter-tutorial/

The documentation of tkinter can be found here: https://docs.python.org/3.7/library/tkinter.html

Hope that helps. Do ask us if you are still stuck. Remember to identify what you need in the GUI on tkinter before implementing it. Drawing wireframes of how the GUI will look like will help in coding the Tkinter GUI.

Using @property versus getters and setters

Using properties is to me more intuitive and fits better into most code.

Comparing

o.x = 5
ox = o.x

vs.

o.setX(5)
ox = o.getX()

is to me quite obvious which is easier to read. Also properties allows for private variables much easier.

Android: upgrading DB version and adding new table

You can use SQLiteOpenHelper's onUpgrade method. In the onUpgrade method, you get the oldVersion as one of the parameters.

In the onUpgrade use a switch and in each of the cases use the version number to keep track of the current version of database.

It's best that you loop over from oldVersion to newVersion, incrementing version by 1 at a time and then upgrade the database step by step. This is very helpful when someone with database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.

Then the updates in the database will be done step-wise, covering all possible cases, i.e. incorporating the changes in the database done for each new version and thereby preventing your application from crashing.

For example:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1:
        String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
        db.execSQL(sql);
        break;

    case 2:
        String sql = "SOME_QUERY";
        db.execSQL(sql);
        break;
    }

}

Changing ImageView source

Or try this one. For me it's working fine:

imageView.setImageDrawable(ContextCompat.getDrawable(this, image));

LINQ query to find if items in a list are contained in another list

I think this would be easiest one:

test1.ForEach(str => test2.RemoveAll(x=>x.Contains(str)));

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I experienced the same problem on my repository. I'm the master of the repository, but I had such an error.

I've unprotected my project and then re-protected again, and the error is gone.

We had upgraded the gitlab version between my previous push and the problematic one. I suppose that this upgrade has created the bug.

Get HTML code from website in C#

You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -

public static string GetInnerHtmlFromDiv(string url)
    {
        string HTML;
        using (var wc = new WebClient())
        {
            HTML = wc.DownloadString(url);
        }
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(HTML);
        
        HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
        if (element != null)
        {
            return element.InnerHtml.ToString();
        }   
        return null;            
    }

What is the difference between Session.Abandon() and Session.Clear()

Clearing a session removes the values that were stored there, but you still can add new ones there. After destroying the session you cannot add new values there.

How to change Label Value using javascript

Try

use an id for hidden field and use id of checkbox in javascript.

and change the ClientIDMode="static" too

<input type="hidden" ClientIDMode="static" id="label1" name="label206451" value="0" />

   <script type="text/javascript"> 
    var cb = document.getElementById('txt206451');
    var label = document.getElementById('label1');
    cb.addEventListener('click',function(evt){
    if(cb.checked){
        label.value='Thanks'
    }else{
        label.value='0'
    }
    },false);
    </script>

How to remove all leading zeroes in a string

Im Fixed with this way.

its very simple. only pass a string its remove zero start of string.

function removeZeroString($str='')
{
    while(trim(substr($str,0,1)) === '0')
    {
        $str = ltrim($str,'0');
    }
    return $str;
}

C++ equivalent of java's instanceof

Instanceof implementation without dynamic_cast

I think this question is still relevant today. Using the C++11 standard you are now able to implement a instanceof function without using dynamic_cast like this:

if (dynamic_cast<B*>(aPtr) != nullptr) {
  // aPtr is instance of B
} else {
  // aPtr is NOT instance of B
}

But you're still reliant on RTTI support. So here is my solution for this problem depending on some Macros and Metaprogramming Magic. The only drawback imho is that this approach does not work for multiple inheritance.

InstanceOfMacros.h

#include <set>
#include <tuple>
#include <typeindex>

#define _EMPTY_BASE_TYPE_DECL() using BaseTypes = std::tuple<>;
#define _BASE_TYPE_DECL(Class, BaseClass) \
  using BaseTypes = decltype(std::tuple_cat(std::tuple<BaseClass>(), Class::BaseTypes()));
#define _INSTANCE_OF_DECL_BODY(Class)                                 \
  static const std::set<std::type_index> baseTypeContainer;           \
  virtual bool instanceOfHelper(const std::type_index &_tidx) {       \
    if (std::type_index(typeid(ThisType)) == _tidx) return true;      \
    if (std::tuple_size<BaseTypes>::value == 0) return false;         \
    return baseTypeContainer.find(_tidx) != baseTypeContainer.end();  \
  }                                                                   \
  template <typename... T>                                            \
  static std::set<std::type_index> getTypeIndexes(std::tuple<T...>) { \
    return std::set<std::type_index>{std::type_index(typeid(T))...};  \
  }

#define INSTANCE_OF_SUB_DECL(Class, BaseClass) \
 protected:                                    \
  using ThisType = Class;                      \
  _BASE_TYPE_DECL(Class, BaseClass)            \
  _INSTANCE_OF_DECL_BODY(Class)

#define INSTANCE_OF_BASE_DECL(Class)                                                    \
 protected:                                                                             \
  using ThisType = Class;                                                               \
  _EMPTY_BASE_TYPE_DECL()                                                               \
  _INSTANCE_OF_DECL_BODY(Class)                                                         \
 public:                                                                                \
  template <typename Of>                                                                \
  typename std::enable_if<std::is_base_of<Class, Of>::value, bool>::type instanceOf() { \
    return instanceOfHelper(std::type_index(typeid(Of)));                               \
  }

#define INSTANCE_OF_IMPL(Class) \
  const std::set<std::type_index> Class::baseTypeContainer = Class::getTypeIndexes(Class::BaseTypes());

Demo

You can then use this stuff (with caution) as follows:

DemoClassHierarchy.hpp*

#include "InstanceOfMacros.h"

struct A {
  virtual ~A() {}
  INSTANCE_OF_BASE_DECL(A)
};
INSTANCE_OF_IMPL(A)

struct B : public A {
  virtual ~B() {}
  INSTANCE_OF_SUB_DECL(B, A)
};
INSTANCE_OF_IMPL(B)

struct C : public A {
  virtual ~C() {}
  INSTANCE_OF_SUB_DECL(C, A)
};
INSTANCE_OF_IMPL(C)

struct D : public C {
  virtual ~D() {}
  INSTANCE_OF_SUB_DECL(D, C)
};
INSTANCE_OF_IMPL(D)

The following code presents a small demo to verify rudimentary the correct behavior.

InstanceOfDemo.cpp

#include <iostream>
#include <memory>
#include "DemoClassHierarchy.hpp"

int main() {
  A *a2aPtr = new A;
  A *a2bPtr = new B;
  std::shared_ptr<A> a2cPtr(new C);
  C *c2dPtr = new D;
  std::unique_ptr<A> a2dPtr(new D);

  std::cout << "a2aPtr->instanceOf<A>(): expected=1, value=" << a2aPtr->instanceOf<A>() << std::endl;
  std::cout << "a2aPtr->instanceOf<B>(): expected=0, value=" << a2aPtr->instanceOf<B>() << std::endl;
  std::cout << "a2aPtr->instanceOf<C>(): expected=0, value=" << a2aPtr->instanceOf<C>() << std::endl;
  std::cout << "a2aPtr->instanceOf<D>(): expected=0, value=" << a2aPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2bPtr->instanceOf<A>(): expected=1, value=" << a2bPtr->instanceOf<A>() << std::endl;
  std::cout << "a2bPtr->instanceOf<B>(): expected=1, value=" << a2bPtr->instanceOf<B>() << std::endl;
  std::cout << "a2bPtr->instanceOf<C>(): expected=0, value=" << a2bPtr->instanceOf<C>() << std::endl;
  std::cout << "a2bPtr->instanceOf<D>(): expected=0, value=" << a2bPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2cPtr->instanceOf<A>(): expected=1, value=" << a2cPtr->instanceOf<A>() << std::endl;
  std::cout << "a2cPtr->instanceOf<B>(): expected=0, value=" << a2cPtr->instanceOf<B>() << std::endl;
  std::cout << "a2cPtr->instanceOf<C>(): expected=1, value=" << a2cPtr->instanceOf<C>() << std::endl;
  std::cout << "a2cPtr->instanceOf<D>(): expected=0, value=" << a2cPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "c2dPtr->instanceOf<A>(): expected=1, value=" << c2dPtr->instanceOf<A>() << std::endl;
  std::cout << "c2dPtr->instanceOf<B>(): expected=0, value=" << c2dPtr->instanceOf<B>() << std::endl;
  std::cout << "c2dPtr->instanceOf<C>(): expected=1, value=" << c2dPtr->instanceOf<C>() << std::endl;
  std::cout << "c2dPtr->instanceOf<D>(): expected=1, value=" << c2dPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2dPtr->instanceOf<A>(): expected=1, value=" << a2dPtr->instanceOf<A>() << std::endl;
  std::cout << "a2dPtr->instanceOf<B>(): expected=0, value=" << a2dPtr->instanceOf<B>() << std::endl;
  std::cout << "a2dPtr->instanceOf<C>(): expected=1, value=" << a2dPtr->instanceOf<C>() << std::endl;
  std::cout << "a2dPtr->instanceOf<D>(): expected=1, value=" << a2dPtr->instanceOf<D>() << std::endl;

  delete a2aPtr;
  delete a2bPtr;
  delete c2dPtr;

  return 0;
}

Output:

a2aPtr->instanceOf<A>(): expected=1, value=1
a2aPtr->instanceOf<B>(): expected=0, value=0
a2aPtr->instanceOf<C>(): expected=0, value=0
a2aPtr->instanceOf<D>(): expected=0, value=0

a2bPtr->instanceOf<A>(): expected=1, value=1
a2bPtr->instanceOf<B>(): expected=1, value=1
a2bPtr->instanceOf<C>(): expected=0, value=0
a2bPtr->instanceOf<D>(): expected=0, value=0

a2cPtr->instanceOf<A>(): expected=1, value=1
a2cPtr->instanceOf<B>(): expected=0, value=0
a2cPtr->instanceOf<C>(): expected=1, value=1
a2cPtr->instanceOf<D>(): expected=0, value=0

c2dPtr->instanceOf<A>(): expected=1, value=1
c2dPtr->instanceOf<B>(): expected=0, value=0
c2dPtr->instanceOf<C>(): expected=1, value=1
c2dPtr->instanceOf<D>(): expected=1, value=1

a2dPtr->instanceOf<A>(): expected=1, value=1
a2dPtr->instanceOf<B>(): expected=0, value=0
a2dPtr->instanceOf<C>(): expected=1, value=1
a2dPtr->instanceOf<D>(): expected=1, value=1

Performance

The most interesting question which now arises is, if this evil stuff is more efficient than the usage of dynamic_cast. Therefore I've written a very basic performance measurement app.

InstanceOfPerformance.cpp

#include <chrono>
#include <iostream>
#include <string>
#include "DemoClassHierarchy.hpp"

template <typename Base, typename Derived, typename Duration>
Duration instanceOfMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = ptr->template instanceOf<Derived>();
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

template <typename Base, typename Derived, typename Duration>
Duration dynamicCastMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = dynamic_cast<Derived *>(ptr) != nullptr;
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

int main() {
  unsigned testCycles = 10000000;
  std::string unit = " us";
  using DType = std::chrono::microseconds;

  std::cout << "InstanceOf performance(A->D)  : " << instanceOfMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->C)  : " << instanceOfMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->B)  : " << instanceOfMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->A)  : " << instanceOfMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  std::cout << "DynamicCast performance(A->D) : " << dynamicCastMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->C) : " << dynamicCastMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->B) : " << dynamicCastMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->A) : " << dynamicCastMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  return 0;
}

The results vary and are essentially based on the degree of compiler optimization. Compiling the performance measurement program using g++ -std=c++11 -O0 -o instanceof-performance InstanceOfPerformance.cpp the output on my local machine was:

InstanceOf performance(A->D)  : 699638 us
InstanceOf performance(A->C)  : 642157 us
InstanceOf performance(A->B)  : 671399 us
InstanceOf performance(A->A)  : 626193 us

DynamicCast performance(A->D) : 754937 us
DynamicCast performance(A->C) : 706766 us
DynamicCast performance(A->B) : 751353 us
DynamicCast performance(A->A) : 676853 us

Mhm, this result was very sobering, because the timings demonstrates that the new approach is not much faster compared to the dynamic_cast approach. It is even less efficient for the special test case which tests if a pointer of A is an instance ofA. BUT the tide turns by tuning our binary using compiler otpimization. The respective compiler command is g++ -std=c++11 -O3 -o instanceof-performance InstanceOfPerformance.cpp. The result on my local machine was amazing:

InstanceOf performance(A->D)  : 3035 us
InstanceOf performance(A->C)  : 5030 us
InstanceOf performance(A->B)  : 5250 us
InstanceOf performance(A->A)  : 3021 us

DynamicCast performance(A->D) : 666903 us
DynamicCast performance(A->C) : 698567 us
DynamicCast performance(A->B) : 727368 us
DynamicCast performance(A->A) : 3098 us

If you are not reliant on multiple inheritance, are no opponent of good old C macros, RTTI and template metaprogramming and are not too lazy to add some small instructions to the classes of your class hierarchy, then this approach can boost your application a little bit with respect to its performance, if you often end up with checking the instance of a pointer. But use it with caution. There is no warranty for the correctness of this approach.

Note: All demos were compiled using clang (Apple LLVM version 9.0.0 (clang-900.0.39.2)) under macOS Sierra on a MacBook Pro Mid 2012.

Edit: I've also tested the performance on a Linux machine using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609. On this platform the perfomance benefit was not so significant as on macOs with clang.

Output (without compiler optimization):

InstanceOf performance(A->D)  : 390768 us
InstanceOf performance(A->C)  : 333994 us
InstanceOf performance(A->B)  : 334596 us
InstanceOf performance(A->A)  : 300959 us

DynamicCast performance(A->D) : 331942 us
DynamicCast performance(A->C) : 303715 us
DynamicCast performance(A->B) : 400262 us
DynamicCast performance(A->A) : 324942 us

Output (with compiler optimization):

InstanceOf performance(A->D)  : 209501 us
InstanceOf performance(A->C)  : 208727 us
InstanceOf performance(A->B)  : 207815 us
InstanceOf performance(A->A)  : 197953 us

DynamicCast performance(A->D) : 259417 us
DynamicCast performance(A->C) : 256203 us
DynamicCast performance(A->B) : 261202 us
DynamicCast performance(A->A) : 193535 us

psql: could not connect to server: No such file or directory (Mac OS X)

I'm not entirely sure why, but my Postgres installation got a little bit screwed and some files were deleted resulting in the error OP is showing.

Despite the fact that I am able to run commands like brew service retart postgres and see the proper messages, this error persisted.

I went through the postgres documentation and found that my file /usr/local/var/postgres was totally empty. So I ran the following:

initdb /usr/local/var/postgres

It seems some configurations took place with that command.

Then it asked me to run this:

postgres -D /usr/local/var/postgres

And that told me a postmaster.pid file already exists.

I just needed to know if brew would be able to pick up the configs I just ran, so I tested it out.

ls /usr/local/var/postgres

That showed me a postmaster.pid file. I then did brew services stop postgresql, and the postmaster.pid file disappeared. Then I did brew services start postgresql, and VIOLA, the file reappeared.

Then I went ahead and ran my app, which did in fact find the server, however my databases seem to be gone.

Although I know that they may not be gone at all - the new initialization I did may have created a new data_area, and the old one isn't being pointed to. I'd have to look at where that's at and point it back over or just create my databases again.

Hope this helps! Reading the postgres docs helped me a lot. I hate reading answers that are like "Paste this in it works!" because I don't know what the hell is happening and why.

Proper way of checking if row exists in table in PL/SQL block

IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in my world - yours may be different :-). In a typical app you're going to use a cursor to find data - so let's say you've got an app that's looking at invoice data, and needs to know if the customer exists. The main body of the app might be something like

FOR aRow IN (SELECT * FROM INVOICES WHERE DUE_DATE < TRUNC(SYSDATE)-60)
LOOP
  -- do something here
END LOOP;

and in the -- do something here you want to find if the customer exists, and if not print an error message.

One way to do this would be to put in some kind of singleton SELECT, as in

-- Check to see if the customer exists in PERSON

BEGIN
  SELECT 'TRUE'
    INTO strCustomer_exists
    FROM PERSON
    WHERE PERSON_ID = aRow.CUSTOMER_ID;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    strCustomer_exists := 'FALSE';
END;

IF strCustomer_exists = 'FALSE' THEN
  DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;

but IMO this is relatively slow and error-prone. IMO a Better Way (tm) to do this is to incorporate it in the main cursor:

FOR aRow IN (SELECT i.*, p.ID AS PERSON_ID
               FROM INVOICES i
               LEFT OUTER JOIN PERSON p
                 ON (p.ID = i.CUSTOMER_PERSON_ID)
               WHERE DUE_DATA < TRUNC(SYSDATE)-60)
LOOP
  -- Check to see if the customer exists in PERSON

  IF aRow.PERSON_ID IS NULL THEN
    DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
  END IF;
END LOOP;

This code counts on PERSON.ID being declared as the PRIMARY KEY on PERSON (or at least as being NOT NULL); the logic is that if the PERSON table is outer-joined to the query, and the PERSON_ID comes up as NULL, it means no row was found in PERSON for the given CUSTOMER_ID because PERSON.ID must have a value (i.e. is at least NOT NULL).

Share and enjoy.

How to put text over images in html?

You can create a div with the exact same size as the image.

<div class="imageContainer">Some Text</div>

use the css background-image property to show the image

 .imageContainer {
       width:200px; 
       height:200px; 
       background-image: url(locationoftheimage);
 }

more here

note: this slichtly tampers the semantics of your document. If needed use javascript to inject the div in the place of a real image.

C# : changing listbox row color?

I think you have to draw the listitems yourself to achieve this.

Here's a post with the same kind of question.

Using grep and sed to find and replace a string

I think that without using -exec you can simply provide /dev/null as at least one argument in case nothing is found:

grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null

How can I throw CHECKED exceptions from inside Java 8 streams?

If you use Spring Framework you can use ReflectionUtils.rethrowRuntimeException(ex) described here https://docs.spring.io/spring/docs/5.2.8.RELEASE/javadoc-api/org/springframework/util/ReflectionUtils.html#rethrowRuntimeException-java.lang.Throwable- The beauty of this util method is that it re-throws exactly same exception but of Runtime type, so your catch block that expects exception of checked type will still catch it as intended.

when exactly are we supposed to use "public static final String"?

static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.

Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.

npm not working after clearing cache

try this one npm cache clean --force after that run npm cache verify

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

CryptographicException 'Keyset does not exist', but only through WCF

I hit this in my service fabric project after the cert used to authenticate against our key vault expired and was rotated, which changed the thumbprint. I got this error because I had missed updating the thumbprint in the applicationManifest.xml file in this block which precisely does what other answers have suggested - to given NETWORK SERVICE (which all my exes run as, standard config for azure servicefabric cluster) permissions to access the LOCALMACHINE\MY cert store location.

Note the "X509FindValue" attribute value.

_x000D_
_x000D_
<!-- this block added to allow low priv processes (such as service fabric processes) that run as NETWORK SERVICE to read certificates from the store -->_x000D_
  <Principals>_x000D_
    <Users>_x000D_
      <User Name="NetworkService" AccountType="NetworkService" />_x000D_
    </Users>_x000D_
  </Principals>_x000D_
  <Policies>_x000D_
    <SecurityAccessPolicies>_x000D_
      <SecurityAccessPolicy ResourceRef="AzureKeyvaultClientCertificate" PrincipalRef="NetworkService" GrantRights="Full" ResourceType="Certificate" />_x000D_
    </SecurityAccessPolicies>_x000D_
  </Policies>_x000D_
  <Certificates>_x000D_
    <SecretsCertificate X509FindValue="[[THIS KEY ALSO NEEDS TO BE UPDATED]]" Name="AzureKeyvaultClientCertificate" />_x000D_
  </Certificates>_x000D_
  <!-- end block -->
_x000D_
_x000D_
_x000D_

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Where do I put image files, css, js, etc. in Codeigniter?

Regardless of where you put the CSS file you can simply use the CodeIgniter "html" helper called link_tag(). You would apply this helper something like this:

echo link_tag('folder/subfolder/stylesheet.css');

It is up to you to locate the CSS file in the most appropriate place (in your opinion). You would have to either autoload the "html" helper or separately load it in to use it.

People keep suggesting the usage of base_url() to achieve this but it is actually not really the "CodeIgniter" way to do it (I think this question has a few duplicates). That will work but one of the reasons for using a framework is to use the pre-made functions within it.

There are many helpers in codeigniter to do this kind of thing.

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

DllImport will work fine without the complete path specified as long as the dll is located somewhere on the system path. You may be able to temporarily add the user's folder to the path.

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

In my opinion SET XACT_ABORT ON was made obsolete by the addition of BEGIN TRY/BEGIN CATCH in SQL 2k5. Before exception blocks in Transact-SQL it was really difficult to handle errors and unbalanced procedures were all too common (procedures that had a different @@TRANCOUNT at exit compared to entry).

With the addition of Transact-SQL exception handling is much easier to write correct procedures that are guaranteed to properly balance the transactions. For instance I use this template for exception handling and nested transactions:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch   
end
go

It allows me to write atomic procedures that rollback only their own work in case of recoverable errors.

One of the main issues Transact-SQL procedures face is data purity: sometimes the parameters received or the data in the tables are just plain wrong, resulting in duplicate key errors, referential constrain errors, check constrain errors and so on and so forth. After all, that's exactly the role of these constrains, if these data purity errors would be impossible and all caught by the business logic, the constrains would be all obsolete (dramatic exaggeration added for effect). If XACT_ABORT is ON then all these errors result in the entire transaction being lost, as opposed to being able to code exception blocks that handle the exception gracefully. A typical example is trying to do an INSERT and reverting to an UPDATE on PK violation.

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

How do you uninstall MySQL from Mac OS X?

If you installed mysql through brew then we can use command to uninstall mysql.

$ brew uninstall mysql

Uninstalling /usr/local/Cellar/mysql/5.6.19...

This worked for me.

What is the easiest way to push an element to the beginning of the array?

What about using the unshift method?

ary.unshift(obj, ...) ? ary
Prepends objects to the front of self, moving other elements upwards.

And in use:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"

Split a large pandas dataframe

Use np.array_split:

Docstring:
Split an array into multiple sub-arrays.

Please refer to the ``split`` documentation.  The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
   ...:                           'foo', 'bar', 'foo', 'foo'],
   ...:                    'B' : ['one', 'one', 'two', 'three',
   ...:                           'two', 'two', 'one', 'three'],
   ...:                    'C' : randn(8), 'D' : randn(8)})

In [3]: print df
     A      B         C         D
0  foo    one -0.174067 -0.608579
1  bar    one -0.860386 -1.210518
2  foo    two  0.614102  1.689837
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468

In [4]: import numpy as np
In [5]: np.array_split(df, 3)
Out[5]: 
[     A    B         C         D
0  foo  one -0.174067 -0.608579
1  bar  one -0.860386 -1.210518
2  foo  two  0.614102  1.689837,
      A      B         C         D
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861,
      A      B         C         D
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468]

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

For all the python3 and pip3 users out there:

curl https://bootstrap.pypa.io/get-pip.py | sudo python3

and then assume you want to install pandas

pip3 install pandas --user

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

<servlet-mapping>
  <servlet-name>server</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

How to return a class object by reference in C++?

You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:

Object& return_Object()
{
    Object object_to_return;
    // ... do stuff ...

    return object_to_return;
}

If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.

Make child div stretch across width of page

Since position: absolute; and viewport width were no options in my special case, there is another quick solution to solve the problem. The only condition is, that overflow in x-direction is not necessary for your website.

You can define negative margins for your element:

#help_panel {
    margin-left: -9999px;
    margin-right: -9999px;
}

But since we get overflow doing this, we have to avoid overflow in x-direction globally e.g. for body:

body {
    overflow-x: hidden;
}

You can set padding to choose the size of your content.

Note that this solution does not bring 100% width for content, but it is helpful in cases where you need e.g. a background color which has full width with a content still depending on container.

BEGIN - END block atomic transactions in PL/SQL

BEGIN-END blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN-END blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.

If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.

However, you cannot declare this pragma for nested blocks. You can only declare this for:

  • Top-level (not nested) anonymous PL/SQL blocks
  • List item
  • Local, standalone, and packaged functions and procedures
  • Methods of a SQL object type
  • Database triggers

Reference: Oracle

How to open CSV file in R when R says "no such file or directory"?

I had to combine Maiasaura and Svun answers to get it to work: using setwd and escaping all the slashes and spaces.

setwd('C:\\Users\\firstname\ lastname\\Desktop\\folder1\\folder2\\folder3')
data = read.csv("file.csv")
data

This solved the issue for me.

JavaScript equivalent of PHP’s die

<script>
     alert("i am ajith fan");
     <?php die(); ?>
     alert("i love boxing");
     alert("i love MMA");
</script>

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

After looking more, the root element has to be associated with a schema-namespace as Blaise is noting. Yet, I didnt have a package-info java. So without using the @XMLSchema annotation, I was able to correct this issue by using

@XmlRootElement (name="RetrieveMultipleSetsResponse", namespace = XMLCodeTable.NS1)
@XmlType(name = "ns0", namespace = XMLCodeTable.NS1)
@XmlAccessorType(XmlAccessType.NONE)
public class RetrieveMultipleSetsResponse {//...}

Hope this helps!

JQuery/Javascript: check if var exists

You can use typeof:

if (typeof pagetype === 'undefined') {
    // pagetype doesn't exist
}

How to pass parameters to a partial view in ASP.NET MVC?

make sure you add {} around Html.RenderPartial, as:

@{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});}

not

@Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});

How can I make my custom objects Parcelable?

Now you can use Parceler library to convert your any custom class in parcelable. Just annotate your POJO class with @Parcel. e.g.

    @Parcel
    public class Example {
    String name;
    int id;

    public Example() {}

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getName() { return name; }

    public int getId() { return id; }
}

you can create an object of Example class and wrap through Parcels and send as a bundle through intent. e.g

Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));

Now to get Custom Class object just use

Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));

Highlight label if checkbox is checked

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

_x000D_
_x000D_
input[type=checkbox] + label {_x000D_
  color: #ccc;_x000D_
  font-style: italic;_x000D_
} _x000D_
input[type=checkbox]:checked + label {_x000D_
  color: #f00;_x000D_
  font-style: normal;_x000D_
} 
_x000D_
<input type="checkbox" id="cb_name" name="cb_name"> _x000D_
<label for="cb_name">CSS is Awesome</label> 
_x000D_
_x000D_
_x000D_

Check if String contains only letters

What do you want? Speed or simplicity? For speed, go for a loop based approach. For simplicity, go for a one liner RegEx based approach.

Speed

public boolean isAlpha(String name) {
    char[] chars = name.toCharArray();

    for (char c : chars) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }

    return true;
}

Simplicity

public boolean isAlpha(String name) {
    return name.matches("[a-zA-Z]+");
}

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Download the android SDK http://developer.android.com/sdk/installing/index.html

You only export the path of SDK folder.

export ANDROID_HOME="YOUR_PATH/sdk/"

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

2018 10 25. Update.

Notepad++ 7.5.8 does not have plugin manager by default. You have to download plugins manually.

Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin. I had a similar issue here.

Use table row coloring for cells in Bootstrap

With the current version of Bootstrap (3.3.7), it is possible to color a single cell of a table like so:

<td class = 'text-center col-md-4 success'>

Why Doesn't C# Allow Static Methods to Implement an Interface?

Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:

T SumElements<T>(T initVal, T[] values)
{
    foreach (var v in values)
    {
        initVal += v;
    }
}

Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.

What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:

constraint CHasPlusEquals
{
    static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}

T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
    foreach (var v in values)
    {
        initVal += v;
    }
}

There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.

DISABLE the Horizontal Scroll

this is the nasty child of your code :)

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 1170px;
}

replace it with

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 100%;
}

how to use Spring Boot profiles

If you are using the Spring Boot Maven Plugin, run:

mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar

(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)

Get total size of file in bytes

You can use the length() method on File which returns the size in bytes.

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

Finding repeated words on a string and counting the repetitions

I hope this will help you

public void countInPara(String str) {

    Map<Integer,String> strMap = new HashMap<Integer,String>();
    List<String> paraWords = Arrays.asList(str.split(" "));
    Set<String> strSet = new LinkedHashSet<>(paraWords);
    int count;

    for(String word : strSet) {
        count = Collections.frequency(paraWords, word);
        strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word));
    }

    for(Map.Entry<Integer,String> entry : strMap.entrySet())
        System.out.println(entry.getKey() +" :: "+ entry.getValue());
}

Hosting a Maven repository on github

The best solution I've been able to find consists of these steps:

  1. Create a branch called mvn-repo to host your maven artifacts.
  2. Use the github site-maven-plugin to push your artifacts to github.
  3. Configure maven to use your remote mvn-repo as a maven repository.

There are several benefits to using this approach:

  • Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
  • Unlike some other proposed solutions, it doesn't conflict with your gh-pages if you're using them.
  • Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would

The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let's patch into that mechanism for this solution.

First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml:

<distributionManagement>
    <repository>
        <id>internal.repo</id>
        <name>Temporary Staging Repository</name>
        <url>file://${project.build.directory}/mvn-repo</url>
    </repository>
</distributionManagement>

<plugins>
    <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
            <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
        </configuration>
    </plugin>
</plugins>

Now try running mvn clean deploy. You'll see that it deployed your maven repository to target/mvn-repo. The next step is to get it to upload that directory to GitHub.

Add your authentication information to ~/.m2/settings.xml so that the github site-maven-plugin can push to GitHub:

<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>YOUR-USERNAME</username>
      <password>YOUR-PASSWORD</password>
    </server>
  </servers>
</settings>

(As noted, please make sure to chmod 700 settings.xml to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)

Then tell the GitHub site-maven-plugin about the new server you just configured by adding the following to your pom:

<properties>
    <!-- github server corresponds to entry in ~/.m2/settings.xml -->
    <github.global.server>github</github.global.server>
</properties>

Finally, configure the site-maven-plugin to upload from your temporary staging repo to your mvn-repo branch on Github:

<build>
    <plugins>
        <plugin>
            <groupId>com.github.github</groupId>
            <artifactId>site-maven-plugin</artifactId>
            <version>0.11</version>
            <configuration>
                <message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
                <noJekyll>true</noJekyll>                                  <!-- disable webpage processing -->
                <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
                <branch>refs/heads/mvn-repo</branch>                       <!-- remote branch name -->
                <includes><include>**/*</include></includes>
                <repositoryName>YOUR-REPOSITORY-NAME</repositoryName>      <!-- github repo name -->
                <repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner>    <!-- github username  -->
            </configuration>
            <executions>
              <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
              <execution>
                <goals>
                  <goal>site</goal>
                </goals>
                <phase>deploy</phase>
              </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The mvn-repo branch does not need to exist, it will be created for you.

Now run mvn clean deploy again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO] 
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------

Visit github.com in your browser, select the mvn-repo branch, and verify that all your binaries are now there.

enter image description here

Congratulations!

You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy.

There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:

<repositories>
    <repository>
        <id>YOUR-PROJECT-NAME-mvn-repo</id>
        <url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Now any project that requires your jar files will automatically download them from your github maven repository.

Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.

How to use Macro argument as string literal?

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

How to quickly drop a user with existing privileges

I had to add one more line to REVOKE...

After running:

REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;

I was still receiving the error: username cannot be dropped because some objects depend on it DETAIL: privileges for schema public

I was missing this:

REVOKE USAGE ON SCHEMA public FROM username;

Then I was able to drop the role.

DROP USER username;

adb not finding my device / phone (MacOS X)

Believe it or not, swapping USB cables solved this for me. I'd been using a random one (which wasn't working), and as soon as I switched over to one that came with an actual Android device, it worked.

Another sign that the good cable was working, was that the Android File Transfer app immediately launched, which wasn't happening with the crappy cable.

How to read a single character from the user?

This might be a use case for a context manager. Leaving aside allowances for Windows OS, here's my suggestion:

#!/usr/bin/env python3
# file: 'readchar.py'
"""
Implementation of a way to get a single character of input
without waiting for the user to hit <Enter>.
(OS is Linux, Ubuntu 14.04)
"""

import tty, sys, termios

class ReadChar():
    def __enter__(self):
        self.fd = sys.stdin.fileno()
        self.old_settings = termios.tcgetattr(self.fd)
        tty.setraw(sys.stdin.fileno())
        return sys.stdin.read(1)
    def __exit__(self, type, value, traceback):
        termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)

def test():
    while True:
        with ReadChar() as rc:
            char = rc
        if ord(char) <= 32:
            print("You entered character with ordinal {}."\
                        .format(ord(char)))
        else:
            print("You entered character '{}'."\
                        .format(char))
        if char in "^C^D":
            sys.exit()

if __name__ == "__main__":
    test()

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

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

Calling a javascript function in another js file

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

You declare function fn1 in first.js, and then in second you can just have fn1();

1.js:

function fn1 () {
    alert();
}

2.js:

fn1();

index.html :

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

CSS pseudo elements in React

You can use styled components.

Install it with npm i styled-components

import React from 'react';
import styled from 'styled-components';

const YourEffect = styled.div`
  height: 50px;
  position: relative;
  &:after {
    // whatever you want with normal CSS syntax. Here, a custom orange line as example
    content: '';
    width: 60px;
    height: 4px;
    background: orange
    position: absolute;
    bottom: 0;
    left: 0;
  },

const YourComponent = props => {
  return (
    <YourEffect>...</YourEffect>
  )
}

export default YourComponent

Best practice to validate null and empty collection in Java

You can use org.apache.commons.lang.Validate's "notEmpty" method:

Validate.notEmpty(myCollection) -> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.

How to calculate distance from Wifi router using Signal Strength?

Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer

All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.

If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.

Difference between the System.Array.CopyTo() and System.Array.Clone()

Both CopyTo() and Clone() make shallow copy. Clone() method makes a clone of the original array. It returns an exact length array.

On the other hand, CopyTo() copies the elements from the original array to the destination array starting at the specified destination array index. Note that, this adds elements to an already existing array.

The following code will contradict the postings saying that CopyTo() makes a deep copy:

public class Test
{
public string s;
}

// Write Main() method and within it call test()

private void test()
{
Test[] array = new Test[1];
array[0] = new Test();
array[0].s = "ORIGINAL";

Test[] copy = new Test[1];
array.CopyTo(copy, 0);

// Next line displays "ORIGINAL"
MessageBox.Show("array[0].s = " + array[0].s);
copy[0].s = "CHANGED";

// Next line displays "CHANGED", showing that
// changing the copy also changes the original.
MessageBox.Show("array[0].s = " + array[0].s);
}

Let me explain it a bit. If the elements of the array are of reference types, then the copy (both for Clone() and CopyTo()) will be made upto the first(top) level. But the lower level doesn't get copied. If we need copy of lower level also, we have to do it explicitly. That's why after Cloning or Copying of reference type elements, each element in the Cloned or Copied array refers to the same memory location as referred by the corresponding element in the original array. This clearly indicates that no separate instance is created for lower level. And if it were so then changing the value of any element in the Copied or Cloned array would not have effect in the corresponding element of the original array.

I think that my explanation is exhaustive but I found no other way to make it understandable.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.


P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

What resources are shared between threads?

Threads share data and code while processes do not. The stack is not shared for both.

Processes can also share memory, more precisely code, for example after a Fork(), but this is an implementation detail and (operating system) optimization. Code shared by multiple processes will (hopefully) become duplicated on the first write to the code - this is known as copy-on-write. I am not sure about the exact semantics for the code of threads, but I assume shared code.

           Process   Thread

   Stack   private   private
   Data    private   shared
   Code    private1  shared2

1 The code is logically private but might be shared for performance reasons. 2 I am not 100% sure.

How can I make grep print the lines below and above each matching line?

Use -B, -A or -C option

grep --help
...
-B, --before-context=NUM  print NUM lines of leading context
-A, --after-context=NUM   print NUM lines of trailing context
-C, --context=NUM         print NUM lines of output context
-NUM                      same as --context=NUM
...

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I had the same problem and got it resolved by deleting .m2 maven repo (C:\Users\user\ .m2)