Programs & Examples On #Fixed length record

can we use xpath with BeautifulSoup?

I can confirm that there is no XPath support within Beautiful Soup.

Source file 'Properties\AssemblyInfo.cs' could not be found

This rings a bell. I came across a similar problem in the past,

  • if you expand Properties folder of the project can you see 'AssemblyInfo.cs' if not that is where the problem is. An assembly info file consists of all of the build options for the project, including version, company name, GUID, compilers options....etc

You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.

Cheers, Tarun

Update 2016-07-08:

For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:

After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.

iCheck check if checkbox is checked

All callbacks and functions are documented here: http://fronteed.com/iCheck/#usage

$('input').iCheck('check'); — change input's state to checked
$('input').iCheck('uncheck'); — remove checked state
$('input').iCheck('toggle'); — toggle checked state
$('input').iCheck('disable'); — change input's state to disabled
$('input').iCheck('enable'); — remove disabled state
$('input').iCheck('indeterminate'); — change input's state to indeterminate
$('input').iCheck('determinate'); — remove indeterminate state
$('input').iCheck('update'); — apply input changes, which were done outside the plugin
$('input').iCheck('destroy'); — remove all traces of iCheck

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

How do I fix the indentation of selected lines in Visual Studio

Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works. However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker. ymmv.

how do I query sql for a latest record date for each user

This is similar to one of the answers above, but in my opinion it is a lot simpler and tidier. Also, shows a good use for the cross apply statement. For SQL Server 2005 and above...

select
    a.username,
    a.date,
    a.value,
from yourtable a
cross apply (select max(date) 'maxdate' from yourtable a1 where a.username=a1.username) b
where a.date=b.maxdate

Writing to CSV with Python adds blank lines

You need to open the file in binary b mode to take care of blank lines in Python 2. This isn't required in Python 3.

So, change open('test.csv', 'w') to open('test.csv', 'wb').

Minimum 6 characters regex expression

Something along the lines of this?

<asp:TextBox id="txtUsername" runat="server" />

<asp:RegularExpressionValidator
    id="RegularExpressionValidator1"
    runat="server"
    ErrorMessage="Field not valid!"
    ControlToValidate="txtUsername"
    ValidationExpression="[0-9a-zA-Z]{6,}" />

How do I append one string to another in Python?

If you need to do many append operations to build a large string, you can use StringIO or cStringIO. The interface is like a file. ie: you write to append text to it.

If you're just appending two strings then just use +.

Error in spring application context schema

use this:

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"

How to upload images into MySQL database using PHP code

This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

How to remove all numbers from string?

Try with regex \d:

$words = preg_replace('/\d/', '', $words );

\d is an equivalent for [0-9] which is an equivalent for numbers range from 0 to 9.

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A simple DELETE before the INSERT would suffice:

DELETE FROM Table2 WHERE Id = (SELECT Id FROM Table1)
INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1

Switching Table1 for Table2 depending on which table's Id and name pairing you want to preserve.

Python: Assign Value if None Exists

Here is the easiest way I use, hope works for you,

var1 = var1 or 4

This assigns 4 to var1 only if var1 is None , False or 0

check if a file is open in Python

if myfile.closed == False:
   print("File is still open ################")

ActivityCompat.requestPermissions not showing dialog box

I had the same issue and it turned out to be due to the manifest merger tool pulling in an android:maxSdkVersion attribute from a dependency.

To view the actual permissions you're requesting in your APK you can use the aapt tool, like this:

/path/to/android-sdk/build-tools/version/aapt d permissions /path/to/your-apk.apk

in my case, it printed:

uses-permission: name='android.permission.WRITE_EXTERNAL_STORAGE' maxSdkVersion='18'

even though I hadn't specified a maxSdkVersion in my manifest. I fixed this issue by changing <uses-permission> in my manifest to:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:remove="android:maxSdkVersion"/>

(where the tools namespace is http://schemas.android.com/tools)

removing new line character from incoming stream using sed

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

C# LINQ select from list

The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.

Let's say you have a list of integers, and want to find the items that match those integers.

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var items = from p in context.Items
                 where numbers.Contains(p.ItemId)
                select p;

Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0

Lining up labels with radio buttons in bootstrap

This is all nicely lined up including the field label. Lining up the field label was the tricky part.

enter image description here

HTML Code:

<div class="form-group">
    <label class="control-label col-md-5">Create a</label>
    <div class="col-md-7">
        <label class="radio-inline control-label">
            <input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
        </label>
        <label class="radio-inline control-label">
            <input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
        </label>
    </div>
</div>

CSHTML / Razor Code:

<div class="form-group">
    @Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
    <div class="col-md-7">
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
        </label>
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
        </label>
    </div>
</div>

Android view layout_width - how to change programmatically?

You can set height and width like this also:

viewinstance.setLayoutParams(new LayoutParams(width, height));

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

Are dictionaries ordered in Python 3.6+?

Are dictionaries ordered in Python 3.6+?

They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).

As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.


How does the Python 3.6 dictionary implementation perform better[2] than the older one while preserving element order?

Essentially, by keeping two arrays.

  • The first array, dk_entries, holds the entries (of type PyDictKeyEntry) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).

  • The second, dk_indices, holds the indices for the dk_entries array (that is, values that indicate the position of the corresponding entry in dk_entries). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices and the corresponding entry is fetched by indexing dk_entries. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t(1 byte) to int32_t/int64_t (4/8 bytes) on 32/64 bit builds)

In the previous implementation, a sparse array of type PyDictKeyEntry and size dk_size had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size full for performance reasons. (and the empty space still had PyDictKeyEntry size!).

This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t (X depending on dict size) 2/3 * dk_sizes full is kept. The empty space changed from type PyDictKeyEntry to intX_t.

So, obviously, creating a sparse array of type PyDictKeyEntry is much more memory demanding than a sparse array for storing ints.

You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.


In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.

For example, the dictionary:

d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}

is currently stored as [keyhash, key, value]:

entries = [['--', '--', '--'],
           [-8522787127447073495, 'barry', 'green'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           [-9092791511155847987, 'timmy', 'red'],
           ['--', '--', '--'],
           [-6480567542315338377, 'guido', 'blue']]

Instead, the data should be organized as follows:

indices =  [None, 1, None, None, None, 0, None, 2]
entries =  [[-9092791511155847987, 'timmy', 'red'],
            [-8522787127447073495, 'barry', 'green'],
            [-6480567542315338377, 'guido', 'blue']]

As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.


[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==, !=). dicts currently don't offer any of those behaviors/methods.


[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.

Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.

Display a decimal in scientific notation

This worked best for me:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

URLs use forward slashes (/), not backward ones (as windows). Try:

serverURLS = "https://abc.my.domain.com:55555/update";

The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host is null.

How to check if a file exists in Ansible?

**

How to check if a file exists in Ansible using when condition

**

Below is the ansible play i used to remove the file when the file exists in the OS end.

 - name: find out /etc/init.d/splunk file exists or not'
      stat:
        path: /etc/init.d/splunk
      register: splunkresult
      tags:
        - always

    - name: 'Remove splunk from init.d file if splunk already running'
      file:
        path: /etc/init.d/splunk
        state: absent
      when: splunkresult.stat.exists == true
      ignore_errors: yes
      tags:
        - always

I have used play condition as like below

when: splunkresult.stat.exists == true --> Remove the file

you can give true/false based on your requirement

when: splunkresult.stat.exists == false
when: splunkresult.stat.exists == true

Implementation difference between Aggregation and Composition in Java

Aggregation vs Composition

Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist.

whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human.

Aggregation relation is “has-a” and composition is “part-of” relation.

Composition is a strong Association whereas Aggregation is a weak Association.

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

How to remove commits from a pull request

This is what helped me:

  1. Create a new branch with the existing one. Let's call the existing one branch_old and new as branch_new.

  2. Reset branch_new to a stable state, when you did not have any problem commit at all. For example, to put it at your local master's level do the following:

    git reset —hard master git push —force origin

  3. cherry-pick the commits from branch_old into branch_new

  4. git push

curl error 18 - transfer closed with outstanding read data remaining

I had this problem working with pycurl and I solved it using

c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0) 

like Eric Caron says.

Changing the cursor in WPF sometimes works, sometimes doesn't

Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:

Mouse.OverrideCursor = Cursors.Wait;
try
{
    // do stuff
}
finally
{
    Mouse.OverrideCursor = null;
}

This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.

Stop handler.postDelayed()

You can use:

 Handler handler = new Handler()
 handler.postDelayed(new Runnable())

Or you can use:

 handler.removeCallbacksAndMessages(null);

Docs

public final void removeCallbacksAndMessages (Object token)

Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Or you could also do like the following:

Handler handler =  new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
    // do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);

Then:

handler.removeCallbacks(myRunnable);

Docs

public final void removeCallbacks (Runnable r)

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

public final void removeCallbacks (Runnable r, Object token)

Edit:

Change this:

@Override
public void onClick(View v) {
    Handler handler =  new Handler();
    Runnable myRunnable = new Runnable() {

To:

@Override
public void onClick(View v) {
    handler = new Handler();
    myRunnable = new Runnable() { /* ... */}

Because you have the below. Declared before onCreate but you re-declared and then initialized it in onClick leading to a NPE.

Handler handler; // declared before onCreate
Runnable myRunnable;

Get the list of stored procedures created and / or modified on a particular date?

You can try this query in any given SQL Server database:

SELECT 
    name,
    create_date,
    modify_date
FROM sys.procedures
WHERE create_date = '20120927'  

which lists out the name, the creation and the last modification date - unfortunately, it doesn't record who created and/or modified the stored procedure in question.

PUT vs. POST in REST

the origin server can create the resource with that URI

So you use POST and probably, but not necessary PUT for resource creation. You don't have to support both. For me POST is perfectly enough. So it is a design decision.

As your quote mentioned, you use PUT for creation of there is no resource assigned to an IRI, and you want to create a resource anyway. For example, PUT /users/123/password usually replaces the old password with a new one, but you can use it to create a password if it does not exist already (for example, by freshly registered users or by restoring banned users).

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

Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;

MySQL – Temporarily disable Foreign Key Checks or Constraints

How to add local .jar file dependency to build.gradle file?

The solution which worked for me is the usage of fileTree in build.gradle file. Keep the .jar which need to add as dependency in libs folder. The give the below code in dependenices block in build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Using comma as list separator with AngularJS

You could do it this way:

<b ng-repeat="email in friend.email">{{email}}{{$last ? '' : ', '}}</b>

..But I like Philipp's answer :-)

Static Block in Java

Static block can be used to show that a program can run without main function also.

//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
    static
    {
        System.out.println("Welcome to Java"); 
        System.exit(0); 
    }
}

How to count the number of occurrences of a character in an Oracle varchar value?

here is a solution that will function for both characters and substrings:

select (length('a') - nvl(length(replace('a','b')),0)) / length('b')
  from dual

where a is the string in which you search the occurrence of b

have a nice day!

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

Python: Remove division decimal

def division(a, b):
    return a / b if a % b else a // b

How to find the extension of a file in C#?

private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}

Remove excess whitespace from within a string

I wrote recently a simple function which removes excess white space from string without regular expression implode(' ', array_filter(explode(' ', $str))).

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

Dealing with multiple Python versions and PIP?

Another possible way could be using conda and pip. Some time you probably want to use just one of those, but if you really need to set up a particular version of python I combine both.

  1. I create a starting conda enviroment with the python I want. As in here https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html. Alternatively you could set up the whole enviroment just using conda.

    conda create -n myenv python=3.6.4

  2. Then activate your enviroment with the python you like. This command could change depending on the OS.

    source activae myenv

  3. Now you have your python active then you could continue using conda but if you need/want to use pip:

    python -m pip -r requirements.txt

Here you have a possible way.

Why am I getting "IndentationError: expected an indented block"?

There are in fact multiples things you need to know about indentation in Python:

Python really cares about indention.

In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.

This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.

There are different indention errors and you reading them helps a lot:

1. "IndentationError: expected an indented block"

They are two main reasons why you could have such an error:

- You have a ":" without an indented block behind.

Here are two examples:

Example 1, no indented block:

Input:

if 3 != 4:
    print("usual")
else:

Output:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

The output states that you need to have an indented block on line 4, after the else: statement

Example 2, unindented block:

Input:

if 3 != 4:
print("usual")

Output

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block

The output states that you need to have an indented block line 2, after the if 3 != 4: statement

- You are using Python2.x and have a mix of tabs and spaces:

Input

def foo():
    if 1:
        print 1

Please note that before if, there is a tab, and before print there is 8 spaces.

Output:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block

It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.

  • You can get some info here.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

2. "IndentationError: unexpected indent"

It is important to indent blocks, but only blocks that should be indent. So basically this error says:

- You have an indented block without a ":" before it.

Example:

Input:

a = 3
  a += 3

Output:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

The output states that he wasn't expecting an indent block line 2, then you should remove it.

3. "TabError: inconsistent use of tabs and spaces in indentation" (python3.x only)

  • You can get some info here.
  • But basically it's, you are using tabs and spaces in your code.
  • You don't want that.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.


Eventually, to come back on your problem:

Just look at the line number of the error, and fix it using the previous information.

Unix ls command: show full path when using options

simply use find tool.

find absolute_path

displays full paths on my Linux machine, while

find relative_path

will not.

How to get the path of running java program

    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){
        System.out.println(url.getFile());
    }

Can't bind to 'ngIf' since it isn't a known property of 'div'

Just for anyone who still has an issue, I also had an issue where I typed ngif rather than ngIf (notice the capital 'I').

Why would I use dirname(__FILE__) in an include or include_once statement?

I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:

Project root directory:
                       file1.php
                       file3.php
                       dir1/
                            file2.php

(dir1 is a directory and file2.php is inside it)

And this is the content of each of the three files above:

//file1.php:
<?php include "dir1/file2.php"

//file2.php:
<?php include "../file3.php"

//file3.php:
<?php echo "Hello, Test!";

Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!

The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).

Now, what should we do ?!

Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!

So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!

The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!

So now if we turn the project above to this:

//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");

//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");

//file3.php:
<?php echo "Hello, Test!";

if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).

It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!

Hope that helps.

Formatting text in a TextBlock

a good site, with good explanations:

http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/

here the author gives you good examples for what you are looking for! Overal the site is great for research material plus it covers a great deal of options you have in WPF

Edit

There are different methods to format the text. for a basic formatting (the easiest in my opinion):

    <TextBlock Margin="10" TextWrapping="Wrap">
                    TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
    </TextBlock>

Example 1 shows basic formatting with Bold Itallic and underscored text.

Following includes the SPAN method, with this you van highlight text:

   <TextBlock Margin="10" TextWrapping="Wrap">
                    This <Span FontWeight="Bold">is</Span> a
                    <Span Background="Silver" Foreground="Maroon">TextBlock</Span>
                    with <Span TextDecorations="Underline">several</Span>
                    <Span FontStyle="Italic">Span</Span> elements,
                    <Span Foreground="Blue">
                            using a <Bold>variety</Bold> of <Italic>styles</Italic>
                    </Span>.
   </TextBlock>

Example 2 shows the span function and the different possibilities with it.

For a detailed explanation check the site!

Examples

Entity Framework 6 Code first Default value

In .NET Core 3.1 you can do the following in the model class:

    public bool? Active { get; set; } 

In the DbContext OnModelCreating you add the default value.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foundation>()
            .Property(b => b.Active)
            .HasDefaultValueSql("1");

        base.OnModelCreating(modelBuilder);
    }

Resulting in the following in the database

enter image description here

Note: If you don't have nullable (bool?) for you property you will get the following warning

The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used for inserts when the property value is 'null'.

String field value length in mongoDB

I had a similar kind of scenario, but in my case string is not a 1st level attribute. It is inside an object. In here I couldn't find a suitable answer for it. So I thought to share my solution with you all(Hope this will help anyone with a similar kind of problem).

Parent Collection 

{
"Child":
{
"name":"Random Name",
"Age:"09"
}
}

Ex: If we need to get only collections that having child's name's length is higher than 10 characters.

 db.getCollection('Parent').find({$where: function() { 
for (var field in this.Child.name) { 
    if (this.Child.name.length > 10) 
        return true;

}
}})

How to create CSV Excel file C#?

Please forgive me

But I think a public open-source repository is a better way to share code and make contributions, and corrections, and additions like "I fixed this, I fixed that"

So I made a simple git-repository out of the topic-starter's code and all the additions:

https://github.com/jitbit/CsvExport

I also added a couple of useful fixes myself. Everyone could add suggestions, fork it to contribute etc. etc. etc. Send me your forks so I merge them back into the repo.

PS. I posted all copyright notices for Chris. @Chris if you're against this idea - let me know, I'll kill it.

Media Queries - In between two widths

