Programs & Examples On #Icarus

Hibernate: Automatically creating/updating the db tables based on entity classes

In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.

For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

How to get the separate digits of an int number?

// could be any num this is a randomly generated one
int num = (int) (Math.random() * 1000);

// this will return each number to a int variable
int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;

// you could continue this pattern for 4,5,6 digit numbers
// dont need to print you could then use the new int values man other ways
System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

Beyond the problematic use of async as pointed out by @Servy, the other issue is that you need to explicitly get T from Task<T> by calling Task.Result. Note that the Result property will block async code, and should be used carefully.

Try:

private async void button1_Click(object sender, EventArgs e)
{
    var s = await methodAsync();
    MessageBox.Show(s.Result);
}

Creating a Plot Window of a Particular Size

As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:

If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.

add an element to int [] array in java

public int[] return_Array() {

int[] a =new int[10];   
int b = 25;
for(int i=0; i<10; i++) {               
    a[i] = b * i;
    }
return a;

}

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Install msi with msiexec in a Specific Directory

Actually, both INSTALLPATH/TARGETDIR are correct. It depends on how MSI processes this.

I create a MSG using wixToolSet. In WXS file, there is "Directory" Node, which root dir maybe like the following:

<Directory Id="**TARGETDIR**" Name="SourceDir">;

As you can see: Id is which you should use.

How to Reload ReCaptcha using JavaScript?

Try this

<script type="text/javascript" src="//www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
          function showRecaptcha() {
            Recaptcha.create("YOURPUBLICKEY", 'captchadiv', {
              theme: 'red',
              callback: Recaptcha.focus_response_field
            });
          }
 </script>

<div id="captchadiv"></div>

If you calll showRecaptcha the captchadiv will be populated with a new recaptcha instance.

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

How can I multiply all items in a list together with Python?

I would use the numpy.prod to perform the task. See below.

import numpy as np
mylist = [1, 2, 3, 4, 5, 6] 
result = np.prod(np.array(mylist))  

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

Increase max_execution_time in PHP?

For increasing execution time and file size, you need to mention below values in your .htaccess file. It will work.

php_value upload_max_filesize 80M
php_value post_max_size 80M
php_value max_input_time 18000
php_value max_execution_time 18000

Python group by

Python's built-in itertools module actually has a groupby function , but for that the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:

from operator import itemgetter
sortkeyfn = itemgetter(1)
input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), 
 ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), 
 ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')] 
input.sort(key=sortkeyfn)

Now input looks like:

[('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'),
 ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH'), ('11013331', 'KAT'),
 ('9843236', 'KAT'), ('9085267', 'NOT'), ('11788544', 'NOT')]

groupby returns a sequence of 2-tuples, of the form (key, values_iterator). What we want is to turn this into a list of dicts where the 'type' is the key, and 'items' is a list of the 0'th elements of the tuples returned by the values_iterator. Like this:

from itertools import groupby
result = []
for key,valuesiter in groupby(input, key=sortkeyfn):
    result.append(dict(type=key, items=list(v[0] for v in valuesiter)))

Now result contains your desired dict, as stated in your question.

You might consider, though, just making a single dict out of this, keyed by type, and each value containing the list of values. In your current form, to find the values for a particular type, you'll have to iterate over the list to find the dict containing the matching 'type' key, and then get the 'items' element from it. If you use a single dict instead of a list of 1-item dicts, you can find the items for a particular type with a single keyed lookup into the master dict. Using groupby, this would look like:

result = {}
for key,valuesiter in groupby(input, key=sortkeyfn):
    result[key] = list(v[0] for v in valuesiter)

