Programs & Examples On #Rpy2

RPy is a very simple, yet robust, Python interface to the R Programming Language. It can manage all kinds of R objects and can execute arbitrary R functions (including the graphic functions). All errors from the R language are converted to Python exceptions. Any module installed for the R system can be used from within Python

How to create an empty R vector to add new items

In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2

For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

No command – neither typenor echo– is necessary to emulate Unix's/Mac OS X's 'touch' command in a Windows Powershell terminal. Simply use the following shorthand:

$null > filename

This will create an empty file named 'filename' at your current location. Use any filename extension that you might need, e.g. '.txt'.

Source: https://superuser.com/questions/502374/equivalent-of-linux-touch-to-create-an-empty-file-with-powershell (see comments)

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

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

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

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

Unable to install Android Studio in Ubuntu

Checkout this page

If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the libncurses5:i386, libstdc++6:i386, and zlib1g:i386 packages using apt-get:

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386

How to run function of parent window when child window closes?

Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer

Java HashMap performance optimization / alternative

As pointed out, your hashcode implementation has too many collisions, and fixing it should result in decent performance. Moreover, caching hashCodes and implementing equals efficiently will help.

If you need to optimize even further:

By your description, there are only (52 * 51 / 2) * (52 * 51 * 50 / 6) = 29304600 different keys (of which 26000000, i.e. about 90%, will be present). Therefore, you can design a hash function without any collisions, and use a simple array rather than a hashmap to hold your data, reducing memory consumption and increasing lookup speed:

T[] array = new T[Key.maxHashCode];

void put(Key k, T value) {
    array[k.hashCode()] = value;

T get(Key k) {
    return array[k.hashCode()];
}

(Generally, it is impossible to design an efficient, collision-free hash function that clusters well, which is why a HashMap will tolerate collisions, which incurs some overhead)

Assuming a and b are sorted, you might use the following hash function:

public int hashCode() {
    assert a[0] < a[1]; 
    int ahash = a[1] * a[1] / 2 
              + a[0];

    assert b[0] < b[1] && b[1] < b[2];

    int bhash = b[2] * b[2] * b[2] / 6
              + b[1] * b[1] / 2
              + b[0];
    return bhash * 52 * 52 / 2 + ahash;
}

static final int maxHashCode = 52 * 52 / 2 * 52 * 52 * 52 / 6;  

I think this is collision-free. Proving this is left as an exercise for the mathematically inclined reader.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

The webfonts link works now, in all browsers!

Simply add your themes to the font link separated by a pipe (|), like this

<link href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined" rel="stylesheet">

Then reference the class, like this:

// class="material-icons" or class="material-icons-outlined"

<i class="material-icons">account_balance</i>
<i class="material-icons-outlined">account_balance</i>

This pattern will also work with Angular Material:

<mat-icon>account_balance</mat-icon>
<mat-icon class="material-icons-outlined">account_balance</mat-icon>

From Arraylist to Array

Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!

ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[foo.size()]);
System.out.println("bar.length = " + bar.length);

outputs

bar.length = 5

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

HTTP GET request in JavaScript?

If you want to use the code for a Dashboard widget, and you don't want to include a JavaScript library in every widget you created, then you can use the object XMLHttpRequest that Safari natively supports.

As reported by Andrew Hedges, a widget doesn't have access to a network, by default; you need to change that setting in the info.plist associated with the widget.

EXC_BAD_ACCESS signal received

Another method for catching EXC_BAD_ACCESS exceptions before they happen is the static analyzer, in XCode 4+.

Run the static analyzer with Product > Analyze (shift+cmd+B). Clicking on any messages generated by the analyzer will overlay a diagram on your source showing the sequence of retains/releases of the offending object.

enter image description here

Get child node index

ES6:

Array.from(element.parentNode.children).indexOf(element)

Explanation :

  • element.parentNode.children ? Returns the brothers of element, including that element.

  • Array.from ? Casts the constructor of children to an Array object

  • indexOf ? You can apply indexOf because you now have an Array object.

How do I get the total number of unique pairs of a set in the database?

This is how you can approach these problems in general on your own:

The first of the pair can be picked in N (=100) ways. You don't want to pick this item again, so the second of the pair can be picked in N-1 (=99) ways. In total you can pick 2 items out of N in N(N-1) (= 100*99=9900) different ways.

But hold on, this way you count also different orderings: AB and BA are both counted. Since every pair is counted twice you have to divide N(N-1) by two (the number of ways that you can order a list of two items). The number of subsets of two that you can make with a set of N is then N(N-1)/2 (= 9900/2 = 4950).

Is there a format code shortcut for Visual Studio?

Yes, you can use the two-chord hotkey (Ctrl+K, Ctrl+F if you're using the General profile) to format your selection.

Other formatting options are under menu EditAdvanced, and like all Visual Studio commands, you can set your own hotkey via menu ToolsOptionsEnvironmentKeyboard (the format selection command is called Edit.FormatSelection).

Formatting doesn't do anything with blank lines, but it will indent your code according to some rules that are usually slightly off from what you probably want.

Number of processors/cores in command line

The most simplest tool comes with glibc and is called getconf:

$ getconf _NPROCESSORS_ONLN
4

How can I list all cookies for the current page with Javascript?

Many people have already mentioned that document.cookie gets you all the cookies (except http-only ones).

I'll just add a snippet to keep up with the times.

document.cookie.split(';').reduce((cookies, cookie) => {
  const [ name, value ] = cookie.split('=').map(c => c.trim());
  cookies[name] = value;
  return cookies;
}, {});

The snippet will return an object with cookie names as the keys with cookie values as the values.

Slightly different syntax:

document.cookie.split(';').reduce((cookies, cookie) => {
  const [ name, value ] = cookie.split('=').map(c => c.trim());
  return { ...cookies, [name]: value };
}, {});

Identify duplicate values in a list in Python

m = len(mylist)
for index,value in enumerate(mylist):
        for i in xrange(1,m):
                if(index != i):
                    if (L[i] == L[index]):
                        print "Location %d and location %d has same list-entry:  %r" % (index,i,value)

This has some redundancy that can be improved however.

How to manually deploy artifacts in Nexus Repository Manager OSS 3

To use mvn deploy:deploy-file, must add ~./m2/settings.xml

<settings>
  <servers>
    <server>
      <id>nexus-repo</id>
      <username>admin</username>
      <password>admin123</password>
    </server>
  </servers>
</settings>

command:

mvn deploy:deploy-file -DgroupId=com.example \
                                       -DartifactId=my-app \
                                       -Dversion=2.0.0 \
                                       -Dpackaging=jar \
                                       -Dfile=my-app.jar \
                                       -DgeneratePom=true \
                                       -DrepositoryId=nexus-repo \
                                       -Durl=http://localhost:8081/repository/maven-releases/

Display PDF file inside my android application

I do not think that you can do this easily. you should consider this answer here:

How can I display a pdf document into a Webview?

basically you'll be able to see a pdf if it is hosted online via google documents, but not if you have it in your device (you'll need a standalone reader for that)

Get integer value of the current year in Java

In Java version 8+ can (advised to) use java.time library. ISO 8601 sets standard way to write dates: YYYY-MM-DD and java.time.Instant uses it, so (for UTC):

import java.time.Instant;
int myYear = Integer.parseInt(Instant.now().toString().substring(0,4));

P.S. just in case (and shorted for getting String, not int), using Calendar looks better and can be made zone-aware.

Start ssh-agent on login

Just to add yet another solution :P, I went with a combination of @spheenik and @collin-anderson 's solutions.

 # Ensure that we have an ssh config with AddKeysToAgent set to true
 if [ ! -f ~/.ssh/config ] || ! cat ~/.ssh/config | grep AddKeysToAgent | grep yes > /dev/null; then
     echo "AddKeysToAgent  yes" >> ~/.ssh/config
 fi
 # Ensure a ssh-agent is running so you only have to enter keys once
 if [ ! -S ~/.ssh/ssh_auth_sock ]; then
   eval `ssh-agent`
   ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
 fi
 export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock

Could be a little more elegant but its simple and readable. This solution:

  • ensures AddKeysToAgent yes is in your ssh config so keys will be automatically added upon use
  • doesn't prompt you to enter any passphrases at login (again, one-time passphrase entering occurs on first use)
  • silently starts an ssh-agent if it has not already started one

Comments welcome :)

How can I stop Chrome from going into debug mode?

You have multiple Google Chrome browser tabs open for the same URL and developer toolbar.