_x000D_
_x000D_
.class {_x000D_
    display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
    .class {_x000D_
        display: block; /* just an example display property */_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Set padding for UITextField with UITextBorderStyleNone

The best solution I found so far is a category. That's how I add a 5 points padding to left and right:

@implementation UITextField (Padding)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectMake(bounds.origin.x + 5, bounds.origin.y,
                      bounds.size.width - 10, bounds.size.height);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}
#pragma clang diagnostic pop

@end

The #pragma's are just for removing the annoying warnings

How to disable spring security for particular url

If you want to ignore multiple API endpoints you can use as follow:

 @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests() 
            .antMatchers("/api/v1/**").authenticated()
            .antMatchers("api/v1/authenticate**").permitAll()
            .antMatchers("**").permitAll()
            .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

Selenium Webdriver submit() vs click()

submit() method can be used to click on the button present in the form and Type attribute should be "submit".

click() method is used to click on the button in the webpage.

Correct me if i am wrong.

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

Location of hibernate.cfg.xml in project?

Somehow placing under "src" folder didn't work for me.

Instead placing cfg.xml as below:

[Project Folder]\src\main\resources\hibernate.cfg.xml

worked. Using this code

new Configuration().configure().buildSessionFactory().openSession();

in a file under

    [Project Folder]/src/main/java/com/abc/xyz/filename.java

In addition have this piece of code in hibernate.cfg.xml

<mapping resource="hibernate/Address.hbm.xml" />
<mapping resource="hibernate/Person.hbm.xml" />

Placed the above hbm.xml files under:

EDIT:

[Project Folder]/src/main/resources/hibernate/Address.hbm.xml
[Project Folder]/src/main/resources/hibernate/Person.hbm.xml

Above structure worked.

Overriding the java equals() method - not working?

Slightly off-topic to your question, but it's probably worth mentioning anyway:

Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.

I also agree that you should use the @Override annotation whenever you're overriding equals (or any other method).

implements Closeable or implements AutoCloseable

Closeable extends AutoCloseable, and is specifically dedicated to IO streams: it throws IOException instead of Exception, and is idempotent, whereas AutoCloseable doesn't provide this guarantee.

This is all explained in the javadoc of both interfaces.

Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitely.

Your class doesn't represent a closeable resource, and there's absolutely no point in implementing this interface: an IOTest can't be closed. It shouldn't even be possible to instantiate it, since it doesn't have any instance method. Remember that implementing an interface means that there is a is-a relationship between the class and the interface. You have no such relationship here.

How can I add a username and password to Jenkins?

If installed as an admin, use:-

uname - admin
pw - the passkey that was generated during installation

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

AES Encryption for an NSString on the iPhone

@owlstead, regarding your request for "a cryptographically secure variant of one of the given answers," please see RNCryptor. It was designed to do exactly what you're requesting (and was built in response to the problems with the code listed here).

RNCryptor uses PBKDF2 with salt, provides a random IV, and attaches HMAC (also generated from PBKDF2 with its own salt. It support synchronous and asynchronous operation.

How to access environment variable values?

There's also a number of great libraries. Envs for example will allow you to parse objects out of your environment variables, which is rad. For example:

from envs import env
env('SECRET_KEY') # 'your_secret_key_here'
env('SERVER_NAMES',var_type='list') #['your', 'list', 'here']

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

ReactJS - How to use comments?

On the other hand, the following is a valid comment, pulled directly from a working application:

render () {
    return <DeleteResourceButton
            //confirm
            onDelete={this.onDelete.bind(this)}
            message="This file will be deleted from the server."
           />
}

Apparantly, when inside the angle brackets of a JSX element, the // syntax is valid, but the {/**/} is invalid. The following breaks:

render () {
    return <DeleteResourceButton
            {/*confirm*/}
            onDelete={this.onDelete.bind(this)}
            message="This file will be deleted from the server."
           />
}

Export a graph to .eps file with R

If you are using ggplot2 to generate a figure, then a ggsave(file="name.eps") will also work.

What's the easy way to auto create non existing dir in ansible

To ensure success with a full path use recurse=yes

- name: ensure custom facts directory exists
    file: >
      path=/etc/ansible/facts.d
      recurse=yes
      state=directory

C# static class why use?

Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.

Bold & Non-Bold Text In A Single UILabel?

In this case you could try,

UILabel *displayLabel = [[UILabel alloc] initWithFrame:/*label frame*/];
displayLabel.font = [UIFont boldSystemFontOfSize:/*bold font size*/];

NSMutableAttributedString *notifyingStr = [[NSMutableAttributedString alloc] initWithString:@"Updated: 2012/10/14 21:59 PM"];
[notifyingStr beginEditing];
[notifyingStr addAttribute:NSFontAttributeName
                     value:[UIFont systemFontOfSize:/*normal font size*/]
                     range:NSMakeRange(8,10)/*range of normal string, e.g. 2012/10/14*/];
[notifyingStr endEditing];

displayLabel.attributedText = notifyingStr; // or [displayLabel setAttributedText: notifyingStr];

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

You have multiple ways to set : as the separator:

awk -F: '{print $1}'

awk -v FS=: '{print $1}'

awk '{print $1}' FS=:

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

All of them are equivalent and will return 1 given a sample input "1:2:3":

$ awk -F: '{print $1}' <<< "1:2:3"
1
$ awk -v FS=: '{print $1}' <<< "1:2:3"
1
$ awk '{print $1}' FS=: <<< "1:2:3"
1
$ awk 'BEGIN{FS=":"} {print $1}' <<< "1:2:3"
1

How to retrieve absolute path given relative

#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"

UPD Some explanations

  1. This script get relative path as argument "$1"
  2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
  3. Then we cd "$(dirname "$1") into this relative dir and get absolute path for it by running pwd shell command
  4. After that we append basename to absolute path: $(basename "$1")
  5. As final step we echo it

Custom ImageView with drop shadow

This works for me ...

public class ShadowImage extends Drawable {

Bitmap bm;

@Override
public void draw(Canvas canvas) {

    Paint mShadow = new Paint();
    Rect rect = new Rect(0,0,bm.getWidth(), bm.getHeight());

    mShadow.setAntiAlias(true);
    mShadow.setShadowLayer(5.5f, 4.0f, 4.0f, Color.BLACK);

    canvas.drawRect(rect, mShadow);
    canvas.drawBitmap(bm, 0.0f, 0.0f, null);

}

public ShadowImage(Bitmap bitmap) {
    super();
    this.bm = bitmap;
} ... }

How to attach a file using mail command on Linux?

$ echo | mutt -a syslogs.tar.gz [email protected]

But it uses mutt, not mail (or mailx).

How to delete duplicate rows in SQL Server?

You need to group by the duplicate records according to the field(s), then hold one of the records and delete the rest. For example:

DELETE prg.Person WHERE Id IN (
SELECT dublicateRow.Id FROM
(
select MIN(Id) MinId, NationalCode
 from  prg.Person group by NationalCode  having count(NationalCode ) > 1
 ) GroupSelect
 JOIN  prg.Person dublicateRow ON dublicateRow.NationalCode = GroupSelect.NationalCode 
 WHERE dublicateRow.Id <> GroupSelect.MinId)

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

git pull fails "unable to resolve reference" "unable to update local ref"

For me, it worked to remove the files that are throwing errors from the folder .git/refs/remotes/origin/.

How do you create a UIImage View Programmatically - Swift

Make sure to put:

imageView.translatesAutoresizingMaskIntoConstraints = false

Your image view will not show if you don't put that, don't ask me why.

How to delete object from array inside foreach loop?

I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.

The steps are :

  1. In the address bar, type "chrome://net-internals/#hsts".
  2. Type the domain name in the text field below "Delete domain".
  3. Click the "Delete" button.
  4. Type the domain name in the text field below "Query domain".
  5. Click the "Query" button.
  6. Your response should be "Not found".

You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers

Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.

Edit : you have to repeat the steps every time you will go on the production site.

Disable validation of HTML5 form elements

Instead of trying to do an end run around the browser's validation, you could put the http:// in as placeholder text. This is from the very page you linked:

Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as you click on (or tab to) the input field, the placeholder text disappears.

You’ve probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”:

enter image description here

When you click on (or tab to) the location bar, the placeholder text disappears:

enter image description here

Ironically, Firefox 3.5 does not support adding placeholder text to your own web forms. C’est la vie.

Placeholder Support

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

Here’s how you can include placeholder text in your own web forms:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

It wouldn't be exactly the same since it wouldn't provide that "starting point" for the user, but it's halfway there at least.

How to add local jar files to a Maven project?

  1. mvn install

You can write code below in command line or if you're using eclipse builtin maven right click on project -> Run As -> run configurations... -> in left panel right click on Maven Build -> new configuration -> write the code in Goals & in base directory :${project_loc:NameOfYourProject} -> Run

mvn install:install-file
   -Dfile=<path-to-file>
   -DgroupId=<group-id>
   -DartifactId=<artifact-id>
   -Dversion=<version>
   -Dpackaging=<packaging>
   -DgeneratePom=true

Where each refers to:

< path-to-file >: the path to the file to load e.g -> c:\kaptcha-2.3.jar

< group-id >: the group that the file should be registered under e.g -> com.google.code

< artifact-id >: the artifact name for the file e.g -> kaptcha

< version >: the version of the file e.g -> 2.3

< packaging >: the packaging of the file e.g. -> jar

2.After installed, just declares jar in pom.xml.

 <dependency>
      <groupId>com.google.code</groupId>
      <artifactId>kaptcha</artifactId>
      <version>2.3</version>
 </dependency>

Update multiple values in a single statement

Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:

update 
    MasterTbl
set
    TotalX = Sum(DetailTbl.X),
    TotalY = Sum(DetailTbl.Y),
    TotalZ = Sum(DetailTbl.Z)
from
    DetailTbl
where
    DetailTbl.MasterID = MasterID

An item with the same key has already been added

I have had the same error. And after I have already thought my mind is broken, because I had rename almost all my models properties the solution was delete one reference on All Syncfusion Controls and add references to the individual controls of this controls. (From Nuget)

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

How can I build multiple submit buttons django form?

Eg:

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

How does DISTINCT work when using JPA and Hibernate

Depending on the underlying JPQL or Criteria API query type, DISTINCT has two meanings in JPA.

Scalar queries

For scalar queries, which return a scalar projection, like the following query:

List<Integer> publicationYears = entityManager
.createQuery(
    "select distinct year(p.createdOn) " +
    "from Post p " +
    "order by year(p.createdOn)", Integer.class)
.getResultList();

LOGGER.info("Publication years: {}", publicationYears);

The DISTINCT keyword should be passed to the underlying SQL statement because we want the DB engine to filter duplicates prior to returning the result set:

SELECT DISTINCT
    extract(YEAR FROM p.created_on) AS col_0_0_
FROM
    post p
ORDER BY
    extract(YEAR FROM p.created_on)

-- Publication years: [2016, 2018]

Entity queries

For entity queries, DISTINCT has a different meaning.

Without using DISTINCT, a query like the following one:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.getResultList();

LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

is going to JOIN the post and the post_comment tables like this:

SELECT p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'

-- Fetched the following Post entity identifiers: [1, 1]

But the parent post records are duplicated in the result set for each associated post_comment row. For this reason, the List of Post entities will contain duplicate Post entity references.

To eliminate the Post entity references, we need to use DISTINCT:

List<Post> posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.getResultList();
 
LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

But then DISTINCT is also passed to the SQL query, and that's not desirable at all:

SELECT DISTINCT
       p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'
 
-- Fetched the following Post entity identifiers: [1]

By passing DISTINCT to the SQL query, the EXECUTION PLAN is going to execute an extra Sort phase which adds overhead without bringing any value since the parent-child combinations always return unique records because of the child PK column:

Unique  (cost=23.71..23.72 rows=1 width=1068) (actual time=0.131..0.132 rows=2 loops=1)
  ->  Sort  (cost=23.71..23.71 rows=1 width=1068) (actual time=0.131..0.131 rows=2 loops=1)
        Sort Key: p.id, pc.id, p.created_on, pc.post_id, pc.review
        Sort Method: quicksort  Memory: 25kB
        ->  Hash Right Join  (cost=11.76..23.70 rows=1 width=1068) (actual time=0.054..0.058 rows=2 loops=1)
              Hash Cond: (pc.post_id = p.id)
              ->  Seq Scan on post_comment pc  (cost=0.00..11.40 rows=140 width=532) (actual time=0.010..0.010 rows=2 loops=1)
              ->  Hash  (cost=11.75..11.75 rows=1 width=528) (actual time=0.027..0.027 rows=1 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    ->  Seq Scan on post p  (cost=0.00..11.75 rows=1 width=528) (actual time=0.017..0.018 rows=1 loops=1)
                          Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
                          Rows Removed by Filter: 3
Planning time: 0.227 ms
Execution time: 0.179 ms

Entity queries with HINT_PASS_DISTINCT_THROUGH

To eliminate the Sort phase from the execution plan, we need to use the HINT_PASS_DISTINCT_THROUGH JPA query hint:

List<Post> posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();
 
LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

And now, the SQL query will not contain DISTINCT but Post entity reference duplicates are going to be removed:

SELECT
       p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'
 
-- Fetched the following Post entity identifiers: [1]

And the Execution Plan is going to confirm that we no longer have an extra Sort phase this time:

Hash Right Join  (cost=11.76..23.70 rows=1 width=1068) (actual time=0.066..0.069 rows=2 loops=1)
  Hash Cond: (pc.post_id = p.id)
  ->  Seq Scan on post_comment pc  (cost=0.00..11.40 rows=140 width=532) (actual time=0.011..0.011 rows=2 loops=1)
  ->  Hash  (cost=11.75..11.75 rows=1 width=528) (actual time=0.041..0.041 rows=1 loops=1)
        Buckets: 1024  Batches: 1  Memory Usage: 9kB
        ->  Seq Scan on post p  (cost=0.00..11.75 rows=1 width=528) (actual time=0.036..0.037 rows=1 loops=1)
              Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
              Rows Removed by Filter: 3
Planning time: 1.184 ms
Execution time: 0.160 ms

How to make Excel VBA variables available to multiple macros?

Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset the selected options

$('select option:selected').removeAttr('selected');

If you actually want to remove the options (although I don't think you mean this).

$('select').empty();

Substitute select for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select> elements on the page

Finding out the name of the original repository you cloned from in Git

I use this:

basename $(git remote get-url origin) .git

Which returns something like gitRepo. (Remove the .git at the end of the command to return something like gitRepo.git.)

(Note: It requires Git version 2.7.0 or later)

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

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


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

What does git rev-parse do?

Just to elaborate on the etymology of the command name rev-parse, Git consistently uses the term rev in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list for example prints a list of 40-char commit hashes for a branch or whatever.

In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.

I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)

Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.

ORA-01036: illegal variable name/number when running query through C#

This error happens when you are also missing cmd.CommandType = System.Data.CommandType.StoredProcedure;

Accessing dict_keys element by index in Python3

Python 3

mydict = {'a': 'one', 'b': 'two', 'c': 'three'}
mykeys = [*mydict]          #list of keys
myvals = [*mydict.values()] #list of values

print(mykeys)
print(myvals)

Output

['a', 'b', 'c']
['one', 'two', 'three']

Also see this detailed answer

HTML Entity Decode

here is another version:

_x000D_
_x000D_
function convertHTMLEntity(text){_x000D_
    const span = document.createElement('span');_x000D_
_x000D_
    return text_x000D_
    .replace(/&[#A-Za-z0-9]+;/gi, (entity,position,text)=> {_x000D_
        span.innerHTML = entity;_x000D_
        return span.innerText;_x000D_
    });_x000D_
}_x000D_
_x000D_
console.log(convertHTMLEntity('Large &lt; &#163; 500'));
_x000D_
_x000D_
_x000D_

jQuery Validate Plugin - How to create a simple custom rule?

You can add a custom rule like this:

$.validator.addMethod(
    'booleanRequired',
    function (value, element, requiredValue) {
        return value === requiredValue;
    },
    'Please check your input.'
);

And add it as a rule like this:

PhoneToggle: {
    booleanRequired: 'on'
}        

What is lexical scope?

Lexical scope refers to the lexicon of identifiers (e.g., variables, functions, etc.) visible from the current position in the execution stack.

- global execution context
    - foo
    - bar
    - function1 execution context
        - foo2
        - bar2
        - function2 execution context
            - foo3
            - bar3

foo and bar are always within the lexicon of available identifiers because they are global.

When function1 is executed, it has access to a lexicon of foo2, bar2, foo, and bar.

When function2 is executed, it has access to a lexicon of foo3, bar3, foo2, bar2, foo, and bar.

The reason global and/or outer functions do not have access to an inner functions identifiers is because the execution of that function has not occurred yet and therefore, none of its identifiers have been allocated to memory. What’s more, once that inner context executes, it is removed from the execution stack, meaning that all of it’s identifiers have been garbage collected and are no longer available.

Finally, this is why a nested execution context can ALWAYS access it’s ancestors execution context and thus why it has access to a greater lexicon of identifiers.

See:

Special thanks to @robr3rd for help simplifying the above definition.

How to delete columns in pyspark dataframe

You could either explicitly name the columns you want to keep, like so:

keep = [a.id, a.julian_date, a.user_id, b.quan_created_money, b.quan_created_cnt]

Or in a more general approach you'd include all columns except for a specific one via a list comprehension. For example like this (excluding the id column from b):

keep = [a[c] for c in a.columns] + [b[c] for c in b.columns if c != 'id']

Finally you make a selection on your join result:

d = a.join(b, a.id==b.id, 'outer').select(*keep)

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app. Kirill Fuchs

Is there a short cut for going back to the beginning of a file by vi editor?

To go end of the file: press ESC

1) type capital G (Capital G)

2) press shift + g (small g)

To go top of the file there are the following ways: press ESC

1) press 1G (Capital G)