result now contains this dict (this is similar to the intermediate res defaultdict in @KennyTM's answer):

{'NOT': ['9085267', '11788544'], 
 'ETH': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 
 'KAT': ['11013331', '9843236']}

(If you want to reduce this to a one-liner, you can:

result = dict((key,list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn))

or using the newfangled dict-comprehension form:

result = {key:list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn)}

Is it possible to create static classes in PHP (like in C#)?

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

Getting unix timestamp from Date()

I dont know if you want to achieve that in js or java, in js the simplest way to get the unix timestampt (this is time in seconds from 1/1/1970) it's as follows:

var myDate = new Date();
console.log(+myDate); // +myDateObject give you the unix from that date

Sorting by date & time in descending order?

If you mean you want to sort by date first then by names

SELECT id, name, form_id, DATE(updated_at) as date
  FROM wp_frm_items
  WHERE user_id = 11 && form_id=9
  ORDER BY updated_at DESC,name ASC

This will sort the records by date first, then by names

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];
data.push(postdata);

console.log(data);

Could not connect to React Native development server on Android

I met this question too in native and react-native pro, my solution was:

  1. open npm server with npm start
  2. run native project with Android Studio
  3. transmission network request with adb reverse tcp:8081 tcp:8081
  4. when you need to reload the page, just input: adb shell input keyevent 82

just keep it in order.

P.S. if you ran a fail project, just run adb kill-server

unable to install pg gem

You just go to here to see if your pg version support Win32 platform, then use this command to install:

gem install pg -v 0.14.1 --platform=x86-mingw32

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

test if event handler is bound to an element in jQuery

Killing off the binding when it does not exist yet is not the best solution but seems effective enough! The second time you ‘click’ you can know with certainty that it will not create a duplicate binding.

I therefore use die() or unbind() like this:

$("#someid").die("click").live("click",function(){...

or

$("#someid").unbind("click").bind("click",function(){...

or in recent jQuery versions:

$("#someid").off("click").on("click",function(){...

How to add 10 days to current time in Rails

days, years, etc., are part of Active Support, So this won't work in irb, but it should work in rails console.

What is the difference between dim and set in vba

Dim simply declares the value and the type.

Set assigns a value to the variable.

Is it safe to expose Firebase apiKey to the public?

I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below

  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }
    }
  }
}

No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains. One can read more about it on Firebase Security rules

Angularjs autocomplete from $http

Use angular-ui-bootstrap's typehead.

It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.

(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)

Passing a Bundle on startActivity()?

You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);

Now in your NewActivity, you can get this bundle and retrive your value.

Bundle bundle = getArguments();
String value = bundle.getString(key);

You can also pass data through the intent. In your current activity, set intent like this,

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

Now in your NewActivity, you can get that value from intent like this,

String value = getIntent().getExtras().getString(key);

Inline JavaScript onclick function

This isn't really recommended, but you can do it all inline like so:

<a href="#" onClick="function test(){ /* Do something */  } test(); return false;"></a>

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

VBA Excel 2-Dimensional Arrays

Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.

This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.

A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.

A VBA 'Array to Range' function

Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)

' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.

' This subroutine saves repetitive coding for a common VBA and Excel task.

' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.

On Error Resume Next

'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code

Dim rngOutput As Excel.Range

Dim iRowCount   As Long
Dim iColCount   As Long
Dim iRow        As Long
Dim iCol        As Long
Dim arrTemp     As Variant
Dim iDimensions As Integer

Dim iRowOffset  As Long
Dim iColOffset  As Long
Dim iStart      As Long


Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
    rngTarget.ClearContents
End If
Application.EnableEvents = True

If IsEmpty(InputArray) Then
    Exit Sub
End If


If TypeName(InputArray) = "Range" Then
    InputArray = InputArray.Value
End If

' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
    rngTarget.Cells(1, 1).Value2 = InputArray
    Exit Sub
End If


iDimensions = ArrayDimensions(InputArray)

If iDimensions < 1 Then

    rngTarget.Value = CStr(InputArray)

ElseIf iDimensions = 1 Then

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iStart = LBound(InputArray)
    iColCount = 1

    If iRowCount > (655354 - rngTarget.Row) Then
        iRowCount = 655354 + iStart - rngTarget.Row
        ReDim Preserve InputArray(iStart To iRowCount)
    End If

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iColCount = 1

    ' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
    ' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
    ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
    For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
        arrTemp(iRow, 1) = InputArray(iRow)
    Next

    With rngTarget.Worksheet
        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
        rngOutput.Value2 = arrTemp
        Set rngTarget = rngOutput
    End With

    Erase arrTemp

ElseIf iDimensions = 2 Then

    iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
    iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)

    iStart = LBound(InputArray, 1)

    If iRowCount > (65534 - rngTarget.Row) Then
        iRowCount = 65534 - rngTarget.Row
        InputArray = ArrayTranspose(InputArray)
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
        InputArray = ArrayTranspose(InputArray)
    End If


    iStart = LBound(InputArray, 2)
    If iColCount > (254 - rngTarget.Column) Then
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
    End If



    With rngTarget.Worksheet

        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))

        Err.Clear
        Application.EnableEvents = False
        rngOutput.Value2 = InputArray
        Application.EnableEvents = True

        If Err.Number <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Formula = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        If Left(InputArray(iRow, iCol), 1) = "=" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "+" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "*" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Value2 = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)

                    If IsObject(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
                    ElseIf IsArray(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
                    ElseIf IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        If Len(InputArray(iRow, iCol)) > 255 Then
                            ' Block-write operations fail on strings exceeding 255 chars. You *have*
                            ' to go back and check, and write this masterpiece one cell at a time...
                            InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Text = InputArray
        End If 'err<>0

        If Err <> 0 Then
            Application.ScreenUpdating = False
            Application.Calculation = xlCalculationManual
            iRowOffset = LBound(InputArray, 1) - 1
            iColOffset = LBound(InputArray, 2) - 1
            For iRow = 1 To iRowCount
                If iRow Mod 100 = 0 Then
                    Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
                End If
                For iCol = 1 To iColCount
                    rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
                Next iCol
            Next iRow
            Application.StatusBar = False
            Application.ScreenUpdating = True


        End If 'err<>0


        Set rngTarget = rngOutput   ' resizes the range This is useful, *most* of the time

    End With

End If

End Sub

You will need the source for ArrayDimensions:

This API declaration is required in the module header:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
                   (Destination As Any, _
                    Source As Any, _
                    ByVal Length As Long)

...And here's the function itself:

Private Function ArrayDimensions(arr As Variant) As Integer
  '-----------------------------------------------------------------
  ' will return:
  ' -1 if not an array
  ' 0  if an un-dimmed array
  ' 1  or more indicating the number of dimensions of a dimmed array
  '-----------------------------------------------------------------


  ' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
  ' Code written by Chris Rae, 25/5/00

  ' Originally published by R. B. Smissaert.
  ' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax

  Dim ptr As Long
  Dim vType As Integer

  Const VT_BYREF = &H4000&

  'get the real VarType of the argument
  'this is similar to VarType(), but returns also the VT_BYREF bit
  CopyMemory vType, arr, 2

  'exit if not an array
  If (vType And vbArray) = 0 Then
    ArrayDimensions = -1
    Exit Function
  End If

  'get the address of the SAFEARRAY descriptor
  'this is stored in the second half of the
  'Variant parameter that has received the array
  CopyMemory ptr, ByVal VarPtr(arr) + 8, 4

  'see whether the routine was passed a Variant
  'that contains an array, rather than directly an array
  'in the former case ptr already points to the SA structure.
  'Thanks to Monte Hansen for this fix

  If (vType And VT_BYREF) Then
    ' ptr is a pointer to a pointer
    CopyMemory ptr, ByVal ptr, 4
  End If

  'get the address of the SAFEARRAY structure
  'this is stored in the descriptor

  'get the first word of the SAFEARRAY structure
  'which holds the number of dimensions
  '...but first check that saAddr is non-zero, otherwise
  'this routine bombs when the array is uninitialized

  If ptr Then
    CopyMemory ArrayDimensions, ByVal ptr, 2
  End If

End Function

Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.

Programmatically extract contents of InstallShield setup.exe

http://www.compdigitec.com/labs/files/isxunpack.exe

Usage: isxunpack.exe yourinstallshield.exe

It will extract in the same folder.

Printf width specifier to maintain precision of floating-point value

In one of my comments to an answer I lamented that I've long wanted some way to print all the significant digits in a floating point value in decimal form, in much the same way the as the question asks. Well I finally sat down and wrote it. It's not quite perfect, and this is demo code that prints additional information, but it mostly works for my tests. Please let me know if you (i.e. anyone) would like a copy of the whole wrapper program which drives it for testing.

static unsigned int
ilog10(uintmax_t v);

/*
 * Note:  As presented this demo code prints a whole line including information
 * about how the form was arrived with, as well as in certain cases a couple of
 * interesting details about the number, such as the number of decimal places,
 * and possibley the magnitude of the value and the number of significant
 * digits.
 */
void
print_decimal(double d)
{
        size_t sigdig;
        int dplaces;
        double flintmax;

        /*
         * If we really want to see a plain decimal presentation with all of
         * the possible significant digits of precision for a floating point
         * number, then we must calculate the correct number of decimal places
         * to show with "%.*f" as follows.
         *
         * This is in lieu of always using either full on scientific notation
         * with "%e" (where the presentation is always in decimal format so we
         * can directly print the maximum number of significant digits
         * supported by the representation, taking into acount the one digit
         * represented by by the leading digit)
         *
         *        printf("%1.*e", DBL_DECIMAL_DIG - 1, d)
         *
         * or using the built-in human-friendly formatting with "%g" (where a
         * '*' parameter is used as the number of significant digits to print
         * and so we can just print exactly the maximum number supported by the
         * representation)
         *
         *         printf("%.*g", DBL_DECIMAL_DIG, d)
         *
         *
         * N.B.:  If we want the printed result to again survive a round-trip
         * conversion to binary and back, and to be rounded to a human-friendly
         * number, then we can only print DBL_DIG significant digits (instead
         * of the larger DBL_DECIMAL_DIG digits).
         *
         * Note:  "flintmax" here refers to the largest consecutive integer
         * that can be safely stored in a floating point variable without
         * losing precision.
         */
#ifdef PRINT_ROUND_TRIP_SAFE
# ifdef DBL_DIG
        sigdig = DBL_DIG;
# else
        sigdig = ilog10(uipow(FLT_RADIX, DBL_MANT_DIG - 1));
# endif
#else
# ifdef DBL_DECIMAL_DIG
        sigdig = DBL_DECIMAL_DIG;
# else
        sigdig = (size_t) lrint(ceil(DBL_MANT_DIG * log10((double) FLT_RADIX))) + 1;
# endif
#endif
        flintmax = pow((double) FLT_RADIX, (double) DBL_MANT_DIG); /* xxx use uipow() */
        if (d == 0.0) {
                printf("z = %.*s\n", (int) sigdig + 1, "0.000000000000000000000"); /* 21 */
        } else if (fabs(d) >= 0.1 &&
                   fabs(d) <= flintmax) {
                dplaces = (int) (sigdig - (size_t) lrint(ceil(log10(ceil(fabs(d))))));
                if (dplaces < 0) {
                        /* XXX this is likely never less than -1 */
                        /*
                         * XXX the last digit is not significant!!! XXX
                         *
                         * This should also be printed with sprintf() and edited...
                         */
                        printf("R = %.0f [%d too many significant digits!!!, zero decimal places]\n", d, abs(dplaces));
                } else if (dplaces == 0) {
                        /*
                         * The decimal fraction here is not significant and
                         * should always be zero  (XXX I've never seen this)
                         */
                        printf("R = %.0f [zero decimal places]\n", d);
                } else {
                        if (fabs(d) == 1.0) {
                                /*
                                 * This is a special case where the calculation
                                 * is off by one because log10(1.0) is 0, but
                                 * we still have the leading '1' whole digit to
                                 * count as a significant digit.
                                 */
#if 0
                                printf("ceil(1.0) = %f, log10(ceil(1.0)) = %f, ceil(log10(ceil(1.0))) = %f\n",
                                       ceil(fabs(d)), log10(ceil(fabs(d))), ceil(log10(ceil(fabs(d)))));
#endif
                                dplaces--;
                        }
                        /* this is really the "useful" range of %f */
                        printf("r = %.*f [%d decimal places]\n", dplaces, d, dplaces);
                }
        } else {
                if (fabs(d) < 1.0) {
                        int lz;

                        lz = abs((int) lrint(floor(log10(fabs(d)))));
                        /* i.e. add # of leading zeros to the precision */
                        dplaces = (int) sigdig - 1 + lz;
                        printf("f = %.*f [%d decimal places]\n", dplaces, d, dplaces);
                } else {                /* d > flintmax */
                        size_t n;
                        size_t i;
                        char *df;

                        /*
                         * hmmmm...  the easy way to suppress the "invalid",
                         * i.e. non-significant digits is to do a string
                         * replacement of all dgits after the first
                         * DBL_DECIMAL_DIG to convert them to zeros, and to
                         * round the least significant digit.
                         */
                        df = malloc((size_t) 1);
                        n = (size_t) snprintf(df, (size_t) 1, "%.1f", d);
                        n++;                /* for the NUL */
                        df = realloc(df, n);
                        (void) snprintf(df, n, "%.1f", d);
                        if ((n - 2) > sigdig) {
                                /*
                                 * XXX rounding the integer part here is "hard"
                                 * -- we would have to convert the digits up to
                                 * this point back into a binary format and
                                 * round that value appropriately in order to
                                 * do it correctly.
                                 */
                                if (df[sigdig] >= '5' && df[sigdig] <= '9') {
                                        if (df[sigdig - 1] == '9') {
                                                /*
                                                 * xxx fixing this is left as
                                                 * an exercise to the reader!
                                                 */
                                                printf("F = *** failed to round integer part at the least significant digit!!! ***\n");
                                                free(df);
                                                return;
                                        } else {
                                                df[sigdig - 1]++;
                                        }
                                }
                                for (i = sigdig; df[i] != '.'; i++) {
                                        df[i] = '0';
                                }
                        } else {
                                i = n - 1; /* less the NUL */
                                if (isnan(d) || isinf(d)) {
                                        sigdig = 0; /* "nan" or "inf" */
                                }
                        }
                        printf("F = %.*s. [0 decimal places, %lu digits, %lu digits significant]\n",
                               (int) i, df, (unsigned long int) i, (unsigned long int) sigdig);
                        free(df);
                }
        }

        return;
}


static unsigned int
msb(uintmax_t v)
{
        unsigned int mb = 0;

        while (v >>= 1) { /* unroll for more speed...  (see ilog2()) */
                mb++;
        }

        return mb;
}

static unsigned int
ilog10(uintmax_t v)
{
        unsigned int r;
        static unsigned long long int const PowersOf10[] =
                { 1LLU, 10LLU, 100LLU, 1000LLU, 10000LLU, 100000LLU, 1000000LLU,
                  10000000LLU, 100000000LLU, 1000000000LLU, 10000000000LLU,
                  100000000000LLU, 1000000000000LLU, 10000000000000LLU,
                  100000000000000LLU, 1000000000000000LLU, 10000000000000000LLU,
                  100000000000000000LLU, 1000000000000000000LLU,
                  10000000000000000000LLU };

        if (!v) {
                return ~0U;
        }
        /*
         * By the relationship "log10(v) = log2(v) / log2(10)", we need to
         * multiply "log2(v)" by "1 / log2(10)", which is approximately
         * 1233/4096, or (1233, followed by a right shift of 12).
         *
         * Finally, since the result is only an approximation that may be off
         * by one, the exact value is found by subtracting "v < PowersOf10[r]"
         * from the result.
         */
        r = ((msb(v) * 1233) >> 12) + 1;

        return r - (v < PowersOf10[r]);
}

A top-like utility for monitoring CUDA activity on a GPU

You can use the monitoring program glances with its GPU monitoring plug-in:

  • open source
  • to install: sudo apt-get install -y python-pip; sudo pip install glances[gpu]
  • to launch: sudo glances

enter image description here

It also monitors the CPU, disk IO, disk space, network, and a few other things:

enter image description here

Select SQL Server database size

Check Database Size in SQL Server for both Azure and On-Premises-

Method 1 – Using ‘sys.database_files’ System View

SELECT
    DB_NAME() AS [database_name],
    CONCAT(CAST(SUM(
        CAST( (size * 8.0/1024) AS DECIMAL(15,2) )
    ) AS VARCHAR(20)),' MB') AS [database_size]
FROM sys.database_files;

enter image description here

Method 2 – Using ‘sp_spaceused’ System Stored Procedure

EXEC sp_spaceused ;

enter image description here

How to override trait function and call it from the overridden function?

Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.

This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.

trait A {
    protected function traitcalc($v) {
        return $v+1;
    }

    function calc($v) {
        return $this->traitcalc($v);
    }
}

class MyClass {
    use A;

    function calc($v) {
        $v++;
        return $this->traitcalc($v);
    }
}

class MyOtherClass {
    use A;
}


print (new MyClass())->calc(2); // will print 4

print (new MyOtherClass())->calc(2); // will print 3

Detect click outside React component

you can you a simple way to solve your problem , i show you :

....

const [dropDwonStatus , setDropDownStatus] = useState(false)

const openCloseDropDown = () =>{
 setDropDownStatus(prev => !prev)
}

const closeDropDown = ()=> {
 if(dropDwonStatus){
   setDropDownStatus(false)
 }
}
.
.
.
<parent onClick={closeDropDown}>
 <child onClick={openCloseDropDown} />
</parent>

this works for me , good luck ;)

How to know what the 'errno' means?

Here is the output from errno -l reformatted for readability:

  1   EPERM             Operation not permitted
  2   ENOENT            No such file or directory
  3   ESRCH             No such process
  4   EINTR             Interrupted system call
  5   EIO               Input/output error
  6   ENXIO             No such device or address
  7   E2BIG             Argument list too long
  8   ENOEXEC           Exec format error
  9   EBADF             Bad file descriptor
 10   ECHILD            No child processes
 11   EAGAIN            Resource temporarily unavailable
 11   EWOULDBLOCK       Resource temporarily unavailable
 12   ENOMEM            Cannot allocate memory
 13   EACCES            Permission denied
 14   EFAULT            Bad address
 15   ENOTBLK           Block device required
 16   EBUSY             Device or resource busy
 17   EEXIST            File exists
 18   EXDEV             Invalid cross-device link
 19   ENODEV            No such device
 20   ENOTDIR           Not a directory
 21   EISDIR            Is a directory
 22   EINVAL            Invalid argument
 23   ENFILE            Too many open files in system
 24   EMFILE            Too many open files
 25   ENOTTY            Inappropriate ioctl for device
 26   ETXTBSY           Text file busy
 27   EFBIG             File too large
 28   ENOSPC            No space left on device
 29   ESPIPE            Illegal seek
 30   EROFS             Read-only file system
 31   EMLINK            Too many links
 32   EPIPE             Broken pipe
 33   EDOM              Numerical argument out of domain
 34   ERANGE            Numerical result out of range
 35   EDEADLK           Resource deadlock avoided
 35   EDEADLOCK         Resource deadlock avoided
 36   ENAMETOOLONG      File name too long
 37   ENOLCK            No locks available
 38   ENOSYS            Function not implemented
 39   ENOTEMPTY         Directory not empty
 40   ELOOP             Too many levels of symbolic links
 42   ENOMSG            No message of desired type
 43   EIDRM             Identifier removed
 44   ECHRNG            Channel number out of range
 45   EL2NSYNC          Level 2 not synchronized
 46   EL3HLT            Level 3 halted
 47   EL3RST            Level 3 reset
 48   ELNRNG            Link number out of range
 49   EUNATCH           Protocol driver not attached
 50   ENOCSI            No CSI structure available
 51   EL2HLT            Level 2 halted
 52   EBADE             Invalid exchange
 53   EBADR             Invalid request descriptor
 54   EXFULL            Exchange full
 55   ENOANO            No anode
 56   EBADRQC           Invalid request code
 57   EBADSLT           Invalid slot
 59   EBFONT            Bad font file format
 60   ENOSTR            Device not a stream
 61   ENODATA           No data available
 62   ETIME             Timer expired
 63   ENOSR             Out of streams resources
 64   ENONET            Machine is not on the network
 65   ENOPKG            Package not installed
 66   EREMOTE           Object is remote
 67   ENOLINK           Link has been severed
 68   EADV              Advertise error
 69   ESRMNT            Srmount error
 70   ECOMM             Communication error on send
 71   EPROTO            Protocol error
 72   EMULTIHOP         Multihop attempted
 73   EDOTDOT           RFS specific error
 74   EBADMSG           Bad message
 75   EOVERFLOW         Value too large for defined data type
 76   ENOTUNIQ          Name not unique on network
 77   EBADFD            File descriptor in bad state
 78   EREMCHG           Remote address changed
 79   ELIBACC           Can not access a needed shared library
 80   ELIBBAD           Accessing a corrupted shared library
 81   ELIBSCN           .lib section in a.out corrupted
 82   ELIBMAX           Attempting to link in too many shared libraries
 83   ELIBEXEC          Cannot exec a shared library directly
 84   EILSEQ            Invalid or incomplete multibyte or wide character
 85   ERESTART          Interrupted system call should be restarted
 86   ESTRPIPE          Streams pipe error
 87   EUSERS            Too many users
 88   ENOTSOCK          Socket operation on non-socket
 89   EDESTADDRREQ      Destination address required
 90   EMSGSIZE          Message too long
 91   EPROTOTYPE        Protocol wrong type for socket
 92   ENOPROTOOPT       Protocol not available
 93   EPROTONOSUPPORT   Protocol not supported
 94   ESOCKTNOSUPPORT   Socket type not supported
 95   ENOTSUP           Operation not supported
 95   EOPNOTSUPP        Operation not supported
 96   EPFNOSUPPORT      Protocol family not supported
 97   EAFNOSUPPORT      Address family not supported by protocol
 98   EADDRINUSE        Address already in use
 99   EADDRNOTAVAIL     Cannot assign requested address
100   ENETDOWN          Network is down
101   ENETUNREACH       Network is unreachable
102   ENETRESET         Network dropped connection on reset
103   ECONNABORTED      Software caused connection abort
104   ECONNRESET        Connection reset by peer
105   ENOBUFS           No buffer space available
106   EISCONN           Transport endpoint is already connected
107   ENOTCONN          Transport endpoint is not connected
108   ESHUTDOWN         Cannot send after transport endpoint shutdown
109   ETOOMANYREFS      Too many references: cannot splice
110   ETIMEDOUT         Connection timed out
111   ECONNREFUSED      Connection refused
112   EHOSTDOWN         Host is down
113   EHOSTUNREACH      No route to host
114   EALREADY          Operation already in progress
115   EINPROGRESS       Operation now in progress
116   ESTALE            Stale file handle
117   EUCLEAN           Structure needs cleaning
118   ENOTNAM           Not a XENIX named type file
119   ENAVAIL           No XENIX semaphores available
120   EISNAM            Is a named type file
121   EREMOTEIO         Remote I/O error
122   EDQUOT            Disk quota exceeded
123   ENOMEDIUM         No medium found
124   EMEDIUMTYPE       Wrong medium type
125   ECANCELED         Operation canceled
126   ENOKEY            Required key not available
127   EKEYEXPIRED       Key has expired
128   EKEYREVOKED       Key has been revoked
129   EKEYREJECTED      Key was rejected by service
130   EOWNERDEAD        Owner died
131   ENOTRECOVERABLE   State not recoverable
132   ERFKILL           Operation not possible due to RF-kill
133   EHWPOISON         Memory page has hardware error

I used tabularise in Vim to align the columns:

:%Tab /^[^ ]*\zs /r1l1l1
:%Tab /^ *[^ ]* *[^ ]*\zs /l1

Node Sass couldn't find a binding for your current environment

This usually happens because the environment has changed since running npm install. Running npm rebuild node-sass builds the binding for the current environment.

getResources().getColor() is deprecated

It looks like the best approach is to use:

ContextCompat.getColor(context, R.color.color_name)

eg:

yourView.setBackgroundColor(ContextCompat.getColor(applicationContext,
                            R.color.colorAccent))

This will choose the Marshmallow two parameter method or the pre-Marshmallow method appropriately.

mysql data directory location

If you are using macOS {mine 'High Sierra'} and Installed XAMPP

You can find mysql data files;

Go to : /Applications/XAMPP/xamppfiles/var/mysql/

multiple packages in context:component-scan, spring config

Another general Annotation approach:

@ComponentScan(basePackages = {"x.y.z"})

Why is it bad style to `rescue Exception => e` in Ruby?

Because this captures all exceptions. It's unlikely that your program can recover from any of them.

You should handle only exceptions that you know how to recover from. If you don't anticipate a certain kind of exception, don't handle it, crash loudly (write details to the log), then diagnose logs and fix code.

Swallowing exceptions is bad, don't do this.

Vertically align text within input field of fixed-height without display: table or padding?

I ran into this problem myself. I found that not specifying an input height, but using the font-height and padding combined, results in vertically aligned text.

For instance, lets say you want to have a 42px tall input box, with a font-size of 20px. You could simply find the difference between the input height and the font-size, divide it by two, and set your padding to that amount. In this case, you would have 22px total worth of padding, which is 11px on each side.

<input type="text" style="padding: 11px 0px 11px 0px; font-size: 20px;" />

That would give you a 42px tall input box with perfect vertical alignment.

Hope that helps.

Convert timestamp to date in Oracle SQL

If the datatype is timestamp then the visible format is irrelevant.

You should avoid converting the data to date or use of to_char. Instead compare the timestamp data to timestamp values using TO_TIMESTAMP()

WHERE start_ts >= TO_TIMESTAMP('2016-05-13', 'YYYY-MM-DD')
   AND start_ts < TO_TIMESTAMP('2016-05-14', 'YYYY-MM-DD')

How to import and use image in a Vue single file component?

It is heavily suggested to make use of webpack when importing pictures from assets and in general for optimisation and pathing purposes

If you wish to load them by webpack you can simply use :src='require('path/to/file')' Make sure you use : otherwise it won't execute the require statement as Javascript.

In typescript you can do almost the exact same operation: :src="require('@/assets/image.png')"

Why the following is generally considered bad practice:

<template>
  <div id="app">
    <img src="./assets/logo.png">
  </div>
</template>

<script>
export default {
}
</script>

<style lang="scss">
</style> 

When building using the Vue cli, webpack is not able to ensure that the assets file will maintain a structure that follows the relative importing. This is due to webpack trying to optimize and chunk items appearing inside of the assets folder. If you wish to use a relative import you should do so from within the static folder and use: <img src="./static/logo.png">

Best way to change the background color for an NSView

Just set backgroundColor on the layer (after making the view layer backed).

view.wantsLayer = true
view.layer?.backgroundColor = CGColor.white

Oracle: How to find out if there is a transaction pending?

Matthew Watson can be modified to be used in RAC

select t.inst_id 
       ,s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;

Re-sign IPA (iPhone)

Finally got this working!

Tested with a IPA signed with cert1 for app store submission with no devices added in the provisioning profile. Results in a new IPA signed with a enterprise account and a mobile provisioning profile for in house deployment (the mobile provisioning profile gets embedded to the IPA).

Solution:

Unzip the IPA

unzip Application.ipa

Remove old CodeSignature

rm -r "Payload/Application.app/_CodeSignature" "Payload/Application.app/CodeResources" 2> /dev/null | true

Replace embedded mobile provisioning profile

cp "MyEnterprise.mobileprovision" "Payload/Application.app/embedded.mobileprovision"

Re-sign

/usr/bin/codesign -f -s "iPhone Distribution: Certificate Name" --resource-rules "Payload/Application.app/ResourceRules.plist" "Payload/Application.app"

Re-package

zip -qr "Application.resigned.ipa" Payload

Edit: Removed the Entitlement part (see alleys comment, thanks)

How to Add Incremental Numbers to a New Column Using Pandas

For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:

df.insert(0, 'New_ID', df.index + 880)

if you want New_ID to be the first column. Otherwise this if you don't mind it being at the end:

df['New_ID'] = df.index + 880

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

Vue v-on:click does not work on component

I think the $emit function works better for what I think you're asking for. It keeps your component separated from the Vue instance so that it is reusable in many contexts.

// Child component
<template>
  <div id="app">
    <test @click="$emit('test-click')"></test>
  </div>
</template>

Use it in HTML

// Parent component
<test @test-click="testFunction">

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

Binding Combobox Using Dictionary as the Datasource

Use -->

comboBox1.DataSource = colors.ToList();

Unless the dictionary is converted to list, combo-box can't recognize its members.

orderBy multiple fields in Angular

Created Pipe for sorting. Accepts both string and array of strings, sorting by multiple values. Works for Angular (not AngularJS). Supports both sort for string and numbers.

@Pipe({name: 'orderBy'})
export class OrderBy implements PipeTransform {
    transform(array: any[], filter: any): any[] {
        if(typeof filter === 'string') {
            return this.sortAray(array, filter)
        } else {
            for (var i = filter.length -1; i >= 0; i--) {
                array = this.sortAray(array, filter[i]);
            }

            return array;
        }
    }

    private sortAray(array, field) {
        return array.sort((a, b) => {
            if(typeof a[field] !== 'string') {
                a[field] !== b[field] ? a[field] < b[field] ? -1 : 1 : 0
            } else {
                a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0
            }
        });
    }
}

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

Vertical align in bootstrap table

Try:

.table thead th{
   vertical-align:middle;
}

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

How to store .pdf files into MySQL as BLOBs using PHP?

In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string () call should be swapped for the newer php versions, according to: http://php.net/manual/en/mysqli.real-escape-string.php

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');
});