In some other tab, you have set breakpoints which are showing up when you are debugging in the current tab.

Solution: Close the developer toolbar in the other tab or the tab itself.

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

How to Detect Browser Window /Tab Close Event?

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

    window.onbeforeunload = function () {
        return "Are you sure?";
    }

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });

How to play YouTube video in my Android application?

This is the btn click event

btnvideo.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

    startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=Hxy8BZGQ5Jo")));
    Log.i("Video", "Video Playing....");

    }
}); 

this type it opened in another page with the youtube where u can show your video

Setting device orientation in Swift iOS

// Swift 2

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    let orientation: UIInterfaceOrientationMask =
    [UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.PortraitUpsideDown]
    return orientation
}

MongoDB relationships: embed or reference?

MongoDB gives freedom to be schema-less and this feature can result in pain in the long term if not thought or planned well,

There are 2 options either Embed or Reference. I will not go through definitions as the above answers have well defined them.

When embedding you should answer one question is your embedded document going to grow, if yes then how much (remember there is a limit of 16 MB per document) So if you have something like a comment on a post, what is the limit of comment count, if that post goes viral and people start adding comments. In such cases, reference could be a better option (but even reference can grow and reach 16 MB limit).

So how to balance it, the answer is a combination of different patterns, check these links, and create your own mix and match based on your use case.

https://www.mongodb.com/blog/post/building-with-patterns-a-summary

https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1

Creating virtual directories in IIS express

I had something else, the files itself where inaccessible in a SBS envirenment.

Delete the files in the config folder (if you can't open them!) and replace them with a copy of the folder on your own local pc.

Fixed it for me :)

How to remove all characters after a specific character in python?

From a file:

import re
sep = '...'

with open("requirements.txt") as file_in:
    lines = []
    for line in file_in:
        res = line.split(sep, 1)[0]
        print(res)

How can I change NULL to 0 when getting a single value from a SQL function?

SELECT COALESCE(
    (SELECT SUM(Price) AS TotalPrice 
    FROM Inventory
    WHERE (DateAdded BETWEEN @StartDate AND @EndDate))
    , 0)

If the table has rows in the response it returns the SUM(Price). If the SUM is NULL or there are no rows it will return 0.

Putting COALESCE(SUM(Price), 0) does NOT work in MSSQL if no rows are found.

Cannot use special principal dbo: Error 15405

To fix this, open the SQL Server Management Studio and click New Query. Then type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

How to delete duplicate lines in a file without sorting it in Unix?

awk '!seen[$0]++' file.txt

seen is an associative-array that Awk will pass every line of the file to. If a line isn't in the array then seen[$0] will evaluate to false. The ! is the logical NOT operator and will invert the false to true. Awk will print the lines where the expression evaluates to true. The ++ increments seen so that seen[$0] == 1 after the first time a line is found and then seen[$0] == 2, and so on.
Awk evaluates everything but 0 and "" (empty string) to true. If a duplicate line is placed in seen then !seen[$0] will evaluate to false and the line will not be written to the output.

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

How do I modify the URL without reloading the page?

You can use this beautiful and simple function to so so anywhere on your application.

function changeurl(url, title) {
    var new_url = '/' + url;
    window.history.pushState('data', title, new_url);
    
}

You can not only edit URL but you can update title along with it.

Quite helpful everyone.

How to stop VBA code running?

~ For those using custom input box

Private Sub CommandButton1_Click()

DoCmd.Close acForm, Me.Name
End

End Sub

Why can't I declare static methods in an interface?

It seems the static method in the interface might be supported in Java 8, well, my solution is just define them in the inner class.

interface Foo {
    // ...
    class fn {
        public static void func1(...) {
            // ...
        }
    }
}

The same technique can also be used in annotations:

public @interface Foo {
    String value();

    class fn {
        public static String getValue(Object obj) {
            Foo foo = obj.getClass().getAnnotation(Foo.class);
            return foo == null ? null : foo.value();
        }
    }
}

The inner class should always be accessed in the form of Interface.fn... instead of Class.fn..., then, you can get rid of ambiguous problem.

How do I get the value of text input field using JavaScript?

simple js

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

Adding a line break in MySQL INSERT INTO text

If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:

INSERT INTO mytable (myfield) VALUES ('hi this is some text
and this is a linefeed.
and another');

I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS() and CHAR() worked for me.

INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));

Download file from web in Python 3

You can use wget which is popular downloading shell tool for that. https://pypi.python.org/pypi/wget This will be the simplest method since it does not need to open up the destination file. Here is an example.

import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'  
wget.download(url, '/Users/scott/Downloads/cat4.jpg') 

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You could create your own class of type Quiz and then deserialize with strong type:

Example:

quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
                 new JsonSerializerSettings
                 {
                     Error = delegate(object sender1, ErrorEventArgs args1)
                     {
                         errors.Add(args1.ErrorContext.Error.Message);
                         args1.ErrorContext.Handled = true;
                     }
                 });

And you could also apply a schema validation.

http://james.newtonking.com/projects/json/help/index.html

OS X Bash, 'watch' command

To prevent flickering when your main command takes perceivable time to complete, you can capture the output and only clear screen when it's done.

function watch {while :; do a=$($@); clear; echo "$(date)\n\n$a"; sleep 1;  done}

Then use it by:

watch istats

How can I add private key to the distribution certificate?

since xcode5 organizer no longer team section exists. but the bold sentence was the answer for me. God thanks there is another mac to restore and import to problemmatic mac. now all is ok.

Gradle Build Android Project "Could not resolve all dependencies" error

As Peter says, they won't be in Maven Central

from the Android SDK Manager download the 'Android Support Repository' and a Maven repo of the support libraries will be downloaded to your Android SDK directory (see 'extras' folder)

to deploy the libraries to your local .m2 repository you can use maven-android-sdk-deployer

2017 edit:

you can now reference the Google online M2 repo

repositories {
google()
jcenter()
}

Where is SQLite database stored on disk?

In Windows 10 if in the prompt command the path where you start sqlite is

C:\users\USER_NAME

You can find it in the user home folder. The .db file is stored where you start the sqlite command. I hope this solve the issue

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

Also make sure the value is not too large or too small for int like in my case.

Ruby: How to iterate over a range, but in set increments?

You can use Numeric#step.

0.step(30,5) do |num|
  puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30

Difference between clean, gradlew clean

You can also use

./gradlew clean build (Mac and Linux) -With ./

gradlew clean build (Windows) -Without ./

it removes build folder, as well configure your modules and then build your project.

i use it before release any new app on playstore.

Simple calculations for working with lat/lon and km distance?

Why not use properly formulated geospatial queries???

Here is the SQL server reference page on the STContains geospatial function:

https://docs.microsoft.com/en-us/sql/t-sql/spatial-geography/stcontains-geography-data-type?view=sql-server-ver15

or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:

DECLARE @CurrentLocation geography; 
SET @CurrentLocation  = geography::Point(12.822222, 80.222222, 4326)

SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km

There should be similar functionality for almost any database out there.

If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

How to add to an NSDictionary

Update version

Objective-C

Create:

NSDictionary *dictionary = @{@"myKey1": @7, @"myKey2": @5}; 

Change:

NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];     //Make the dictionary mutable to change/add
mutableDictionary[@"myKey3"] = @3;

The short-hand syntax is called Objective-C Literals.

Swift

Create:

var dictionary = ["myKey1": 7, "myKey2": 5]

Change:

dictionary["myKey3"] = 3

Base 64 encode and decode example code

something like

