Programs & Examples On #Steganography

Steganography is the study of hidden information in pictures, text, audio or video. It covers both methods of concealing information and methods of detecting hidden information.

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

How to use UTF-8 in resource properties with ResourceBundle

Given that you have an instance of ResourceBundle and you can get String by:

String val = bundle.getString(key); 

I solved my Japanese display problem by:

return new String(val.getBytes("ISO-8859-1"), "UTF-8");

scrollTop jquery, scrolling to div with id?

My solution was the following:

document.getElementById("agent_details").scrollIntoView();

How to read/write arbitrary bits in C/C++

You have to do a shift and mask (AND) operation. Let b be any byte and p be the index (>= 0) of the bit from which you want to take n bits (>= 1).

First you have to shift right b by p times:

x = b >> p;

Second you have to mask the result with n ones:

mask = (1 << n) - 1;
y = x & mask;

You can put everything in a macro:

#define TAKE_N_BITS_FROM(b, p, n) ((b) >> (p)) & ((1 << (n)) - 1)

java.lang.OutOfMemoryError: Java heap space

To increase the heap size you can use the -Xmx argument when starting Java; e.g.

-Xmx256M

How to set up java logging using a properties file? (java.util.logging)

you can set your logging configuration file through command line:

$ java -Djava.util.logging.config.file=/path/to/app.properties MainClass

this way seems cleaner and easier to maintain.

Open text file and program shortcut in a Windows batch file

"location of notepad file" > notepad Filename

C:\Users\Desktop\Anaconda> notepad myfile

works for me! :)

How to get back to most recent version in Git?

When you checkout to a specific commit, git creates a detached branch. So, if you call:

$ git branch 

You will see something like:

* (detached from 3i4j25)
  master
  other_branch

To come back to the master branch head you just need to checkout to your master branch again:

$ git checkout master

This command will automatically delete the detached branch.

If git checkout doesn't work you probably have modified files conflicting between branches. To prevent you to lose code git requires you to deal with these files. You have three options:

  1. Stash your modifications (you can pop them later):

    $ git stash
    
  2. Discard the changes reset-ing the detached branch:

    $ git reset --hard
    
  3. Create a new branch with the previous modifications and commit them:

    $ git checkout -b my_new_branch
    $ git add my_file.ext
    $ git commit -m "My cool msg"
    

After this you can go back to your master branch (most recent version):

$ git checkout master

Java8: sum values from specific field of the objects in a list

You can also collect with an appropriate summing collector like Collectors#summingInt(ToIntFunction)

Returns a Collector that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.

For example

Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));

Best way in asp.net to force https for an entire site?

-> Simply ADD [RequireHttps] on top of the public class HomeController : Controller.

-> And add GlobalFilters.Filters.Add(new RequireHttpsAttribute()); in 'protected void Application_Start()' method in Global.asax.cs file.

Which forces your entire application to HTTPS.

Maintain aspect ratio of div but fill screen width and height in CSS?

Just reformulating Danield's answer in a LESS mixin, for further usage:

// Mixin for ratio dimensions    
.viewportRatio(@x, @y) {
  width: 100vw;
  height: @y * 100vw / @x;
  max-width: @x / @y * 100vh;
  max-height: 100vh;
}

div {

  // Force a ratio of 5:1 for all <div>
  .viewportRatio(5, 1);

  background-color: blue;
  margin: 0;
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

RegEx match open tags except XHTML self-contained tags

Don't listen to these guys. You totally can parse context-free grammars with regex if you break the task into smaller pieces. You can generate the correct pattern with a script that does each of these in order:

  1. Solve the Halting Problem.
  2. Square a circle.
  3. Work out the Traveling Salesman Problem in O(log n) or less. If it's any more than that, you'll run out of RAM and the engine will hang.
  4. The pattern will be pretty big, so make sure you have an algorithm that losslessly compresses random data.
  5. Almost there - just divide the whole thing by zero. Easy-peasy.

I haven't quite finished the last part myself, but I know I'm getting close. It keeps throwing CthulhuRlyehWgahnaglFhtagnExceptions for some reason, so I'm going to port it to VB 6 and use On Error Resume Next. I'll update with the code once I investigate this strange door that just opened in the wall. Hmm.

P.S. Pierre de Fermat also figured out how to do it, but the margin he was writing in wasn't big enough for the code.

Requested registry access is not allowed

app.manifest should be like this:

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
   <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
      <security>
         <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
         </requestedPrivileges>
      </security>
   </trustInfo>
</asmv1:assembly>

How do I correctly use "Not Equal" in MS Access?

I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.

I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.

Thanks to all above though.

Performance of Java matrix math libraries?

Linalg code that relies heavily on Pentiums and later processors' vector computing capabilities (starting with the MMX extensions, like LAPACK and now Atlas BLAS) is not "fantastically optimized", but simply industry-standard. To replicate that perfomance in Java you are going to need native libraries. I have had the same performance problem as you describe (mainly, to be able to compute Choleski decompositions) and have found nothing really efficient: Jama is pure Java, since it is supposed to be just a template and reference kit for implementers to follow... which never happened. You know Apache math commons... As for COLT, I have still to test it but it seems to rely heavily on Ninja improvements, most of which were reached by building an ad-hoc Java compiler, so I doubt it's going to help. At that point, I think we "just" need a collective effort to build a native Jama implementation...

What's the best way to store Phone number in Django models

Others mentioned django-phonenumber-field. To get the display format how you want you need to set PHONENUMBER_DEFAULT_FORMAT setting to "E164", "INTERNATIONAL", "NATIONAL", or "RFC3966", however you want it displayed. See the GitHub source.

How to use ES6 Fat Arrow to .filter() an array of objects

return arrayname.filter((rec) => rec.age > 18)

Write this in the method and call it

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

How do I clear the std::queue efficiently?

Apparently, there are two most obvious ways to clear std::queue: swapping with empty object and assignment to empty object.

I would suggest using assignment because it simply faster, more readable, and unambiguous.

I measured performance using following simple code and I found that swapping in C++03 version works 70-80% slower than assignment to an empty object. In C++11 there is no difference in performance, however. Anyway, I would go with assignment.

#include <algorithm>
#include <ctime>
#include <iostream>
#include <queue>
#include <vector>

int main()
{
    std::cout << "Started" << std::endl;

    std::queue<int> q;

    for (int i = 0; i < 10000; ++i)
    {
        q.push(i);
    }

    std::vector<std::queue<int> > queues(10000, q);

    const std::clock_t begin = std::clock();

    for (std::vector<int>::size_type i = 0; i < queues.size(); ++i)
    {
        // OK in all versions
        queues[i] = std::queue<int>();

        // OK since C++11
        // std::queue<int>().swap(queues[i]);

        // OK before C++11 but slow
        // std::queue<int> empty;
        // std::swap(empty, queues[i]);
    }

    const double elapsed = double(clock() - begin) / CLOCKS_PER_SEC;

    std::cout << elapsed << std::endl;

    return 0;
}

Celery Received unregistered task of type (run example)

If you are using the apps config in installed apps like this:

LOCAL_APPS = [
'apps.myapp.apps.MyAppConfig']

Then in your config app, import the task in ready method like this:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'apps.myapp'

    def ready(self):
        try:
            import apps.myapp.signals  # noqa F401
            import apps.myapp.tasks
        except ImportError:
            pass

How to get my activity context?

You can use Application class(public class in android.application package),that is:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

To use this class do:

public class App extends Application {

    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    public static void setContext(Context mContext) {
        this.mContext = mContext;
    }

    ...

}

In your manifest:

<application
        android:icon="..."
        android:label="..."
        android:name="com.example.yourmainpackagename.App" >
                       class that extends Application ^^^

In Activity B:

public class B extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sampleactivitylayout);

        App.setContext(this);
                  ...
        }
...
}

In class A:

Context c = App.getContext();

Note:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

SQL Server - transactions roll back on error?

Here the code with getting the error message working with MSSQL Server 2016:

BEGIN TRY
    BEGIN TRANSACTION 
        -- Do your stuff that might fail here
    COMMIT
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN

        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE()
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY()
        DECLARE @ErrorState INT = ERROR_STATE()

    -- Use RAISERROR inside the CATCH block to return error  
    -- information about the original error that caused  
    -- execution to jump to the CATCH block.  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I had the same problem in Xcode 8.1 and iOS 10.1. What worked for me was going into Simulator-> Hardware->Keyboard and unchecking Connect Hardware Keyboard.

Send text to specific contact programmatically (whatsapp)

This approach works with WhatsApp Business app as well!

Change package name as sendIntent.setPackage("com.whatsapp.w4b"); for WhatsApp Business.

Great hack Rishabh, thanks a lot, I was looking for this solution since last 3 years.

As per the Rishabh Maurya's answer above, I have implemented this code which is working fine for both text and image sharing on WhatsApp.

Note that in both the cases it opens a whatsapp conversation (if toNumber exists in users whatsapp contact list), but user have to click send button to complete the action. That means it helps in skipping contact selection step.

For text messages

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);

For sharing images

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
context.startActivity(sendIntent);

Enjoy WhatsApping!

Convert date to UTC using moment.js

here, I'm passing the date object and converting it into UTC time.

$.fn.convertTimeToUTC = function (convertTime) {
   if($(this).isObject(convertTime)) {
        return moment.tz(convertTime.format("Y-MM-DD HH:mm:ss"), moment.tz.guess()).utc().format("Y-MM-DD HH:mm:ss");
    }
};
// Returns if a value is an object
$.fn.isObject =  function(value) {
    return value && typeof value === 'object';
};


//you can call it as below
$(this).convertTimeToUTC(date);

Save each sheet in a workbook to separate CSV files

Use Visual Basic to loop through worksheets and save .csv files.

  1. Open up .xlsx file in Excel.

  2. Press option+F11

  3. Insert ? Module

  4. Insert this into the module code:

    Public Sub SaveWorksheetsAsCsv()
    
     Dim WS As Excel.Worksheet
     Dim SaveToDirectory As String
    
     SaveToDirectory = "./"
    
     For Each WS In ThisWorkbook.Worksheets
        WS.SaveAs SaveToDirectory & WS.Name & ".csv", xlCSV
     Next
    
    End Sub
    
  5. Find your .csv files in ~/Library/Containers/com.microsoft.Excel/Data.

    open ~/Library/Containers/com.microsoft.Excel/Data
    
  6. Close .xlsx file.

  7. Rinse and repeat for other .xlsx files.

How should I edit an Entity Framework connection string?

If you remove the connection string from the app.config file, re-running the entity Data Model wizard will guide you to build a new connection.

Codeigniter LIKE with wildcard(%)

$this->db->like() automatically adds the %s and escapes the string. So all you need is

$this->db->like('title', $query);
$res = $this->db->get('film');

See the CI documentation for reference: CI 2, CI 3, CI 4

What’s the best RESTful method to return total number of items in an object?

I prefer using HTTP Headers for this kind of contextual information.