Also note that return true; is redundant in your logic, so it can be removed.

How to call a method with a separate thread in Java?

Another quicker option to call things (like DialogBoxes and MessageBoxes and creating separate threads for not-thread safe methods) would be to use the Lamba Expression

  new Thread(() -> {
                      "code here"
            }).start();

How can I replace non-printable Unicode characters in Java?

methods in blow for your goal

public static String removeNonAscii(String str)
{
    return str.replaceAll("[^\\x00-\\x7F]", "");
}

public static String removeNonPrintable(String str) // All Control Char
{
    return str.replaceAll("[\\p{C}]", "");
}

public static String removeSomeControlChar(String str) // Some Control Char
{
    return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
}

public static String removeFullControlChar(String str)
{
    return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
} 

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

How to set layout_weight attribute dynamically from code?

Using Kotlin you can do something like:

import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.CardView
import android.widget.*

import android.widget.LinearLayout

class RespondTo : CardView {
    constructor(context: Context) : super(context) {
        init(context)
    }

    private fun init(context: Context) {


        val parent = LinearLayout(context)

        parent.apply {
            layoutParams = LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT, 1.0f).apply {
                orientation = LinearLayout.HORIZONTAL

                addView(EditText(context).apply {
                    id = generateViewId()
                    layoutParams = LinearLayout.LayoutParams(0,
                            LinearLayout.LayoutParams.WRAP_CONTENT, 0.9f).apply {
                    }
                })
                addView(ImageButton(context).apply({
                    layoutParams = LinearLayout.LayoutParams(0,
                            LinearLayout.LayoutParams.WRAP_CONTENT, 0.1f)
                    background = null
                    setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_save_black_24px))
                    id = generateViewId()
                    layoutParams = RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT).apply {
                        addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
                        // addRule(RelativeLayout.LEFT_OF, myImageButton.id)
                    }
                }))
            }
        }
        this.addView(parent)
    }
}

How to escape a JSON string to have it in a URL?

Answer given by Delan is perfect. Just adding to it - incase someone wants to name the parameters or pass multiple JSON strings separately - the below code could help!

JQuery

var valuesToPass = new Array(encodeURIComponent(VALUE_1), encodeURIComponent(VALUE_2), encodeURIComponent(VALUE_3), encodeURIComponent(VALUE_4));

data = {elements:JSON.stringify(valuesToPass)}

PHP

json_decode(urldecode($_POST('elements')));

Hope this helps!

HTML email with Javascript

I don't think that is possible in an email, nor should it be. There would be major security ramifications.