2) press gg (small g) or 1gg

3) You can jump to the particular line number,e.g wanted to go 1 line number, press 1 + G

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

this solution from this link helped me a lot. you can check it out.

The curl.php file with those line of instruction can work.

<?php 
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' );
$ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p>&nbsp;</p>";
echo "The Result : ".$result;

Remember you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.

multiple packages in context:component-scan, spring config

<context:component-scan base-package="x.y.z"/>

will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.

Reliable way to convert a file to a byte[]

Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:

  1. System.IO.File.ReadAllBytes(filename);
  2. File.Exists(filename)
  3. Path.Combine(folderName, resOfThePath);
  4. Path.GetFullPath(path); // converts a relative path to absolute one
  5. Path.GetExtension(path);

Prevent users from submitting a form by hitting Enter

Disallow enter key anywhere

If you don't have a <textarea> in your form, then just add the following to your <form>:

<form ... onkeydown="return event.key != 'Enter';">

Or with jQuery:

$(document).on("keydown", "form", function(event) { 
    return event.key != "Enter";
});

This will cause that every key press inside the form will be checked on the key. If it is not Enter, then it will return true and anything continue as usual. If it is Enter, then it will return false and anything will stop immediately, so the form won't be submitted.

The keydown event is preferred over keyup as the keyup is too late to block form submit. Historically there was also the keypress, but this is deprecated, as is the KeyboardEvent.keyCode. You should use KeyboardEvent.key instead which returns the name of the key being pressed. When Enter is checked, then this would check 13 (normal enter) as well as 108 (numpad enter).