String source = "password"; 
byte[] byteArray;
try {
    byteArray = source.getBytes("UTF-16");
    System.out.println(new String(Base64.decode(Base64.encode(byteArray,
           Base64.DEFAULT), Base64.DEFAULT)));
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Disable nginx cache for JavaScript files

I know this question is a bit old but i would suggest to use some cachebraking hash in the url of the javascript. This works perfectly in production as well as during development because you can have both infinite cache times and intant updates when changes occur.

Lets assume you have a javascript file /js/script.min.js, but in the referencing html/php file you do not use the actual path but:

<script src="/js/script.<?php echo md5(filemtime('/js/script.min.js')); ?>.min.js"></script>

So everytime the file is changed, the browser gets a different url, which in turn means it cannot be cached, be it locally or on any proxy inbetween.

To make this work you need nginx to rewrite any request to /js/script.[0-9a-f]{32}.min.js to the original filename. In my case i use the following directive (for css also):

location ~* \.(css|js)$ {
                expires max;
                add_header Pragma public;
                etag off;
                add_header Cache-Control "public";
                add_header Last-Modified "";
                rewrite  "^/(.*)\/(style|script)\.min\.([\d\w]{32})\.(js|css)$" /$1/$2.min.$4 break;
        }

I would guess that the filemtime call does not even require disk access on the server as it should be in linux's file cache. If you have doubts or static html files you can also use a fixed random value (or incremental or content hash) that is updated when your javascript / css preprocessor has finished or let one of your git hooks change it.

In theory you could also use a cachebreaker as a dummy parameter (like /js/script.min.js?cachebreak=0123456789abcfef), but then the file is not cached at least by some proxies because of the "?".

How to create CSV Excel file C#?

I added ExportToStream so the csv didn't have to save to the hard drive first.

public Stream ExportToStream()
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(Export(true));
    writer.Flush();
    stream.Position = 0;
    return stream;
}

Read a plain text file with php

http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.explode.php

$array = explode("\n", file_get_contents($filename));

This wont actually read it line by line, but it will get you an array which can be used line by line. There are a number of alternatives.

Including a .js file within a .js file

I basically do like this, create new element and attach that to <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

x.onload=callback_function;

How to loop through all elements of a form jQuery

$('#new_user_form :input') should be your way forward. Note the omission of the > selector. A valid HTML form wouldn't allow for a input tag being a direct child of a form tag.

Fastest way to determine if record exists

create or replace procedure ex(j in number) as
i number;
begin
select id into i from student where id=j;
if i is not null then
dbms_output.put_line('exists');
end if;
exception
   when no_data_found then
        dbms_output.put_line(i||' does not exists');

end;

Import Script from a Parent Directory

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
    +-- __init__.py
    +-- moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

Return value from exec(@sql)

Was playing with this today... I beleive you can also use @@ROWCOUNT, like this:

DECLARE @SQL VARCHAR(50)
DECLARE @Rowcount INT
SET @SQL = 'SELECT 1 UNION SELECT 2'
EXEC(@SQL)
SET @Rowcount = @@ROWCOUNT
SELECT @Rowcount

Then replace the 'SELECT 1 UNION SELECT 2' with your actual select without the count. I'd suggest just putting 1 in your select, like this:

SELECT 1
FROM dbo.Comm_Services
WHERE....
....

(as opposed to putting SELECT *)

Hope that helps.

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Try this one.

Sample Code

String str = " hello     there   ";
System.out.println(str.replaceAll("( +)"," ").trim());

OUTPUT

hello there

First it will replace all the spaces with single space. Than we have to supposed to do trim String because Starting of the String and End of the String it will replace the all space with single space if String has spaces at Starting of the String and End of the String So we need to trim them. Than you get your desired String.

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

TypeError: expected a character buffer object - while trying to save integer to textfile

Just try the code below:

As I see you have inserted 'r+' or this command open the file in read mode so you are not able to write into it, so you have to open file in write mode 'w' if you want to overwrite the file contents and write new data, otherwise you can append data to file by using 'a'

I hope this will help ;)

f = open('testfile.txt', 'w')# just put 'w' if you want to write to the file 

x = f.readlines() #this command will read file lines

y = int(x)+1

print y
z = str(y) #making data as string to avoid buffer error
f.write(z)

f.close()

Clear a terminal screen for real

Just to add that tmux scroll buffer does not clear with clear, reset or printf. You need to :clear-history. See link.

Hide axis and gridlines Highcharts

i managed to turn off mine with just

       lineColor: 'transparent',
       tickLength: 0

How to see the changes between two commits without commits in-between?

git diff <a-commit> <another-commit> path

Example:

git diff commit1 commit2 config/routes.rb

It shows the difference on that file between those commits.

Convert hex to binary

bin(int("abc123efff", 16))[2:]

Change all files and folders permissions of a directory to 644/755

On https://help.directadmin.com/item.php?id=589 they write:

If you need a quick way to reset your public_html data to 755 for directories and 644 for files, then you can use something like this:

cd /home/user/domains/domain.com/public_html
find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

I tested and ... it works!

Check if SQL Connection is Open or Closed

This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

if (_databaseConnection.State == ConnectionState.Closed) {
    _databaseConnection.Open();
}

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

In order to better understand [] and new Array():

> []
  []
> new Array()
  []
> [] == []
  false
> [] === []
  false
> new Array() == new Array()
  false
> new Array() === new Array()
  false
> typeof ([])
  "object"
> typeof (new Array())
  "object"
> [] === new Array()
  false
> [] == new Array()
  false

The above result is from Google Chrome console on Windows 7.

How to parse a string in JavaScript?

Use split on string:

var array = coolVar.split(/-/);

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

I have issue with itextsharp and itextsharp.xmlworker dlls for exception-from-hresult-0x80131040 so I have removed those both dlls from references and downloaded new dlls directly from nuget packages, which resolved my issue.

May be this method can be useful to resolved the issue to other people.

Check if a time is between two times (time DataType)

Should be AND instead of OR

select *
from MyTable
where CAST(Created as time) >= '23:00:00' 
   AND CAST(Created as time) < '07:00:00'

String to object in JS

Your string looks like a JSON string without the curly braces.

This should work then:

obj = eval('({' + str + '})');

HTML5 Video Autoplay not working correctly

Working solution October 2018, for videos including audio channel

 $(document).ready(function() {
     $('video').prop('muted',true).play()
 });

Have a look at another of mine, more in-depth answer: https://stackoverflow.com/a/57723549/3049675

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

Postgresql query between date ranges

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

How can I send mail from an iPhone application

On iOS 3.0 and later you should use the MFMailComposeViewController class, and the MFMailComposeViewControllerDelegate protocol, that is tucked away in the MessageUI framework.

First add the framework and import:

#import <MessageUI/MFMailComposeViewController.h>

Then, to send a message:

MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"My Subject"];
[controller setMessageBody:@"Hello there." isHTML:NO]; 
if (controller) [self presentModalViewController:controller animated:YES];
[controller release];

Then the user does the work and you get the delegate callback in time:

- (void)mailComposeController:(MFMailComposeViewController*)controller  
          didFinishWithResult:(MFMailComposeResult)result 
                        error:(NSError*)error;
{
  if (result == MFMailComposeResultSent) {
    NSLog(@"It's away!");
  }
  [self dismissModalViewControllerAnimated:YES];
}

Remember to check if the device is configured for sending email:

if ([MFMailComposeViewController canSendMail]) {
  // Show the composer
} else {
  // Handle the error
}

CSS Calc Viewport Units Workaround?

As a workaround you can use the fact percent vertical padding and margin are computed from the container width. It's quite a ugly solution and I don't know if you'll be able to use it but well, it works: http://jsfiddle.net/bFWT9/

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <div>It works!</div>
    </body>
</html>

html, body, div {
    height: 100%;
}
body {
    margin: 0;
}
div {
    box-sizing: border-box;
    margin-top: -75%;
    padding-top: 75%;
    background: #d35400;
    color: #fff;
}

How do I perform query filtering in django templates

I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.