For the total number of elements, I use the X-total-count header.
For links to next, previous page, etc. I use HTTP Link header:
http://www.w3.org/wiki/LinkHeader

Github does it the same way: https://developer.github.com/v3/#pagination

In my opinion, it's cleaner since it can be used also when you return content that doesn't support hyperlinks (i.e binaries, pictures).

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

How to initialize all the elements of an array to any specific value in java

You could do this if it's short:

int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

but that gets bad for more than just a few.

Easier would be a for loop:

  int[] myArray = new int[10];
  for (int i = 0; i < array.length; i++)
       myArray[i] = -1;

Edit: I also like the Arrays.fill() option other people have mentioned.

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

Bootstrap Element 100% Width

In bootstrap 4, you can use 'w-100' class (w as width, and 100 as 100%)

You can find documentation here: https://getbootstrap.com/docs/4.0/utilities/sizing/

Android Dialog: Removing title bar

use below code before setcontentview :-

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
dialog.setContentView(R.layout.custom_dialog);

Note:- above code must have to use above dialog.setContentView(R.layout.custom_dialog);

In XML use a theme

android:theme="@android:style/Theme.NoTitleBar"

also styles.xml:

<style name="hidetitle" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

And then:

Dialog dialog_hidetitle_example = new Dialog(context, R.style.hidetitle);

Remap values in pandas column with a dict

DSM has the accepted answer, but the coding doesn't seem to work for everyone. Here is one that works with the current version of pandas (0.23.4 as of 8/2018):

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 2, 3, 1],
            'col2': ['negative', 'positive', 'neutral', 'neutral', 'positive']})

conversion_dict = {'negative': -1, 'neutral': 0, 'positive': 1}
df['converted_column'] = df['col2'].replace(conversion_dict)

print(df.head())

You'll see it looks like:

   col1      col2  converted_column
0     1  negative                -1
1     2  positive                 1
2     2   neutral                 0
3     3   neutral                 0
4     1  positive                 1

The docs for pandas.DataFrame.replace are here.

How to change node.js's console font color?

I really liked @Daniel's answer, but the console.log{color} functions didn't work the same way as regular console.log. I have made a few changes, and now all parameters to the new functions will be passed to console.log (as well as the color codes).

const _colors = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

const enableColorLogging = function(){
    Object.keys(_colors).forEach(key => {
        console['log' + key] = function(){
            return console.log(_colors[key], ...arguments, _colors.Reset);
        }
    });
}

Python IndentationError unindent does not match any outer indentation level

I had the same problem quite a few times. It happened especially when i tried to paste a few lines of code from an editor online, the spaces are not registered properly as 'tabs' or 'spaces'.

However the fix was quite simple. I just had to remove the spacing across all the lines of code in that specific set and space it again with the tabs correctly. This fixed my problem.

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

@echo off

:START
rmdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause

echo.
echo.
echo Note the directory is not found
echo.
echo Press any key to make a temporary directory, cls, and test again
pause

Mkdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause
echo.
echo press any key to goto START and remove temporary directory 
pause 

goto START

how to specify new environment location for conda create

like Paul said, use

conda create --prefix=/users/.../yourEnvName python=x.x

if you are located in the folder in which you want to create your virtual environment, just omit the path and use

conda create --prefix=yourEnvName python=x.x

conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

source activate yourEnvName

Delayed function calls

It's indeed a very bad design, let alone singleton by itself is bad design.

However, if you really do need to delay execution, here's what you may do:

BackgroundWorker barInvoker = new BackgroundWorker();
barInvoker.DoWork += delegate
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));
        bar();
    };
barInvoker.RunWorkerAsync();

This will, however, invoke bar() on a separate thread. If you need to call bar() in the original thread you might need to move bar() invocation to RunWorkerCompleted handler or do a bit of hacking with SynchronizationContext.

How to use index in select statement?

The optimiser will judge if the use of your index will make your query run faster, and if it is, it will use the index.

Depending on your RDBMS you can force the use of an index, although it is not recommended unless you know what you are doing.

In general you should index columns that you use in table join's and where statements

vertical divider between two columns in bootstrap

If your code looks like this:

<div class="row">
  <div class="span6">
  </div>
  <div class="span6">
  </div>
</div>

Then I'd assume you're using additional DIVS within the "span6" DIVS for holding/styling your content? So...

<div class="row">
  <div class="span6">
    <div class="mycontent-left">
    </div>
  </div>
  <div class="span6">
    <div class="mycontent-right">
    </div>
  </div>
</div>

So you could simply add some CSS to the "mycontent-left" class to create your divider.

.mycontent-left {
  border-right: 1px dashed #333;
}

JavaScript: Create and save file

Tried this in the console, and it works.

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));

Detecting an undefined object property

You can use the JavaScript object function like this:

var ojb ={
    age: 12
}

if(ojb.hasOwnProperty('name')){
    console.log('property exists and is not undefined');
}

The above method returns true if it got that property or the property is not undefined.

LINQ - Left Join, Group By, and Count

While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.

Here's my solution:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }

Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)

How to list all installed packages and their versions in Python?

My take:

#!/usr/bin/env python3

import pkg_resources

dists = [str(d).replace(" ","==") for d in pkg_resources.working_set]
for i in dists:
    print(i)

Comparing two java.util.Dates to see if they are in the same day

For Kotlin devs this is the version with comparing formatted strings approach:

val sdf = SimpleDateFormat("yyMMdd")
if (sdf.format(date1) == sdf.format(date2)) {
    // same day
}

It's not the best way, but it's short and working.

How to add new elements to an array?

I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size. You have to use an ArrayList or a Vector or any other dynamic structure.

How to concat a string to xsl:value-of select="...?

Easiest method is

  <TD>
    <xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
  </TD>

when the XML Structure is

<title>The Confidence Man</title>
<author>
  <first-name>Herman</first-name>
  <last-name>Melville</last-name>
</author>
<price>11.99</price>

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

Add to python path mac os x

Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile

export PYTHONPATH=/path/to/dir:$PYTHONPATH

my directory is now on the pythonpath -

my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...  

and I can import modules from that directory.

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I'm using jQuery 3.3.1 and I received the same error, in my case, the URL was an Object vs a string.

What happened was, that I took URL = window.location - which returned an object. Once I've changed it into window.location.href - it worked w/o the e.indexOf error.

Average of multiple columns

In PostgreSQL, to get the average of multiple (2 to 8) columns in one row just define a set of seven functions called average(). Will produce the average of the non-null columns.

And then just

select *,(r1+r2+r3+r4+r5)/5.0,average(r1,r2,r3,r4,r5) from request;
 req_id | r1 | r2 | r3 | r4 | r5 |      ?column?      |      average
--------+----+----+----+----+----+--------------------+--------------------
 R12673 |  2 |  5 |  3 |  7 | 10 | 5.4000000000000000 | 5.4000000000000000
 R34721 |  3 |  5 |  2 |  1 |  8 | 3.8000000000000000 | 3.8000000000000000
 R27835 |  1 |  3 |  8 |  5 |  6 | 4.6000000000000000 | 4.6000000000000000
(3 rows)

update request set r4=NULL where req_id='R34721';
UPDATE 1

select *,(r1+r2+r3+r4+r5)/5.0,average(r1,r2,r3,r4,r5) from request;
 req_id | r1 | r2 | r3 | r4 | r5 |      ?column?      |      average
--------+----+----+----+----+----+--------------------+--------------------
 R12673 |  2 |  5 |  3 |  7 | 10 | 5.4000000000000000 | 5.4000000000000000
 R34721 |  3 |  5 |  2 |    |  8 |                    | 4.5000000000000000
 R27835 |  1 |  3 |  8 |  5 |  6 | 4.6000000000000000 | 4.6000000000000000
(3 rows)

select *,(r3+r4+r5)/3.0,average(r3,r4,r5) from request;
 req_id | r1 | r2 | r3 | r4 | r5 |      ?column?      |      average
--------+----+----+----+----+----+--------------------+--------------------
 R12673 |  2 |  5 |  3 |  7 | 10 | 6.6666666666666667 | 6.6666666666666667
 R34721 |  3 |  5 |  2 |    |  8 |                    | 5.0000000000000000
 R27835 |  1 |  3 |  8 |  5 |  6 | 6.3333333333333333 | 6.3333333333333333
(3 rows)

Like this:

CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
    COUNT NUMERIC;
    TOTAL NUMERIC;
BEGIN
    COUNT=0;
    TOTAL=0;
    IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
    IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
    RETURN TOTAL/COUNT;
    EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
    COUNT NUMERIC;
    TOTAL NUMERIC;
BEGIN
    COUNT=0;
    TOTAL=0;
    IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
    IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
    IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
    RETURN TOTAL/COUNT;
    EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
    COUNT NUMERIC;
    TOTAL NUMERIC;
BEGIN
    COUNT=0;
    TOTAL=0;
    IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
    IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
    IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
    IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
    RETURN TOTAL/COUNT;
    EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
    COUNT NUMERIC;
    TOTAL NUMERIC;
BEGIN
    COUNT=0;
    TOTAL=0;
    IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
    IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
    IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
    IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
    IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
    RETURN TOTAL/COUNT;
    EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
    COUNT NUMERIC;
    TOTAL NUMERIC;
BEGIN
    COUNT=0;
    TOTAL=0;
    IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
    IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
    IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
    IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
    IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
    IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
    RETURN TOTAL/COUNT;
    EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC,
V7 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
    COUNT NUMERIC;
    TOTAL NUMERIC;
BEGIN
    COUNT=0;
    TOTAL=0;
    IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
    IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
    IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
    IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
    IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
    IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
    IF V7 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V7; END IF;
    RETURN TOTAL/COUNT;
    EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC,
V7 NUMERIC,
V8 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
    COUNT NUMERIC;
    TOTAL NUMERIC;
BEGIN
    COUNT=0;
    TOTAL=0;
    IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
    IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
    IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
    IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
    IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
    IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
    IF V7 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V7; END IF;
    IF V8 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V8; END IF;
    RETURN TOTAL/COUNT;
    EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;

Type definition in object literal in TypeScript

In your code:

var obj = {
  myProp: string;
};

You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):

var string = 'A string';

var obj = {
  property: string
};

However, what you want is that the object literal is typed. This can be achieved in various ways:

Interface:

interface myObj {
    property: string;
}

var obj: myObj = { property: "My string" };

Type alias:

type myObjType = {
    property: string
};

var obj: myObjType = { property: "My string" };

Object type literal:

var obj: { property: string; } = { property: "Mystring" };

AttributeError: 'module' object has no attribute 'model'

I realized that by looking at the stack trace it was trying to load my own script in place of another module called the same way,i.e., my script was called random.py and when a module i used was trying to import the "random" package, it was loading my script causing a circular reference and so i renamed it and deleted a .pyc file it had created from the working folder and things worked just fine.

Sort list in C# with LINQ