When to use Spring Security`s antMatcher()?

Basically http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

Installing TensorFlow on Windows (Python 3.6.x)

Windows batch file for installing TensorFlow and Python 3.5 on Windows. The issue is that as of this date, TensorFlow is not updated to support Python 3.6+ and will not install. Additionally, many systems have an incompatible version of Python. This batch file should create a compatible environment without effecting other Python installs. See REM comments for assumptions.

REM download Anaconda3-4.2.0-Windows-x86_64.exe (contains python 3.5) from https://repo.continuum.io/archive/index.html
REM Assumes download is in %USERPROFILE%\Downloads
%USERPROFILE%\Downloads\Anaconda3-4.2.0-Windows-x86_64.exe

REM change path to use Anaconda3 (python 3.5).
PATH %USERPROFILE%\Anaconda3;%USERPROFILE%\Anaconda3\Scripts;%USERPROFILE%\Anaconda3\Library\bin;%PATH%

REM update pip to 9.0 or later (mandatory)
python -m pip install --upgrade pip

REM tell conda where to load tensorflow
conda config --add channels conda-forge

REM elevate command (mandatory) and install tensorflow - use explicit path to conda %USERPROFILE%\Anaconda3\scripts\conda
powershell.exe -Command start-process -verb runas cmd {/K "%USERPROFILE%\Anaconda3\scripts\conda install tensorflow"}

Be sure the above PATH is used when invoking TensorFlow.

Using SimpleXML to create an XML object from scratch

Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.

$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
    $w->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));

By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.

Disable LESS-CSS Overwriting calc()

The solutions of Fabricio works just fine.

A very common usecase of calc is add 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable: 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);
width: -o-calc(~"100% - "@someMarginVariable*2);

Or can use a mixin like:

.fullWidthMinusMarginPaddingMixin(@marginSize,@paddingSize) {
  @minusValue: (@marginSize+@paddingSize)*2;
  padding: @paddingSize;
  margin: @marginSize;
  width: calc(~"100% - "@minusValue);
  width: -moz-calc(~"100% - "@minusValue);
  width: -webkit-calc(~"100% - "@minusValue);
  width: -o-calc(~"100% - "@minusValue);
}

Subtract one day from datetime

You can try this.

Timestamp=2008-11-11 13:23:44.657;

SELECT DATE_SUB(OrderDate,INTERVAL 1 DAY) AS SubtractDate FROM Orders

output :2008-11-10 13:23:44.657

I hope, it will help to solve your problem.

Create a Bitmap/Drawable from file path

Create bitmap from file path:

File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);

If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.

I think you are giving the wrong file path. :) Hope this helps.

How to get element value in jQuery

  <div class="inter">
      <p>Liste des Produits</p>
      <ul>
          <li><a href="#1">P1</a></li>
          <li><a href="#2">P2</a></li>
          <li><a href="#3">P3</a></li>
      </ul>
  </div>

        $(document).ready(function(){
            $(".inter li").bind(
            "click", function(){
                alert($(this).children("a").text());
            });
        });

How to get file URL using Storage facade in laravel 5?

this work for me in 2020 at laravel 7

        $image_resize = Image::make($image->getRealPath());
        $image_resize->resize(800,600);
        $image_resize->save(Storage::disk('episodes')->path('') . $imgname);

so you can use it like this

echo Storage::disk('public')->path('');

Disabling buttons on react native

This seems like the kind of thing that could be solved using a Higher Order Component. I could be wrong though because I'm struggling to understand it 100% myself, but maybe it'll be helpful to you (here's a couple links)...

PHP 5 disable strict standards error

The default value of error_reporting flag is E_ALL & ~E_NOTICE if not set in php.ini. But in some installation (particularly installations targeting development environments) has E_ALL | E_STRICT set as value of this flag (this is the recommended value during development). In some cases, specially when you'll want to run some open source projects, that was developed prior to PHP 5.3 era and not yet updated with best practices defined by PHP 5.3, in your development environment, you'll probably run into getting some messages like you are getting. The best way to cope up on this situation, is to set only E_ALL as the value of error_reporting flag, either in php.ini or in code (probably in a front-controller like index.php in web-root as follows:

if(defined('E_STRICT')){
    error_reporting(E_ALL);
}

Where is the Docker daemon log?

Add ways to find docker daemon log in windows:

try

When using docker machine on Windows and Mac OSX, the daemon runs inside a virtual machine.

First, find your active Docker machine.

docker-machine ls Find the name of the active docker machine under the NAME column in the output.

You can copy the docker daemon log file to your local directory for analysis:

docker-machine scp default:/var/log/docker.log ./ Where default is the name of active your docker machine.

Android: Access child views from a ListView

A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.

Found it here

Enabling CORS in Cloud Functions for Firebase

In my case the error was caused by cloud function invoker limit access. Please add allUsers to cloud function invoker. Please catch link. Please refer to article for more info

VBScript - How to make program wait until process has finished?

You need to tell the run to wait until the process is finished. Something like:

const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set oShell = WScript.CreateObject("WScript.Shell")
command = "cmd /c C:\windows\system32\wscript.exe <path>\myScript.vbs " & args
oShell.Run command, DontShowWindow, WaitUntilFinished

In the script itself, start Excel like so. While debugging start visible:

File = "c:\test\myfile.xls"
oShell.run """C:\Program Files\Microsoft Office\Office14\EXCEL.EXE"" " & File, 1, true

How to stop a function

In this example, the line do_something_else() will not be executed if do_not_continue is True. Control will return, instead, to whichever function called some_function.

def some_function():
    if do_not_continue:
        return  # implicitly, this is the same as saying `return None` 
    do_something_else()

Return JSON with error status code MVC

The neatest solution I've found is to create your own JsonResult that extends the original implementation and allows you to specify a HttpStatusCode:

public class JsonHttpStatusResult : JsonResult
{
    private readonly HttpStatusCode _httpStatus;

    public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
    {
        Data = data;
        _httpStatus = httpStatus;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
        base.ExecuteResult(context);
    }
}

You can then use this in your controller action like so:

if(thereWereErrors)
{
    var errorModel = new { error = "There was an error" };
    return new JsonHttpStatusResult(errorModel, HttpStatusCode.InternalServerError);
}

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

How to run Linux commands in Java?

Runtime run = Runtime.getRuntime();  
//The best possible I found is to construct a command which you want to execute  
//as a string and use that in exec. If the batch file takes command line arguments  
//the command can be constructed a array of strings and pass the array as input to  
//the exec method. The command can also be passed externally as input to the method.  

Process p = null;  
String cmd = "ls";  
try {  
    p = run.exec(cmd);  

    p.getErrorStream();  
    p.waitFor();

}  
catch (IOException e) {  
    e.printStackTrace();  
    System.out.println("ERROR.RUNNING.CMD");  

}finally{
    p.destroy();
}  

How can I consume a WSDL (SOAP) web service in Python?

I recently stumbled up on the same problem. Here is the synopsis of my solution:

Basic constituent code blocks needed

The following are the required basic code blocks of your client application

  1. Session request section: request a session with the provider
  2. Session authentication section: provide credentials to the provider
  3. Client section: create the Client
  4. Security Header section: add the WS-Security Header to the Client
  5. Consumption section: consume available operations (or methods) as needed

What modules do you need?

Many suggested to use Python modules such as urllib2 ; however, none of the modules work-at least for this particular project.

So, here is the list of the modules you need to get. First of all, you need to download and install the latest version of suds from the following link:

pypi.python.org/pypi/suds-jurko/0.4.1.jurko.2

Additionally, you need to download and install requests and suds_requests modules from the following links respectively ( disclaimer: I am new to post in here, so I can't post more than one link for now).

pypi.python.org/pypi/requests

pypi.python.org/pypi/suds_requests/0.1

Once you successfully download and install these modules, you are good to go.

The code

Following the steps outlined earlier, the code looks like the following: Imports:

import logging
from suds.client import Client
from suds.wsse import *
from datetime import timedelta,date,datetime,tzinfo
import requests
from requests.auth import HTTPBasicAuth
import suds_requests

Session request and authentication:

username=input('Username:')
password=input('password:')
session = requests.session()
session.auth=(username, password)

Create the Client:

client = Client(WSDL_URL, faults=False, cachingpolicy=1, location=WSDL_URL, transport=suds_requests.RequestsTransport(session))

Add WS-Security Header:

...
addSecurityHeader(client,username,password)
....

def addSecurityHeader(client,username,password):
    security=Security()
    userNameToken=UsernameToken(username,password)
    timeStampToken=Timestamp(validity=600)
    security.tokens.append(userNameToken)
    security.tokens.append(timeStampToken)
    client.set_options(wsse=security)

Please note that this method creates the security header depicted in Fig.1. So, your implementation may vary depending on the correct security header format provided by the owner of the service you are consuming.

Consume the relevant method (or operation) :

result=client.service.methodName(Inputs)

Logging:

One of the best practices in such implementations as this one is logging to see how the communication is executed. In case there is some issue, it makes debugging easy. The following code does basic logging. However, you can log many aspects of the communication in addition to the ones depicted in the code.

logging.basicConfig(level=logging.INFO) 
logging.getLogger('suds.client').setLevel(logging.DEBUG) 
logging.getLogger('suds.transport').setLevel(logging.DEBUG)

Result:

Here is the result in my case. Note that the server returned HTTP 200. This is the standard success code for HTTP request-response.

(200, (collectionNodeLmp){
   timestamp = 2014-12-03 00:00:00-05:00
   nodeLmp[] = 
      (nodeLmp){
         pnodeId = 35010357
         name = "YADKIN"
         mccValue = -0.19
         mlcValue = -0.13
         price = 36.46
         type = "500 KV"
         timestamp = 2014-12-03 01:00:00-05:00
         errorCodeId = 0
      },
      (nodeLmp){
         pnodeId = 33138769
         name = "ZION 1"
         mccValue = -0.18
         mlcValue = -1.86
         price = 34.75
         type = "Aggregate"
         timestamp = 2014-12-03 01:00:00-05:00
         errorCodeId = 0
      },
 })

Set Culture in an ASP.Net MVC app

1: Create a custom attribute and override method like this:

public class CultureAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
    // Retreive culture from GET
    string currentCulture = filterContext.HttpContext.Request.QueryString["culture"];

    // Also, you can retreive culture from Cookie like this :
    //string currentCulture = filterContext.HttpContext.Request.Cookies["cookie"].Value;

    // Set culture
    Thread.CurrentThread.CurrentCulture = new CultureInfo(currentCulture);
    Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentCulture);
    }
}

2: In App_Start, find FilterConfig.cs, add this attribute. (this works for WHOLE application)

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
    // Add custom attribute here
    filters.Add(new CultureAttribute());
    }
}    

That's it !

If you want to define culture for each controller/action in stead of whole application, you can use this attribute like this:

[Culture]
public class StudentsController : Controller
{
}

Or:

[Culture]
public ActionResult Index()
{
    return View();
}

How can I refresh a page with jQuery?

use

location.reload();

or

window.location.reload();

SQL: How to get the id of values I just INSERTed?

Ms SQL Server: this is good solution even if you inserting more rows:

 Declare @tblInsertedId table (Id int not null)

 INSERT INTO Test ([Title], [Text])
 OUTPUT inserted.Id INTO @tblInsertedId (Id)
 SELECT [Title], [Text] FROM AnotherTable

 select Id from @tblInsertedId 

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Sum of two input value by jquery

use parseInt as a = parseInt($('input[name=service_price]').val())

What is the best way to remove a table row with jQuery?

You're right:

$('#myTableRow').remove();

This works fine if your row has an id, such as:

<tr id="myTableRow"><td>blah</td></tr>

If you don't have an id, you can use any of jQuery's plethora of selectors.

Static Initialization Blocks

If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:

public class Foo {
    private static final int widgets;

    static {
        int first = Widgets.getFirstCount();
        int second = Widgets.getSecondCount();
        // Imagine more complex logic here which really used first/second
        widgets = first + second;
    }
}

If first and second weren't in a block, they'd look like fields. If they were in a block without static in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.

Now in this particular case, you could use a static method instead:

public class Foo {
    private static final int widgets = getWidgets();

    static int getWidgets() {
        int first = Widgets.getFirstCount();
        int second = Widgets.getSecondCount();
        // Imagine more complex logic here which really used first/second
        return first + second;
    }
}

... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

What Worked for me was:

Open localhost/reports
Go to properties tab (SSRS 2008)
Security->New Role Assignment
Add DOMAIN/USERNAME or DOMAIN/USERGROUP
Check Report builder

Printing out a number in assembly language?

DOS Print 32 bit value stored in EAX with hexadecimal output (for 80386+)
(on 64 bit OS use DOSBOX)

.code
    mov ax,@DATA        ; get the address of the data segment
    mov ds,ax           ; store the address in the data segment register
;-----------------------
    mov eax,0FFFFFFFFh  ; 32 bit value (0 - FFFFFFFF) for example
;-----------------------
; convert the value in EAX to hexadecimal ASCIIs
;-----------------------
    mov di,OFFSET ASCII ; get the offset address
    mov cl,8            ; number of ASCII
P1: rol eax,4           ; 1 Nibble (start with highest byte)
    mov bl,al
    and bl,0Fh          ; only low-Nibble
    add bl,30h          ; convert to ASCII
    cmp bl,39h          ; above 9?
    jna short P2
    add bl,7            ; "A" to "F"
P2: mov [di],bl         ; store ASCII in buffer
    inc di              ; increase target address
    dec cl              ; decrease loop counter
    jnz P1              ; jump if cl is not equal 0 (zeroflag is not set)
;-----------------------
; Print string
;-----------------------
    mov dx,OFFSET ASCII ; DOS 1+ WRITE STRING TO STANDARD OUTPUT
    mov ah,9            ; DS:DX->'$'-terminated string
    int 21h             ; maybe redirected under DOS 2+ for output to file
                        ; (using pipe character">") or output to printer

  ; terminate program...

.data
ASCII DB "00000000",0Dh,0Ah,"$" ; buffer for ASCII string

Alternative string output directly to the videobuffer without using software interupts:

;-----------------------
; Print string
;-----------------------
    mov ax,0B800h       ; segment address of textmode video buffer
    mov es,ax           ; store address in extra segment register

    mov si,OFFSET ASCII ; get the offset address of the string

; using a fixed target address for example (screen page 0)
; Position`on screen = (Line_number*80*2) + (Row_number*2)

    mov di,(10*80*2)+(10*2)
    mov cl,8            ; number of ASCII
    cld                 ; clear direction flag