Note that $(window) as suggested in some other answers instead of $(document) doesn't work for keydown/keyup in IE<=8, so that's not a good choice if you're like to cover those poor users as well.

Allow enter key on textareas only

If you have a <textarea> in your form (which of course should accept the Enter key), then add the keydown handler to every individual input element which isn't a <textarea>.

<input ... onkeydown="return event.key != 'Enter';">
<select ... onkeydown="return event.key != 'Enter';">
...

To reduce boilerplate, this is better to be done with jQuery:

$(document).on("keydown", ":input:not(textarea)", function(event) {
    return event.key != "Enter";
});

If you have other event handler functions attached on those input elements, which you'd also like to invoke on enter key for some reason, then only prevent event's default behavior instead of returning false, so it can properly propagate to other handlers.

$(document).on("keydown", ":input:not(textarea)", function(event) {
    if (event.key == "Enter") {
        event.preventDefault();
    }
});

Allow enter key on textareas and submit buttons only

If you'd like to allow enter key on submit buttons <input|button type="submit"> too, then you can always refine the selector as below.

$(document).on("keydown", ":input:not(textarea):not(:submit)", function(event) {
    // ...
});

Note that input[type=text] as suggested in some other answers doesn't cover those HTML5 non-text inputs, so that's not a good selector.

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

How can I print the contents of an array horizontally?

int[] n=new int[5];

for (int i = 0; i < 5; i++)
{
    n[i] = i + 100;
}

foreach (int j in n)
{
    int i = j - 100;

    Console.WriteLine("Element [{0}]={1}", i, j);
    i++;
}

TypeError: 'list' object is not callable in python

You have already assigned a value to list.
So, you cannot use the list() when it’s a variable.
Restart the shell or IDE, by pressing Ctrl+F6 on your computer.
Hope this works too.

Get a UTC timestamp

"... that are independent of their timezone"

var timezone =  d.getTimezoneOffset() // difference in minutes from GMT

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Continuous Integration: The practice of merging the development work with the main branch constantly so that the code has been tested as often as possible to catch issues early.

Continuous Delivery: Continuous delivery of code to an environment once the code is ready to ship. This could be staging or production. The idea is the product is delivered to a user base, which can be QA's or customers for review and inspection.

Unit test during the Continuous Integration phase can not catch all the bugs and business logic, particularly design issues that is why we need QA, or staging environment for testing.

Continuous Deployment: The deployment or release of code as soon as it's ready. Continuous Deployment requires Continuous Integration and Continuous Delivery otherwise the code quality won't be guarantee in a release.

Continuous Deployment ~~ Continuous Integration + Continuous Delivery

Log4net rolling daily filename with date in the file name

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
  <file value="logs\" />
  <datePattern value="dd.MM.yyyy'.log'" />
  <staticLogFileName value="false" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="5MB" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

How do I create a datetime in Python from milliseconds?

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

How to run a function when the page is loaded?

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

The problem was quite stupid for me.

I used to get the same issue on AWS EC2 Ubuntu machine (MariaDB is installed locally for the time being), so I tried to make SSH tunneling, and had the same issue. So I tried to ssh tunnel over terminal:

ssh -L13306:127.0.0.1:3306 [email protected] -i my/private/key.pem

And it told me this:

Please login as the user "ubuntu" rather than the user "root".

I changed ssh user from root to ubuntu, just like my ssh config, and it connected just fine.

So check your SSH connecting user.

I oversaw this, so this too half an hour of my time, so I hope this will be useful for you.

Setting the selected value on a Django forms.ChoiceField

This doesn't touch on the immediate question at hand, but this Q/A comes up for searches related to trying to assign the selected value to a ChoiceField.

If you have already called super().__init__ in your Form class, you should update the form.initial dictionary, not the field.initial property. If you study form.initial (e.g. print self.initial after the call to super().__init__), it will contain values for all the fields. Having a value of None in that dict will override the field.initial value.

e.g.

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        # assign a (computed, I assume) default value to the choice field
        self.initial['choices_field_name'] = 'default value'
        # you should NOT do this:
        self.fields['choices_field_name'].initial = 'default value'

Force LF eol in git repo and working copy

Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)

Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....

However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.

As you're partially working on Linux and Windows, make sure core.eol is set to native and core.autocrlf is set to true.

Then, replace the content of your .gitattributes file with the following

* text=auto

This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.

However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.

Provided you work on a C based image processing project, replace the content of your .gitattributes file with the following

* text=auto
*.txt text
*.c text
*.h text
*.jpg binary

This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.

In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.

As a real world example, you can also peek at this commit where those changes to a .gitattributes file are demonstrated.

UPDATE to the answer considering the following comment

I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory

Makes sense. Thanks for the clarification. In this specific context, the .gitattributes file by itself won't be enough.

Run the following commands against your repository

$ git config core.eol lf
$ git config core.autocrlf input

As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol will make sure text files bear LF line endings on checkouts. core.autocrlf will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.

Optionally, you can help Git distinguish what is a text file by creating a .gitattributes file containing something similar to the following:

# Autodetect text files
* text=auto

# ...Unless the name matches the following
# overriding patterns

# Definitively text files 
*.txt text
*.c text
*.h text

# Ensure those won't be messed up with
*.jpg binary
*.data binary

If you decided to create a .gitattributes file, commit it.

Lastly, ensure git status mentions "nothing to commit (working directory clean)", then perform the following operation

$ git checkout-index --force --all

This will recreate your files in your working directory, taking into account your config changes and the .gitattributes file and replacing any potential overlooked CRLF in your text files.

Once this is done, every text file in your working directory WILL bear LF line endings and git status should still consider the workdir as clean.

python: [Errno 10054] An existing connection was forcibly closed by the remote host

there are many causes such as

  • The network link between server and client may be temporarily going down.
  • running out of system resources.
  • sending malformed data.

To examine the problem in detail, you can use Wireshark.

or you can just re-request or re-connect again.

Eclipse IDE: How to zoom in on text?

The googlecode fontsupdate does not work anymore unfortunately. You can however just download the code from github:

https://github.com/gkorland/Eclipse-Fonts

Just download it as .zip, and add it in eclipse:

Adding a local plugin

Then you have the familiar buttons again!

Convert string in base64 to image and save on filesystem in Python

Starting with

img_data = b'iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQVR42uzBAQEAAACAkP6v7ggK\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAA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nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAIcAeHkAAeLqlDIAAAAASUVORK5CYII='

Decoded the data using the base64 codec, and then write it to the filesystem.

# In Python 2.7
fh = open("imageToSave.png", "wb")
fh.write(img_data.decode('base64'))
fh.close()

# or, more concisely using with statement
with open("imageToSave.png", "wb") as fh:
    fh.write(img_data.decode('base64'))

Modernizing this example to Python 3, which removed arbitrary codec support from string/bytes .encode() and .decode() functions:

# For both Python 2.7 and Python 3.x
import base64
with open("imageToSave.png", "wb") as fh:
    fh.write(base64.decodebytes(img_data))

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

No assembly found containing an OwinStartupAttribute Error

Check you have the correct startup project selected. I had a web api project as startup. That generated this error.

Java: Get first item from a collection

In java 8:

Optional<String> firstElement = collection.stream().findFirst();

For older versions of java, there is a getFirst method in Guava Iterables:

Iterables.getFirst(iterable, defaultValue)

Launching Spring application Address already in use

I was looking for a solution for Windows but didn't found any. Finally, figured out that that there is a dangling java application using the port. Maybe it's the earlier instance of the spring application and ended the process.

I used tcpview from Microsoft. It shows services/applications using which port on your computer.

enter image description here