Well, the simplest way using LINQ would be something like this:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true, but the first form makes it clearer IMO, because everyone knows that 0 < 1.

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. If you want to sort in place, you should use the List<T>.Sort method.

prevent refresh of page when button inside form clicked

<form method="POST">
    <button name="data" onclick="getData()">Click</button>
</form>

instead of using button tag, use input tag. Like this,

<form method="POST">
    <input type = "button" name="data" onclick="getData()" value="Click">
</form>

Detect iPhone/iPad purely by css

I use these:

/* Non-Retina */
@media screen and (-webkit-max-device-pixel-ratio: 1) {
}

/* Retina */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
}

/* iPhone Portrait */
@media screen and (max-device-width: 480px) and (orientation:portrait) {
} 

/* iPhone Landscape */
@media screen and (max-device-width: 480px) and (orientation:landscape) {
}

/* iPad Portrait */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
}

/* iPad Landscape */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
}

http://zsprawl.com/iOS/2012/03/css-for-iphone-ipad-and-retina-displays/

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

How to break lines in PowerShell?

Try "`n" with double quotes. (not single quotes '`n' )

For a complete list of escaping characters see:

Help about_Escape_character

The code should be

$str += "`n"

Error: fix the version conflict (google-services plugin)

Important Update

Both Firebase & Play-service dependencies are having independent versions unlike past. If you have version conflicts then you can update your com.google.gms:google-services. and start defining independent version.

Step(1): Update com.google.gms:google-services

Open project level build.gradle and update com.google.gms:google-services to version 4.1.0 MUST CHECK newer if available.

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'com.google.gms:google-services:4.1.0' //< update this 
    }
}

Step(2): Update Firebase dependencies Latest Versions

Firebase dependency versions can be individual.

com.google.firebase:firebase-core:16.0.3    //Analytics, check latest too
com.google.firebase:firebase-database:16.0.2    //Realtime Database, check latest too

Step(3): Update Play Services dependencies Latest Versions

Play services versions also can have individual versions.

com.google.android.gms:play-services-ads:17.1.2 //Ads, check latest too
com.google.android.gms:play-services-analytics:16.0.6   //Analytics, check latest too

Still having issue? You can check which dependency is making conflict by reading this answer.

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Styling an anchor tag to look like a submit button

Using CSS:

.button {
    display: block;
    width: 115px;
    height: 25px;
    background: #4E9CAF;
    padding: 10px;
    text-align: center;
    border-radius: 5px;
    color: white;
    font-weight: bold;
}

<a href="some_url" class="button ">Cancel</a>

How can an html element fill out 100% of the remaining screen height, using css only?

The trick to this is specifying 100% height on the html and body elements. Some browsers look to the parent elements (html, body) to calculate the height.

<html>
    <body>
        <div id="Header">
        </div>
        <div id="Content">
        </div>
    </body>
</html>

html, body
{
    height: 100%;
}
#Header
{
    width: 960px;
    height: 150px;
}
#Content
{
    height: 100%;
    width: 960px;
}

How to call VS Code Editor from terminal / command line

Step 1: create a .bat file with the name you want e.g vscode.bat Step 2: Write your path to Visual Studio Code Step 3: Save it in C:\Windows\System32 directory

**
C:
cd Users\Bino\AppData\Local\Programs\Microsoft VS Code
Code.exe**

Step 4: You can call visual studio code from any where by typing "vscode" which is the name of your bat file

Combining multiple commits before pushing in Git

I came up with

#!/bin/sh

message=`git log --format=%B origin..HEAD | sort | uniq | grep -v '^$'`
git reset --soft origin
git commit -m "$message"

Combines, sorts, unifies and remove empty lines from the commit message. I use this for local changes to a github wiki (using gollum)

How can I invert color using CSS?

Add the same color of the background to the paragraph and then invert with CSS:

_x000D_
_x000D_
div {_x000D_
    background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
    color: #f00;_x000D_
    -webkit-filter: invert(100%);_x000D_
    filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
    <p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Change visibility of ASP.NET label with JavaScript

If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.

How do I convert a Swift Array to a String?

If you want to ditch empty strings in the array.

["Jet", "Fire"].filter { !$0.isEmpty }.joined(separator: "-")

If you want to filter nil values as well:

["Jet", nil, "", "Fire"].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: "-")

remote rejected master -> master (pre-receive hook declined)

simple answer

$ heroku config:set DISABLE_COLLECTSTATIC=1

after

$ git push heroku master

How to provide animation when calling another activity in Android?

You must use OverridePendingTransition method to achieve it, which is in the Activity class. Sample Animations in the apidemos example's res/anim folder. Check it. More than check the demo in ApiDemos/App/Activity/animation.

Example:

@Override
public void onResume(){
    // TODO LC: preliminary support for views transitions
    this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}

Generating random numbers with normal distribution in Excel

As @osknows said in a comment above (rather than an answer which is why I am adding this), the Analysis Pack includes Random Number Generation functions (e.g. NORM.DIST, NORM.INV) to generate a set of numbers. A good summary link is at http://www.bettersolutions.com/excel/EUN147/YI231420881.htm.

Get started with Latex on Linux

LaTeX comes with most Linux distributions in the form of the teTeX distribution. Find all packages with 'teTeX' in the name and install them.

  • Most editors such as vim or emacs come with TeX editing modes. You can also get WYSIWIG-ish front-ends (technically WYSIWYM), of which perhaps the best known is LyX.

  • The best quick intro to LaTeX is Oetiker's 'The not so short intro to LaTeX'

  • LaTeX works like a compiler. You compile the LaTeX document (which can include other files), which generates a file called a .dvi (device independent). This can be post-processed to various formats (including PDF) with various post-processors.

  • To do PDF, use dvips and use the flag -PPDF (IIRC - I don't have a makefile to hand) to produce a PS with font rendering set up for conversion to pdf. PDF conversion can then be done with ps2pdf or distiller (if you have this).

  • The best format for including graphics in this environment is eps (Encapsulated Postscript) although not all software produces well-behaved postscript. Photographs in jpeg or other formats can be included using various mechanisms.

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

Compiler error: "initializer element is not a compile-time constant"

You can certainly #define a macro as shown below. The compiler will replace "IMAGE_SEGMENT" with its value before compilation. While you will achieve defining a global lookup for your array, it is not the same as a global variable. When the macro is expanded, it works just like inline code and so a new image is created each time. So if you are careful in where you use the macro, then you would have effectively achieved creating a global variable.

#define IMAGE_SEGMENT [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];

Then use it where you need it as shown below. Each time the below code is executed, a new object is created with a new memory pointer.

imageSegment = IMAGE_SEGMENT

<hr> tag in Twitter Bootstrap not functioning correctly?

By default, the hr element in Twitter Bootstrap CSS file has a top and bottom margin of 18px. That's what creates a gap. If you want the gap to be smaller you'll need to adjust margin property of the hr element.

In your example, do something like this:

.container hr {
margin: 2px 0;
}

How to set bootstrap navbar active class with Angular JS?

Just you'll have to add the required active-class with required color code.

Ex: ng-class="{'active': currentNavSelected}" ng-click="setNav"

Oracle DB: How can I write query ignoring case?

You can use either lower or upper function on both sides of the where condition

How can I set a custom baud rate on Linux?

BOTHER appears to be available from <asm/termios.h> on Linux. Pulling the definition from there is going to be wildly non-portable, but I assume this API is non-portable anyway, so it's probably no big loss.

How to "pull" from a local branch into another one?

Quite old post, but it might help somebody new into git.

I will go with

git rebase master
  • much cleaner log history and no merge commits (if done properly)
  • need to deal with conflicts, but it's not that difficult.

PHP - Insert date into mysql

try converting the date first.

$date = "2012-08-06";

mysql_query("INSERT INTO data_table (title, date_of_event)
               VALUES('" . $_POST['post_title'] . "',
                      '" . $date . "')") 
           or die(mysql_error());

c# datagridview doubleclick on row with FullRowSelect

You get the index number of the row in the datagridview using northwind database employees tables as an example:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'nORTHWNDDataSet.Employees' table. You can move, or remove it, as needed.
            this.employeesTableAdapter.Fill(this.nORTHWNDDataSet.Employees);

        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var dataIndexNo = dataGridView1.Rows[e.RowIndex].Index.ToString();
            string cellValue = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

            MessageBox.Show("The row index = " + dataIndexNo.ToString() + " and the row data in second column is: "
                + cellValue.ToString());
        }
    }
}

the result will show you index number of record and the contents of the second table column in datagridview:

enter image description here

Chart creating dynamically. in .net, c#

Microsoft has a nice chart control. Download it here. Great video on this here. Example code is here. Happy coding!

Error: [ng:areq] from angular controller

This happened to me when I have multiple angular modules in the same page

I encountered this error when I used partial views

One partial view had

<script src="~/Scripts/Items.js"></script>
<div ng-app="SearchModule">
    <div ng-controller="SearchSomething" class="col-md-1">
        <input class="searchClass" type="text" placeholder="Search" />
    </div>
</div>

Other had

<div ng-app="FeaturedItems" ng-controller="featured">
    <ul>
        <li ng-repeat="item in Items">{{item.Name}}</li>
    </ul>
</div>

I had them in same module with different controller and it started working

Angularjs $http post file and form data

You can also upload using HTML5. You can use this AJAX uploader.

The JS code is basically:

  $scope.doPhotoUpload = function () {
    // ..
    var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
    myUploader.send();
    // ..
  }

Which reads from an HTML input element

<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">

Syntax error: Illegal return statement in JavaScript

in javascript return statement only used inside function block. if you try to use return statement inside independent if else block it trigger syntax error : Illegal return statement in JavaScript

Here is my example code to avoid such error :

<script type = 'text/javascript'>
(function(){
    var ss= 'no';
    if(getStatus(ss)){
        alert('Status return true');   
    }else{
        alert('Status return false'); 
    }

    function getStatus(ask){
        if(ask=='yes')
        {
        return true;     
        }
        else
        {
        return false;
        }
    }
})();
</script>

Please check Jsfiddle example

Swing vs JavaFx for desktop applications

As stated by Oracle, JavaFX is the next step in their Java based rich client strategy. Accordingly, this is what I recommend for your situation:

What would be easier and cleaner to maintain

  • JavaFX has introduced several improvements over Swing, such as, possibility to markup UIs with FXML, and theming with CSS. It has great potential to write a modular, clean & maintainable code.

What would be faster to build from scratch

  • This is highly dependent on your skills and the tools you use.
    • For swing, various IDEs offer tools for rapid development. The best I personally found is the GUI builder in NetBeans.
    • JavaFX has support from various IDEs as well, though not as mature as the support Swing has at the moment. However, its support for markup in FXML & CSS make GUI development on JavaFX intuitive.

MVC Pattern Support

  • JavaFX is very friendly with MVC pattern, and you can cleanly separate your work as: presentation (FXML, CSS), models(Java, domain objects) and logic(Java).
  • IMHO, the MVC support in Swing isn't very appealing. The flow you'll see across various components lacks consistency.