P3: lodsb  ; get the ASCII from the address in DS:SI + increase si
    stosb  ; write ASCII directly to the screen using ES:DI + increase di
    inc di ; step over attribut byte
    dec cl ; decrease counter
    jnz P3 ; repeat (print only 8 ASCII, not used bytes are: 0Dh,0Ah,"$")

; Hint: this directly output to the screen do not touch or move the cursor
; but feel free to modify..

Is there 'byte' data type in C++?

No there is no byte data type in C++. However you could always include the bitset header from the standard library and create a typedef for byte:

typedef bitset<8> BYTE;

NB: Given that WinDef.h defines BYTE for windows code, you may want to use something other than BYTE if your intending to target Windows.

Edit: In response to the suggestion that the answer is wrong. The answer is not wrong. The question was "Is there a 'byte' data type in C++?". The answer was and is: "No there is no byte data type in C++" as answered.

With regards to the suggested possible alternative for which it was asked why is the suggested alternative better?

According to my copy of the C++ standard, at the time:

"Objects declared as characters (char) shall be large enough to store any member of the implementations basic character set": 3.9.1.1

I read that to suggest that if a compiler implementation requires 16 bits to store a member of the basic character set then the size of a char would be 16 bits. That today's compilers tend to use 8 bits for a char is one thing, but as far as I can tell there is certainly no guarantee that it will be 8 bits.

On the other hand, "the class template bitset<N> describes an object that can store a sequence consisting of a fixed number of bits, N." : 20.5.1. In otherwords by specifying 8 as the template parameter I end up with an object that can store a sequence consisting of 8 bits.

Whether or not the alternative is better to char, in the context of the program being written, therefore depends, as far as I understand, although I may be wrong, upon your compiler and your requirements at the time. It was therefore upto the individual writing the code, as far as I'm concerned, to do determine whether the suggested alternative was appropriate for their requirements/wants/needs.

Enable UTF-8 encoding for JavaScript

just add your script like this:

<script src="/js/intlTelInput.min.js" charset="utf-8"></script>

Turn off textarea resizing

It can done easy by just using html draggable attribute

<textarea name="mytextarea" draggable="false"></textarea>

Default value is true.

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

In my case it appears it was because I had "copied settings" from a 32-bit to a new configuration (64 bit) and it hadn't updated the libraries. Odd.

1>MSVCRTD.lib(ti_inst.obj) : fatal error LNK1112: module machine type ‘X86’ conflicts with target machine type ‘x64’

this meant “your properties -> VC++ Directories -> Library Directories” is pointing to a directory that has 32 bit libs built in it. Fix somehow!

In my case http://social.msdn.microsoft.com/Forums/ar/vcgeneral/thread/c747cd6f-32be-4159-b9d3-d2e33d2bab55

ref: http://betterlogic.com/roger/2012/02/visual-studio-2010-express-64-bit-woe

How can I change the default width of a Twitter Bootstrap modal box?

In Bootstrap 3 all you need is this

<style>
    .modal .modal-dialog { width: 80%; }
</style>

Most of the above answers did not worked for me !!!

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<style>_x000D_
  #myModal1 .modal-dialog {_x000D_
    width: 80%;_x000D_
  }_x000D_
  #myModal2 .modal-dialog {_x000D_
    width: 50%;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal1">_x000D_
  80%_x000D_
</button>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal2">_x000D_
  50%_x000D_
</button>_x000D_
<center>_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
    <div class="modal-dialog" role="document">_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>_x000D_
          </button>_x000D_
          <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          custom width : 80%_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
          <button type="button" class="btn btn-primary">Save changes</button>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
    <div class="modal-dialog" role="document">_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>_x000D_
          </button>_x000D_
          <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          custom width : 50%_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
          <button type="button" class="btn btn-primary">Save changes</button>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</center>
_x000D_
_x000D_
_x000D_

How to get hostname from IP (Linux)?

In order to use nslookup, host or gethostbyname() then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.

Apply function to each column in a data frame observing each columns existing data type

A solution using retype() from hablar to coerce factors to character or numeric type depending on feasability. I'd use dplyr for applying max to each column.

Code

library(dplyr)
library(hablar)

# Retype() simplifies each columns type, e.g. always removes factors
d <- d %>% retype()

# Check max for each column
d %>% summarise_all(max)

Result

Not the new column types.

     v1 v2       v3 v4   
  <dbl> <chr> <dbl> <chr>
1 0.974 j      1.09 J   

Data

# Sample data borrowed from @joran
d <- data.frame(v1 = runif(10), v2 = letters[1:10], 
                v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)

how to implement Interfaces in C++?

There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.

How to get full width in body element

You should set body and html to position:fixed;, and then set right:, left:, top:, and bottom: to 0;. That way, even if content overflows it will not extend past the limits of the viewport.

For example:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

JS Fiddle Example

Caveat: Using this method, if the user makes their window smaller, content will be cut off.

Node.js setting up environment specific configs to be used with everyauth

How about doing this in a much more elegant way with nodejs-config module.

This module is able to set configuration environment based on your computer's name. After that when you request a configuration you will get environment specific value.

For example lets assume your have two development machines named pc1 and pc2 and a production machine named pc3. When ever you request configuration values in your code in pc1 or pc2 you must get "development" environment configuration and in pc3 you must get "production" environment configuration. This can be achieved like this:

  1. Create a base configuration file in the config directory, lets say "app.json" and add required configurations to it.
  2. Now simply create folders within the config directory that matches your environment name, in this case "development" and "production".
  3. Next, create the configuration files you wish to override and specify the options for each environment at the environment directories(Notice that you do not have to specify every option that is in the base configuration file, but only the options you wish to override. The environment configuration files will "cascade" over the base files.).

Now create new config instance with following syntax.

var config = require('nodejs-config')(
   __dirname,  // an absolute path to your applications 'config' directory
   {
      development: ["pc1", "pc2"],
      production: ["pc3"],

   }
);

Now you can get any configuration value without worrying about the environment like this:

config.get('app').configurationKey;

Setting a div's height in HTML with CSS

I can think of 2 options

  1. Use javascript to resize the smaller column on page load.
  2. Fake the equal heights by setting the background-color for the column on the container <div/> instead (<div class="separator"/>) with repeat-y

How to delete multiple rows in SQL where id = (x to y)

You can use BETWEEN:

DELETE FROM table
where id between 163 and 265

RestSharp simple complete example

Changing

RestResponse response = client.Execute(request);

to

IRestResponse response = client.Execute(request);

worked for me.

How do you create a REST client for Java?

I used RestAssured most of the time to parse rest service response and test the services. Apart from Rest Assured, I used below libraries too to communicate with Resful services.

a. Jersey Rest Client

b. Spring RestTemplate

c. Apache HTTP Client

Pandas: rolling mean by time interval

visualize the rolling averages to see if it makes sense. I don't understand why sum was used when the rolling average was requested.

  df=pd.read_csv('poll.csv',parse_dates=['enddate'],dtype={'favorable':np.float,'unfavorable':np.float,'other':np.float})

  df.set_index('enddate')
  df=df.fillna(0)

 fig, axs = plt.subplots(figsize=(5,10))
 df.plot(x='enddate', ax=axs)
 plt.show()


 df.rolling(window=3,min_periods=3).mean().plot()
 plt.show()
 print("The larger the window coefficient the smoother the line will appear")
 print('The min_periods is the minimum number of observations in the window required to have a value')

 df.rolling(window=6,min_periods=3).mean().plot()
 plt.show()

Can I use complex HTML with Twitter Bootstrap's Tooltip?

This parameter is just about whether you are going to use complex html into the tooltip. Set it to true and then hit the html into the title attribute of the tag.

See this fiddle here - I've set the html attribute to true through the data-html="true" in the <a> tag and then just added in the html ad hoc as an example.

here-document gives 'unexpected end of file' error

Note one can also get this error if you do this;

while read line; do
  echo $line
done << somefile

Because << somefile should read < somefile in this case.

Object Dump JavaScript

Firebug + console.log(myObjectInstance)

socket.emit() vs. socket.send()

TL;DR:

socket.send(data, callback) is essentially equivalent to calling socket.emit('message', JSON.stringify(data), callback)

Without looking at the source code, I would assume that the send function is more efficient edit: for sending string messages, at least?

So yeah basically emit allows you to send objects, which is very handy.

Take this example with socket.emit:

sendMessage: function(type, message) {
    socket.emit('message', {
        type: type,
        message: message
    });
}

and for those keeping score at home, here is what it looks like using socket.send:

sendMessage: function(type, message) {
    socket.send(JSON.stringify({
        type: type,
        message: message
    }));
}

Calling javascript function in iframe

Instead of getting the frame from the document, try getting the frame from the window object.

in the above example change this:

if (typeof (document.all.resultFrame.Reset) == "function")
    document.all.resultFrame.Reset();
else
    alert("resultFrame.Reset NOT found");

to

if (typeof (window.frames[0].Reset) == "function")
    window.frames[0].Reset();
else
    alert("resultFrame.Reset NOT found");

the problem is that the scope of the javascript inside the iframe is not exposed through the DOM element for the iframe. only window objects contain the javascript scoping information for the frames.

Find object in list that has attribute equal to some value (that meets any condition)

Old question but I use this quite frequently (for version 3.8). It's a bit of syntactic salt, but it has the advantage over the top answer in that you could retrieve a list of results (if there are multiple) by simply removing the [0] and it still defaults to None if nothing is found. For any other condition, simply change the x.value==value to what ever you're looking for.

_[0] if (_:=[x for x in test_list if x.value==value]) else None

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Alert handling in Selenium WebDriver (selenium 2) with Java

This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage

public void checkAlert() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
    } catch (Exception e) {
        //exception handling
    }
}

Notepad++ Multi editing

You can use the plugin ConyEdit to do this. With ConyEdit running in the background, follow these steps:

  1. use the command line cc.spc /\t/ a to split the text into columns and store them in a two-dim array.
  2. use the command cc.p to print, using the contents of the array.

Cross origin requests are only supported for HTTP but it's not cross-domain

If you’re working on a little front-end project and want to test it locally, you’d typically open it by pointing your local directory in the web browser, for instance entering file:///home/erick/mysuperproject/index.html in your URL bar. However, if your site is trying to load resources, even if they’re placed in your local directory, you might see warnings like this:

XMLHttpRequest cannot load file:///home/erick/mysuperproject/mylibrary.js. Cross origin requests are only supported for HTTP.

Chrome and other modern browsers have implemented security restrictions for Cross Origin Requests, which means that you cannot load anything through file:/// , you need to use http:// protocol at all times, even locally -due Same Origin policies. Simple as that, you’d need to mount a webserver to run your project there.

This is not the end of the world and there are many solutions out there, including the good old Apache (with VirtualHosts if you’re running several other projects), node.js with express, a Ruby server, etc. or simply modifying your browser settings.

However there’s a simpler and lightweight solution for the lazy ones. You can use Python’s SimpleHTTPServer. It comes already bundled with python so you don’t need to install or configure anything at all!