You can end the process. And Done!

Plot two graphs in same plot in R

You can use points for the overplot, that is.

plot(x1, y1,col='red')

points(x2,y2,col='blue')

How to clear text area with a button in html using javascript?

Your Html

<input type="button" value="Clear" onclick="clearContent()"> 
<textarea id='output' rows=20 cols=90></textarea>

Your Javascript

function clearContent()
{
    document.getElementById("output").value='';
}

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Use an overload of rfind which has the pos parameter:

std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) {
  // s starts with prefix
}

Who needs anything else? Pure STL!

Many have misread this to mean "search backwards through the whole string looking for the prefix". That would give the wrong result (e.g. string("tititito").rfind("titi") returns 2 so when compared against == 0 would return false) and it would be inefficient (looking through the whole string instead of just the start). But it does not do that because it passes the pos parameter as 0, which limits the search to only match at that position or earlier. For example:

std::string test = "0123123";
size_t match1 = test.rfind("123");    // returns 4 (rightmost match)
size_t match2 = test.rfind("123", 2); // returns 1 (skipped over later match)
size_t match3 = test.rfind("123", 0); // returns std::string::npos (i.e. not found)

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

I believe I have encountered the same quandary. I started encountering the problem when I changed to:

</system.web>
<httpRuntime targetFramework="4.5"/>

Which gives the error message you describe above.

adding:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

Solves the issue, but then it makes your validation controls/scripts throw Javascript runtime errors. If you change to:

</system.web>
<httpRuntime targetFramework="4.0"/>

You should be OK, but you’ll have to make sure the rest of your code does/ behaves as desired. You might also have to forgo some new features only available in 4.5 onward.

P.S. It is highly recommended that you read the following before implementing this solution. Especially, if you use Async functionality:

https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/

UPDATE April 2017: After some some experimentation and testing I have come up with a combination that works:

<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<httpRuntime targetFramework="4.5.1" />

with:

jQuery version 1.11.3

Creating a zero-filled pandas data frame

It's best to do this with numpy in my opinion

import numpy as np
import pandas as pd
d = pd.DataFrame(np.zeros((N_rows, N_cols)))

How to use null in switch

You can't. You can use primitives (int, char, short, byte) and String (Strings in java 7 only) in switch. primitives can't be null.
Check i in separate condition before switch.

Which ChromeDriver version is compatible with which Chrome Browser version?

At the time of writing this I have discovered that chromedriver 2.46 or 2.36 works well with Chrome 75.0.3770.100

Documentation here: http://chromedriver.chromium.org/downloads states align driver and browser alike but I found I had issues even with the most up-to-date driver when using Chrome 75

I am running Selenium 2 on Windows 10 Machine.

Get single listView SelectedItem

This works for single as well as multi selection list:

foreach (ListViewItem item in listView1.SelectedItems)
{
    int index = ListViewItem.Index;
    //index is now zero based index of selected item
}

Read .mat files in Python

Having MATLAB 2014b or newer installed, the MATLAB engine for Python could be used:

import matlab.engine
eng = matlab.engine.start_matlab()
content = eng.load("example.mat", nargout=1)

Javascript call() & apply() vs bind()?

JavaScript Call()

const person = {
    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.call(anotherPerson,1,2)

JavaScript apply()

    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.apply(anotherPerson,[1,2])

**call and apply function are difference call take separate argument but apply take array like:[1,2,3] **

JavaScript bind()

    name: "Lokamn",
    dob: 12,
    anotherPerson: {
        name: "Pappu",
        dob: 12,
        print2: function () {
            console.log(this)
        }
    }
}

var bindFunction = person.anotherPerson.print2.bind(person)
 bindFunction()

How get value from URL

Website URL:

http://www.example.com/?id=2

Code:

$id = intval($_GET['id']);
$results = mysql_query("SELECT * FROM next WHERE id=$id");    
while ($row = mysql_fetch_array($results))     
{       
    $url = $row['url'];
    echo $url; //Outputs: 2
}

get unique machine id

There are two ways possible to this that I know:

  1. Get the Processor id of the system:

    public string getCPUId()
    {
        string cpuInfo = string.Empty;
        ManagementClass mc = new ManagementClass("win32_processor");
        ManagementObjectCollection moc = mc.GetInstances();
    
        foreach (ManagementObject mo in moc)
        {
            if (cpuInfo == "")
            {
                //Get only the first CPU's ID
                cpuInfo = mo.Properties["processorID"].Value.ToString();
                break;
            }
        }
        return cpuInfo;
    }
    
  2. Get UUID of the system:

    public string getUUID()
    {
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "CMD.exe";
            startInfo.Arguments = "/C wmic csproduct get UUID";
            process.StartInfo = startInfo;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            process.WaitForExit();
            string output = process.StandardOutput.ReadToEnd();
            return output;
    }
    

AngularJS view not updating on model change

Just use $interval

Here is your code modified. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope, $interval) {
   $scope.testValue = 0;

    $interval(function() {
        $scope.testValue++;
    }, 500);
});

Check if two unordered lists are equal

You want to see if they contain the same elements, but don't care about the order.

You can use a set:

>>> set(['one', 'two', 'three']) == set(['two', 'one', 'three'])
True

But the set object itself will only contain one instance of each unique value, and will not preserve order.

>>> set(['one', 'one', 'one']) == set(['one'])
True

So, if tracking duplicates/length is important, you probably want to also check the length:

def are_eq(a, b):
    return set(a) == set(b) and len(a) == len(b)

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

I think your problem is that you assume that the bytes that represent the utf8 string will result in the same string when interpreted as something else (iso-8859-1). And that is simply just not the case. I recommend that you read this excellent article by Joel spolsky.

Proper way to renew distribution certificate for iOS

This was a really a helpful thread, I followed the same steps as @junjie mentioned but for me something weird happened, the below are the steps I did.

  1. Went to developer portal and revoked the certificate which was about to expire.
  2. Went to XCode6.4 and in the Account settings, the certificate still showed valid, I went crazy.
  3. Then I opened XCode7, there the certificate was shown with "Reset" button instead of create and I hit the reset button and later in the portal I was able to see an extended certificate present. This is what Apple says about Reset button

If Xcode detects an issue with a signing identity, it displays an appropriate action in Accounts preferences. If Xcode displays a Create button, the signing identity doesn’t exist in Member Center or on your Mac. If Xcode displays a Reset button, the signing identity is not usable on your Mac—for example, it is missing the private key. If you click the Reset button, Xcode revokes and requests the corresponding certificate.

  1. I tried creating an Appstore ipa with that, just to test and it worked fine so I am saved, but still not sure what has happened. May be I had multiple accounts configured in my Mac, dont know.

How do I detect if software keyboard is visible on Android Device or not?

Here is a workaround to know if softkeyboard is visible.

  1. Check for running services on the system using ActivityManager.getRunningServices(max_count_of_services);
  2. From the returned ActivityManager.RunningServiceInfo instances, check clientCount value for soft keyboard service.
  3. The aforementioned clientCount will be incremented every time, the soft keyboard is shown. For example, if clientCount was initially 1, it would be 2 when the keyboard is shown.
  4. On keyboard dismissal, clientCount is decremented. In this case, it resets to 1.

Some of the popular keyboards have certain keywords in their classNames:

  1. Google AOSP = IME
  2. Swype = IME
  3. Swiftkey = KeyboardService
  4. Fleksy = keyboard
  5. Adaptxt = IME (KPTAdaptxtIME)
  6. Smart = Keyboard (SmartKeyboard)

From ActivityManager.RunningServiceInfo, check for the above patterns in ClassNames. Also, ActivityManager.RunningServiceInfo's clientPackage=android, indicating that the keyboard is bound to system.

The above mentioned information could be combined for a strict way to find out if soft keyboard is visible.

Saving and Reading Bitmaps/Images from Internal memory in Android

/**
 * Created by Ilya Gazman on 3/6/2016.
 */
public class ImageSaver {

    private String directoryName = "images";
    private String fileName = "image.png";
    private Context context;
    private boolean external;

    public ImageSaver(Context context) {
        this.context = context;
    }

    public ImageSaver setFileName(String fileName) {
        this.fileName = fileName;
        return this;
    }

    public ImageSaver setExternal(boolean external) {
        this.external = external;
        return this;
    }

    public ImageSaver setDirectoryName(String directoryName) {
        this.directoryName = directoryName;
        return this;
    }

    public void save(Bitmap bitmapImage) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(createFile());
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @NonNull
    private File createFile() {
        File directory;
        if(external){
            directory = getAlbumStorageDir(directoryName);
        }
        else {
            directory = context.getDir(directoryName, Context.MODE_PRIVATE);
        }
        if(!directory.exists() && !directory.mkdirs()){
            Log.e("ImageSaver","Error creating directory " + directory);
        }

        return new File(directory, fileName);
    }