For more info, please take a look these FAQ post by Oracle regarding JavaFX here.

Fastest way(s) to move the cursor on a terminal command line?

To be clear, you don't want a "fast way to move the cursor on a terminal command line". What you actually want is a fast way to navigate over command line in you shell program.

Bash is very common shell, for example. It uses Readline library to implement command line input. And so to say, it is very convenient to know Readline bindings since it is used not only in bash. For example, gdb also uses Readline to process input.

In Readline documentation you can find all navigation related bindings (and more): http://www.gnu.org/software/bash/manual/bash.html#Readline-Interaction

Short copy-paste if the link above goes down:

Bare Essentials

  • Ctrl-b Move back one character.
  • Ctrl-f Move forward one character.
  • [DEL] or [Backspace] Delete the character to the left of the cursor.
  • Ctrl-d Delete the character underneath the cursor.
  • Ctrl-_ or C-x C-u Undo the last editing command. You can undo all the way back to an empty line.

Movement

  • Ctrl-a Move to the start of the line.
  • Ctrl-e Move to the end of the line.
  • Meta-f Move forward a word, where a word is composed of letters and digits.
  • Meta-b Move backward a word.
  • Ctrl-l Clear the screen, reprinting the current line at the top.

Kill and yank

  • Ctrl-k Kill the text from the current cursor position to the end of the line.
  • M-d Kill from the cursor to the end of the current word, or, if between words, to the end of the next word. Word boundaries are the same as those used by M-f.
  • M-[DEL] Kill from the cursor the start of the current word, or, if between words, to the start of the previous word. Word boundaries are the same as those used by M-b.
  • Ctrl-w Kill from the cursor to the previous whitespace. This is different than M- because the word boundaries differ.
  • Ctrl-y Yank the most recently killed text back into the buffer at the cursor.
  • M-y Rotate the kill-ring, and yank the new top. You can only do this if the prior command is C-y or M-y.

M is Meta key. For Max OS X Terminal you can enable "Use option as meta key" in Settings/Keyboard for that. For Linux its more complicated.

Update

Also note, that Readline can operate in two modes:

  • emacs mode (which is the default)
  • vi mode

To switch Bash to use vi mode:

$ set -o vi

Personaly I prefer vi mode since I use vim for text editing.

Bonus

In macOS Terminal app (and in iTerm too) you can Option-Click to move the cursor (cursor will move to clicked position). This even works inside vim.

Java: how to add image to Jlabel?

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

Default value in Doctrine

Adding to @romanb brilliant answer.

This adds a little overhead in migration, because you obviously cannot create a field with not null constraint and with no default value.

// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");

//lets add property without not null contraint        
$this->addSql("ALTER TABLE tablename ADD property BOOLEAN");

//get the default value for property       
$object = new Object();
$defaultValue = $menuItem->getProperty() ? "true":"false";

$this->addSql("UPDATE tablename SET property = {$defaultValue}");

//not you can add constraint
$this->addSql("ALTER TABLE tablename ALTER property SET NOT NULL");

With this answer, I encourage you to think why do you need the default value in the database in the first place? And usually it is to allow creating objects with not null constraint.

How to programmatically tell if a Bluetooth device is connected?

BluetoothAdapter.getDefaultAdapter().isEnabled -> returns true when bluetooth is open

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager

audioManager.isBluetoothScoOn -> returns true when device connected

Regular Expressions: Search in list

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

how to format date in Component of angular 5

There is equally formatDate

const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);

According to the API it takes as param either a date string, a Date object, or a timestamp.

Gotcha: Out of the box, only en-US is supported.

If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:

import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");

Don't forget to add corresponding import:

import { formatDate } from "@angular/common";

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

Get name of property as a string

I had some difficulty using the solutions already suggested for my specific use case, but figured it out eventually. I don't think my specific case is worthy of a new question, so I am posting my solution here for reference. (This is very closely related to the question and provides a solution for anyone else with a similar case to mine).

The code I ended up with looks like this:

public class HideableControl<T>: Control where T: class
{
    private string _propertyName;
    private PropertyInfo _propertyInfo;

    public string PropertyName
    {
        get { return _propertyName; }
        set
        {
            _propertyName = value;
            _propertyInfo = typeof(T).GetProperty(value);
        }
    }

    protected override bool GetIsVisible(IRenderContext context)
    {
        if (_propertyInfo == null)
            return false;

        var model = context.Get<T>();

        if (model == null)
            return false;

        return (bool)_propertyInfo.GetValue(model, null);
    }

    protected void SetIsVisibleProperty(Expression<Func<T, bool>> propertyLambda)
    {
        var expression = propertyLambda.Body as MemberExpression;
        if (expression == null)
            throw new ArgumentException("You must pass a lambda of the form: 'vm => vm.Property'");

        PropertyName = expression.Member.Name;
    }
}

public interface ICompanyViewModel
{
    string CompanyName { get; }
    bool IsVisible { get; }
}

public class CompanyControl: HideableControl<ICompanyViewModel>
{
    public CompanyControl()
    {
        SetIsVisibleProperty(vm => vm.IsVisible);
    }
}

The important part for me is that in the CompanyControl class the compiler will only allow me to choose a boolean property of ICompanyViewModel which makes it easier for other developers to get it right.

The main difference between my solution and the accepted answer is that my class is generic and I only want to match properties from the generic type that are boolean.

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Actually you don't have to deal with the static metamodel if you had your annotations right.

With the following entities :

@Entity
public class Pet {
  @Id
  protected Long id;
  protected String name;
  protected String color;
  @ManyToOne
  protected Set<Owner> owners;
}

@Entity
public class Owner {
  @Id
  protected Long id;
  protected String name;
}

You can use this :

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> petMetaModel = m.entity(Pet.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(petMetaModel.getSet("owners", Owner.class));

How is "mvn clean install" different from "mvn install"?

You can call more than one target goal with maven. mvn clean install calls clean first, then install. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.

clean removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).

we call it target in ant and goal in maven

Cannot assign requested address using ServerSocket.socketBind

In my case, delete from /etc/hosts

  • 127.0.0.1 localhost
  • 192.168.100.20 localhost <<<<---- (delete or comment)

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

Although I've tried all the previous answers, only the following one worked out:

1 - Open Powershell (as Admin)

2 - Run:

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

3 - Run:

Install-PackageProvider -Name NuGet

The author is Niels Weistra: Microsoft Forum

Can I use wget to check , but not download

There is the command line parameter --spider exactly for this. In this mode, wget does not download the files and its return value is zero if the resource was found and non-zero if it was not found. Try this (in your favorite shell):

wget -q --spider address
echo $?

Or if you want full output, leave the -q off, so just wget --spider address. -nv shows some output, but not as much as the default.

Suppress warning messages using mysql from within Terminal, but password written in bash script

You can also just redirect the standard error STDERR output to /dev/null

So just do:

mysql -u $user -p$password -e "statement" 2> /dev/null

Starting a shell in the Docker Alpine container

ole@T:~$ docker run -it --rm alpine /bin/ash
(inside container) / # 

Options used above:

  • /bin/ash is Ash (Almquist Shell) provided by BusyBox
  • --rm Automatically remove the container when it exits (docker run --help)
  • -i Interactive mode (Keep STDIN open even if not attached)
  • -t Allocate a pseudo-TTY

Reading Xml with XmlReader in C#

Three years later, perhaps with the renewed emphasis on WebApi and xml data, I came across this question. Since codewise I am inclined to follow Skeet out of an airplane without a parachute, and seeing his initial code doubly corraborated by the MS Xml team article as well as an example in BOL Streaming Transform of Large Xml Docs, I very quickly overlooked the other comments, most specifically from 'pbz', who pointed out that if you have the same elements by name in succession, every other one is skipped because of the double read. And in fact, the BOL and MS blog articles both were parsing source documents with target elements nested deeper than second level, masking this side-effect.

The other answers address this problem. I just wanted to offer a slightly simpler revision that seems to work well so far, and takes into account that the xml might come from different sources, not just a uri, and so the extension works on the user managed XmlReader. The one assumption is that the reader is in its initial state, since otherwise the first 'Read()' might advance past a desired node:

public static IEnumerable<XElement> ElementsNamed(this XmlReader reader, string elementName)
{
    reader.MoveToContent(); // will not advance reader if already on a content node; if successful, ReadState is Interactive
    reader.Read();          // this is needed, even with MoveToContent and ReadState.Interactive
    while(!reader.EOF && reader.ReadState == ReadState.Interactive)
    {
        // corrected for bug noted by Wes below...
        if(reader.NodeType == XmlNodeType.Element && reader.Name.Equals(elementName))
        {
             // this advances the reader...so it's either XNode.ReadFrom() or reader.Read(), but not both
             var matchedElement = XNode.ReadFrom(reader) as XElement;
             if(matchedElement != null)
                 yield return matchedElement;
        }
        else
            reader.Read();
    }
}

How to convert date to timestamp?

Split the string into its parts and provide them directly to the Date constructor:

Update:

_x000D_
_x000D_
var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
_x000D_
_x000D_
_x000D_

What does %~dp0 mean, and how does it work?

%~dp0 expands to current directory path of the running batch file.

To get clear understanding, let's create a batch file in a directory.

C:\script\test.bat

with contents:

@echo off
echo %~dp0

When you run it from command prompt, you will see this result:

C:\script\

c# how to add byte to byte array

To prevent recopy the array every time which isn't efficient

What about using Stack

csharp> var i = new Stack<byte>();
csharp> i.Push(1);
csharp> i.Push(2); 
csharp> i.Push(3); 
csharp> i; { 3, 2, 1 }

csharp> foreach(var x in i) {
  >       Console.WriteLine(x);
  >     }

3 2 1

How to Debug Variables in Smarty like in PHP var_dump()

In smarty there is built in modifier you could use that by using | (single pipeline operator). Like this {$varname|@print_r} will print value as print_r($php_variable)

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Java Inheritance - calling superclass method

Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.

If you write super() at that time parents's default constructor is called. same if you write super.

this keyword refers the current object same as super key word facilty for accessing parents.

How to merge 2 JSON objects from 2 files using jq?

First, {"value": .value} can be abbreviated to just {value}.

Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.

Putting these together, the two objects in the two files can be combined in the specified way as follows:

$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'

The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.

Note on --argfile

The jq manual deprecates --argfile because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.

If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile does not incur the inefficiencies of the -s command-line option when the latter is used with multiple files.

When does Java's Thread.sleep throw InterruptedException?

A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.

How to make FileFilter in java?

You are going wrong here:

int retval = chooser.showOpenDialog(null); 
public boolean accept(File directory, String fileName) {`
return fileName.endsWith(".txt");`
}

You first show the file chooser dialog and then apply the filter! This wont work. First apply the filter and then show the dialog:

public boolean accept(File directory, String fileName) {
        return fileName.endsWith(".txt");
}
int retval = chooser.showOpenDialog(null);