Some other possible solutions:

  1. Use the {% expr <expression> as <var_name> %} template tag found at http://www.djangosnippets.org/snippets/9/ The expression is any legal Python expression with your template's Context as your local scope.

  2. Change your template processor. Jinja2 (http://jinja.pocoo.org/2/) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that you are working on, but use Django's "safer" templates for designer-maintained pages.

Plot inline or a separate window using Matplotlib in Spyder IDE

type

%matplotlib qt

when you want graphs in a separate window and

%matplotlib inline

when you want an inline plot

How to convert a PIL Image into a numpy array?

You're not saying how exactly putdata() is not behaving. I'm assuming you're doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).

Oracle SqlDeveloper JDK path

In your SQL Developer Bin Folder find

\sqldeveloper\bin\sqldeveloper.conf

It should be

SetJavaHome \path\to\jdk

You said it was ../../jdk originally so you could ultimatey do 1 of two things:

SetJavaHome C:\Program Files\Java\jdk1.7.0_60

This is assuming that you have JDK 1.7.60 installed in that directory; you don't want to point it to the bin folder you want the whole JDK folder.

OR

The second thing you can do is find the jdk folder in the sqldeveloper folder for me its sqldeveloper\jdk and copy and paste the contents from C:\Program Files\Java\jdk1.7.0_60. You then have to revert your change to read

SetJavaHome ../../jdk

in your sqldeveloper.conf

If all else fails you can always redownload the sqldeveloper that already contains the jdk7 all zipped up and ready for you to run at will: Download SQL Developer The file I talk about is called Windows 64-bit - zip file includes the JDK 7

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

Finally I got it:

as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8  
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')

Let me check:

as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec  6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'utf8'
>>>

The above shows the default encoding of python is utf8. Then the error is no more.

Python 3: EOF when reading a line (Sublime Text 2 is angry)

It seems as of now, the only solution is still to install SublimeREPL.

To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:

To enable it, go to Preferences->Key Bindings - User, and copy this in there:

[
    {"keys":["ctrl+r"] , 
    "caption": "SublimeREPL: Python - RUN current file",
    "command": "run_existing_window_command", 
    "args":
        {
            "id": "repl_python_run",
            "file": "config/Python/Main.sublime-menu"
        }
    },
]

Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

  • groupByKey() is just to group your dataset based on a key. It will result in data shuffling when RDD is not already partitioned.
  • reduceByKey() is something like grouping + aggregation. We can say reduceBykey() equvelent to dataset.group(...).reduce(...). It will shuffle less data unlike groupByKey().
  • aggregateByKey() is logically same as reduceByKey() but it lets you return result in different type. In another words, it lets you have a input as type x and aggregate result as type y. For example (1,2),(1,4) as input and (1,"six") as output. It also takes zero-value that will be applied at the beginning of each key.

Note : One similarity is they all are wide operations.

Validating parameters to a Bash script

The sh solution by Brian Campbell, while noble and well executed, has a few problems, so I thought I'd provide my own bash solution.

The problems with the sh one:

  • The tilde in ~/foo doesn't expand to your homedirectory inside heredocs. And neither when it's read by the read statement or quoted in the rm statement. Which means you'll get No such file or directory errors.
  • Forking off grep and such for basic operations is daft. Especially when you're using a crappy shell to avoid the "heavy" weight of bash.
  • I also noticed a few quoting issues, for instance around a parameter expansion in his echo.
  • While rare, the solution cannot cope with filenames that contain newlines. (Almost no solution in sh can cope with them - which is why I almost always prefer bash, it's far more bulletproof & harder to exploit when used well).

While, yes, using /bin/sh for your hashbang means you must avoid bashisms at all costs, you can use all the bashisms you like, even on Ubuntu or whatnot when you're honest and put #!/bin/bash at the top.

So, here's a bash solution that's smaller, cleaner, more transparent, probably "faster", and more bulletproof.

[[ -d $1 && $1 != *[^0-9]* ]] || { echo "Invalid input." >&2; exit 1; }
rm -rf ~/foo/"$1"/bar ...
  1. Notice the quotes around $1 in the rm statement!
  2. The -d check will also fail if $1 is empty, so that's two checks in one.
  3. I avoided regular expressions for a reason. If you must use =~ in bash, you should be putting the regular expression in a variable. In any case, globs like mine are always preferable and supported in far more bash versions.

What is the difference between __str__ and __repr__?

To put it simply:

__str__ is used in to show a string representation of your object to be read easily by others.

__repr__ is used to show a string representation of the object.

Let's say I want to create a Fraction class where the string representation of a fraction is '(1/2)' and the object (Fraction class) is to be represented as 'Fraction (1,2)'

So we can create a simple Fraction class:

class Fraction:
    def __init__(self, num, den):
        self.__num = num
        self.__den = den

    def __str__(self):
        return '(' + str(self.__num) + '/' + str(self.__den) + ')'

    def __repr__(self):
        return 'Fraction (' + str(self.__num) + ',' + str(self.__den) + ')'



f = Fraction(1,2)
print('I want to represent the Fraction STRING as ' + str(f)) # (1/2)
print('I want to represent the Fraction OBJECT as ', repr(f)) # Fraction (1,2)

How do you parse and process HTML/XML in PHP?

phpQuery and QueryPath are extremely similar in replicating the fluent jQuery API. That's also why they're two of the easiest approaches to properly parse HTML in PHP.

Examples for QueryPath

Basically you first create a queryable DOM tree from an HTML string:

 $qp = qp("<html><body><h1>title</h1>..."); // or give filename or URL

The resulting object contains a complete tree representation of the HTML document. It can be traversed using DOM methods. But the common approach is to use CSS selectors like in jQuery:

 $qp->find("div.classname")->children()->...;

 foreach ($qp->find("p img") as $img) {
     print qp($img)->attr("src");
 }

Mostly you want to use simple #id and .class or DIV tag selectors for ->find(). But you can also use XPath statements, which sometimes are faster. Also typical jQuery methods like ->children() and ->text() and particularly ->attr() simplify extracting the right HTML snippets. (And already have their SGML entities decoded.)

 $qp->xpath("//div/p[1]");  // get first paragraph in a div

QueryPath also allows injecting new tags into the stream (->append), and later output and prettify an updated document (->writeHTML). It can not only parse malformed HTML, but also various XML dialects (with namespaces), and even extract data from HTML microformats (XFN, vCard).

 $qp->find("a[target=_blank]")->toggleClass("usability-blunder");

.

phpQuery or QueryPath?

Generally QueryPath is better suited for manipulation of documents. While phpQuery also implements some pseudo AJAX methods (just HTTP requests) to more closely resemble jQuery. It is said that phpQuery is often faster than QueryPath (because of fewer overall features).

For further information on the differences see this comparison on the wayback machine from tagbyte.org. (Original source went missing, so here's an internet archive link. Yes, you can still locate missing pages, people.)

And here's a comprehensive QueryPath introduction.

Advantages

  • Simplicity and Reliability
  • Simple to use alternatives ->find("a img, a object, div a")
  • Proper data unescaping (in comparison to regular expression grepping)

Better way to Format Currency Input editText?

After looking at most of the StackOverflow posts on different ways to achieve this using a TextWatcher, InputFilter, or library like CurrencyEditText I've settled on this simple solution using an OnFocusChangeListener.

The logic is to parse the EditText to a number when it is focused and to format it back when it loses focus.

amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            Number numberAmount = 0f;
            try {
                numberAmount = Float.valueOf(amount.getText().toString());
            } catch (NumberFormatException e1) {
                e1.printStackTrace();
                try {
                    numberAmount = NumberFormat.getCurrencyInstance().parse(amount.getText().toString());
                } catch (ParseException e2) {
                    e2.printStackTrace();
                }
            }
            if (hasFocus) {
                amount.setText(numberAmount.toString());
            } else {
                amount.setText(NumberFormat.getCurrencyInstance().format(numberAmount));
            }
        }
    });

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

How do I start my app on startup?

Listen for the ACTION_BOOT_COMPLETE and do what you need to from there. There is a code snippet here.

Update:

Original link on answer is down, so based on the comments, here it is linked code, because no one would ever miss the code when the links are down.

In AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

...

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  //MyActivity can be anything which you want to start on bootup...
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

Source: https://web.archive.org/web/20150520124552/http://www.androidsnippets.com/autostart-an-application-at-bootup

How to show full height background image?

This worked for me (though it's for reactjs & tachyons used as inline CSS)

<div className="pa2 cf vh-100-ns" style={{backgroundImage: `url(${a6})`}}> 
........
</div>

This takes in css as height: 100vh

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

If the other answers don't work you can check if something else is using the port with netstat:

netstat -ano | findstr <your port number>

If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:

netsh interface ipv4 show excludedportrange protocol=tcp

How to stop a PowerShell script on the first error?

$ErrorActionPreference = "Stop" will get you part of the way there (i.e. this works great for cmdlets).

However for EXEs you're going to need to check $LastExitCode yourself after every exe invocation and determine whether that failed or not. Unfortunately I don't think PowerShell can help here because on Windows, EXEs aren't terribly consistent on what constitutes a "success" or "failure" exit code. Most follow the UNIX standard of 0 indicating success but not all do. Check out the CheckLastExitCode function in this blog post. You might find it useful.

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Extracting Nupkg files using command line

With PowerShell 5.1 (PackageManagement module)

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

JAVA_HOME is set to an invalid directory:

I am using using Ubuntu.

Problem for me solved by using sudo in terminal with the command.

Flutter Countdown Timer

Here is my Timer widget, not related to the Question but may help someone.

import 'dart:async';

import 'package:flutter/material.dart';

class OtpTimer extends StatefulWidget {
  @override
  _OtpTimerState createState() => _OtpTimerState();
}

class _OtpTimerState extends State<OtpTimer> {
  final interval = const Duration(seconds: 1);

  final int timerMaxSeconds = 60;

  int currentSeconds = 0;

  String get timerText =>
      '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: ${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}';

  startTimeout([int milliseconds]) {
    var duration = interval;
    Timer.periodic(duration, (timer) {
      setState(() {
        print(timer.tick);
        currentSeconds = timer.tick;
        if (timer.tick >= timerMaxSeconds) timer.cancel();
      });
    });
  }

  @override
  void initState() {
    startTimeout();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Icon(Icons.timer),
        SizedBox(
          width: 5,
        ),
        Text(timerText)
      ],
    );
  }
}