    private File getAlbumStorageDir(String albumName) {
        return new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), albumName);
    }

    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

    public Bitmap load() {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(createFile());
            return BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

Usage

  • To save:

    new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            save(bitmap);
    
  • To load:

    Bitmap bitmap = new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            load();
    

Edit:

Added ImageSaver.setExternal(boolean) to support saving to external storage based on googles example.

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

how to generate public key from windows command prompt

ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key

Convert Rtf to HTML

You can try to upload it to google docs, and download it as HTML.

Cygwin Make bash command not found

While instaling (updating) check 'Devel' to 'Install', it will install a lot of MB but helps. I don't have time to check which exacly I (we) need.

CYGWIN INSTALL STEP

Store a closure as a variable in Swift

I've provide an example not sure if this is what you're after.

var completionHandler: (_ value: Float) -> ()

func printFloat(value: Float) {
    print(value)
}

completionHandler = printFloat

completionHandler(5)

It simply prints 5 using the completionHandler variable declared.

What is the best way to implement a "timer"?

Reference ServiceBase to your class and put the below code in the OnStartevent:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

StartSendingMails = function name you want to run in the application.

 protected override void OnStart(string[] args)
        {
            // It tells in what interval the service will run each time.
            Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
            base.OnStart(args);
            TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
            serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
        }

Debugging in Maven?

If you are using Netbeans, there is a nice shortcut to this. Just define a goal exec:java and add the property jpda.listen=maven Netbeans screenshot

Tested on Netbeans 7.3

How to export JavaScript array info to csv (on client side)?

You can use the below piece of code to export array to CSV file using Javascript.

This handles special characters part as well

var arrayContent = [["Séjour 1, é,í,ú,ü,u"],["Séjour 2, é,í,ú,ü,u"]];
var csvContent = arrayContent.join("\n");
var link = window.document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent));
link.setAttribute("download", "upload_data.csv");
link.click(); 

Here is the link to working jsfiddle

Nuget connection attempt failed "Unable to load the service index for source"

In my case it is happened because I don’t have internet connection and it is trying to scaffolding

How to drop all tables in a SQL Server database?

Spot on!!

You can use below query to remove all the tables from database

EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

Happy coding !

Failed to locate the winutils binary in the hadoop binary path

Simple Solution: Download it from here and add to $HADOOP_HOME/bin

(Source)

IMPORTANT UPDATE:

For hadoop-2.6.0 you can download binaries from Titus Barik blog >>.

I have not only needed to point HADOOP_HOME to extracted directory [path], but also provide system property -Djava.library.path=[path]\bin to load native libs (dll).

CRON job to run on the last day of the month

What about this?

edit user's .bashprofile adding:

export LAST_DAY_OF_MONTH=$(cal | awk '!/^$/{ print $NF }' | tail -1)

Then add this entry to crontab:

mm hh * * 1-7 [[ $(date +'%d') -eq $LAST_DAY_OF_MONTH ]] && /absolutepath/myscript.sh

get name of a variable or parameter

Alternatively,

1) Without touching System.Reflection namespace,

GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}

2) The below one can be faster though (from my tests)

GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

You can also extend this for properties of objects (may be with extension methods):

new { myClass.MyProperty1 }.GETNAME();

You can cache property values to improve performance further as property names don't change during runtime.

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

Using ListView : How to add a header view?

I found out that inflating the header view as:

inflater.inflate(R.layout.listheader, container, false);

being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

So, my problem was solved solved by inflating the header view passing the list as container:

ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);

then

list.addHeaderView(headerView, null, false);

Kinda late answer but I hope this can help someone

Django Rest Framework -- no module named rest_framework

rest_framework module

Try pressing the icon given if you are getting the following error:

"ModuleNotFoundError: No module named 'rest_framework'"

It will ask you to import the given package, that is rest_framework and run the code again.

This worked for me and trying to solve that error for a couple of days.

How do I create a Bash alias?

On OS X you want to use ~/.bash_profile. This is because by default Terminal.app opens a login shell for each new window.

See more about the different configuration files and when they are used here: What's the difference between .bashrc, .bash_profile, and .environment?

and in relation to OSX here: About .bash_profile, .bashrc, and where should alias be written in?

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

How to get post slug from post in WordPress?

use global variable $post

<?php 
    global $post;
    $post_slug=$post->post_name;
?>

Negative regex for Perl string pattern match

Your regex does not work because [] defines a character class, but what you want is a lookahead:

(?=) - Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) - Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) - Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) - Negative look behind assertion (?<!foo)bar matches bar when NOT preceded by foo
(?>) - Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) - Conditional subpatterns
(?(3)foo|fu)bar - Matches foo if 3rd subpattern has matched, fu if not
(?#) - Comment (?# Pattern does x y or z)

So try: (?!bush)

How to set environment variables in PyCharm?

You can set environmental variables in Pycharm's run configurations menu.

  1. Open the Run Configuration selector in the top-right and cick Edit Configurations...

    Edit Configurations...

  2. Find Environmental variables and click ...

    Environmental variables

  3. Add or change variables, then click OK

    Editing environmental variables

You can access your environmental variables with os.environ

import os
print(os.environ['SOME_VAR'])

How to check if all of the following items are in a list?

What if your lists contain duplicates like this:

v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']

Sets do not contain duplicates. So, the following line returns True.

set(v2).issubset(v1)

To count for duplicates, you can use the code:

v1 = sorted(v1)
v2 = sorted(v2)


def is_subseq(v2, v1):
    """Check whether v2 is a subsequence of v1."""
    it = iter(v1)
    return all(c in it for c in v2) 

So, the following line returns False.

is_subseq(v2, v1)

How to change text and background color?

Colors are bit-encoded. If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output.click this icon of the console and go to properties and change color.

The second way is calling the system colors.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    //Changing Font Colors of the System

    system("Color 7C");
    cout << "\t\t\t ****CEB Electricity Bill Calculator****\t\t\t " << endl;
    cout << "\t\t\t  ***                MENU           ***\t\t\t  " <<endl;

    return 0;

}

Delete specific line number(s) from a text file using sed?

This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;

grep -nh error logfile | cut -d: -f1 | deletelines logfile

(where deletelines is the utility you are imagining you need) is the same as

grep -v error logfile

Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed.

sed 's%$%d%' linenumbers

This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d appended after each. This is a valid sed script, which we can save to a file, or (on some platforms) pipe to another sed instance:

sed 's%$%d%' linenumbers | sed -f - logfile

On some platforms, sed -f does not understand the option argument - to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin or /proc/$pid/fd/1 if your OS (or shell) has that.

As always, you can add -i before the -f option to have sed edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i as well; a common idiom is to supply an empty argument; -i ''.

Java Comparator class to sort arrays

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

HTML input time in 24 format

In my case, it is taking time in AM and PM but sending data in 00-24 hours format to the server on form submit. and when use that DB data in its value then it will automatically select the appropriate AM or PM to edit form value.

Load local javascript file in chrome for testing?