Display image as grayscale using matplotlib

try this:

import pylab
from scipy import misc

pylab.imshow(misc.lena(),cmap=pylab.gray())
pylab.show()

Finding a branch point with Git?

How about something like

git log --pretty=oneline master > 1
git log --pretty=oneline branch_A > 2

git rev-parse `diff 1 2 | tail -1 | cut -c 3-42`^

Angular 2 / 4 / 5 not working in IE11

  1. Uncomment IE section in the src/polyfill.js,

    /** IE10 and IE11 requires the following for NgClass support on SVG elements*/

    import 'classlist.js';

  2. If any build error for missing package then,

    npm install classlist.js --save-exact

  3. Make sure to include below line to set the default IE document mode. Other wise it will open in version 7

 <meta http-equiv="X-UA-Compatible" content="IE=edge" />

How do I set the background color of Excel cells using VBA?

This is a perfect example of where you should use the macro recorder. Turn on the recorder and set the color of the cells through the UI. Stop the recorder and review the macro. It will generate a bunch of extraneous code, but it will also show you syntax that works for what you are trying to accomplish. Strip out what you don't need and modify (if you need to) what's left.

Exposing the current state name with ui router

Answering your question in this format is quite challenging.

On the other hand you ask about navigation and then about current $state acting all weird.

For the first I'd say it's too broad question and for the second I'd say... well, you are doing something wrong or missing the obvious :)

 

Take the following controller:

app.controller('MainCtrl', function($scope, $state) {
  $scope.state = $state;
});

Where app is configured as:

app.config(function($stateProvider) {
  $stateProvider
    .state('main', {
        url: '/main',
        templateUrl: 'main.html',
        controller: 'MainCtrl'
    })
    .state('main.thiscontent', {
        url: '/thiscontent',
        templateUrl: 'this.html',
        controller: 'ThisCtrl'
    })
    .state('main.thatcontent', {
        url: '/thatcontent',
        templateUrl: 'that.html'
    });
});

Then simple HTML template having

<div>
  {{ state | json }}
</div>

Would "print out" e.g. the following

{ 
  "params": {}, 
  "current": { 
    "url": "/thatcontent", 
    "templateUrl": "that.html", 
    "name": "main.thatcontent" 
  }, 
  "transition": null
}

I put up a small example showing this, using ui.router and pascalprecht.translate for the menus. I hope you find it useful and figure out what is it you are doing wrong.

Plunker here http://plnkr.co/edit/XIW4ZE

 

Screencap


imgur

Adding line break in C# Code behind page

 result = "Minimum MarketData"+ Environment.NewLine
           + "Refresh interval is 1";

React component initialize state from props

You can use componentWillReceiveProps.

constructor(props) {
    super(props);
    this.state = {
      productdatail: ''
    };
}

componentWillReceiveProps(nextProps){
    this.setState({ productdatail: nextProps.productdetailProps })
}

How to use HTML to print header and footer on every printed page of a document?

I found one solution. The basic idea is to make a table and in thead section place the data of header in tr and by css force to show that tr only in print not in screen then your normal header should be force to show only in screen not in print. 100% working on many pages print. sample code is here

<style> 
    @media screen {
        .only_print{
            display:none;
        }
    }
    @media print {
        .no-print {
            display: none !important;
        }
    }
    TABLE{border-collapse: collapse;}
    TH, TD {border:1px solid grey;}
</style>
<div class="no-print">  <!-- This is header for screen and will not be printed -->
    <div>COMPANY NAME FOR SCREEN</div>
    <div>DESCRIPTION FOR SCREEN</div>
</div>

<table>
    <thead>
        <tr class="only_print"> <!-- This is header for print and will not be shown on screen -->
            <td colspan="100" style="border: 0px;">
                <div>COMPANY NAME FOR PRINT</div>
                <div>DESCRIPTION FOR PRINT</div>
            </td>
        </tr>
        <!-- From here Actual Data of table start -->
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1-1</td>
            <td>1-2</td>
            <td>1-3</td>
        </tr>
        <tr>
            <td>2-1</td>
            <td>2-2</td>
            <td>2-3</td>
        </tr>
    </tbody>
</table>

Genymotion error at start 'Unable to load virtualbox'

I am using Intellij IDEA and same error happened to me, I found that the path to genymotion folder was not configured properly. Either open settings using File > Settings or press Ctrl + Alt + S then in IDE Settings check if the path to the genymotion folder is correct or not.

Since Android Studio are almost similar to Intellij IDEA so you can apply the same steps above to Android Studio as well.

genymotion settings

How do I deploy Node.js applications as a single executable file?

You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.

#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common

You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.

#!/bin/sh
#clone git repo
git clone your-repo.git

Android REST client, Sample?

We have open-sourced our lightweight async REST client library for Android, you might find it useful if you have minimal requirements and don't want to handle the multithreading yourself - it is very OK for basic communications but not a full-blown REST client library.

It's called libRESTfulClient and can be found on GitHub.

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

I received same error despite jar being in lib directory & added to deployment assembly in Eclipse.

So I doubted two things ,

1.Some Weblogic cache issue - as this app was deployed before & I was trying to redeploy after some changes

2.Jar itself is corrupt due to partial download etc

So I re downloaded the jar & deleted everything in directory - ..\Oracle_Home\user_projects\domains\base_domain\lib and redeployed again & all went well.

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

Group array items using object

Start by creating a mapping of group names to values. Then transform into your desired format.

_x000D_
_x000D_
var myArray = [_x000D_
    {group: "one", color: "red"},_x000D_
    {group: "two", color: "blue"},_x000D_
    {group: "one", color: "green"},_x000D_
    {group: "one", color: "black"}_x000D_
];_x000D_
_x000D_
var group_to_values = myArray.reduce(function (obj, item) {_x000D_
    obj[item.group] = obj[item.group] || [];_x000D_
    obj[item.group].push(item.color);_x000D_
    return obj;_x000D_
}, {});_x000D_
_x000D_
var groups = Object.keys(group_to_values).map(function (key) {_x000D_
    return {group: key, color: group_to_values[key]};_x000D_
});_x000D_
_x000D_
var pre = document.createElement("pre");_x000D_
pre.innerHTML = "groups:\n\n" + JSON.stringify(groups, null, 4);_x000D_
document.body.appendChild(pre);
_x000D_
_x000D_
_x000D_

Using Array instance methods such as reduce and map gives you powerful higher-level constructs that can save you a lot of the pain of looping manually.

Detect the Internet connection is offline?

The HTML5 Application Cache API specifies navigator.onLine, which is currently available in the IE8 betas, WebKit (eg. Safari) nightlies, and is already supported in Firefox 3

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

Look in the SDK Manager what is your highest Android SDK Build-tools version, and copy this version number in your project build.gradle file, in the android/buildToolsVersion property (for me, version was "18.1.1").

Hope it help!

Git: How configure KDiff3 as merge tool and diff tool

These sites were very helpful, almost, mergetool and difftool. I used the global configuration, but can be used by repository without problems. You just need to execute the following commands:

git config --global merge.tool kdiff3
git config --global mergetool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global mergetool.kdiff3.trustExitCode false

git config --global diff.guitool kdiff3
git config --global difftool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global difftool.kdiff3.trustExitCode false

Note that the latest version kdiff3 moved the executable from the root of the application folder C:/Program Files/KDiff3 into the bin/ folder inside the application folder. If you're using an older version, remove "bin/" from the paths above.

The use of the trustExitCode option depends on what you want to do when diff tool returns. From documentation:

git-difftool invokes a diff tool individually on each file. Errors reported by the diff tool are ignored by default. Use --trust-exit-code to make git-difftool exit when an invoked diff tool returns a non-zero exit code.

HTML CSS Button Positioning

try changing that line-height change to a margin-top or padding-top change instead

#btnhome:active{
margin-top : 25px;
}

Edit: You could also try adding a span inside the button

<div id="header">           
    <button id="btnhome"><span>Home</span></button>          
    <button id="btnabout">About</button>
    <button id="btncontact">Contact</button>
    <button id="btnsup">Help Us</button>           
</div>

Then style that

#btnhome span:active { padding-top:25px;}

Proxy with urllib2

You have to install a ProxyHandler

urllib2.install_opener(
    urllib2.build_opener(
        urllib2.ProxyHandler({'http': '127.0.0.1'})
    )
)
urllib2.urlopen('http://www.google.com')

jQuery 1.9 .live() is not a function

You can avoid refactoring your code by including the following JavaScript code

jQuery.fn.extend({
    live: function (event, callback) {
       if (this.selector) {
            jQuery(document).on(event, this.selector, callback);
        }
        return this;
    }
});

Entity Framework Code First - two Foreign Keys from same table

This is because Cascade Deletes are enabled by default. The problem is that when you call a delete on the entity, it will delete each of the f-key referenced entities as well. You should not make 'required' values nullable to fix this problem. A better option would be to remove EF Code First's Cascade delete convention:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); 

It's probably safer to explicitly indicate when to do a cascade delete for each of the children when mapping/config. the entity.

Install opencv for Python 3.3

I can't comment on midopa's excellent answer due to lack of reputation.

On a Mac I (finally) successfully installed opencv from source using the following commands:

cmake -D CMAKE_BUILD_TYPE=RELEASE 
-D CMAKE_INSTALL_PREFIX=/usr/local 
-D PYTHON_EXECUTABLE=/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 
-D PYTHON_LIBRARY=/Library/Frameworks/Python.framework//Versions/3.4/lib/libpython3.4m.dylib 
-D PYTHON_INCLUDE_DIR=/Library/Frameworks/Python.framework/Versions/3.4/include/python3.4m 
-D PYTHON_NUMPY_INCLUDE_DIRS=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/numpy/core/include/numpy 
-D PYTHON_PACKAGES_PATH=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages 
/relative/path/to/source/directory/

Then,

make -j8

change 8 for the number of threads your machine can handle, to speed things up

sudo make install

I added a PYTHONPATH environment variable to my ~/.bash_profile file so that Python could find cv2.so:

PYTHONPATH="${PYTHONPATH}:/usr/local/lib/python3.4/site-packages”
export PYTHONPATH