So cd to your project directory, for instance

1 cd /home/erick/mysuperproject and then simply use

1 python -m SimpleHTTPServer And that’s it, you’ll see this message in your terminal

1 Serving HTTP on 0.0.0.0 port 8000 ... So now you can go back to your browser and visit http://0.0.0.0:8000 with all your directory files served there. You can configure the port and other things, just see the documentation. But this simply trick works for me when I’m in a rush to test a new library or work out a new idea.

There you go, happy coding!

EDIT: In Python 3+, SimpleHTTPServer has been replaced with http.server. So In Python 3.3, for example, the following command is equivalent:

python -m http.server 8000

All possible array initialization syntaxes

These are the current declaration and initialization methods for a simple array.

    string[] array = new string[3];
    string[] array2 = new string[] { "1", "2" ,"3" };
    string[] array3 = { "1", "2" ,"3" };
    string[] array4 = new[] { "1", "2" ,"3" };

Usage of @see in JavaDoc?

@see is useful for information about related methods/classes in an API. It will produce a link to the referenced method/code on the documentation. Use it when there is related code that might help the user understand how to use the API.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

For those who are getting the error as:

I/O error on POST request for "anothermachine:31112/url/path";: class path 
resource [fileName.csv] cannot be resolved to URL because it does not exist.

It can be resolved by using the

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));

If the file is not present in the classpath, and an absolute path is required.

Parsing command-line arguments in C

This is my favourite way of doing the command line, especially, but definitely not only when efficiency is an issue. It might seem overkill, but I think there are few disadvantages to this overkill.

Use gperf for efficient C/C++ command line processing

Disadvantages:

  • You have to run a separate tool first to generate the code for a hash table in C/C++
  • No support for specific command line interfaces. For example the posix shorthand system "-xyz" declaring multiple options with one dash would be hard to implement.

Advantages:

  • Your command line options are stored separately from your C++ code (in a separate configuration file, which doesn't need to be read at runtime, only at compile time).
  • All you have in your code is exactly one switch (switching on enum values) to figure out which option you have
  • Efficiency is O(n) where n is the number of options on the command line and the number of possible options is irrelevant. The slowest part is possibly the implementation of the switch (sometimes compilers tend to implement them as if else blocks, reducing their efficiency, albeit this is unlikely if you choose contiguous values, see: this article on switch efficiency )
  • The memory allocated to store the keywords is precisely large enough for the keyword set and no larger.
  • Also works in C

Using an IDE like eclipse you can probably automate the process of running gperf, so the only thing you would have to do is add an option to the config file and to your switch statement and press build...

I used a batch file to run gperf and do some cleanup and add include guards with sed (on the gperf generated .hpp file)...

So, extremely concise and clean code within your software and one auto-generated hash table file that you don't really need to change manually. I doubt if boost::program_options actually would beat that even without efficiency as a priority.

Jenkins Slave port number for firewall

We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").

TCP
49187 - Fixed jnlp port
8080 - jenkins http port

Other ports needed to launch slave as a windows service

TCP
135 
139 
445

UDP
137
138

Retina displays, high-res background images

If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200 and have two icons in top row and two icon in bottom row. So, it's four quadrants.

.sprite-of-icons {
  background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
  background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}

.sp-logo-1 { background-position: 0 0; }

/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }

Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.


Another handy SCSS mixin solution by Ryan Benhase.

/****************************
 HIGH PPI DISPLAY BACKGROUNDS
*****************************/

@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {

  $at1x_path: "#{$path}.#{$ext}";
  $at2x_path: "#{$path}@2x.#{$ext}";

  background-image: url("#{$at1x_path}");
  background-size: $w $h;
  background-position: $pos;
  background-repeat: $repeat;

  @media all and (-webkit-min-device-pixel-ratio : 1.5),
  all and (-o-min-device-pixel-ratio: 3/2),
  all and (min--moz-device-pixel-ratio: 1.5),
  all and (min-device-pixel-ratio: 1.5) {
    background-image: url("#{$at2x_path}"); 
  }
}

div.background {
  @include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}

For more info about above mixin READ HERE.

How to sort by Date with DataTables jquery plugin?

Just in case someone is having trouble where they have blank spaces either in the date values or in cells, you will have to handle those bits. Sometimes an empty space is not handled by trim function coming from html it's like "$nbsp;". If you don't handle these, your sorting will not work properly and will break where ever there is a blank space.

I got this bit of code from jquery extensions here too and changed it a little bit to suit my requirement. You should do the same:) cheers!

function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

jQuery.fn.dataTableExt.oSort['uk-date-time-asc'] = function(a, b) {
    if (trim(a) != '' && a!="&nbsp;") {
        if (a.indexOf(' ') == -1) {
            var frDatea = trim(a).split(' ');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
        }
        else {
            var frDatea = trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        }
    } else {
        var x = 10000000; // = l'an 1000 ...
    }

    if (trim(b) != '' && b!="&nbsp;") {
        if (b.indexOf(' ') == -1) {
            var frDateb = trim(b).split(' ');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
        }
        else {
            var frDateb = trim(b).split(' ');
            var frTimeb = frDateb[1].split(':');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
        }
    } else {
        var y = 10000000;
    }
    var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
    return z;
};

jQuery.fn.dataTableExt.oSort['uk-date-time-desc'] = function(a, b) {
    if (trim(a) != '' && a!="&nbsp;") {
        if (a.indexOf(' ') == -1) {
            var frDatea = trim(a).split(' ');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
        }
        else {
            var frDatea = trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        }
    } else {
        var x = 10000000;
    }

    if (trim(b) != '' && b!="&nbsp;") {
        if (b.indexOf(' ') == -1) {
            var frDateb = trim(b).split(' ');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
        }
        else {
            var frDateb = trim(b).split(' ');
            var frTimeb = frDateb[1].split(':');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
        }
    } else {
        var y = 10000000;
    }

    var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));
    return z;
};

Deadly CORS when http://localhost is the origin

I think my solution to this might be the simplest. On my development machine, I added a fake domain in my hosts file similar to http://myfakedomain.notarealtld and set it to 127.0.0.1. Then I changed my server's CORS configuration (in my case an S3 bucket) to allow that domain. That way I can use Chrome on localhost and it works great.

Make sure your CORS configuration takes into account the entire hostname with port, ie. http://myfakedomain.notarealtld:3000

You can modify your hosts file easily on Linux, Mac, and Windows.

How to get root access on Android emulator?

Use android image without PlayServices then you'll be able to run add root and access whatever you want.

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

BSTR to std::string (std::wstring) and vice versa

Simply pass the BSTR directly to the wstring constructor, it is compatible with a wchar_t*:

BSTR btest = SysAllocString(L"Test");
assert(btest != NULL);
std::wstring wtest(btest);
assert(0 == wcscmp(wtest.c_str(), btest));

Converting BSTR to std::string requires a conversion to char* first. That's lossy since BSTR stores a utf-16 encoded Unicode string. Unless you want to encode in utf-8. You'll find helper methods to do this, as well as manipulate the resulting string, in the ICU library.

"Please provide a valid cache path" error in laravel

Try the following:

create these folders under storage/framework:

  • sessions
  • views
  • cache

Now it should work

Unzip files programmatically in .net

You can do it all within .NET 3.5 using DeflateStream. The thing lacking in .NET 3.5 is the ability to process the file header sections that are used to organize the zipped files. PKWare has published this information, which you can use to process the zip file after you create the structures that are used. It is not particularly onerous, and it a good practice in tool building without using 3rd party code.

It isn't a one line answer, but it is completely doable if you are willing and able to take the time yourself. I wrote a class to do this in a couple of hours and what I got from that is the ability to zip and unzip files using .NET 3.5 only.

What's the common practice for enums in Python?

I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.

class enumSeason():
    Spring = 0
    Summer = 1
    Fall = 2
    Winter = 3
    def __init__(self, Type):
        self.value = Type
    def __str__(self):
        if self.value == enumSeason.Spring:
            return 'Spring'
        if self.value == enumSeason.Summer:
            return 'Summer'
        if self.value == enumSeason.Fall:
            return 'Fall'
        if self.value == enumSeason.Winter:
            return 'Winter'
    def __eq__(self,y):
       return self.value==y.value

Usage:

>>> s = enumSeason(enumSeason.Spring)

>>> print(s)

Spring

How to set up googleTest as a shared library on Linux

Just in case somebody else gets in the same situation like me yesterday (2016-06-22) and also does not succeed with the already posted approaches - on Lubuntu 14.04 it worked for me using the following chain of commands:

git clone https://github.com/google/googletest
cd googletest
cmake -DBUILD_SHARED_LIBS=ON .
make
cd googlemock
sudo cp ./libgmock_main.so ./gtest/libgtest.so gtest/libgtest_main.so ./libgmock.so /usr/lib/
sudo ldconfig

How to compile multiple java source files in command line

Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java 

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class

Adding an onclicklistener to listview (android)

listView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = prestListView.getItemAtPosition(position);
        prestationEco str = (prestationEco)o; //As you are using Default String Adapter
        Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
    }
});

Short description of the scoping rules?

Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.)

LEGB Rule

  • Local — Names assigned in any way within a function (def or lambda), and not declared global in that function

  • Enclosing-function — Names assigned in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer

  • Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file

  • Built-in (Python) — Names preassigned in the built-in names module: open, range, SyntaxError, etc

So, in the case of

code1
class Foo:
    code2
    def spam():
        code3
        for code4:
            code5
            x()

The for loop does not have its own namespace. In LEGB order, the scopes would be

  • L: Local in def spam (in code3, code4, and code5)
  • E: Any enclosing functions (if the whole example were in another def)
  • G: Were there any x declared globally in the module (in code1)?
  • B: Any builtin x in Python.

x will never be found in code2 (even in cases where you might expect it would, see Antti's answer or here).

How do you use the "WITH" clause in MySQL?

I followed the link shared by lisachenko and found another link to this blog: http://guilhembichot.blogspot.co.uk/2013/11/with-recursive-and-mysql.html

The post lays out ways of emulating the 2 uses of SQL WITH. Really good explanation on how these work to do a similar query as SQL WITH.

1) Use WITH so you don't have to perform the same sub query multiple times

CREATE VIEW D AS (SELECT YEAR, SUM(SALES) AS S FROM T1 GROUP BY YEAR);
SELECT D1.YEAR, (CASE WHEN D1.S>D2.S THEN 'INCREASE' ELSE 'DECREASE' END) AS TREND
FROM
 D AS D1,
 D AS D2
WHERE D1.YEAR = D2.YEAR-1;
DROP VIEW D;

2) Recursive queries can be done with a stored procedure that makes the call similar to a recursive with query.

CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
  SELECT ID, NAME, MANAGER_ID, 0 AS REPORTS
  FROM EMPLOYEES
  WHERE ID NOT IN (SELECT MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IS NOT NULL)
",
"
  SELECT M.ID, M.NAME, M.MANAGER_ID, SUM(1+E.REPORTS) AS REPORTS
  FROM EMPLOYEES M JOIN EMPLOYEES_EXTENDED E ON M.ID=E.MANAGER_ID
  GROUP BY M.ID, M.NAME, M.MANAGER_ID
",
"SELECT * FROM EMPLOYEES_EXTENDED",
0,
""
);

And this is the code or the stored procedure

# Usage: the standard syntax:
#   WITH RECURSIVE recursive_table AS
#    (initial_SELECT
#     UNION ALL
#     recursive_SELECT)
#   final_SELECT;
# should be translated by you to 
# CALL WITH_EMULATOR(recursive_table, initial_SELECT, recursive_SELECT,
#                    final_SELECT, 0, "").

# ALGORITHM:
# 1) we have an initial table T0 (actual name is an argument
# "recursive_table"), we fill it with result of initial_SELECT.
# 2) We have a union table U, initially empty.
# 3) Loop:
#   add rows of T0 to U,
#   run recursive_SELECT based on T0 and put result into table T1,
#   if T1 is empty
#      then leave loop,
#      else swap T0 and T1 (renaming) and empty T1
# 4) Drop T0, T1
# 5) Rename U to T0
# 6) run final select, send relult to client

# This is for *one* recursive table.
# It would be possible to write a SP creating multiple recursive tables.

delimiter |