You can use a light weight webserver to serve the file.
For example,
1. install Node
2. install the "http-server" (or similar) package
3. Run the http-server package ( "http-server -c-1") from the folder where the script file is located
4. Load the script from chrome console (run the following script on chrome console

var ele = document.createElement("script");
var scriptPath = "http://localhost:8080/{scriptfilename}.js" //verify the script path
ele.setAttribute("src",scriptPath);
document.head.appendChild(ele)
  1. The script is now loaded the browser. You can test it from console.

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

How to query all the GraphQL type fields without writing a long query?

I guess the only way to do this is by utilizing reusable fragments:

fragment UserFragment on Users {
    id
    username
    count
} 

FetchUsers {
    users(id: "2") {
        ...UserFragment
    }
}

Is it possible to auto-format your code in Dreamweaver?

Following works perfectly for me: -*click on COMMAND and click on APPLY SOURCE FORMATTING - *And click on Clean Up HTML

Thank you PEKA

What is the difference between JSF, Servlet and JSP?

Java Server Pages (JSP) is java technology which enables Web developers and designers to rapidly develop and easily maintain, information-rich, dynamic Web pages that leverage existing business systems. JSP technology separates the user interface from content generation, enabling designers to change the overall page layout without altering the underlying dynamic content.

Facelets is the first non JSP page declaration language designed for JSF (Java Server Faces) which provided a simpler and more powerful programming model to JSF developers as compare to JSP. It resolves different issues occurs in JSP for web applications development.

Here is a table that compares the features of scriplets and facelets:

enter image description here Source

How to make an introduction page with Doxygen

Following syntax may help for adding a main page and related subpages for doxygen:

/*! \mainpage Drawing Shapes
 *
 * This project helps user to draw shapes.
 * Currently two types of shapes can be drawn:
 * - \subpage drawingRectanglePage "How to draw rectangle?"
 *
 * - \subpage drawingCirclePage "How to draw circle?"
 *
 */ 

/*! \page drawingRectanglePage How to draw rectangle?
 *
 * Lorem ipsum dolor sit amet
 *
 */

/*! \page drawingCirclePage How to draw circle?
 *
 * This page is about how to draw a circle.
 * Following sections describe circle:
 * - \ref groupCircleDefinition "Definition of Circle"
 * - \ref groupCircleClass "Circle Class"
 */

Creating groups as following also help for designing pages:

/** \defgroup groupCircleDefinition Circle Definition
 * A circle is a simple shape in Euclidean geometry.
 * It is the set of all points in a plane that are at a given distance from a given point, the centre;
 * equivalently it is the curve traced out by a point that moves so that its distance from a given point is constant.
 * The distance between any of the points and the centre is called the radius.
 */

An example can be found here

Run Button is Disabled in Android Studio

just to go File -> Sync Project with Gradle files then it solves problem.

Constructor of an abstract class in C#

an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.

How to kill zombie process

I tried

kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')

and it works for me.

How to implement debounce in Vue2?

Although pretty much all answers here are already correct, if anyone is in search of a quick solution I have a directive for this. https://www.npmjs.com/package/vue-lazy-input

It applies to @input and v-model, supports custom components and DOM elements, debounce and throttle.

_x000D_
_x000D_
Vue.use(VueLazyInput)_x000D_
  new Vue({_x000D_
    el: '#app', _x000D_
    data() {_x000D_
      return {_x000D_
        val: 42_x000D_
      }_x000D_
    },_x000D_
    methods:{_x000D_
      onLazyInput(e){_x000D_
        console.log(e.target.value)_x000D_
      }_x000D_
    }_x000D_
  })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<script src="https://unpkg.com/lodash/lodash.min.js"></script><!-- dependency -->_x000D_
<script src="https://unpkg.com/vue-lazy-input@latest"></script> _x000D_
_x000D_
<div id="app">_x000D_
  <input type="range" v-model="val" @input="onLazyInput" v-lazy-input /> {{val}}_x000D_
</div>
_x000D_
_x000D_
_x000D_

Run a command shell in jenkins

As far as I know, Windows will not support shell scripts out of the box. You can install Cygwin or Git for Windows, go to Manage Jenkins > Configure System Shell and point it to the location of sh.exe file found in their installation. For example:

C:\Program Files\Git\bin\sh.exe

There is another option I've discovered. This one is better because it allowed me to use shell in pipeline scripts with simple sh "something".

Add the folder to system PATH. Right click on Computer, click properties > advanced system settings > environmental variables, add C:\Program Files\Git\bin\ to your system Path property.

IMPORTANT note: for some reason I had to add it to the system wide Path, adding to user Path didn't work, even though Jenkins was running on this user.

An important note (thanks bugfixr!):

This works. It should be noted that you will need to restart Jenkins in order for it to pick up the new PATH variable. I just went to my services and restated it from there.

Disclaimer: the names may differ slightly as I'm not using English Windows.

Extracting extension from filename in Python

You can find some great stuff in pathlib module (available in python 3.x).

import pathlib
x = pathlib.PurePosixPath("C:\\Path\\To\\File\\myfile.txt").suffix
print(x)

# Output 
'.txt'

Using a cursor with dynamic SQL in a stored procedure

This code is a very good example for a dynamic column with a cursor, since you cannot use '+' in @STATEMENT:

ALTER PROCEDURE dbo.spTEST
AS
    SET NOCOUNT ON
    DECLARE @query NVARCHAR(4000) = N'' --DATA FILTER
    DECLARE @inputList NVARCHAR(4000) = ''
    DECLARE @field sysname = '' --COLUMN NAME
    DECLARE @my_cur CURSOR
    EXECUTE SP_EXECUTESQL
        N'SET @my_cur = CURSOR FAST_FORWARD FOR
            SELECT
                CASE @field
                    WHEN ''fn'' then fn
                    WHEN ''n_family_name'' then n_family_name
                END
            FROM
                dbo.vCard
            WHERE
                CASE @field
                    WHEN ''fn'' then fn
                    WHEN ''n_family_name'' then n_family_name
                END
                LIKE ''%''+@query+''%'';
            OPEN @my_cur;',
        N'@field sysname, @query NVARCHAR(4000), @my_cur CURSOR OUTPUT',
        @field = @field,
        @query = @query,
        @my_cur = @my_cur OUTPUT
    FETCH NEXT FROM @my_cur INTO @inputList
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @inputList
        FETCH NEXT FROM @my_cur INTO @inputList
    END
    RETURN

Return JSON for ResponseEntity<String>

public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
    JSONObject resp = new JSONObject();
    resp.put("status", 0);
    resp.put("id", id);

    return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}

How can I insert new line/carriage returns into an element.textContent?

I ran into this a while ago. I found a good solution was to use the ASCII representation of carriage returns (CODE 13). JavaScript has a handy feature called String.fromCharCode() which generates the string version of an ASCII code, or multiple codes separate by a comma. In my case, I needed to generate a CSV file from a long string and write it to a text area. I needed to be able to cut the text from the text area and save it into notepad. When I tried to use the <br /> method it would not preserve the carriage returns, however, using the fromCharCode method it does retain the returns. See my code below:

h1.innerHTML += "...I would like to insert a carriage return here..." + String.fromCharCode(13);
h1.innerHTML += "Ant the other line here..." + String.fromCharCode(13);
h1.innerHTML += "And so on..." + String.fromCharCode(13);
h1.innerHTML += "This prints hello: " + String.fromCharCode(72,69,76,76,79);

See here for more details on this method: w3Schools-fromCharCode()

See here for ASCII codes: ASCII Codes

Cannot open new Jupyter Notebook [Permission Denied]

In windows, I copied, what I think is a snapshot:

.~SomeAmazingNotebook.ipynb

renamed it:

SomeAmazingNotebook.ipynb

and could open it.

How do I verify/check/test/validate my SSH passphrase?

If your passphrase is to unlock your SSH key and you don't have ssh-agent, but do have sshd (the SSH daemon) installed on your machine, do:

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys;
ssh localhost -i ~/.ssh/id_rsa

Where ~/.ssh/id_rsa.pub is the public key, and ~/.ssh/id_rsa is the private key.

How do I make a JAR from a .java file?

Open a command prompt.

Go to the directory where you have your .java files

Create a directory build

Run java compilation from the command line

javac -d ./build *.java

if there are no errors, in the build directory you should have your class tree

move to the build directory and do a

jar cvf YourJar.jar *

For adding manifest check jar command line switches

What's the best way to calculate the size of a directory in .NET?

I do not believe there is a Win32 API to calculate the space consumed by a directory, although I stand to be corrected on this. If there were then I would assume Explorer would use it. If you get the Properties of a large directory in Explorer, the time it takes to give you the folder size is proportional to the number of files/sub-directories it contains.

Your routine seems fairly neat & simple. Bear in mind that you are calculating the sum of the file lengths, not the actual space consumed on the disk. Space consumed by wasted space at the end of clusters, file streams etc, are being ignored.

How to remove the arrow from a select element in Firefox

Important Update:

As of Firefox V35 the appearance property now works !!

From firefox's official release notes on V35:

Using -moz-appearance with the none value on a combobox now remove the dropdown button (bug 649849).

So now in order to hide the default arrow - it's as easy as adding the following rules on our select element:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

DEMO

_x000D_
_x000D_
select {_x000D_
  margin: 50px;_x000D_
  border: 1px solid #111;_x000D_
  background: transparent;_x000D_
  width: 150px;_x000D_
  padding: 5px;_x000D_
  font-size: 16px;_x000D_
  border: 1px solid #ccc;_x000D_
  height: 34px;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
}
_x000D_
<select>_x000D_
  <option>Apples</option>_x000D_
  <option selected>Pineapples</option>_x000D_
  <option>Chocklate</option>_x000D_
  <option>Pancakes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

You can also add

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
/> 

under META-INF/context.xml file (This will be only at application level).

How do you change the launcher logo of an app in Android Studio?

Here are my steps for the task:

  1. Create PNG image file of size 512x512 pixels
  2. In Android Studio, in project view, highlight a mipmap directory
  3. In menu, go to File>New>Image Asset
  4. Click Image Button in Asset type button row
  5. Click on 3 Dot Box at right of Path Box.
  6. Drag image to source asset box
  7. Click Next (Note: Existing launcher files will be overwritten)
  8. Click Finish

OSError - Errno 13 Permission denied

You need to change the directory permission so that web server process can change the directory.

  • To change ownership of the directory, use chown:

    chown -R user-id:group-id /path/to/the/directory
    
  • To see which user own the web server process (change httpd accordingly):

    ps aux | grep httpd | grep -v grep
    

    OR

    ps -efl | grep httpd | grep -v grep
    

Why call super() in a constructor?

It simply calls the default constructor of the superclass.