[For those using PyCharm, I had to go to Preferences > Project Structure > Add Content Root, and added the path to cv2.so's parent directory: /usr/local/lib/python3.4/site-packages]

This command got me past errors such as:

Could NOT find PythonLibs, by explicitly declaring the python library path

ld: can't link with a main executable for architecture x86_64
collect2: error: ld returned 1 exit status
make[2]: *** [lib/cv2.so] Error 1
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make: *** [all] Error 2

by explicitly pointing to the libpython3.4m.dylib

In terminal, check that it worked with:

$python3
>>> import cv2

It's all good if you don't get ImportError: No module named 'cv2'

This worked on a Macbook Pro Retina 15" 2013, Mavericks 10.9.4, Python 3.4.1 (previously installed from official download), opencv3 from source. Hope that this helps someone.

How do you check whether a number is divisible by another number (Python)?

a = 1400
a1 = 5
a2 = 3

b= str(a/a1)
b1 = str(a/a2)
c =b[(len(b)-2):len(b)]
c1 =b[(len(b1)-2):len(b1)]
if c == ".0":
    print("yeah for 5!")
if c1 == ".0":
    print("yeah for 3!")

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

What is the correct syntax for 'else if'?

since olden times, the correct syntax for if/else if in Python is elif. By the way, you can use dictionary if you have alot of if/else.eg

d={"1":"1a","2":"2a"}
if not a in d: print("3a")
else: print (d[a])

For msw, example of executing functions using dictionary.

def print_one(arg=None):
    print "one"

def print_two(num):
    print "two %s" % num

execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
try:
    execfunctions[1][0]()
except KeyError,e:
    print "Invalid option: ",e

try:
    execfunctions[2][0]("test")
except KeyError,e:
    print "Invalid option: ",e
else:
    sys.exit()

How to map a composite key with JPA and Hibernate?

Let's take a simple example. Let's say two tables named test and customer are there described as:

create table test(
  test_id int(11) not null auto_increment,
  primary key(test_id));

create table customer(
  customer_id int(11) not null auto_increment,
  name varchar(50) not null,
  primary key(customer_id));

One more table is there which keeps the track of tests and customer:

create table tests_purchased(
  customer_id int(11) not null,
  test_id int(11) not null,
  created_date datetime not null,
  primary key(customer_id, test_id));

We can see that in the table tests_purchased the primary key is a composite key, so we will use the <composite-id ...>...</composite-id> tag in the hbm.xml mapping file. So the PurchasedTest.hbm.xml will look like:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="entities.PurchasedTest" table="tests_purchased">

    <composite-id name="purchasedTestId">
      <key-property name="testId" column="TEST_ID" />
      <key-property name="customerId" column="CUSTOMER_ID" />
    </composite-id>

    <property name="purchaseDate" type="timestamp">
      <column name="created_date" />
    </property>

  </class>
</hibernate-mapping>

But it doesn't end here. In Hibernate we use session.load (entityClass, id_type_object) to find and load the entity using primary key. In case of composite keys, the ID object should be a separate ID class (in above case a PurchasedTestId class) which just declares the primary key attributes like below:

import java.io.Serializable;

public class PurchasedTestId implements Serializable {
  private Long testId;
  private Long customerId;

  // an easy initializing constructor
  public PurchasedTestId(Long testId, Long customerId) {
    this.testId = testId;
    this.customerId = customerId;
  }

  public Long getTestId() {
    return testId;
  }

  public void setTestId(Long testId) {
    this.testId = testId;
  }

  public Long getCustomerId() {
    return customerId;
  }

  public void setCustomerId(Long customerId) {
    this.customerId = customerId;
  }

  @Override
  public boolean equals(Object arg0) {
    if(arg0 == null) return false;
    if(!(arg0 instanceof PurchasedTestId)) return false;
    PurchasedTestId arg1 = (PurchasedTestId) arg0;
    return (this.testId.longValue() == arg1.getTestId().longValue()) &&
           (this.customerId.longValue() == arg1.getCustomerId().longValue());
  }

  @Override
  public int hashCode() {
    int hsCode;
    hsCode = testId.hashCode();
    hsCode = 19 * hsCode+ customerId.hashCode();
    return hsCode;
  }
}

Important point is that we also implement the two functions hashCode() and equals() as Hibernate relies on them.

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

What is an IIS application pool?

Assume scenario where swimmers swim in swimming pool in the areas reserved for them.what happens if swimmers swim other than the areas reserved for them,the whole thing would become mess.similarly iis uses application pools to seperate one process from another.

What is a good Hash Function?

I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.

How do I improve ASP.NET MVC application performance?

A compiled list of possible sources of improvement are below:

General

  • Make use of a profiler to discover memory leaks and performance problems in your application. personally I suggest dotTrace
  • Run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.

Caching

  • Use CompiledQuery.Compile() recursively avoiding recompilation of your query expressions
  • Cache not-prone-to-change content using OutputCacheAttribute to save unnecessary and action executions
  • Use cookies for frequently accessed non sensitive information
  • Utilize ETags and expiration - Write your custom ActionResult methods if necessary
  • Consider using the RouteName to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method.
  • Consider implementing a route resolution caching strategy
  • Put repetitive code inside your PartialViews, avoid render it xxxx times: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that. Explanation And Benchmarks

Routing

Security

  • Use Forms Authentication, Keep your frequently accessed sensitive data in the authentication ticket

DAL

Load balancing

  • Utilize reverse proxies, to spread the client load across your app instance. (Stack Overflow uses HAProxy (MSDN).

  • Use Asynchronous Controllers to implement actions that depend on external resources processing.

Client side

  • Optimize your client side, use a tool like YSlow for suggestions to improve performance
  • Use AJAX to update components of your UI, avoid a whole page update when possible.
  • Consider implement a pub-sub architecture -i.e. Comet- for content delivery against reload based in timeouts.
  • Move charting and graph generation logic to the client side if possible. Graph generation is a expensive activity. Deferring to the client side your server from an unnecessary burden, and allows you to work with graphs locally without make a new request (i.e. Flex charting, jqbargraph, MoreJqueryCharts).
  • Use CDN's for scripts and media content to improve loading on the client side (i.e. Google CDN)
  • Minify -Compile- your JavaScript in order to improve your script size
  • Keep cookie size small, since cookies are sent to the server on every request.
  • Consider using DNS and Link Prefetching when possible.

Global configuration

  • If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine.

    ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine());

  • Add gzip (HTTP compression) and static cache (images, css, ...) in your web.config <system.webServer> <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/> </system.webServer>

  • Remove unused HTTP Modules
  • Flush your HTML as soon as it is generated (in your web.config) and disable viewstate if you are not using it <pages buffer="true" enableViewState="false">

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

How to use RANK() in SQL Server

You have already grouped by ContenderNum, no need to partition again by it. Use Dense_rank()and order by totals desc. In short,

SELECT contendernum,totals, **DENSE_RANK()** 
OVER (ORDER BY totals **DESC**) 
AS xRank 
FROM
(
   SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
   FROM dbo.Cat1GroupImpersonation
   GROUP BY ContenderNum
) AS a

How to execute only one test spec with angular-cli

This is working for me in Angular 7. It is based on the --main option of the ng command. I am not sure if this option is undocumented and possibly subject to change, but it works for me. I put a line in my package.json file in scripts section. There using the --main option of with the ng test command, I specify the path to the .spec.ts file I want to execute. For example

"test 1": "ng test --main E:/WebRxAngularClient/src/app/test/shared/my-date-utils.spec.ts",

You can run the script as you run any such script. I run it in Webstorm by clicking on "test 1" in the npm section.

How to append elements at the end of ArrayList in Java?

I ran into a similar problem and just passed the end of the array to the ArrayList.add() index param like so:

public class Stack {

    private ArrayList<String> stringList = new ArrayList<String>();

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){
        String random = rsg.randomStringGenerator();
        stringList.add(stringList.size(), random);
    }

}

How do you create a Spring MVC project in Eclipse?

You want to create a "Dynamic Web Project". Follow the steps here: Spring MVC Tutorial with Eclipse and Tomcat.

Also, here is the Eclipse documentation for Dynamic Web Projects: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.webtools.doc.user/topics/ccwebprj.html

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

What is the purpose of the "final" keyword in C++11 for functions?

  • It is to prevent a class from being inherited. From Wikipedia:

    C++11 also adds the ability to prevent inheriting from classes or simply preventing overriding methods in derived classes. This is done with the special identifier final. For example:

    struct Base1 final { };
    
    struct Derived1 : Base1 { }; // ill-formed because the class Base1 
                                 // has been marked final
    
  • It is also used to mark a virtual function so as to prevent it from being overridden in the derived classes:

    struct Base2 {
        virtual void f() final;
    };
    
    struct Derived2 : Base2 {
        void f(); // ill-formed because the virtual function Base2::f has 
                  // been marked final
    };
    

Wikipedia further makes an interesting point:

Note that neither override nor final are language keywords. They are technically identifiers; they only gain special meaning when used in those specific contexts. In any other location, they can be valid identifiers.

That means, the following is allowed:

int const final = 0;     // ok
int const override = 1;  // ok

How to include view/partial specific styling in AngularJS

Could append a new stylesheet to head within $routeProvider. For simplicity am using a string but could create new link element also, or create a service for stylesheets

/* check if already exists first - note ID used on link element*/
/* could also track within scope object*/
if( !angular.element('link#myViewName').length){
    angular.element('head').append('<link id="myViewName" href="myViewName.css" rel="stylesheet">');
}

Biggest benefit of prelaoding in page is any background images will already exist, and less lieklyhood of FOUC

What is the difference between `Enum.name()` and `Enum.toString()`?

The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum.

Therefore, if you need the name of the field itself, use name(). If you need a string representation of the value of the field, use toString().

For instance:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

In this example, WeekDay.MONDAY.name() returns "MONDAY", and WeekDay.MONDAY.toString() returns "Monday".

WeekDay.valueOf(WeekDay.MONDAY.name()) returns WeekDay.MONDAY, but WeekDay.valueOf(WeekDay.MONDAY.toString()) throws an IllegalArgumentException.

How to compare the contents of two string objects in PowerShell

You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title

-match is for regex matching ( the second argument is a regex )

Copy mysql database from remote server to local computer

This answer is not remote server but local server. The logic should be the same. To copy and backup my local machine MAMP database to my local desktop machine folder, go to console then

mysqldump -h YourHostName -u YourUserNameHere -p YourDataBaseNameHere > DestinationPath/xxxwhatever.sql

In my case YourHostName was localhost. DestinationPath is the path to the download; you can drag and drop your desired destination folder and it will paste the path in.

Then password may be asked:

Enter password: xxxxxxxx

How to get the Display Name Attribute of an Enum member via MVC Razor code?

Based on Aydin's answer I would suggest a less "duplicatious" implementation (because we could easily get the Type from the Enum value itself, instead of providing it as a parameter :

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static string GetDisplayName(this Enum enumValue)
{
    return enumValue.GetType().GetMember(enumValue.ToString())
                   .First()
                   .GetCustomAttribute<DisplayAttribute>()
                   .Name;
}