CREATE PROCEDURE WITH_EMULATOR(
recursive_table varchar(100), # name of recursive table
initial_SELECT varchar(65530), # seed a.k.a. anchor
recursive_SELECT varchar(65530), # recursive member
final_SELECT varchar(65530), # final SELECT on UNION result
max_recursion int unsigned, # safety against infinite loop, use 0 for default
create_table_options varchar(65530) # you can add CREATE-TABLE-time options
# to your recursive_table, to speed up initial/recursive/final SELECTs; example:
# "(KEY(some_column)) ENGINE=MEMORY"
)

BEGIN
  declare new_rows int unsigned;
  declare show_progress int default 0; # set to 1 to trace/debug execution
  declare recursive_table_next varchar(120);
  declare recursive_table_union varchar(120);
  declare recursive_table_tmp varchar(120);
  set recursive_table_next  = concat(recursive_table, "_next");
  set recursive_table_union = concat(recursive_table, "_union");
  set recursive_table_tmp   = concat(recursive_table, "_tmp"); 
  # Cleanup any previous failed runs
  SET @str =
    CONCAT("DROP TEMPORARY TABLE IF EXISTS ", recursive_table, ",",
    recursive_table_next, ",", recursive_table_union,
    ",", recursive_table_tmp);
  PREPARE stmt FROM @str;
  EXECUTE stmt; 
 # If you need to reference recursive_table more than
  # once in recursive_SELECT, remove the TEMPORARY word.
  SET @str = # create and fill T0
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table, " ",
    create_table_options, " AS ", initial_SELECT);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  SET @str = # create U
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table_union, " LIKE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  SET @str = # create T1
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table_next, " LIKE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  if max_recursion = 0 then
    set max_recursion = 100; # a default to protect the innocent
  end if;
  recursion: repeat
    # add T0 to U (this is always UNION ALL)
    SET @str =
      CONCAT("INSERT INTO ", recursive_table_union, " SELECT * FROM ", recursive_table);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we are done if max depth reached
    set max_recursion = max_recursion - 1;
    if not max_recursion then
      if show_progress then
        select concat("max recursion exceeded");
      end if;
      leave recursion;
    end if;
    # fill T1 by applying the recursive SELECT on T0
    SET @str =
      CONCAT("INSERT INTO ", recursive_table_next, " ", recursive_SELECT);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we are done if no rows in T1
    select row_count() into new_rows;
    if show_progress then
      select concat(new_rows, " new rows found");
    end if;
    if not new_rows then
      leave recursion;
    end if;
    # Prepare next iteration:
    # T1 becomes T0, to be the source of next run of recursive_SELECT,
    # T0 is recycled to be T1.
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table, " RENAME ", recursive_table_tmp);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we use ALTER TABLE RENAME because RENAME TABLE does not support temp tables
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table_next, " RENAME ", recursive_table);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table_tmp, " RENAME ", recursive_table_next);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # empty T1
    SET @str =
      CONCAT("TRUNCATE TABLE ", recursive_table_next);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
  until 0 end repeat;
  # eliminate T0 and T1
  SET @str =
    CONCAT("DROP TEMPORARY TABLE ", recursive_table_next, ", ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # Final (output) SELECT uses recursive_table name
  SET @str =
    CONCAT("ALTER TABLE ", recursive_table_union, " RENAME ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # Run final SELECT on UNION
  SET @str = final_SELECT;
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # No temporary tables may survive:
  SET @str =
    CONCAT("DROP TEMPORARY TABLE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # We are done :-)
END|

delimiter ;

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

Check if table exists and if it doesn't exist, create it in SQL Server 2008

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE  TABLE_NAME = 'd020915'))
BEGIN
  declare @result int
  set @result=1
  select @result as result
END

How can change width of dropdown list?

This:

<select style="width: XXXpx;">

XXX = Any Number

Works great in Google Chrome v70.0.3538.110

Force IE8 Into IE7 Compatiblity Mode

its even simpler than that. Using HTML you can just add this metatag to your page (first thing on the page):

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

If you wanted to do it using.net, you just have to send your http request with that meta information in the header. This would require a page refresh to work though.

Also, you can look at a similar question here: Compatibility Mode in IE8 using VBScript

How to change an application icon programmatically in Android?

As mentioned before you need use <activity-alias> to change the application icon. To avoid killing the application after enabling appropriate activity-alias you need to do this after the application is killed. To find out if the application was killed you can use this method

  1. Create activity aliases in AndroidManifest.xml
<activity android:name=".ui.MainActivity"/>

<activity-alias
    android:name=".one"
    android:icon="@mipmap/ic_launcher_one"
    android:targetActivity=".ui.MainActivity"
    android:enabled="true">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>

<activity-alias
    android:name=".two"
    android:icon="@mipmap/ic_launcher_two"
    android:targetActivity=".ui.MainActivity"
    android:enabled="false">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>
  1. ?reate a service that will change the active activity-alias after killing the application. You need store the name of new active activity-alias somewhere (e.g. SharedPreferences)
class ChangeAppIconService: Service() {
    private val aliases = arrayOf(".one", ".two")

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onTaskRemoved(rootIntent: Intent?) {
        changeAppIcon()
        stopSelf()
    }

    fun changeAppIcon() {
        val sp = getSharedPreferences("appSettings", Context.MODE_PRIVATE)

        sp.getString("activeActivityAlias", ".one").let { aliasName ->
            if (!isAliasEnabled(aliasName)) {
                setAliasEnabled(aliasName)
            }
        }
    }

    private fun isAliasEnabled(aliasName: String): Boolean {
        return packageManager.getComponentEnabledSetting(
            ComponentName(
                this,
                "${BuildConfig.APPLICATION_ID}$aliasName"
            )
        ) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
    }

    private fun setAliasEnabled(aliasName: String) {
        aliases.forEach {
            val action = if (it == aliasName)
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            else
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                
            packageManager.setComponentEnabledSetting(
                ComponentName(
                    this,
                    "${BuildConfig.APPLICATION_ID}$aliasName"
                ),
                action,
                PackageManager.DONT_KILL_APP
            )
        }
    }
}
  1. Add service to AndroidManifest.xml
<service 
    android:name=".ChangeAppIconService"
    android:stopWithTask="false"
    />
  1. Start ChangeAppIconService in MainActivity.onCreate
class MainActivity: Activity {

    ...

    override fun onCreate(savedInstanceState: Bundle?) {
       ...

       startService(Intent(this, ChangeAppIconService::class.java))

       ...
    }

    ...

}

Why shouldn't I use "Hungarian Notation"?

If you don't know the type of a variable without being told, you probably shouldn't be messing with it anyways

The type might also not be that important. If you know what the methods do, you can figure out what is being done with the variable and then you'll what the program is doing

There may be times you want it; when type is important and the declaration isn't near or the type can't be inferred with ease. But it should never be seen as absolute

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

Important to know in what file it comes to this error (in you example it is META-INF/LICENSE.txt) , in my case it was in META-INF/LICENSE [without ".txt"], and then in the file META-INF/ASL2.0 so I added to my build.gradle this lines:

android {
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/ASL2.0'
    }
}

Very important (!) -> add the name of the file in the same style, that you see it in the error message: the text is case sensitive, and there is a difference between *.txt and *(without "txt").

Convert NSArray to NSString in Objective-C

The way I know is easy.

var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String

n is the inner position in the array This in SWIFT Language. It might work in Objective C

Stretch horizontal ul to fit width of div

People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">

How to prevent scrollbar from repositioning web page?

Simply setting the width of your container element like this will do the trick

width: 100vw;

This will make that element ignore the scrollbar and it works with background color or images.

SQLite error 'attempt to write a readonly database' during insert?

In summary, I've fixed the problem by putting the database file (* .db) in a subfolder.

  • The subfolder and the database file within it must be a member of the www-data group.
  • In the www-data group, you must have the right to write to the subfolder and the database file.

Laravel Eloquent - distinct() and count() not working properly together

try this

$ad->getcodes()->groupby('pid')->distinct()->count('pid')

check if a file is open in Python

None of the other provided examples would work for me when dealing with this specific issue with excel on windows 10. The only other option I could think of was to try and rename the file or directory containing the file temporarily, then rename it back.

import os

try: 
    os.rename('file.xls', 'tempfile.xls')
    os.rename('tempfile.xls', 'file.xls')
except OSError:
    print('File is still open.')

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Make sure you've copied the whole public key to authorized_keys; the ssh rsa prefix is necessary for the key to work.

Reimport a module in python while interactive

Actually, in Python 3 the module imp is marked as DEPRECATED. Well, at least that's true for 3.4.

Instead the reload function from the importlib module should be used:

https://docs.python.org/3/library/importlib.html#importlib.reload

But be aware that this library had some API-changes with the last two minor versions.

How to delete a selected DataGridViewRow and update a connected database table?

have a look this way:

if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
  foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
  {
      bindingSource1.RemoveAt(item.Index);
  }
      adapter.Update(ds);
 }

Which command do I use to generate the build of a Vue app?

I think you've created your project like this:

vue init webpack myproject

Well, now you can run

npm run build

Copy index.html and /dist/ folder into your website root directory. Done.

sqlplus how to find details of the currently connected database session

select sys_context('USERENV','INSTANCE_NAME') from dual;

&

select instance_name from v$instance;

will give you the instance name. You can also use select * from global_name; to view the global name of the instance.

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

Read environment variables in Node.js

You can use env package to manage your environment variables per project:

  • Create a .env file under the project directory and put all of your variables there.
  • Add this line in the top of your application entry file:
    require('dotenv').config();

Done. Now you can access your environment variables with process.env.ENV_NAME.

TypeError: 'dict_keys' object does not support indexing

Clearly you're passing in d.keys() to your shuffle function. Probably this was written with python2.x (when d.keys() returned a list). With python3.x, d.keys() returns a dict_keys object which behaves a lot more like a set than a list. As such, it can't be indexed.

The solution is to pass list(d.keys()) (or simply list(d)) to shuffle.

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

How to create UILabel programmatically using Swift?

override func viewDidLoad()
{
  super.viewDidLoad()
  var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
  label.center = CGPointMake(160, 284)
  label.textAlignment = NSTextAlignment.Center
  label.text = "I'm a test label"
  self.view.addSubview(label)
}  

Swift 3.0+ Update:

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "I'm a test label"
self.view.addSubview(label)

Deleting a local branch with Git

Ran into this today and switching to another branch didn't help. It turned out that somehow my worktree information had gotten corrupted and there was a worktree with the same folder path as my working directory with a HEAD pointing at the branch (git worktree list). I deleted the .git/worktree/ folder that was referencing it and git branch -d worked.

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

If you put Datetime nullable like DateTime? in your model it doesn't throw exception.

I solved the problem like this in my case.

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

Visual C++: How to disable specific linker warnings?

(For the record and before the thread disappears on the msdn forums) You can't disable the warning (at least under VS2010) because it is on the list of the warnings that can't be disabled (so /wd4099 will not work), but what you can do instead is patch link.exe (usually C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.exe) to remove it from said list . Sounds like a jackhammer, i know. It works though.

For instance, if you want to remove the warning for 4099, open link.exe with an hex editor, goto line 15A0 which reads 03 10 (little endian for 4099) and replace it with FF 00 (which does not exist.)

Convert string to float?

Use Float.valueOf(String) to do the conversion.

The difference between valueOf() and parseFloat() is only the return. Use the former if you want a Float (object) and the latter if you want the float number.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

What is the standard way to add N seconds to datetime.time in Python?

If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. When you go past midnight, it wraps around zero. Now, "What time will it be, 24 hours from now" has a lot of corner cases, including daylight savings time, leap seconds, historical timezone changes, and so on. But sometimes you really do need the simple case, and that's what this will do.

Your example would be written:

>>> import datetime
>>> import nptime
>>> nptime.nptime(11, 34, 59) + datetime.timedelta(0, 3)
nptime(11, 35, 2)

nptime inherits from datetime.time, so any of those methods should be usable, too.

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

What is the difference between x86 and x64

The difference is that Java binaries compiled as x86 (32-bit) or x64 (64-bit) applications respectively.

On a 64-bit Windows you can use either version, since x86 will run in WOW64 mode. On a 32-bit Windows you should use only x86 obviously.

For a Linux you should select appropriate type x86 for 32-bit OS, and x64 for 64-bit OS.

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

Can an Android App connect directly to an online mysql database