You will get something like this

enter image description here

Select distinct values from a list using LINQ in C#

You could implement a custom IEqualityComparer<Employee>:

public class Employee
{
    public string empName { get; set; }
    public string empID { get; set; }
    public string empLoc { get; set; }
    public string empPL { get; set; }
    public string empShift { get; set; }

    public class Comparer : IEqualityComparer<Employee>
    {
        public bool Equals(Employee x, Employee y)
        {
            return x.empLoc == y.empLoc
                && x.empPL == y.empPL
                && x.empShift == y.empShift;
        }

        public int GetHashCode(Employee obj)
        {
            unchecked  // overflow is fine
            {
                int hash = 17;
                hash = hash * 23 + (obj.empLoc ?? "").GetHashCode();
                hash = hash * 23 + (obj.empPL ?? "").GetHashCode();
                hash = hash * 23 + (obj.empShift ?? "").GetHashCode();
                return hash;
            }
        }
    }
}

Now you can use this overload of Enumerable.Distinct:

var distinct = employees.Distinct(new Employee.Comparer());

The less reusable, robust and efficient approach, using an anonymous type:

var distinctKeys = employees.Select(e => new { e.empLoc, e.empPL, e.empShift })
                            .Distinct();
var joined = from e in employees
             join d in distinctKeys
             on new { e.empLoc, e.empPL, e.empShift } equals d
             select e;
// if you want to replace the original collection
employees = joined.ToList();

SQL variable to hold list of integers

Assuming the variable is something akin to:

CREATE TYPE [dbo].[IntList] AS TABLE(
[Value] [int] NOT NULL
)

And the Stored Procedure is using it in this form:

ALTER Procedure [dbo].[GetFooByIds]
    @Ids [IntList] ReadOnly
As 

You can create the IntList and call the procedure like so:

Declare @IDs IntList;
Insert Into @IDs Select Id From dbo.{TableThatHasIds}
Where Id In (111, 222, 333, 444)
Exec [dbo].[GetFooByIds] @IDs

Or if you are providing the IntList yourself

DECLARE @listOfIDs dbo.IntList
INSERT INTO @listofIDs VALUES (1),(35),(118);

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

Resize image proportionally with CSS?

Notice that width:50% will resize it to 50% of the available space for the image, while max-width:50% will resize the image to 50% of its natural size. This is very important to take into account when using this rules for mobile web design, so for mobile web design max-width should always be used.

UPDATE: This was probably an old Firefox bug, that seems to have been fixed by now.

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

How can I view live MySQL queries?

This is the easiest setup on a Linux Ubuntu machine I have come across. Crazy to see all the queries live.

Find and open your MySQL configuration file, usually /etc/mysql/my.cnf on Ubuntu. Look for the section that says “Logging and Replication”

#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.

log = /var/log/mysql/mysql.log

Just uncomment the “log” variable to turn on logging. Restart MySQL with this command:

sudo /etc/init.d/mysql restart

Now we’re ready to start monitoring the queries as they come in. Open up a new terminal and run this command to scroll the log file, adjusting the path if necessary.

tail -f /var/log/mysql/mysql.log

Now run your application. You’ll see the database queries start flying by in your terminal window. (make sure you have scrolling and history enabled on the terminal)

FROM http://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/

Http post and get request in angular 6

For reading full response in Angular you should add the observe option:

{ observe: 'response' }
    return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });

Python Image Library fails with message "decoder JPEG not available" - PIL

I was already using Pillow and got the same error. Tried installing libjpeg or libjpeg-dev as suggested by others but was told that a (newer) version was already installed.

In the end all it took was reinstalling Pillow:

sudo pip uninstall Pillow
sudo pip install Pillow

Using Selenium Web Driver to retrieve value of a HTML input

As was mentioned before, you could do something like that

public String getVal(WebElement webElement) {
    JavascriptExecutor e = (JavascriptExecutor) driver;
    return (String) e.executeScript(String.format("return $('#%s').val();", webElement.getAttribute("id")));
}

But as you can see, your element must have an id attribute, and also, jquery on your page.

What version of JBoss I am running?

JBoss has an MBean called Server. That reports the build and version of JBoss itself. Once you know the version, you can see what components are involved. It is not that well cataloged, but you can see it in the release notes.

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

Disable resizing of a Windows Forms form

Another way is to change properties "AutoSize" (set to True) and "AutosizeMode" (set to GrowAndShrink).

This has the effect of the form autosizing to the elements on it and never allowing the user to change its size.

How can I get a first element from a sorted list?