EDIT (based upon @Vahagn Nahapetyan's comment)

public static string GetDisplayName(this Enum enumValue)
{
    return enumValue.GetType()?
                    .GetMember(enumValue.ToString())?
                    .First()?
                    .GetCustomAttribute<DisplayAttribute>()?
                    .Name;
}

Now we can use it very clean in this way:

public enum Season 
{
    [Display(Name = "The Autumn")]
    Autumn,

    [Display(Name = "The Weather")]
    Winter,

    [Display(Name = "The Tease")]
    Spring,

    [Display(Name = "The Dream")]
    Summer
}

Season.Summer.GetDisplayName();

Which results in

"The Dream"

Cordova : Requirements check failed for JDK 1.8 or greater

Guys to get the mix right on Windows, you need to do the following

  1. Download and install any version of JDK 1.8 or higher.
  2. Open environment variables, create an environment variable called JAVA_HOME and set value to JDK install path. C:\Program Files\Java\jdk1.8.0_162 make sure you do not add the \bin in the value.

enter image description here

  1. In your system path variable, put a semi-colon ; and add this value to system path e.g C:\Program Files\Java\jdk1.8.0_162\bin; Here the \bin is added.

Note: The environment variables are tricky.They are supposed to be closed by a ; before opening another. That is why we put one before adding the value and one after the value to close it.

enter image description here

  1. Now close terminal and reopen then run previous commands.

Group by month and year in MySQL

GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime);

is what you want.

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Invalid application of sizeof to incomplete type with a struct

I am a beginner and may not clear syntax. To refer above information, I still not clear.

/*
 * main.c
 *
 *  Created on: 15 Nov 2019
 */

#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "dummy.h"

char arrA[] = {
        0x41,
        0x43,
        0x45,
        0x47,
        0x00,
};

#define sizeA sizeof(arrA)

int main(void){

    printf("\r\n%s",arrA);
    printf("\r\nsize of = %d", sizeof(arrA));
    printf("\r\nsize of = %d", sizeA);

    printf("\r\n%s",arrB);
    //printf("\r\nsize of = %d", sizeof(arrB));
    printf("\r\nsize of = %d", sizeB);


    while(1);

    return 0;
};

/*
 * dummy.c
 *
 *  Created on: 29 Nov 2019
 */


#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "dummy.h"


char arrB[] = {
        0x42,
        0x44,
        0x45,
        0x48,
        0x00,
};

/*
 * dummy.h
 *
 *  Created on: 29 Nov 2019
 */

#ifndef DUMMY_H_
#define DUMMY_H_

extern char arrB[];

#define sizeB sizeof(arrB)

#endif /* DUMMY_H_ */

15:16:56 **** Incremental Build of configuration Debug for project T3 ****
Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\\main.c" 
In file included from ..\main.c:12:
..\main.c: In function 'main':
..\dummy.h:13:21: **error: invalid application of 'sizeof' to incomplete type 'char[]'**
 #define sizeB sizeof(arrB)
                     ^
..\main.c:32:29: note: in expansion of macro 'sizeB'
  printf("\r\nsize of = %d", sizeB);
                             ^~~~~

15:16:57 Build Failed. 1 errors, 0 warnings. (took 384ms)

Both "arrA" & "arrB" can be accessed (print it out). However, can't get a size of "arrB".

What is a problem there?

  1. Is 'char[]' incomplete type? or
  2. 'sizeof' does not accept the extern variable/ label?

In my program, "arrA" & "arrB" are constant lists and fixed before to compile. I would like to use a label(let me easy to maintenance & save RAM memory).

How to disable Compatibility View in IE

Adding a tag to your page will not control the UI in the Internet Control Panel (the dialog that appears when you selection Tools -> Options). If you're looking at your homepage which could be google.com, msn.com, about:blank or example.com, the Internet Control Panel has no way of knowing what the contents of your page may be, and it will not download it in the background.

Have a look at this document on MSDN which discussed compatibility mode and how to turn it off for your site.

How can I select all children of an element except the last child?

to find elements from last, use

<style>
ul li:nth-last-of-type(3n){ color:#a94442}  /**/
</style>

Change color of Back button in navigation bar

All the answers setting UINavigationBar.appearance().tintColor conflict with Apple's documentation in UIAppearance.h.

Note for iOS7: On iOS7 the tintColor property has moved to UIView, and now has special inherited behavior described in UIView.h. This inherited behavior can conflict with the appearance proxy, and therefore tintColor is now disallowed with the appearance proxy.

In Xcode, you need to command-click on each property you want to use with appearance proxy to inspect the header file and make sure the property is annotated with UI_APPEARANCE_SELECTOR.

So the correct way to color the navigation bar purple and the title and buttons white throughout the app via the appearance proxy is:

UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().barTintColor = .purple
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
UIBarButtonItem.appearance().tintColor = .white

Note that UIBarButtonItem is not a subclass of UIView but rather NSObject. So its tintColor property is not the inherited tintColor from UIView.

Unfortunately, UIBarButtonItem.tintColor is not annotated with UI_APPEARANCE_SELECTOR – but that seems to me a documentation bug. The response from Apple Engineering in this radar states it is supported.

What's the easiest way to call a function every 5 seconds in jQuery?

The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete

// IIFE
(function runForever(){
  // Do something here
  setTimeout(runForever, 5000)
})()

// Regular function with arguments
function someFunction(file, directory){
  // Do something here
  setTimeout(someFunction, 5000, file, directory)
  // YES, setTimeout passes any extra args to
  // function being called
}

How to lay out Views in RelativeLayout programmatically?

Android 22 minimal runnable example

enter image description here

Source:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final RelativeLayout relativeLayout = new RelativeLayout(this);

        final TextView tv1;
        tv1 = new TextView(this);
        tv1.setText("tv1");
        // Setting an ID is mandatory.
        tv1.setId(View.generateViewId());
        relativeLayout.addView(tv1);

        // tv2.
        final TextView tv2;
        tv2 = new TextView(this);
        tv2.setText("tv2");
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.FILL_PARENT);
        lp.addRule(RelativeLayout.BELOW, tv1.getId());
        relativeLayout.addView(tv2, lp);

        // tv3.
        final TextView tv3;
        tv3 = new TextView(this);
        tv3.setText("tv3");
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        );
        lp2.addRule(RelativeLayout.BELOW, tv2.getId());
        relativeLayout.addView(tv3, lp2);

        this.setContentView(relativeLayout);
    }
}

Works with the default project generated by android create project .... GitHub repository with minimal build code.

Importing two classes with same name. How to handle?

You can import one of them using import. For all other similar class , you need to specify Fully qualified class names. Otherwise you will get compilation error.

Eg:

import java.util.Date;

class Test{

  public static void main(String [] args){

    // your own date
    my.own.Date myOwndate ;

    // util.Date
    Date utilDate;
  }
}

Double Iteration in List Comprehension

If you want to keep the multi dimensional array, one should nest the array brackets. see example below where one is added to every element.

>>> a = [[1, 2], [3, 4]]

>>> [[col +1 for col in row] for row in a]
[[2, 3], [4, 5]]

>>> [col +1 for row in a for col in row]
[2, 3, 4, 5]

How can I create and style a div using JavaScript?

Here's one solution that I'd use:

var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';

If you wanted the attribute and/or attribute values to be based on variables:

var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';

Then, to append to the body:

document.getElementsByTagName("body").innerHTML = div;

Easy as pie.

how to call javascript function in html.actionlink in asp.net mvc?

This is a bit of an old post, but there is actually a way to do an onclick operator that calls a function instead of going anywhere in ASP.NET

helper.ActionLink("Choose", null, null, null, 
    new {@onclick = "Locations.Choose(" + location.Id + ")", @href="#"})

If you specify empty quotes or the like in the controller/action, it'll likely add a link to what you listed. You can do that, and do a return false in the onclick. You can read more about that at:

What's the effect of adding 'return false' to a click event listener?

If you're doing this onclick in an cshtml file, it'd be a bit cleaner to just specify the link yourself (a href...) instead of having the ActionLink handle it. If you're doing an HtmlHelper, like my example above is coming from, then I'd argue that calling ActionLink is an okay solution, or potentially better, is to use tagbuilder instead.

Force an Android activity to always use landscape mode

Use the ActivityInfo (android.content.pm.ActivityInfo) in your onCreate method before calling setLayout method like this

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

what is the difference between XSD and WSDL

WSDL (Web Services Description Language) describes your service and its operations - what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?

It's a description of the behavior of the service - it's functionality.

XSD (Xml Schema Definition) describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern) and so forth.

It's a description of datatypes and thus static properties of the service - it's about data.

onclick on a image to navigate to another page using Javascript

I'd set up your HTML like so:

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />

Then use the following code:

<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function(event) {
         window.location.href = this.id + '.html';
    };
}
</script>

That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

Python spacing and aligning strings

@IronMensan's format method answer is the way to go. But in the interest of answering your question about ljust:

>>> def printit():
...     print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
...     print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
...     print 'User: LOD'.ljust(40) + 'Time: 10:15'
...
>>> printit()
Location: 10-10-10-10                   Revision: 1
District: Tower                         Date: May 16, 2012
User: LOD                               Time: 10:15

Edit to note this method doesn't require you to know how long your strings are. .format() may also, but I'm not familiar enough with it to say.

>>> uname='LOD'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: LOD                               Time: 10:15'
>>> uname='Tiddlywinks'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: Tiddlywinks                       Time: 10:15'

Eclipse internal error while initializing Java tooling

I would just like to add, that simply closing and reopening eclipse has always worked for me with this type of error.

Import mysql DB with XAMPP in command LINE

/opt/lampp/bin/./mysql -u dbusername -p dbname < sqlfilepath.sql

HTML CSS How to stop a table cell from expanding

It appears that your HTML syntax is incorrect for the table cell. Before you try the other idea below, confirm if this works or not... You can also try adding this to your table itself: table-layout:fixed.. .

<td style="overflow: hidden; width: 280px; text-align: left; valign: top; whitespace: nowrap;">
   [content]
</td>

New HTML

<td>
   <div class="MyClass"">
       [content]
   </div>
</td>

CSS Class:

.MyClass{
   height: 280px; 
   width: 456px; 
   overflow: hidden;
   white-space: nowrap;
}

JPA Query.getResultList() - use in a generic way

Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.

    //simpleExample
    Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u,  someTable s WHERE s.user_id = u.id", 
NameSomething.class);
    List list = (List<NameSomething.class>) query.getResultList();

Entity class:

    @Entity
    public class NameSomething {

        @Id
        private String name;

        private String something;

        // getters/setters



        /**
         * Generic put method to map JPA native Query to this object.
         *
         * @param column
         * @param value
         */
        public void put(Object column, Object value) {
            if (((String) column).equals("name")) {
                setName(String) value);
            } else if (((String) column).equals("something")) {
                setSomething((String) value);
            }
        }
    }

Firebase FCM force onTokenRefresh() to be called

Try to implement FirebaseInstanceIdService to get refresh token.

Access the registration token:

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

     @Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

Full Code:

   import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}

See my answer here.

EDITS:

You shouldn't be starting a FirebaseInstanceIdService yourself.

It will Called when the system determines that the tokens need to be refreshed. The application should call getToken() and send the tokens to all application servers.

This will not be called very frequently, it is needed for key rotation and to handle Instance ID changes due to:

  • App deletes Instance ID
  • App is restored on a new device User
  • uninstalls/reinstall the app
  • User clears app data

The system will throttle the refresh event across all devices to avoid overloading application servers with token updates.

Try below way:

you'd call FirebaseInstanceID.getToken() anywhere off your main thread (whether it is a service, AsyncTask, etc), store the returned token locally and send it to your server. Then whenever onTokenRefresh() is called, you'd call FirebaseInstanceID.getToken() again, get a new token, and send that up to the server (probably including the old token as well so your server can remove it, replacing it with the new one).

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

Force LF eol in git repo and working copy

Starting with git 2.10 (released 2016-09-03), it is not necessary to enumerate each text file separately. Git 2.10 fixed the behavior of text=auto together with eol=lf. Source.

.gitattributes file in the root of your git repository:

* text=auto eol=lf

Add and commit it.

Afterwards, you can do following to steps and all files are normalized now:

git rm --cached -r .  # Remove every file from git's index.
git reset --hard      # Rewrite git's index to pick up all the new line endings.

Source: Answer by kenorb.

What's a decent SFTP command-line client for windows?

WinSCP has the command line functionality:

c:\>winscp.exe /console /script=example.txt

where scripting is done in example.txt.

See http://winscp.net/eng/docs/guide_automation

Refer to http://winscp.net/eng/docs/guide_automation_advanced for details on how to use a scripting language such as Windows command interpreter/php/perl.

FileZilla does have a command line but it is limited to only opening the GUI with a pre-defined server that is in the Site Manager.

How do I check if a SQL Server text column is empty?

Are null and an empty string equivalent? If they are, I would include logic in my application (or maybe a trigger if the app is "out-of-the-box"?) to force the field to be either null or '', but not the other. If you went with '', then you could set the column to NOT NULL as well. Just a data-cleanliness thing.

Finding the position of bottom of a div with jquery

The answers so far will work.. if you only want to use the height without padding, borders, etc.

If you would like to account for padding, borders, and margin, you should use .outerHeight.

var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);

JPA : How to convert a native query result set to POJO class collection

Simple way to converting SQL query to POJO class collection ,

Query query = getCurrentSession().createSQLQuery(sqlQuery).addEntity(Actors.class);
List<Actors> list = (List<Actors>) query.list();
return list;

Unique constraint violation during insert: why? (Oracle)

Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

CREATE TABLE [DB] (
    [DBId] bigint NOT NULL IDENTITY,
    ...

    CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),

); 

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

For CGSize

CGSize(width: self.view.frame.width * 3, height: self.view.frame.size.height)

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Here is some weak adobe documentation on different flash 9 wmode settings.

A note of caution on wmode transparent is here in the adobe bug trac.

And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.

How to copy a file from one directory to another using PHP?

Best way to copy all files from one folder to another using PHP

<?php
$src = "/home/www/example.com/source/folders/123456";  // source folder or file
$dest = "/home/www/example.com/test/123456";   // destination folder or file        

shell_exec("cp -r $src $dest");

echo "<H2>Copy files completed!</H2>"; //output when done
?>

How to handle-escape both single and double quotes in an SQL-Update statement

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"

Pure CSS collapse/expand div

Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary> and <detail> tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.

I've made an example here:

<details>
<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>
</details>

Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.

How to iterate through LinkedHashMap with lists as values

// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
    // iterate over each entry
    for(String item : entry.getValue()){
        // print the map's key with each value in the ArrayList
        System.out.println(entry.getKey() + ": " + item);
    }
}

Switching to landscape mode in Android Emulator

I'm using Android Studio and none of the suggestions worked. I can turn the emulator but it stays in portrait. I didn't want to add a command in the manifest forcing landscape. The fix for me was:

  1. turn the emulator to landscape mode using ctrlF11 (the image will still be in portrait though)

  2. Open up the camera in the os, it opens up in landscape mode, the only app that does this

  3. without doing anything else, debug my app from Android Studio and now it shows up in landscape

Injecting @Autowired private field during testing

I believe in order to have auto-wiring work on your MyLauncher class (for myService), you will need to let Spring initialize it instead of calling the constructor, by auto-wiring myLauncher. Once that is being auto-wired (and myService is also getting auto-wired), Spring (1.4.0 and up) provides a @MockBean annotation you can put in your test. This will replace a matching single beans in context with a mock of that type. You can then further define what mocking you want, in a @Before method.

public class MyLauncherTest
    @MockBean
    private MyService myService;

    @Autowired
    private MyLauncher myLauncher;

    @Before
    private void setupMockBean() {
        doNothing().when(myService).someVoidMethod();
        doReturn("Some Value").when(myService).someStringMethod();
    }

    @Test
    public void someTest() {
        myLauncher.doSomething();
    }
}

Your MyLauncher class can then remain unmodified, and your MyService bean will be a mock whose methods return values as you defined:

@Component
public class MyLauncher {
    @Autowired
    MyService myService;

    public void doSomething() {
        myService.someVoidMethod();
        myService.someMethodThatCallsSomeStringMethod();
    }

    //other methods
}

A couple advantages of this over other methods mentioned is that:

  1. You don't need to manually inject myService.
  2. You don't need use the Mockito runner or rules.

How to overcome "datetime.datetime not JSON serializable"?

def j_serial(o):     # self contained
    from datetime import datetime, date
    return str(o).split('.')[0] if isinstance(o, (datetime, date)) else None

Usage of above utility:

import datetime
serial_d = j_serial(datetime.datetime.now())
if serial_d:
    print(serial_d)  # output: 2018-02-28 02:23:15

Calculate age based on date of birth

For a birthday date with format Date/Month/Year

function age($birthday){
 list($day, $month, $year) = explode("/", $birthday);
 $year_diff  = date("Y") - $year;
 $month_diff = date("m") - $month;
 $day_diff   = date("d") - $day;
 if ($day_diff < 0 && $month_diff==0) $year_diff--;
 if ($day_diff < 0 && $month_diff < 0) $year_diff--;
 return $year_diff;
}

or the same function that accepts day, month, year as parameters :

function age($day, $month, $year){
 $year_diff  = date("Y") - $year;
 $month_diff = date("m") - $month;
 $day_diff   = date("d") - $day;
 if ($day_diff < 0 && $month_diff==0) $year_diff--;
 if ($day_diff < 0 && $month_diff < 0) $year_diff--;
 return $year_diff;
}

You can use it like this :

echo age("20/01/2000");

which will output the correct age (On 4 June, it's 14).

Running sites on "localhost" is extremely slow

For people using a mac. When you're using different host names say test.local and test2.local. Try changing test.local to test.dev. I found out that Mac OS X lion controls the .local tld. So when you change it to something else it's faster.

And of course use above suggestions like turning off the ipv6 reference in your hosts file:
#::1 localhost

and setting this in the hosts file: 127.0.0.1 localhost

so it points to ipv4.

Create instance of generic type whose constructor requires a parameter?

You can do by using reflection:

public void AddFruit<T>()where T: BaseFruit
{
  ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
  if (constructor == null)
  {
    throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
  }
  BaseFruit fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
  fruit.Enlist(fruitManager);
}

EDIT: Added constructor == null check.

EDIT: A faster variant using a cache:

public void AddFruit<T>()where T: BaseFruit
{
  var constructor = FruitCompany<T>.constructor;
  if (constructor == null)
  {
    throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
  }
  var fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
  fruit.Enlist(fruitManager);
}
private static class FruitCompany<T>
{
  public static readonly ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
}

Execute a shell function with timeout

I have a slight modification of @Tiago Lopo's answer that can handle commands with multiple arguments. I've also tested TauPan's solution, but it does not work if you use it multiple times in a script, while Tiago's does.

function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}

Here's a fully functional script thant you can use to test the function above:

$ ./test_timeout.sh -h
Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h

Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].

For example you cnal launch like this:

$ ./test_timeout.sh -r 2 -s 5 -t 3
Try no: 1
  - Set timeout to: 3
child: 2540
    -> retval: 143
    -> The command timed out
Try no: 2
  - Set timeout to: 3
child: 2593
    -> retval: 143
    -> The command timed out
Done!
#!/usr/bin/env bash

#shellcheck disable=SC2128
SOURCED=false && [ "$0" = "$BASH_SOURCE" ] || SOURCED=true

if ! $SOURCED; then
  set -euo pipefail
  IFS=$'\n\t'
fi

#################### helpers
function check_posint() {
  local re='^[0-9]+$'
  local mynum="$1"
  local option="$2"

  if ! [[ "$mynum" =~ $re ]] ; then
     (echo -n "Error in option '$option': " >&2)
     (echo "must be a positive integer, got $mynum." >&2)
     exit 1
  fi

  if ! [ "$mynum" -gt 0 ] ; then
     (echo "Error in option '$option': must be positive, got $mynum." >&2)
     exit 1
  fi
}
#################### end: helpers

#################### usage
function short_usage() {
  (>&2 echo \
"Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h"
  )
}

function usage() {
  (>&2 short_usage )
  (>&2 echo \
"
Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].
")
}
#################### end: usage

help_flag=false
dryrun_flag=false
SLEEP_TIME=5
TIMEOUT=-1
REPEAT=1

while getopts ":hnr:s:t:" opt; do
  case $opt in
    h)
      help_flag=true
      ;;    
    n)
      dryrun_flag=true
      ;;
    r)
      check_posint "$OPTARG" '-r'

      REPEAT="$OPTARG"
      ;;
    s)
      check_posint "$OPTARG" '-s'

      SLEEP_TIME="$OPTARG"
      ;;
    t)
      check_posint "$OPTARG" '-t'

      TIMEOUT="$OPTARG"
      ;;
    \?)
      (>&2 echo "Error. Invalid option: -$OPTARG.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
    :)
      (>&2 echo "Error.Option -$OPTARG requires an argument.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
  esac
done

if $help_flag; then
  usage
  exit 0
fi

#################### utils
if $dryrun_flag; then
  function wrap_run() {
    ( echo -en "[dry run]\\t" )
    ( echo "$@" )
  }
else
  function wrap_run() { "$@"; }
fi

# Execute a shell function with timeout
# https://stackoverflow.com/a/24416732/2377454
function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}
####################

function sleep_func() {
  local secs
  local waitsec

  waitsec=1
  secs=$(($1))
  while [ "$secs" -gt 0 ]; do
   echo -ne "$secs\033[0K\r"
   sleep "$waitsec"
   secs=$((secs-waitsec))
  done

}

command=("wrap_run" \
         "sleep_func" "${SLEEP_TIME}"
         )

for i in $(seq 1 "$REPEAT"); do
  echo "Try no: $i"

  if [ "$TIMEOUT" -gt 0 ]; then
    echo "  - Set timeout to: $TIMEOUT"
    set +e
    timeout_cmd "$TIMEOUT" "${command[@]}"
    retval="$?"
    set -e

    echo "    -> retval: $retval"
    # check if (retval % 128) == SIGTERM (== 15)
    if [[ "$((retval % 128))" -eq 15 ]]; then
      echo "    -> The command timed out"
    fi
  else
    echo "  - No timeout"
    "${command[@]}"
    retval="$?"
  fi
done

echo "Done!"

exit 0