Yes you can do that.

Materials you need:

  1. WebServer
  2. A Database Stored in the webserver
  3. And a little bit android knowledge :)
  4. Webservices (json ,Xml...etc) whatever you are comfortable with

1. First set the internet permissions in your manifest file

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

2. Make a class to make an HTTPRequest from the server (i am using json parisng to get the values)

for eg:

    public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

3. In your MainActivity Make an object of the class JsonFunctions and pass the url as an argument from where you want to get the data

eg:

JSONObject jsonobject;

jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");

4. And then finally read the jsontags and store the values in an arraylist and later show it in listview if you want

and if you have any problem you can follow this blog he gives excellent android tutorials AndroidHive

Since the above answer i wrote was long back and now HttpClient, HttpPost,HttpEntity have been removed in Api 23. You can use the below code in the build.gradle(app-level) to still continue using org.apache.httpin your project.

android {
    useLibrary 'org.apache.http.legacy'
    signingConfigs {}
    buildTypes {}
}

or You can use HttpURLConnection like below to get your response from server

public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
    URL u = new URL(url);
    c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(timeout);
    c.setReadTimeout(timeout);
    c.connect();
    int status = c.getResponseCode();

    switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            br.close();
            return sb.toString();
    }

} catch (MalformedURLException ex) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
   if (c != null) {
      try {
          c.disconnect();
      } catch (Exception ex) {
         Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
      }
   }
}
return null;

}

or You can use 3rd party Library like Volley, Retrofit to call the webservice api and get the response and later parse it with using FasterXML-jackson, google-gson.

Apply CSS Style to child elements

If you want to add style in all child and no specification for html tag then use it.

Parent tag div.parent

child tag inside the div.parent like <a>, <input>, <label> etc.

code : div.parent * {color: #045123!important;}

You can also remove important, its not required

What are CN, OU, DC in an LDAP search?

I want to add somethings different from definitions of words. Most of them will be visual.

Technically, LDAP is just a protocol that defines the method by which directory data is accessed.Necessarily, it also defines and describes how data is represented in the directory service

Data is represented in an LDAP system as a hierarchy of objects, each of which is called an entry. The resulting tree structure is called a Directory Information Tree (DIT). The top of the tree is commonly called the root (a.k.a base or the suffix).the Data (Information) Model

To navigate the DIT we can define a path (a DN) to the place where our data is (cn=DEV-India,ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com will take us to a unique entry) or we can define a path (a DN) to where we think our data is (say, ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com) then search for the attribute=value or multiple attribute=value pairs to find our target entry (or entries).

enter image description here

If you want to get more depth information, you visit here

A method to reverse effect of java String.split()?

I wrote this one:

public static String join(Collection<String> col, String delim) {
    StringBuilder sb = new StringBuilder();
    Iterator<String> iter = col.iterator();
    if (iter.hasNext())
        sb.append(iter.next());
    while (iter.hasNext()) {
        sb.append(delim);
        sb.append(iter.next());
    }
    return sb.toString();
}

Collection isn't supported by JSP, so for TLD I wrote:

public static String join(List<?> list, String delim) {
    int len = list.size();
    if (len == 0)
        return "";
    StringBuilder sb = new StringBuilder(list.get(0).toString());
    for (int i = 1; i < len; i++) {
        sb.append(delim);
        sb.append(list.get(i).toString());
    }
    return sb.toString();
}

and put to .tld file:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
    <function>
        <name>join</name>
        <function-class>com.core.util.ReportUtil</function-class>
        <function-signature>java.lang.String join(java.util.List, java.lang.String)</function-signature>
    </function>
</taglib>

and use it in JSP files as:

<%@taglib prefix="funnyFmt" uri="tag:com.core.util,2013:funnyFmt"%>
${funnyFmt:join(books, ", ")}

How to use awk sort by column 3

How about just sort.

sort -t, -nk3 user.csv

where

  • -t, - defines your delimiter as ,.

  • -n - gives you numerical sort. Added since you added it in your attempt. If your user field is text only then you dont need it.

  • -k3 - defines the field (key). user is the third field.

Using ping in c#

Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress), which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation namespace contains a class called PingReply that has properties designed to translate the ICMP response and deliver useful information about the pinged server such as:

  • IPStatus: Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply.
  • IPAddress: Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message.
  • RoundtripTime (System.Int64): Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request.
  • PingOptions (System.Byte[]): Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message.

The following is a simple example using WinForms to demonstrate how ping works in c#. By providing a valid IP address in textBox1 and clicking button1, we are creating an instance of the Ping class, a local variable PingReply, and a string to store the IP or URL address. We assign PingReply to the ping Send method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success status. Finally, we extract from PingReply the information we need to display for the user, which is described above.

    using System;
    using System.Net.NetworkInformation;
    using System.Windows.Forms;

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

            private void button1_Click(object sender, EventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s;
                s = textBox1.Text;
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                {
                    lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
                }
            }

            private void textBox1_Validated(object sender, EventArgs e)
            {
                if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
                {
                    MessageBox.Show("Please use valid IP or web address!!");
                }
            }
        }
    }

Best way to select random rows PostgreSQL

Add a column called r with type serial. Index r.

Assume we have 200,000 rows, we are going to generate a random number n, where 0 < n <= 200, 000.

Select rows with r > n, sort them ASC and select the smallest one.

Code:

select * from YOUR_TABLE 
where r > (
    select (
        select reltuples::bigint AS estimate
        from   pg_class
        where  oid = 'public.YOUR_TABLE'::regclass) * random()
    )
order by r asc limit(1);

The code is self-explanatory. The subquery in the middle is used to quickly estimate the table row counts from https://stackoverflow.com/a/7945274/1271094 .

In application level you need to execute the statement again if n > the number of rows or need to select multiple rows.

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Fastest way to copy a file in Node.js

For fast copies you should use the fs.constants.COPYFILE_FICLONE flag. It allows (for filesystems that support this) to not actually copy the content of the file. Just a new file entry is created, but it points to a Copy-on-Write "clone" of the source file.

To do nothing/less is the fastest way of doing something ;)

https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_flags_callback

let fs = require("fs");

fs.copyFile(
  "source.txt",
  "destination.txt",
  fs.constants.COPYFILE_FICLONE,
  (err) => {
    if (err) {
      // TODO: handle error
      console.log("error");
    }
    console.log("success");
  }
);

Using promises instead:

let fs = require("fs");
let util = require("util");
let copyFile = util.promisify(fs.copyFile);


copyFile(
  "source.txt",
  "destination.txt",
  fs.constants.COPYFILE_FICLONE
)
  .catch(() => console.log("error"))
  .then(() => console.log("success"));

how to get all markers on google-maps-v3

For an specific cluster use: getMarkers() Gets the array of markers in the clusterer.

For all the markers in the map use: getTotalMarkers() Gets the array of markers in the clusterer.

Rounding integer division (instead of truncating)

Here's my solution. I like it because I find it more readable and because it has no branching (neither ifs nor ternaries).

int32_t divide(int32_t a, int32_t b) {
  int32_t resultIsNegative = ((a ^ b) & 0x80000000) >> 31;
  int32_t sign = resultIsNegative*-2+1;
  return (a + (b / 2 * sign)) / b;
}

Full test program that illustrates intended behaviour:

#include <stdint.h>
#include <assert.h>

int32_t divide(int32_t a, int32_t b) {
  int32_t resultIsNegative = ((a ^ b) & 0x80000000) >> 31;
  int32_t sign = resultIsNegative*-2+1;
  return (a + (b / 2 * sign)) / b;
}

int main() {
  assert(divide(0, 3) == 0);

  assert(divide(1, 3) == 0);
  assert(divide(5, 3) == 2);

  assert(divide(-1, 3) == 0);
  assert(divide(-5, 3) == -2);

  assert(divide(1, -3) == 0);
  assert(divide(5, -3) == -2);

  assert(divide(-1, -3) == 0);
  assert(divide(-5, -3) == 2);
}

How do I call a specific Java method on a click/submit event of a specific button in JSP?

If you have web.xml then

HTML/JSP

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
</form>

web.xml

<servlet>
        <display-name>Servlet Name</display-name>
        <servlet-name>myservlet</servlet-name>
        <servlet-class>package.SomeController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/myservlet</url-pattern>
</servlet-mapping>

Java SomeController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Write your code below");
}

react-router getting this.props.location in child components

(Update) V5.1 & Hooks (Requires React >= 16.8)

You can use useHistory, useLocation and useRouteMatch in your component to get match, history and location .

const Child = () => {
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch("write-the-url-you-want-to-match-here");

  return (
    <div>{location.pathname}</div>
  )
}

export default Child

(Update) V4 & V5

You can use withRouter HOC in order to inject match, history and location in your component props.

class Child extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

(Update) V3

You can use withRouter HOC in order to inject router, params, location, routes in your component props.

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

Original answer

If you don't want to use the props, you can use the context as described in React Router documentation

First, you have to set up your childContextTypes and getChildContext

class App extends React.Component{

  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

Then, you will be able to access to the location object in your child components using the context like this

class Child extends React.Component{

   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }

}

Child.contextTypes = {
    location: React.PropTypes.object
 }

How to run a PowerShell script without displaying a window?

I was having this problem when running from c#, on Windows 7, the "Interactive Services Detection" service was popping up when running a hidden powershell window as the SYSTEM account.

Using the "CreateNoWindow" parameter prevented the ISD service popping up it's warning.

process.StartInfo = new ProcessStartInfo("powershell.exe",
    String.Format(@" -NoProfile -ExecutionPolicy unrestricted -encodedCommand ""{0}""",encodedCommand))
{
   WorkingDirectory = executablePath,
   UseShellExecute = false,
   CreateNoWindow = true
};

Maximum value of maxRequestLength?

As per MSDN the default value is 4096 KB (4 MB).

UPDATE

As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

Increment a database field by 1

This is more a footnote to a number of the answers above which suggest the use of ON DUPLICATE KEY UPDATE, BEWARE that this is NOT always replication safe, so if you ever plan on growing beyond a single server, you'll want to avoid this and use two queries, one to verify the existence, and then a second to either UPDATE when a row exists, or INSERT when it does not.

Why would a JavaScript variable start with a dollar sign?

Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.

For example, I would define:

var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself

I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

Filtering DataSet

You can use DataTable.Select:

var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";

// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);  

Or you can use DataView:

ds.Tables[0].DefaultView.RowFilter = strExpr;  

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

deleting folder from java

If you use Apache Commons IO it's a one-liner:

FileUtils.deleteDirectory(dir);

See FileUtils.deleteDirectory()


Guava used to support similar functionality:

Files.deleteRecursively(dir);

This has been removed from Guava several releases ago.


While the above version is very simple, it is also pretty dangerous, as it makes a lot of assumptions without telling you. So while it may be safe in most cases, I prefer the "official way" to do it (since Java 7):

public static void deleteFileOrFolder(final Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
      throws IOException {
      Files.delete(file);
      return CONTINUE;
    }

    @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) {
      return handleException(e);
    }

    private FileVisitResult handleException(final IOException e) {
      e.printStackTrace(); // replace with more robust error handling
      return TERMINATE;
    }

    @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
      throws IOException {
      if(e!=null)return handleException(e);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};

Check if a given key already exists in a dictionary

You don't have to call keys:

if 'key1' in dict:
  print("blah")
else:
  print("boo")

That will be much faster as it uses the dictionary's hashing as opposed to doing a linear search, which calling keys would do.

How do I remove newlines from a text file?

I would do it with awk, e.g.

awk '/[0-9]+/ { a = a $0 ";" } END { print a }' file.txt

(a disadvantage is that a is "accumulated" in memory).

EDIT

Forgot about printf! So also

awk '/[0-9]+/ { printf "%s;", $0 }' file.txt

or likely better, what it was already given in the other ans using awk.

Execute bash script from URL

bash | curl http://your.url.here/script.txt

actual example:

juan@juan-MS-7808:~$ bash | curl https://raw.githubusercontent.com/JPHACKER2k18/markwe/master/testapp.sh


Oh, wow im alive


juan@juan-MS-7808:~$ 

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

When I drag files in, the "Add to targets" box seems to be un-ticked by default. If I leave it un-ticked then I have the problem described. Fix it by deleting the files then dragging them back in but making sure to tick "Add to targets". enter image description here

Base64 String throwing invalid character error

One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.