If your collection is not a List (and thus you can't use get(int index)), then you can use the iterator:

Iterator iter = collection.iterator();
if (iter.hasNext()) {
    Object first = iter.next();
}

Generating a random password in php

I know you are trying to generate your password in a specific way, but you might want to look at this method as well...

$bytes = openssl_random_pseudo_bytes(2);

$pwd = bin2hex($bytes);

It's taken from the php.net site and it creates a string which is twice the length of the number you put in the openssl_random_pseudo_bytes function. So the above would create a password 4 characters long.

In short...

$pwd = bin2hex(openssl_random_pseudo_bytes(4));

Would create a password 8 characters long.

Note however that the password only contains numbers 0-9 and small cap letters a-f!

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Npm Error - No matching version found for

try

npm install --force
npm install --legacy-peer-deps

Proxy setting for R

This post pertains to R proxy issues on *nix. You should know that R has many libraries/methods to fetch data over internet.

For 'curl', 'libcurl', 'wget' etc, just do the following:

  1. Open a terminal. Type the following command:

    sudo gedit /etc/R/Renviron.site
    
  2. Enter the following lines:

    http_proxy='http://username:[email protected]:port/'
    https_proxy='https://username:[email protected]:port/'
    

    Replace username, password, abc.com, xyz.com and port with these settings specific to your network.

  3. Quit R and launch again.

This should solve your problem with 'libcurl' and 'curl' method. However, I have not tried it with 'httr'. One way to do that with 'httr' only for that session is as follows:

library(httr)
set_config(use_proxy(url="abc.com",port=8080, username="username", password="password"))

You need to substitute settings specific to your n/w in relevant fields.

Error: class X is public should be declared in a file named X.java

error example:

public class MaainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

correct example:just make sure that you written correct name of activity that is"main activity"

public class MainActivity extends Activity {


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

How to shutdown a Spring Boot Application in a correct way?

Use the static exit() method in the SpringApplication class for closing your spring boot application gracefully.

public class SomeClass {
    @Autowire
    private ApplicationContext context

    public void close() {
        SpringApplication.exit(context);
    }
}

How can I use UIColorFromRGB in Swift?

I really liked Nate Cook's answer but I wanted something a little more idiomatic. I believe this is a really good use case for a convenience initializer via a custom extension.

// UIColorExtensions.swift
import Foundation
import UIKit

extension UIColor {
    convenience init(rgb: UInt) {
        self.init(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}

This can now be used like so:

view.backgroundColor = UIColor(rgb: 0x209624)

I would only recommend monkey patching UIKit classes like this in your own client code, not libraries.

How to initialize a struct in accordance with C programming language standards

If MS has not updated to C99, MY_TYPE a = { true,15,0.123 };

How to handle notification when app in background in Firebase

you want to work onMessageReceived(RemoteMessage remoteMessage) in background send only data part notification part this:

"data":    "image": "",    "message": "Firebase Push Message Using API", 

"AnotherActivity": "True", "to" : "device id Or Device token"

By this onMessageRecivied is call background and foreground no need to handle notification using notification tray on your launcher activity. Handle data payload in using this:

  public void onMessageReceived(RemoteMessage remoteMessage)
    if (remoteMessage.getData().size() > 0) 
    Log.d(TAG, "Message data payload: " + remoteMessage.getData());      

Trying to include a library, but keep getting 'undefined reference to' messages

Yes, It is required to add libraries after the source files/objects files. This command will solve the problem:

gcc -static -L/usr/lib -I/usr/lib main.c -ltommath

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

Getting the PublicKeyToken of .Net assemblies

Another options is to use the open source tool NuGet Package Explorer for this.

From a Nuget package (.nupkg) you could check the PublicKeyToken, or drag the binary (.dll) in the tool. For the latter select first "File -> new"

enter image description here

Why can't I inherit static classes?

My answer: poor design choice. ;-)

This is an interesting debate focused on syntax impact. The core of the argument, in my view, is that a design decision led to sealed static classes. A focus on transparency of the static class's names appearing at the top level instead of hiding ('confusing') behind child names? One can image a language implementation that could access the base or the child directly, confusing.

A pseudo example, assuming static inheritance was defined in some way.

public static class MyStaticBase
{
    SomeType AttributeBase;
}

public static class MyStaticChild : MyStaticBase
{
    SomeType AttributeChild;
}

would lead to:

 // ...
 DoSomethingTo(MyStaticBase.AttributeBase);
// ...

which could (would?) impact the same storage as

// ...
DoSomethingTo(MyStaticChild.AttributeBase);
// ...

Very confusing!

But wait! How would the compiler deal with MyStaticBase and MyStaticChild having the same signature defined in both? If the child overrides than my above example would NOT change the same storage, maybe? This leads to even more confusion.

I believe there is a strong informational space justification for limited static inheritance. More on the limits shortly. This pseudocode shows the value:

public static class MyStaticBase<T>
{
   public static T Payload;
   public static void Load(StorageSpecs);
   public static void Save(StorageSpecs);
   public static SomeType AttributeBase
   public static SomeType MethodBase(){/*...*/};
}

Then you get:

public static class MyStaticChild : MyStaticBase<MyChildPlayloadType>
{
   public static SomeType AttributeChild;
   public static SomeType SomeChildMethod(){/*...*/};
   // No need to create the PlayLoad, Load(), and Save().
   // You, 'should' be prevented from creating them, more on this in a sec...
} 

Usage looks like:

// ...
MyStaticChild.Load(FileNamePath);
MyStaticChild.Save(FileNamePath);
doSomeThing(MyStaticChild.Payload.Attribute);
doSomething(MyStaticChild.AttributeBase);
doSomeThing(MyStaticChild.AttributeChild);
// ...

The person creating the static child does not need to think about the serialization process as long as they understand any limitations that might be placed on the platform's or environment's serialization engine.

Statics (singletons and other forms of 'globals') often come up around configuration storage. Static inheritance would allow this sort of responsibility allocation to be cleanly represented in the syntax to match a hierarchy of configurations. Though, as I showed, there is plenty of potential for massive ambiguity if basic static inheritance concepts are implemented.

I believe the right design choice would be to allow static inheritance with specific limitations:

  1. No override of anything. The child cannot replace the base attributes, fields, or methods,... Overloading should be ok, as long as there is a difference in signature allowing the compiler to sort out child vs base.
  2. Only allow generic static bases, you cannot inherit from a non-generic static base.

You could still change the same store via a generic reference MyStaticBase<ChildPayload>.SomeBaseField. But you would be discouraged since the generic type would have to be specified. While the child reference would be cleaner: MyStaticChild.SomeBaseField.

I am not a compiler writer so I am not sure if I am missing something about the difficulties of implementing these limitations in a compiler. That said, I am a strong believer that there is an informational space need for limited static inheritance and the basic answer is that you can't because of a poor (or over simple) design choice.

Get the client IP address using PHP

In PHP 5.3 or greater, you can get it like this:

$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');

Extract the maximum value within each group in a dataframe

Using sqldf and standard sql to get the maximum values grouped by another variable

https://cran.r-project.org/web/packages/sqldf/sqldf.pdf

library(sqldf)
sqldf("select max(Value),Gene from df1 group by Gene")

or

Using the excellent Hmisc package for a groupby application of function (max) https://www.rdocumentation.org/packages/Hmisc/versions/4.0-3/topics/summarize

library(Hmisc)
summarize(df1$Value,df1$Gene,max)

Count lines in large files

Hadoop is essentially providing a mechanism to perform something similar to what @Ivella is suggesting.

Hadoop's HDFS (Distributed file system) is going to take your 20GB file and save it across the cluster in blocks of a fixed size. Lets say you configure the block size to be 128MB, the file would be split into 20x8x128MB blocks.

You would then run a map reduce program over this data, essentially counting the lines for each block (in the map stage) and then reducing these block line counts into a final line count for the entire file.

As for performance, in general the bigger your cluster, the better the performance (more wc's running in parallel, over more independent disks), but there is some overhead in job orchestration that means that running the job on smaller files will not actually yield quicker throughput than running a local wc

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

The error Cannot find module '../lib/utils/unsupported.js' is caused by require('../lib/utils/unsupported.js') in ./lib/node_modules/npm/bin/npm-cli.js.

According to the nodejs require docs, the required module is searched relative to the file, as it starts with ../.

Thus, if we take the relative path ../lib/utils/unsupported.js starting from ./lib/node_modules/npm/bin/npm-cli.js, the required module must reside in ./lib/node_modules/npm/lib/utils/unsupported.js. If it is not there, I see two options:

  • the installation is corrupt, in which case Vincent Ducastel's answer to reinstall node might work
  • npm is no symlink to ./lib/node_modules/npm/bin/npm-cli.js. This is what caused the error in my setup. If you call npm, it will typically find it be searching it in the directories listed in the PATH env var. It might for example be located in ./bin. However, npm in a ./bin directory should only be a symlink to the aforementioned ./lib/node_modules/npm/bin/npm-cli.js. If it is not a symlink but directly contains the code, somewhere in the installation process the symlink got replaced by the file it links to. In this case, it should be sufficient to recreate the symlink: cd ./bin; rm npm; ln -s ../lib/node_modules/npm/bin/npm-cli.js npm (update: command fixed, thx @massimo)

All answers that suggest to check the NODE_PATH or the npmrc config should be ignored, as these are not considered when searching modules relatively.

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

While other suggested solutions work, If you really want the solution to be made thread safe you should replace ArrayList with CopyOnWriteArrayList

    //List<String> s = new ArrayList<>(); //Will throw exception
    List<String> s = new CopyOnWriteArrayList<>();
    s.add("B");
    Iterator<String> it = s.iterator();
    s.add("A");

    //Below removes only "B" from List
    while (it.hasNext()) {
        s.remove(it.next());
    }
    System.out.println(s);

How to NodeJS require inside TypeScript file?

Use typings to access node functions from TypeScript:

typings install env~node --global

If you don't have typings install it:

npm install typings --global

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

__FILE__ macro shows full path

In VC, when using /FC, __FILE__ expands to the full path, without the /FC option __FILE__ expands file name. ref: here

Swift: print() vs println() vs NSLog()

There's another method called dump() which can also be used for logging:

func dump<T>(T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)

Dumps an object’s contents using its mirror to standard output.

From Swift Standard Library Functions

VBA error 1004 - select method of range class failed

You have to select the sheet before you can select the range.

I've simplified the example to isolate the problem. Try this:

Option Explicit


Sub RangeError()

    Dim sourceBook As Workbook
    Dim sourceSheet As Worksheet
    Dim sourceSheetSum As Worksheet

    Set sourceBook = ActiveWorkbook
    Set sourceSheet = sourceBook.Sheets("Sheet1")
    Set sourceSheetSum = sourceBook.Sheets("Sheet2")

    sourceSheetSum.Select

    sourceSheetSum.Range("C3").Select           'THIS IS THE PROBLEM LINE

End Sub

Replace Sheet1 and Sheet2 with your sheet names.

IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.

File path for project files?

I was facing a similar issue, I had a file on my project, and wanted to test a class which had to deal with loading files from the FS and process them some way. What I did was:

  • added the file test.txt to my test project
  • on the solution explorer hit alt-enter (file properties)
  • there I set BuildAction to Content and Copy to Output Directory to Copy if newer, I guess Copy always would have done it as well

then on my tests I just had to Path.Combine(Environment.CurrentDirectory, "test.txt") and that's it. Whenever the project is compiled it will copy the file (and all it's parent path, in case it was in, say, a folder) to the bin\Debug (or whatever configuration you are using) folder.

Hopes this helps someone

Google Map API - Removing Markers

You can try this

    markers[markers.length-1].setMap(null);

Hope it works.

is it possible to update UIButton title/text programmatically?

As of Swift 4:

    button.setTitle("Click", for: .normal)

Remove all special characters, punctuation and spaces from string

Removing Punctuations, Numbers, and Special Characters

Example :-

enter image description here

Code

combi['tidy_tweet'] = combi['tidy_tweet'].str.replace("[^a-zA-Z#]", " ") 

Result:- enter image description here

Thanks :)

How can I serve static html from spring boot?

In Spring boot, /META-INF/resources/, /resources/, static/ and public/ directories are available to serve static contents.

So you can create a static/ or public/ directory under resources/ directory and put your static contents there. And they will be accessible by: http://localhost:8080/your-file.ext. (assuming the server.port is 8080)

You can customize these directories using spring.resources.static-locations in the application.properties.

For example:

spring.resources.static-locations=classpath:/custom/

Now you can use custom/ folder under resources/ to serve static files.

Update:

This is also possible using java config:

@Configuration
public class StaticConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/custom/");
    }
}

This confugration maps contents of custom directory to the http://localhost:8080/static/** url.

Is there a NumPy function to return the first index of something in an array?

There are lots of operations in NumPy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:

numpy.nonzero(array - item)

You could then take the first elements of the lists to get a single element.

Relative imports in Python 3

I needed to run python3 from the main project directory to make it work.

For example, if the project has the following structure:

project_demo/
+-- main.py
+-- some_package/
¦   +-- __init__.py
¦   +-- project_configs.py
+-- test/
    +-- test_project_configs.py

Solution

I would run python3 inside folder project_demo/ and then perform a

from some_package import project_configs

How to test enum types?

I agree with aberrant80.

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

I would expand on it by adding that unit testings an Enum can be very useful. If you work in a large code base, build time starts to mount up and a unit test can be a faster way to verify functionality (tests only build their dependencies). Another really big advantage is that other developers cannot change the functionality of your code unintentionally (a huge problem with very large teams).

And with all Test Driven Development, tests around an Enums Methods reduce the number of bugs in your code base.

Simple Example

public enum Multiplier {
    DOUBLE(2.0),
    TRIPLE(3.0);

    private final double multiplier;

    Multiplier(double multiplier) {
        this.multiplier = multiplier;
    }

    Double applyMultiplier(Double value) {
        return multiplier * value;
    }

}

public class MultiplierTest {

    @Test
    public void should() {
        assertThat(Multiplier.DOUBLE.applyMultiplier(1.0), is(2.0));
        assertThat(Multiplier.TRIPLE.applyMultiplier(1.0), is(3.0));
    }
}

Attach a file from MemoryStream to a MailMessage in C#

If all you're doing is attaching a string, you could do it in just 2 lines:

mail.Attachments.Add(Attachment.CreateAttachmentFromString("1,2,3", "text/csv");
mail.Attachments.Last().ContentDisposition.FileName = "filename.csv";

I wasn't able to get mine to work using our mail server with StreamWriter.
I think maybe because with StreamWriter you're missing a lot of file property information and maybe our server didn't like what was missing.
With Attachment.CreateAttachmentFromString() it created everything I needed and works great!

Otherwise, I'd suggest taking your file that is in memory and opening it using MemoryStream(byte[]), and skipping the StreamWriter all together.

SQL Insert Query Using C#

Try

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username, @password, @email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
    //a shorter syntax to adding parameters
    command.Parameters.Add("@id", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@username", SqlDbType.NChar).Value = "abc";

    //a longer syntax for adding parameters
    command.Parameters.Add("@password", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@email", SqlDbType.NChar).Value = "abc";

    //make sure you open and close(after executing) the connection
    connection.Open();
    command.ExecuteNonQuery();
}

Correctly Parsing JSON in Swift 3

This is an other way to solve your problem. So please check out below solution. Hope it will help you.

let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
    let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
    if let names = json["names"] as? [String] {
        print(names)
    }
} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}

How to check if a symlink exists

  1. first you can do with this style:

    mda="/usr/mda"
    if [ ! -L "${mda}" ]; then
      echo "=> File doesn't exist"
    fi
    
  2. if you want to do it in more advanced style you can write it like below:

    #!/bin/bash
    mda="$1"
    if [ -e "$1" ]; then
        if [ ! -L "$1" ]
        then
            echo "you entry is not symlink"
        else
            echo "your entry is symlink"
        fi
    else
      echo "=> File doesn't exist"
    fi
    

the result of above is like:

root@linux:~# ./sym.sh /etc/passwd
you entry is not symlink
root@linux:~# ./sym.sh /usr/mda 
your entry is symlink
root@linux:~# ./sym.sh 
=> File doesn't exist

MAX(DATE) - SQL ORACLE

SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
    SELECT MAX(p2.PAYM_DATE)
    FROM user_payments as p2
    WHERE p2.USER_ID = p.USER_ID
)

Import pandas dataframe column as string not int

This probably isn't the most elegant way to do it, but it gets the job done.

In[1]: import numpy as np

In[2]: import pandas as pd

In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])

In[4]: df
Out[4]: 
                       ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

Just replace '/Users/spencerlyon2/Desktop/test.csv' with the path to your file

How do I query for all dates greater than a certain date in SQL Server?

DateTime start1 = DateTime.Parse(txtDate.Text);

SELECT * 
FROM dbo.March2010 A
WHERE A.Date >= start1;

First convert TexBox into the Datetime then....use that variable into the Query

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

Mobile Safari: Javascript focus() method on inputfield only works with click?

Please try using on-tap instead of ng-click event. I had this issue. I resolved it by making my clear-search-box button inside search form label and replaced ng-click of clear-button by on-tap. It works fine now.

Constants in Objective-C

If you want to call something like this NSString.newLine; from objective c, and you want it to be static constant, you can create something like this in swift:

public extension NSString {
    @objc public static let newLine = "\n"
}

And you have nice readable constant definition, and available from within a type of your choice while stile bounded to context of type.

Apply style to cells of first row

Below works for first tr of the table under thead

table thead tr:first-child {
   background: #f2f2f2;
}

And this works for the first tr of thead and tbody both:

table thead tbody tr:first-child {
   background: #f2f2f2;
}

ruby LoadError: cannot load such file

The problem shall have solved if you specify your path.

e.g.

"require 'st.rb'" --> "require './st.rb'"

See if your problem get solved or not.

jQuery datepicker, onSelect won't work

<script type="text/javascript">
    $(function() {
        $("#datepicker").datepicker({ 
              onSelect: function(value, date) { 
                 window.location = 'day.jsp' ; 
              } 
        });
    });
 </script>

<div id="datepicker"></div>

I think you can try this .It works fine .

Checkbox value true/false

Checkboxes can be really weird in JS. You're best off checking for the presence of the checked attribute. (I've had older jQuery versions return true even if checked is set to 'false'.) Once you've determined that something is checked then you can get the value from the value attribute.

What jsf component can render a div tag?

I think we can you use verbatim tag, as in this tag we use any of the HTML tags

Clearing Magento Log Data

Try:

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;

You can also refer to following tutorial:
http://www.crucialwebhost.com/kb/article/log-cache-maintenance-script/

Thanks

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

public static void main(String[] args) {
    String start = "THIS_IS_A_TEST";
    StringBuffer sb = new StringBuffer();
    for (String s : start.split("_")) {
        sb.append(Character.toUpperCase(s.charAt(0)));
        if (s.length() > 1) {
            sb.append(s.substring(1, s.length()).toLowerCase());
        }
    }
    System.out.println(sb);
}

Change a Nullable column to NOT NULL with Default Value

Try this

ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;

Could you explain STA and MTA?

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

Reading all files in a directory, store them in objects, and send the object

async/await

const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)

try {
  async function emitData(directory) {
    let filenames = await pathnames
    var ob = {}
    const data = filenames.map(async function(filename, i) {
      if (filename.includes(".")) {
        var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
          encoding: "utf8",
        })
        ob[filename.replace(".js", "")] = await storedFile
        socket.emit("init", { data: ob })
      }
      return ob
    })
  }

  emitData(directory)
} catch (err) {
  console.log(err)
}

Who wants to try with generators?

How to set radio button checked as default in radiogroup?

It's a bug of RadioGroup

RadioButton radioBtn2 = new RadioButton(context);

radioBtn2 without viewId, and generateViewId is in onChildViewAdded()

public void onChildViewAdded(View parent, View child) {
    if (parent == RadioGroup.this && child instanceof RadioButton) {
        int id = child.getId();
        // generates an id if it's missing
        if (id == View.NO_ID) {
            id = View.generateViewId();
            child.setId(id);
        }
        ((RadioButton) child).setOnCheckedChangeWidgetListener(
                mChildOnCheckedChangeListener);
    }

    if (mOnHierarchyChangeListener != null) {
        mOnHierarchyChangeListener.onChildViewAdded(parent, child);
    }
}

so, first radioGroup.addView(radioBtn2), then radioBtn2.setChecked(true);

Like this:

RadioGroup radioGroup = new RadioGroup(context);
RadioButton radioBtn1 = new RadioButton(context);
RadioButton radioBtn2 = new RadioButton(context);
RadioButton radioBtn3 = new RadioButton(context);

radioBtn1.setText("Less");
radioBtn2.setText("Normal");
radioBtn3.setText("More");

radioGroup.addView(radioBtn1);
radioGroup.addView(radioBtn2);
radioGroup.addView(radioBtn3);

radioBtn2.setChecked(true);

PYTHONPATH on Linux

PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

How to get attribute of element from Selenium?

You are probably looking for get_attribute(). An example is shown here as well

def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?
    val = org.get_attribute("attribute name")

JQuery, setTimeout not working

You've got a couple of issues here.

Firstly, you're defining your code within an anonymous function. This construct:

(function() {
  ...
)();

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

(function() {
  $(document).ready(function() {update();});

  function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);     }
  }
)();

because the function pointer update is within scope of that block.

But like I said, there is no need for the anonymous function so you can rewrite it like this:

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout(update, 1000);     }
}

or

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);     }
}

and both of these work. The second works because the update() within the code block is within scope now.

I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

$(function() {
  setInterval(update, 1000);
});

function update() {
  $("#board").append(".");
}

Hope that clears that up.

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How do I get sed to read from standard input?

use "-e" to specify the sed-expression

cat input.txt | sed -e 's/foo/bar/g'

Eclipse doesn't stop at breakpoints

I suddenly experienced the skipping of breakpoints as well in Eclipse Juno CDT. For me the issue was that I had set optimization levels up. Once I set it back to none it was working fine. To set optimization levels go to Project Properties -> C/C++ Build -> Settings -> Tool Settings pan depending on which compiler you are using go to -> Optimization and set Optimization Level to: None (-O0). Hope this helps! Best

Difference between View and table in sql

Table:

Table stores the data in database and contains the data.

View:

View is an imaginary table, contains only the fields(columns) and does not contain data(row) which will be framed at run time Views created from one or more than one table by joins, with selected columns. Views are created to hide some columns from the user for security reasons, and to hide information exist in the column. Views reduces the effort for writing queries to access specific columns every time Instead of hitting the complex query to database every time, we can use view

MySQL maximum memory usage

We use these settings:

etc/my.cnf
innodb_buffer_pool_size = 384M
key_buffer = 256M
query_cache_size = 1M
query_cache_limit = 128M
thread_cache_size = 8
max_connections = 400
innodb_lock_wait_timeout = 100

for a server with the following specifications:

Dell Server
CPU cores: Two
Processor(s): 1x Dual Xeon
Clock Speed: >= 2.33GHz
RAM: 2 GBytes
Disks: 1×250 GB SATA

How do you synchronise projects to GitHub with Android Studio?

For existing project end existing repository with files:

git init
git remote add origin <.git>
git checkout -b master
git branch --set-upstream-to=origin/master master
git pull --allow-unrelated-histories

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

Setting a Sheet and cell as variable

Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:

Sub RangeExample()
Dim MyRNG As Range

Set MyRNG = Sheets("Sheet1").Cells(23, 4)

Debug.Print MyRNG.Value

End Sub

Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:

Sub ValueExample()
Dim MyVal As String

MyVal = Sheets("Sheet1").Cells(23, 4).Value

Debug.Print MyVal

End Sub

What is an AssertionError? In which case should I throw it from my own code?

The meaning of an AssertionError is that something happened that the developer thought was impossible to happen.

So if an AssertionError is ever thrown, it is a clear sign of a programming error.

How do I check what version of Python is running my script?

I like sys.hexversion for stuff like this.

>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True

Javascript change Div style

Using jQuery:

$(document).ready(function(){
    $('div').click(function(){
        $(this).toggleClass('clicked');
    });
});?

Live example

Using sendmail from bash script for multiple recipients

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add yout Recepient list to message itself like To: [email protected] [email protected] right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

Where to install Android SDK on Mac OS X?

By default the android sdk installer path is ~/Library/Android/sdk/

Change SVN repository URL

If you are using TortoiseSVN client then you can follow the below steps

Right-click in the source directory and then click on SVN Relocate Image#1

After that, you need to change the URL to what you want, click ok, it will be taking a few seconds.Image#2

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

What is ANSI format?

Basically "ANSI" refers to the legacy codepage on Windows. See also an article by Raymond Chen on this topic:

The source of this comes from the fact that the Windows code page 1252 was originally based on an ANSI draft, which became ISO Standard 8859-1.

The first 127 characters are identical to ASCII in most code pages, the upper characters vary, though.

However, ANSI does not automatically mean CP1252 or Latin 1.

All confusion notwithstanding you should simply avoid such issues nowadays and use Unicode.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Or simply run this comment to add the server Certificate to your database:

echo $(echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpGilabPort 2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p') >> /etc/ssl/certs/ca-certificates.crt

Then do git clone again.

(413) Request Entity Too Large | uploadReadAheadSize

I was having the same issue with IIS 7.5 with a WCF REST Service. Trying to upload via POST any file above 65k and it would return Error 413 "Request Entity too large".

The first thing you need to understand is what kind of binding you've configured in the web.config. Here's a great article...

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

If you have a REST service then you need to configure it as "webHttpBinding". Here's the fix:

<system.serviceModel>

<bindings>
   <webHttpBinding>
    <binding 
      maxBufferPoolSize="2147483647" 
      maxReceivedMessageSize="2147483647" 
      maxBufferSize="2147483647" transferMode="Streamed">
    </binding>  
   </webHttpBinding>
</bindings>

Add alternating row color to SQL Server Reporting services report

If for the entire report you need an alternating color, you can use the DataSet your Tablix is bound to for a report-wide identity rownumber on the report and use that in the RowNumber function...

=IIf(RowNumber("DataSet1")  Mod 2 = 1, "White","Blue")

Disable single warning error

as @rampion mentioned, if you are in clang gcc, the warnings are by name, not number, and you'll need to do:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
// ..your code..
#pragma clang diagnostic pop

this info comes from here

How to append one file to another in Linux from the shell?

Just for reference, using ddrescue provides an interruptible way of achieving the task if, for example, you have large files and the need to pause and then carry on at some later point:

ddrescue -o $(wc --bytes file1 | awk '{ print $1 }') file2 file1 logfile

The logfile is the important bit. You can interrupt the process with Ctrl-C and resume it by specifying the exact same command again and ddrescue will read logfile and resume from where it left off. The -o A flag tells ddrescue to start from byte A in the output file (file1). So wc --bytes file1 | awk '{ print $1 }' just extracts the size of file1 in bytes (you can just paste in the output from ls if you like).

As pointed out by ngks in the comments, the downside is that ddrescue will probably not be installed by default, so you will have to install it manually. The other complication is that there are two versions of ddrescue which might be in your repositories: see this askubuntu question for more info. The version you want is the GNU ddrescue, and on Debian-based systems is the package named gddrescue:

sudo apt install gddrescue

For other distros check your package management system for the GNU version of ddrescue.

Running Python on Windows for Node.js dependencies

Example : pg_config not executable / error node-gyp

Solution : On windows just try to add PATH Env -> C:\Program Files\PostgreSQL\12\bin

Work for me, Now i can use npm i pg-promise for example or other dependencies.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

In my case, I was getting the above error for my email id with github was not verified yet. GitHub was giving this warning of un-verified email.

Verifying the email, and then pushing worked for me.

CSS 100% height with padding/margin

The better way is with the calc() property. So your case would look like:

#myDiv {
    width: calc(100% - 5px);
    height: calc(100% - 5px);
    padding: 5px;
}

Simple, clean, no workarounds. Just make sure you don't forget the space between the values and the operator (eg (100%-5px) that will break the syntax. Enjoy!