Programs & Examples On #Excel 2003

The Excel-2003 tag is used for referencing the Excel Version 2003 spreadsheet application from Microsoft. The version independent Tag is "excel". If your question is about VBA then also tag it VBA. If it is about an Excel formula or worksheet function, then tag it worksheet-function.

Conditional Formatting (IF not empty)

This worked for me:

=NOT(ISBLANK(A1))

I wanted a box around NOT Blank cells in an entire worksheet. Use the $A1 if you want the WHOLE ROW formatted based on the A1, B1, etc result.

Thanks!

Is there a macro to conditionally copy rows to another worksheet?

The way I would do this manually is:

  • Use Data - AutoFilter
  • Apply a custom filter based on a date range
  • Copy the filtered data to the relevant month sheet
  • Repeat for every month

Listed below is code to do this process via VBA.

It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.

    Sub SeperateData()

    Dim vMonthText As Variant
    Dim ExcelLastCell As Range
    Dim intMonth As Integer

   vMonthText = Array("January", "February", "March", "April", "May", _
 "June", "July", "August", "September", "October", "November", "December")

        ThisWorkbook.Worksheets("Sharepoint").Select
        Range("A1").Select

    RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
'Forces excel to determine the last cell, Usually only done on save
    Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
     Cells.SpecialCells(xlLastCell)
'Determines the last cell with data in it


        Selection.EntireColumn.Insert
        Range("A1").FormulaR1C1 = "Month No."
        Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
        Range("A2").Select
        Selection.Copy
        Range("A3:A" & ExcelLastCell.Row).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Calculate
    'Insert a helper column to determine the month number for the date

        For intMonth = 1 To 12
            Range("A1").CurrentRegion.Select
            Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
            Selection.Copy
            ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
            Range("A1").Select
            ActiveSheet.Paste
            Columns("A:A").Delete Shift:=xlToLeft
            Cells.Select
            Cells.EntireColumn.AutoFit
            Range("A1").Select
            ThisWorkbook.Worksheets("Sharepoint").Select
            Range("A1").Select
            Application.CutCopyMode = False
        Next intMonth
    'Filter the data to a particular month
    'Convert the month number to text
    'Copy the filtered data to the month sheet
    'Delete the helper column
    'Repeat for each month

        Selection.AutoFilter
        Columns("A:A").Delete Shift:=xlToLeft
 'Get rid of the auto-filter and delete the helper column

    End Sub

Excel: the Incredible Shrinking and Expanding Controls

Add this code to a .reg file. Double-click and and confirm. Restart Excel.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Excel\options]
"LegacyAnchorResize"=dword:00000001

[HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Common\Draw]
"UpdateDeviceInfoForEmf"=dword:00000001

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

Excel: VLOOKUP that returns true or false?

You can use:

=IF(ISERROR(VLOOKUP(lookup value,table array,column no,FALSE)),"FALSE","TRUE")

How to show current user name in a cell?

This displays the name of the current user:

Function Username() As String
    Username = Application.Username
End Function

The property Application.Username holds the name entered with the installation of MS Office.

Enter this formula in a cell:

=Username()

How do I auto size columns through the Excel interop objects?

This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.

 public static void AutoFitExcelSheets()
    {
        Microsoft.Office.Interop.Excel.Application _excel = null;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        try
        {
            string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
            _excel = new Microsoft.Office.Interop.Excel.Application();
            _excel.Visible = false;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            excelWorkbook = _excel.Workbooks.Open(ExcelPath,
                   0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                   true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
            {
                string Name = currentSheet.Name;
                Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
                Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
                excelCells.Columns.AutoFit();
            }
        }
        catch (Exception ex)
        {
            ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
        }
        finally
        {
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(excelWorkbook);
            releaseObject(_excel);
        }
    }

Loop through each row of a range in Excel

Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).

I frequently write code like this:

Sub arrayBuilder()

myarray = Range("A1:D4")

'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned

For i = 1 To UBound(myarray)

    For j = 1 To UBound(myarray, 2)

    Debug.Print (myarray(i, j))

    Next j

Next i

End Sub

Assigning ranges to variables is a very powerful way to manipulate data in VBA.

How to edit my Excel dropdown list?

The answers above will work for changing the values.

If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:

go to your 'Formulas' tab

choose "Name Manager"

a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.

Excel add one hour

=A1+TIME(1,0,0)

Although, maybe this should be posted on Super User.

Get User Selected Range

This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.

Sub test()
    Dim myString As String
    myString = Selection.Address
End Sub

POI setting Cell Background to a Custom Color

Slot free in NPOI excel indexedcolors from 57+

            Color selColor;

        var wb = new HSSFWorkbook();

        var sheet = wb.CreateSheet("NPOI");
        var style = wb.CreateCellStyle();
        var font = wb.CreateFont();
        var palette = wb.GetCustomPalette();

        short indexColor = 57; 
        palette.SetColorAtIndex(indexColor, (byte)selColor.R, (byte)selColor.G, (byte)selColor.B);

        font.Color = palette.GetColor(indexColor).Indexed;

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

Comparing two vectors in an if statement

all is one option:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

But you may have to watch out for recycling:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

The documentation for length says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all.

Show special characters in Unix while using 'less' Command

Now, sometimes you already have less open, and you can't use cat on it. For example, you did a | less, and you can't just reopen a file, as that's actually a stream.

If all you need is to identify end of line, one easy way is to search for the last character on the line: /.$. The search will highlight the last character, even if it is a blank, making it easy to identify it.

That will only help with the end of line case. If you need other special characters, you can use the cat -vet solution above with marks and pipe:

  • mark the top of the text you're interested in: ma
  • go to the bottom of the text you're interested in and mark it, as well: mb
  • go back to the mark a: 'a
  • pipe from a to b through cat -vet and view the result in another less command: |bcat -vet | less

This will open another less process, which shows the result of running cat -vet on the text that lies between marks a and b.

If you want the whole thing, instead, do g|$cat -vet | less, to go to the first line and filter all lines through cat.

The advantage of this method over less options is that it does not mess with the output you see on the screen.

One would think that eight years after this question was originally posted, less would have that feature... But I can't even see a feature request for it on https://github.com/gwsw/less/issues

Save Javascript objects in sessionStorage

This is a dynamic solution which works with all value types including objects :

class Session extends Map {
  set(id, value) {
    if (typeof value === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(id, value);
  }

  get(id) {
    const value = sessionStorage.getItem(id);
    try {
      return JSON.parse(value);
    } catch (e) {
      return value;
    }
  }
}

Then :

const session = new Session();

session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');

Return date as ddmmyyyy in SQL Server

CONVERT style 103 is dd/mm/yyyy. Then use the REPLACE function to eliminate the slashes.

SELECT REPLACE(CONVERT(CHAR(10), [MyDateTime], 103), '/', '')

How to iterate over the keys and values with ng-repeat in AngularJS?

Complete example here:-

<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="./bootstrap.min.css">
<script src="./bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>
<body ng-controller="myController">
    <table border='1'>
        <tr ng-repeat="(key,val) in collValues">
            <td ng-if="!hasChildren(val)">{{key}}</td>  
            <td ng-if="val === 'string'">
                <input type="text" name="{{key}}"></input>
            </td>
            <td ng-if="val === 'number'">
                <input type="number" name="{{key}}"></input>
            </td>
            <td ng-if="hasChildren(val)" td colspan='2'>
                <table border='1' ng-repeat="arrVal in val">
                    <tr ng-repeat="(key,val) in arrVal">
                        <td>{{key}}</td>    
                        <td ng-if="val === 'string'">
                            <input type="text" name="{{key}}"></input>
                        </td>
                        <td ng-if="val === 'number'">
                            <input type="number" name="{{key}}"></input>
                        </td>
                    </tr>
                </table>                
            </td>

        </tr>       
    </table>
</body>

<script type="text/javascript">

    var app = angular.module("dashboard",[]);
    app.controller("myController",function($scope){
        $scope.collValues = {
            'name':'string',
            'id':'string',
            'phone':'number',
            'depart':[
                    {
                        'depart':'string',
                        'name':'string' 
                    }
            ]   
        };

        $scope.hasChildren = function(bigL1) {
            return angular.isArray(bigL1);
} 
    });
</script>
</html>

how to check if a file is a directory or regular file in python?

An educational example from the stat documentation:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname)[ST_MODE]
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)

Prevent screen rotation on Android

The following attribute on the ACTIVITY in AndroidManifest.xml is all you need:

android:configChanges="orientation"

So, the full activity node would be:

<activity android:name="Activity1"
          android:icon="@drawable/icon"
          android:label="App Name"
          android:excludeFromRecents="true"
          android:configChanges="orientation">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

Sorting std::map using value

If you want to present the values in a map in sorted order, then copy the values from the map to vector and sort the vector.

Deserialize JSON with C#

Here is another site that will help you with all the code you need as long as you have a correctly formated JSON string available:

https://app.quicktype.io/

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

I routinely use INSERT IGNORE, and it sounds like exactly the kind of behavior you're looking for as well. As long as you know that rows which would cause index conflicts will not be inserted and you plan your program accordingly, it shouldn't cause any trouble.

Specify an SSH key for git push for a given domain

you most specified in the file config key ssh:

# Default GitHub user
Host one
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-one
 IdentitiesOnly yes

#two user
Host two
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-two
 IdentitiesOnly yes

Location Services not working in iOS 8

Before [locationManager startUpdatingLocation];, add an iOS8 location services request:

if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
    [locationManager requestAlwaysAuthorization];

Edit your app's Info.plist and add key NSLocationAlwaysUsageDescription with the string value that will be displayed to the user (for example, We do our best to preserve your battery life.)

If your app needs location services only while the app is open, replace:

requestAlwaysAuthorization with requestWhenInUseAuthorization and

NSLocationAlwaysUsageDescription with NSLocationWhenInUseUsageDescription.

How to retrieve SQL result column value using column name in Python?

selecting values from particular column:

import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
    #query execution
    cursor.execute(sql)
    #fetch all rows 
    rs = cursor.fetchall()
    #iterate through rows
    for i in rs:
        #converting set to list
        k=list(i)
        #taking the first element from the list and append it to the list
        l.append(k[0])
    db.commit()
except:
    db.rollback()
db.close()
print(l)

Load HTML file into WebView

The Accepted Answer is not working for me, This is what works for me

WebSettings webSetting = webView.getSettings();
    webSetting.setBuiltInZoomControls(true);
    webView1.setWebViewClient(new WebViewClient());

   webView.loadUrl("file:///android_asset/index.html");

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

How do I install soap extension?

They dont support it as in in they wont help you or be responsible for you hosing anything, but you can install custom extensions. To do so you need to first set up a local install of php 5, during that process you can compile in extensions you need or you can add them dynamically to the php.ini after the fact.

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

Convert list or numpy array of single element to float in python

np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead.

For example:

a = np.array([[0.6813]])
print(a.item())

gives:

0.6813

How to resize Image in Android?

resized = Bitmap.createScaledBitmap(yourImageBitmap,(int)(yourImageBitmap.getWidth()*0.9), (int)(yourBitmap.getHeight()*0.9), true);

Client on Node.js: Uncaught ReferenceError: require is not defined

I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.

The line

const {ipcRenderer} = require('electron')

throws the Uncaught ReferenceError: require is not defined

I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.

function createAddItemWindow() {

    // Create a new window
    addItemWindown = new BrowserWindow({
        width: 300,
        height: 200,
        title: 'Add Item',

        // The lines below solved the issue
        webPreferences: {
            nodeIntegration: true
        }
})}

That solved the issue for me. The solution was proposed here.

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The only difference is that CHARACTER VARYING is more human friendly than VARCHAR

Decode JSON with unknown structure

The issue I had is that sometimes I will need to get at a value that is deeply nested. Normally you would need to do a type assertion at each level, so I went ahead and just made a method that takes a map[string]interface{} and a string key, and returns the resulting map[string]interface{}.

The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:

package main
type Slice []interface{}
type Map map[string]interface{}

func (m Map) M(s string) Map {
   return m[s].(map[string]interface{})
}

func (m Map) A(s string) Slice {
   return m[s].([]interface{})
}

func (a Slice) M(n int) Map {
   return a[n].(map[string]interface{})
}

and example code:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "os"
)

func main() {
   o, e := os.Open("a.json")
   if e != nil {
      log.Fatal(e)
   }
   in_m := Map{}
   json.NewDecoder(o).Decode(&in_m)
   out_m := in_m.
      M("contents").
      M("sectionListRenderer").
      A("contents").
      M(0).
      M("musicShelfRenderer").
      A("contents").
      M(0).
      M("musicResponsiveListItemRenderer").
      M("navigationEndpoint").
      M("browseEndpoint")
   fmt.Println(out_m)
}

Clear data in MySQL table with PHP?

TRUNCATE TABLE `table`

unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer

DELETE FROM `table`

though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using

ALTER TABLE `table` AUTO_INCREMENT = value

will happen a lot faster.

How to call a stored procedure from Java and JPA

May be it's not the same for Sql Srver but for people using oracle and eclipslink it's working for me

ex: a procedure that have one IN param (type CHAR) and two OUT params (NUMBER & VARCHAR)

in the persistence.xml declare the persistence-unit :

<persistence-unit name="presistanceNameOfProc" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/DataSourceName</jta-data-source>
    <mapping-file>META-INF/eclipselink-orm.xml</mapping-file>
    <properties>
        <property name="eclipselink.logging.level" value="FINEST"/>
        <property name="eclipselink.logging.logger" value="DefaultLogger"/>
        <property name="eclipselink.weaving" value="static"/>
        <property name="eclipselink.ddl.table-creation-suffix" value="JPA_STORED_PROC" />
    </properties>
</persistence-unit>

and declare the structure of the proc in the eclipselink-orm.xml

<?xml version="1.0" encoding="UTF-8"?><entity-mappings version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd">
<named-stored-procedure-query name="PERSIST_PROC_NAME" procedure-name="name_of_proc" returns-result-set="false">
    <parameter direction="IN" name="in_param_char" query-parameter="in_param_char" type="Character"/>
    <parameter direction="OUT" name="out_param_int" query-parameter="out_param_int" type="Integer"/>
    <parameter direction="OUT" name="out_param_varchar" query-parameter="out_param_varchar" type="String"/>
</named-stored-procedure-query>

in the code you just have to call your proc like this :

try {
        final Query query = this.entityManager
                .createNamedQuery("PERSIST_PROC_NAME");
        query.setParameter("in_param_char", 'V'); 
        resultQuery = (Object[]) query.getSingleResult();

    } catch (final Exception ex) {
        LOGGER.log(ex);
        throw new TechnicalException(ex);
    }

to get the two output params :

Integer myInt = (Integer) resultQuery[0];
String myStr =  (String) resultQuery[1];

Open a new tab in the background?

As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.

For example in firefox preferences:

Firefox setup example

Notice the last option.

How do I make a newline after a twitter bootstrap element?

Using br elements is fine, and as long as you don't need a lot of space between elements, is actually a logical thing to do as anyone can read your code and understand what spacing logic you are using.

The alternative is to create a custom class for white space. In bootstrap 4 you can use

<div class="w-100"></div>

to make a blank row across the page, but this is no different to using the <br> tag. The downside to creating a custom class for white space is that it can be a pain to read for others who view your code. A custom class would also apply the same amount of white space each time you used it, so if you wanted different amounts of white space on the same page, then you would need to create several white space classes.

In most cases, it is just easier to use <br> or <div class="w-100"></div> for the sake of ease and readability. it doesn't look pretty, but it works.

Converting to upper and lower case in Java

/* This code is just for convert a single uppercase character to lowercase 
character & vice versa.................*/

/* This code is made without java library function, and also uses run time input...*/



import java.util.Scanner;

class CaseConvert {
char c;
void input(){
//@SuppressWarnings("resource")  //only eclipse users..
Scanner in =new Scanner(System.in);  //for Run time input
System.out.print("\n Enter Any Character :");
c=in.next().charAt(0);     // input a single character
}
void convert(){
if(c>=65 && c<=90){
    c=(char) (c+32);
    System.out.print("Converted to Lowercase :"+c);
}
else if(c>=97&&c<=122){
        c=(char) (c-32);
        System.out.print("Converted to Uppercase :"+c);
}
else
    System.out.println("invalid Character Entered  :" +c);

}


  public static void main(String[] args) {
    // TODO Auto-generated method stub
    CaseConvert obj=new CaseConvert();
    obj.input();
    obj.convert();
    }

}



/*OUTPUT..Enter Any Character :A Converted to Lowercase :a 
Enter Any Character :a Converted to Uppercase :A
Enter Any Character :+invalid Character Entered  :+*/

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

Reducing the gap between a bullet and text in a list item

To achieve the look I wanted, I made a div containing a basic UL and several LIs. I couldn't easily adjust the indent between the bullet and text with any of the suggested ideas above (technically possible, but not simple.) I just left the UL and LI without any listing feature (list-style-type: none) then adding a &bull; to the beginning of each line. It did give me a bit of trouble at first, it only displayed the first bullet, so I added a bullet character to the end of the first line, refreshed, then removed it and they all popped up. Just manually add a bullet HTML entity if you don't want a huge indent, add space HTML entities if you want more space :o I know it isn't the best method, but it worked for me.

How to print formatted BigDecimal values?

BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)

Unzip a file with php

PHP has its own inbuilt class that can be used to unzip or extracts contents from a zip file. The class is ZipArchive. Below is the simple and basic PHP code that will extract a zip file and place it in a specific directory:

<?php
$zip_obj = new ZipArchive;
$zip_obj->open('dummy.zip');
$zip_obj->extractTo('directory_name/sub_dir');
?>

If you want some advance features then below is the improved code that will check if the zip file exists or not:

<?php
$zip_obj = new ZipArchive;
if ($zip_obj->open('dummy.zip') === TRUE) {
   $zip_obj->extractTo('directory/sub_dir');
   echo "Zip exists and successfully extracted";
}
else {
   echo "This zip file does not exists";
}
?>

Source: How to unzip or extract zip files in PHP?

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

For checking if the shiftkey is pressed while clicking with the mouse, there is an exact property in the click event object: shiftKey (and also for ctrl and alt and meta key): https://www.w3schools.com/jsref/event_shiftkey.asp

So using jQuery:

$('#anchor').on('click', function (e) {
    if (e.shiftKey) {
        // your code
    }
});

Remove files from Git commit

Actually, I think a quicker and easier way is to use git rebase interactive mode.

git rebase -i head~1  

(or head~4, how ever far you want to go)

and then, instead of 'pick', use 'edit'. I did not realize how powerful 'edit' is.

https://www.youtube.com/watch?v=2dQosJaLN18

Hope you will find it helpful.

Count the number of occurrences of a string in a VARCHAR field?

This is the mysql function using the space technique (tested with mysql 5.0 + 5.5): CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32)) RETURNS INTEGER DETERMINISTIC RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );

Convert Pandas DataFrame to JSON format

To transform a dataFrame in a real json (not a string) I use:

    from io import StringIO
    import json
    import DataFrame

    buff=StringIO()
    #df is your DataFrame
    df.to_json(path_or_buf=buff,orient='records')
    dfJson=json.loads(buff)

How to open in default browser in C#

public static void GoToSite(string url)
{
     System.Diagnostics.Process.Start(url);
}

that should solve your problem

onSaveInstanceState () and onRestoreInstanceState ()

As a workaround, you could store a bundle with the data you want to maintain in the Intent you use to start activity A.

Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("bundle", theBundledData);
startActivity(intent);

Activity A would have to pass this back to Activity B. You would retrieve the intent in Activity B's onCreate method.

Intent intent = getIntent();
Bundle intentBundle;
if (intent != null)
    intentBundle = intent.getBundleExtra("bundle");
// Do something with the data.

Another idea is to create a repository class to store activity state and have each of your activities reference that class (possible using a singleton structure.) Though, doing so is probably more trouble than it's worth.

NoSql vs Relational database

Not all data is relational. For those situations, NoSQL can be helpful.

With that said, NoSQL stands for "Not Only SQL". It's not intended to knock SQL or supplant it.

SQL has several very big advantages:

  1. Strong mathematical basis.
  2. Declarative syntax.
  3. A well-known language in Structured Query Language (SQL).

Those haven't gone away.

It's a mistake to think about this as an either/or argument. NoSQL is an alternative that people need to consider when it fits, that's all.

Documents can be stored in non-relational databases, like CouchDB.

Maybe reading this will help.

MySQL Error 1215: Cannot add foreign key constraint

I can not find this error

CREATE TABLE RATING (

Riv_Id INT(5),
Mov_Id INT(10) DEFAULT 0,
Stars INT(5),
Rating_date DATE, 

PRIMARY KEY (Riv_Id, Mov_Id),

FOREIGN KEY (Riv_Id) REFERENCES REVIEWER(Reviewer_ID)
ON DELETE SET NULL ON UPDATE CASCADE,

FOREIGN KEY (Mov_Id) REFERENCES MOVIE(Movie_ID)
ON DELETE SET DEFAULT ON UPDATE CASCADE
)

Find length of 2D array Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

How do you get a timestamp in JavaScript?

Short & Snazzy:

+ new Date()

A unary operator like plus triggers the valueOf method in the Date object and it returns the timestamp (without any alteration).

Details:

On almost all current browsers you can use Date.now() to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).

You can easily make a shim for this, though:

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

To get the timestamp in seconds, you can use:

Math.floor(Date.now() / 1000)

Or alternatively you could use:

Date.now() / 1000 | 0

Which should be slightly faster, but also less readable (also see this answer).

I would recommend using Date.now() (with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:

new Date().getTime()

Which you can then convert to seconds like this:

Math.round(new Date().getTime()/1000)

And you can also use the valueOf method which we showed above:

new Date().valueOf()

Timestamp in Milliseconds

_x000D_
_x000D_
var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();_x000D_
_x000D_
console.log(timeStampInMs, Date.now());
_x000D_
_x000D_
_x000D_

How to set layout_weight attribute dynamically from code?

Use LinearLayout.LayoutParams:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);

EDIT: Ah, Erich's answer is easier!

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I just found a simple and reliable solution if you are using the system UI approach (https://developer.android.com/training/system-ui/immersive.html).

It works in the case when you are using View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, e.g. if you are using CoordinatorLayout.

It won't work for WindowManager.LayoutParams.FLAG_FULLSCREEN (The one you can also set in theme with android:windowFullscreen), but you can achieve similar effect with SYSTEM_UI_FLAG_LAYOUT_STABLE (which "has the same visual effect" according to the docs) and this solution should work again.

getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION /* If you want to hide navigation */
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE)

I've tested it on my device running Marshmallow.

The key is that soft keyboards are also one of the system windows (such as status bar and navigation bar), so the WindowInsets dispatched by system contains accurate and reliable information about it.

For the use case such as in DrawerLayout where we are trying to draw behind the status bar, We can create a layout that ignores only the top inset, and applies the bottom inset which accounts for the soft keyboard.

Here is my custom FrameLayout:

/**
 * Implements an effect similar to {@code android:fitsSystemWindows="true"} on Lollipop or higher,
 * except ignoring the top system window inset. {@code android:fitsSystemWindows="true"} does not
 * and should not be set on this layout.
 */
public class FitsSystemWindowsExceptTopFrameLayout extends FrameLayout {

    public FitsSystemWindowsExceptTopFrameLayout(Context context) {
        super(context);
    }

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(),
                    insets.getSystemWindowInsetBottom());
            return insets.replaceSystemWindowInsets(0, insets.getSystemWindowInsetTop(), 0, 0);
        } else {
            return super.onApplyWindowInsets(insets);
        }
    }
}

And to use it:

<com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Your original layout here -->
</com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout>

This should theoretically work for any device without insane modification, much better than any hack that tries to take a random 1/3 or 1/4 of screen size as reference.

(It requires API 16+, but I'm using fullscreen only on Lollipop+ for drawing behind the status bar so it's the best solution in this case.)

Any free WPF themes?

I bought a theme from www.xamltemplates.net. The themes ship with source code so you can tweak them. They also offer a free theme (source code included).

Keeping ASP.NET Session Open / Alive

Do you really need to keep the session (do you have data in it?) or is it enough to fake this by reinstantiating the session when a request comes in? If the first, use the method above. If the second, try something like using the Session_End event handler.

If you have Forms Authentication, then you get something in the Global.asax.cs like

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(formsCookie.Value);
if (ticket.Expired)
{
    Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
    FormsAuthentication.SignOut();
    ...             
     }
else
{   ...
    // renew ticket if old
    ticket = FormsAuthentication.RenewTicketIfOld(ticket);
    ...
     }

And you set the ticket lifetime much longer than the session lifetime. If you're not authenticating, or using a different authentication method, there are similar tricks. Microsoft TFS web interface and SharePoint seem to use these - the give away is that if you click a link on a stale page, you get authentication prompts in the popup window, but if you just use a command, it works.

git rebase fatal: Needed a single revision

The error occurs when your repository does not have the default branch set for the remote. You can use the git remote set-head command to modify the default branch, and thus be able to use the remote name instead of a specified branch in that remote.

To query the remote (in this case origin) for its HEAD (typically master), and set that as the default branch:

$ git remote set-head origin --auto

If you want to use a different default remote branch locally, you can specify that branch:

$ git remote set-head origin new-default

Once the default branch is set, you can use just the remote name in git rebase <remote> and any other commands instead of explicit <remote>/<branch>.

Behind the scenes, this command updates the reference in .git/refs/remotes/origin/HEAD.

$ cat .git/refs/remotes/origin/HEAD 
ref: refs/remotes/origin/master

See the git-remote man page for further details.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

You need to only depend on one major version of angular, so update all modules depending on angular 2.x :

  • update @angular/flex-layout to ^2.0.0-beta.9
  • update @angular/material to ^2.0.0-beta.12
  • update angularfire2 to ^4.0.0-rc.2
  • update zone.js to ^0.8.18
  • update webpack to ^3.8.1
  • add @angular/[email protected] (required for @angular/material)
  • replace angular2-google-maps by @agm/[email protected] (new name)

Matplotlib scatter plot legend

if you are using matplotlib version 3.1.1 or above, you can try:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)

results2

Can't connect to docker from docker-compose

If you started docker using sudo , then you should run docker-compose up with sudo Like: sudo docker-compose up

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

Unique device identification

I have following idea how you can deal with such Access Device ID (ADID):

Gen ADID

  • prepare web-page https://mypage.com/manager-login where trusted user e.g. Manager can login from device - that page should show button "Give access to this device"
  • when user press button, page send request to server to generate ADID
  • server gen ADID, store it on whitelist and return to page
  • then page store it in device localstorage
  • trusted user now logout.

Use device

  • Then other user e.g. Employee using same device go to https://mypage.com/statistics and page send to server request for statistics including parameter ADID (previous stored in localstorage)
  • server checks if the ADID is on the whitelist, and if yes then return data

In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.

You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.

In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.

UPDATE

Simpler approach based on links:

  • Manager login to system using any device and generate ONE-TIME USE LINK https://mypage.com/access-link/ZD34jse24Sfses3J (which works e.g. 24h).
  • Then manager send this link to employee (or someone else; e.g. by email) which put that link into device and server returns ADID to device which store it in Local Storage. After that link above stops working - so only the system and device know ADID
  • Then employee using this device can read data from https://mypage.com/statistics because it has ADID which is on servers whitelist

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

If you get errors trying to install mysqlclient with pip, you may lack the mysql dev library. Install it by running:

apt-get install libmysqlclient-dev

and try again to install mysqlclient:

pip install mysqlclient

Removing a non empty directory programmatically in C or C++

//======================================================
// Recursely Delete files using:
//   Gnome-Glib & C++11
//======================================================

#include <iostream>
#include <string>
#include <glib.h>
#include <glib/gstdio.h>

using namespace std;

int DirDelete(const string& path)
{
   const gchar*    p;
   GError*   gerr;
   GDir*     d;
   int       r;
   string    ps;
   string    path_i;
   cout << "open:" << path << "\n";
   d        = g_dir_open(path.c_str(), 0, &gerr);
   r        = -1;

   if (d) {
      r = 0;

      while (!r && (p=g_dir_read_name(d))) {
          ps = string{p};
          if (ps == "." || ps == "..") {
            continue;
          }

          path_i = path + string{"/"} + p;


          if (g_file_test(path_i.c_str(), G_FILE_TEST_IS_DIR) != 0) {
            cout << "recurse:" << path_i << "\n";
            r = DirDelete(path_i);
          }
          else {
            cout << "unlink:" << path_i << "\n";
            r = g_unlink(path_i.c_str());
          }
      }

      g_dir_close(d);
   }

   if (r == 0) {
      r = g_rmdir(path.c_str());
     cout << "rmdir:" << path << "\n";

   }

   return r;
}

laravel Eloquent ORM delete() method

Before delete , there are several methods in laravel.

User::find(1) and User::first() return an instance.

User::where('id',1)->get and User::all() return a collection of instance.

call delete on an model instance will returns true/false

$user=User::find(1);
$user->delete(); //returns true/false

call delete on a collection of instance will returns a number which represents the number of the records had been deleted

//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)

//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0)  ) 

Also there are other delete methods, you can call destroy as a model static method like below

$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted

One more thing ,if you are new to laravel ,you can use php artisan tinker to see the result, which is more efficient and then dd($result) , print_r($result);

How to create a new instance from a class object in Python

I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.

class k:
  pass

a = k()
k2 = a.__class__
a2 = k2()

At this point, a and a2 are both instances of the same class (class k).

What are DDL and DML?

In layman terms suppose you want to build a house, what do you do.

DDL i.e Data Definition Language

  1. Build from scratch
  2. Rennovate it
  3. Destroy the older one and recreate it from scratch

that is

  1. CREATE
  2. ALTER
  3. DROP & CREATE

DML i.e. Data Manipulation Language

People come/go inside/from your house

  1. SELECT
  2. DELETE
  3. UPDATE
  4. TRUNCATE

DCL i.e. Data Control Language

You want to control the people what part of the house they are allowed to access and kind of access.

  1. GRANT PERMISSION

Check time difference in Javascript

When i tried the difference between same time stamp it gave 0 Days 5 Hours 30 Minutes

so to get it exactly i have subtracted 5 hours and 30 min

function get_time_diff( datetime )
{
var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";

var datetime = new Date(datetime).getTime();
var now = new Date().getTime();

if( isNaN(datetime) )
{
    return "";
}

console.log( datetime + " " + now);

if (datetime < now) {
    var milisec_diff = now - datetime;
}else{
    var milisec_diff = datetime - now;
}

var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));

var date_diff = new Date( milisec_diff );

return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}

HMAC-SHA256 Algorithm for signature calculation

Here is my solution:

public static String encode(String key, String data) throws Exception {
  Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
  sha256_HMAC.init(secret_key);

  return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}

public static void main(String [] args) throws Exception {
  System.out.println(encode("key", "The quick brown fox jumps over the lazy dog"));
}

Or you can return the hash encoded in Base64:

Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes("UTF-8")));

The output in hex is as expected:

f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

What is a StackOverflowError?

StackOverflowError is to the stack as OutOfMemoryError is to the heap.

Unbounded recursive calls result in stack space being used up.

The following example produces StackOverflowError:

class  StackOverflowDemo
{
    public static void unboundedRecursiveCall() {
     unboundedRecursiveCall();
    }

    public static void main(String[] args) 
    {
        unboundedRecursiveCall();
    }
}

StackOverflowError is avoidable if recursive calls are bounded to prevent the aggregate total of incomplete in-memory calls (in bytes) from exceeding the stack size (in bytes).

JavaScript code to stop form submission

The following works as of now (tested in Chrome and Firefox):

<form onsubmit="event.preventDefault(); validateMyForm();">

Where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().

Why is $$ returning the same id as the parent process?

You can use one of the following.

  • $! is the PID of the last backgrounded process.
  • kill -0 $PID checks whether it's still running.
  • $$ is the PID of the current shell.

How to show imageView full screen on imageView click?

Actually there are three ways to enable full screnn, visit : https://developer.android.com/training/system-ui/immersive

but if you wanna get full screen when the activity is opened, just put this code in your_activity.java

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}

private void hideSystemUI() {
    // Enables regular immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
    // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            // Hide the nav bar and status bar
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

Windows Explorer "Command Prompt Here"

Almost the same as yours:

  • Alt+d, Ctrl+c
  • Win+r
  • cmd /K cd , Ctrl+v, ENTER

React won't load local images

src={"/images/resto.png"}

Using of src attribute in this way means, your image will be loaded from the absolute path "/images/resto.png" for your site. Images directory should be located at the root of your site. Example: http://www.example.com/images/resto.png

Reading Space separated input in python

For Python3:

a, b = list(map(str, input().split()))
v = int(b)

Image steganography that could survive jpeg compression

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

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

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

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

Why can't I reference my class library?

I deleted *.csproj.user ( resharper file) of my project, then, close all tabs and reopen it. After that I was able to compile my project and there was no resharper warnings.

Java: Static Class?

Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)

My $.02

equals vs Arrays.equals in Java

The equals() of arrays is inherited from Object, so it does not look at the contents of the arrrays, it only considers each array equal to itself.

The Arrays.equals() methods do compare the arrays' contents. There's overloads for all primitive types, and the one for objects uses the objects' own equals() methods.

ES6 Class Multiple inheritance

As a proof of concept, I did the following function. It takes a list of classes and composes them into a new class (the last prototype wins so there are no conflicts). When creating a composed function, the user can choose to use all original constructors [sic!] or pass their own. This was the biggest challenge of this experiment: to come up with a description of what constructor should do. Copying methods into a prototype is not an issue but what's the intended logic of newly composed object. Or maybe it should be constructorless? In Python, from what I know, it finds the matching constructor but functions in JS are more accepting, hence one can pass to a function just about everything and from signature it won't be clear.

I don't think it's optimised but the purpose was exploring possibilities. instanceof will not behave as expected which, I guess, is a bummer, since class-oriented developers like to use this as a tool.

Maybe JavaScript just doesn't have it.

_x000D_
_x000D_
/*_x000D_
    (c) Jon Krazov 2019_x000D_
_x000D_
    Below is an experiment searching boundaries of JavaScript._x000D_
    It allows to compute one class out of many classes._x000D_
_x000D_
    Usage 1: Without own constructor_x000D_
_x000D_
    If no constructor is passed then constructor of each class will be called_x000D_
    with params passed in object. In case of missing params, constructor_x000D_
    will be called without params._x000D_
_x000D_
    Example:_x000D_
_x000D_
    const MyClass1 = computeClass([Class1, Class2, Class3]);_x000D_
    const myClass1Instance = new MyClass1({_x000D_
        'Class1': [1, 2],_x000D_
        'Class2': ['test'],_x000D_
        'Class3': [(value) => value],_x000D_
    });_x000D_
_x000D_
    Usage 2: With own constructor_x000D_
_x000D_
    If constructor is passed in options object (second param) then it will_x000D_
    be called in place of constructors of all classes._x000D_
_x000D_
    Example:_x000D_
_x000D_
    const MyClass2 = computeClass([Class1, Class2, Class3], {_x000D_
        ownConstructor(param1) {_x000D_
            this.name = param1;_x000D_
        }_x000D_
    });_x000D_
    const myClass2Instance = new MyClass2('Geoffrey');_x000D_
*/_x000D_
_x000D_
// actual function_x000D_
_x000D_
var computeClass = (classes = [], { ownConstructor = null } = {}) => {_x000D_
    const noConstructor = (value) => value != 'constructor';_x000D_
_x000D_
    const ComputedClass = ownConstructor === null_x000D_
        ? class ComputedClass {_x000D_
            constructor(args) {_x000D_
                classes.forEach((Current) => {_x000D_
                    const params = args[Current.name];_x000D_
_x000D_
                    if (params) {_x000D_
                        Object.assign(this, new Current(...params));_x000D_
                    } else {_x000D_
                        Object.assign(this, new Current());_x000D_
                    }_x000D_
                })_x000D_
            }_x000D_
        }_x000D_
        : class ComputedClass {_x000D_
            constructor(...args) {_x000D_
                if (typeof ownConstructor != 'function') {_x000D_
                    throw Error('ownConstructor has to be a function!');_x000D_
                }_x000D_
                ownConstructor.call(this, ...args);_x000D_
            } _x000D_
        };_x000D_
_x000D_
    const prototype = classes.reduce(_x000D_
        (composedPrototype, currentClass) => {_x000D_
            const partialPrototype = Object.getOwnPropertyNames(currentClass.prototype)_x000D_
                .reduce(_x000D_
                    (result, propName) =>_x000D_
                        noConstructor(propName)_x000D_
                            ? Object.assign(_x000D_
                                    result,_x000D_
                                    { [propName]: currentClass.prototype[propName] }_x000D_
                                )_x000D_
                            : result,_x000D_
                    {}_x000D_
                );_x000D_
_x000D_
            return Object.assign(composedPrototype, partialPrototype);_x000D_
        },_x000D_
        {}_x000D_
    );_x000D_
_x000D_
    Object.entries(prototype).forEach(([prop, value]) => {_x000D_
 Object.defineProperty(ComputedClass.prototype, prop, { value });_x000D_
    });_x000D_
    _x000D_
    return ComputedClass;_x000D_
}_x000D_
_x000D_
// demo part_x000D_
_x000D_
var A = class A {_x000D_
    constructor(a) {_x000D_
        this.a = a;_x000D_
    }_x000D_
    sayA() { console.log('I am saying A'); }_x000D_
}_x000D_
_x000D_
var B = class B {_x000D_
    constructor(b) {_x000D_
        this.b = b;_x000D_
    }_x000D_
    sayB() { console.log('I am saying B'); }_x000D_
}_x000D_
_x000D_
console.log('class A', A);_x000D_
console.log('class B', B);_x000D_
_x000D_
var C = computeClass([A, B]);_x000D_
_x000D_
console.log('Composed class');_x000D_
console.log('var C = computeClass([A, B]);', C);_x000D_
console.log('C.prototype', C.prototype);_x000D_
_x000D_
var c = new C({ A: [2], B: [32] });_x000D_
_x000D_
console.log('var c = new C({ A: [2], B: [32] })', c);_x000D_
console.log('c instanceof A', c instanceof A);_x000D_
console.log('c instanceof B', c instanceof B);_x000D_
_x000D_
console.log('Now c will say:')_x000D_
c.sayA();_x000D_
c.sayB();_x000D_
_x000D_
console.log('---');_x000D_
_x000D_
var D = computeClass([A, B], {_x000D_
    ownConstructor(c) {_x000D_
        this.c = c;_x000D_
    }_x000D_
});_x000D_
_x000D_
console.log(`var D = computeClass([A, B], {_x000D_
    ownConstructor(c) {_x000D_
        this.c = c;_x000D_
    }_x000D_
});`);_x000D_
_x000D_
var d = new D(42);_x000D_
_x000D_
console.log('var d = new D(42)', d);_x000D_
_x000D_
console.log('Now d will say:')_x000D_
d.sayA();_x000D_
d.sayB();_x000D_
_x000D_
console.log('---');_x000D_
_x000D_
var E = computeClass();_x000D_
_x000D_
console.log('var E = computeClass();', E);_x000D_
_x000D_
var e = new E();_x000D_
_x000D_
console.log('var e = new E()', e);
_x000D_
_x000D_
_x000D_

Originally posted here (gist.github.com).

Recyclerview inside ScrollView not scrolling smoothly

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent">

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintlayout_main"
                android:layout_width="match_parent"
                android:layout_height="@dimen/layout_width_height_fortyfive"
                android:layout_marginLeft="@dimen/padding_margin_sixteen"
                android:layout_marginRight="@dimen/padding_margin_sixteen"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent">

                <TextView
                    android:id="@+id/textview_settings"
                    style="@style/textviewHeaderMain"
                    android:gravity="start"
                    android:text="@string/app_name"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent" />

            </android.support.constraint.ConstraintLayout>

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintlayout_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/padding_margin_zero"
                android:layout_marginTop="@dimen/padding_margin_zero"
                android:layout_marginEnd="@dimen/padding_margin_zero"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/constraintlayout_main">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerview_list"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:nestedScrollingEnabled="false"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent" />

            </android.support.constraint.ConstraintLayout>

        </android.support.constraint.ConstraintLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.constraint.ConstraintLayout>

This code is working for in ConstraintLayout android

Get a list of numbers as input from the user

a=[]
b=int(input())
for i in range(b):
    c=int(input())
    a.append(c)

The above code snippets is easy method to get values from the user.

How to get Git to clone into current directory

I had this same need. In my case I had a standard web folder which is created by a web server install. For the purposes of this illustration let's say this is

/server/webroot

and webroot contains other standard files and folders. My repo just has the site specific files (html, javascript, CFML, etc.)

All I had to do was:

cd /server/webroot

git init

git pull [url to my repo.git]

You need to be careful to do the git init in the target folder because if you do NOT one of two things will happen:

  1. The git pull will simply fail with a message about no git file, in my case:

fatal: Not a git repository (or any of the parent directories): .git

  1. If there is a .git file somewhere in the parent path to your folder your pulled repo will be created in THAT parent that contains the .git file. This happened to me and I was surprised by it ;-)

This did NOT disturb any of the "standard" files I have in my webroot folder but I did need to add them to the .gitignore file to prevent the inadvertent addition of them to subsequent commits.

This seems like an easy way to "clone" into a non-empty directory. If you don't want the .git and .gitignore files created by the pull, just delete them after the pull.

How to "properly" create a custom object in JavaScript?

There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.

The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)

Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.

function Shape(x, y) {
    this.x= x;
    this.y= y;
}

We can add methods to the instance created by new Shape by writing them to the prototype lookup of this constructor function:

Shape.prototype.toString= function() {
    return 'Shape at '+this.x+', '+this.y;
};

Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype property:

function Circle(x, y, r) {
    Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
    this.r= r;
}
Circle.prototype= new Shape();

before adding methods to it:

Circle.prototype.toString= function() {
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}

This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.

So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:

function subclassOf(base) {
    _subclassOf.prototype= base.prototype;
    return new _subclassOf();
}
function _subclassOf() {};

This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.prototype= subclassOf(Shape);

instead of the new Shape() wrongness. We now have an acceptable set of primitives to built classes.

There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:

Function.prototype.subclass= function(base) {
    var c= Function.prototype.subclass.nonconstructor;
    c.prototype= base.prototype;
    this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};

...

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.subclass(Shape);

Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply, but still you have to write out:

function Point() {
    Shape.apply(this, arguments);
}
Point.subclass(Shape);

So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:

function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!

Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass, turning it round and letting the base class's Function spit out subclasses:

Function.prototype.makeSubclass= function() {
    function Class() {
        if ('_init' in this)
            this._init.apply(this, arguments);
    }
    Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
    Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
    return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};

...

Shape= Object.makeSubclass();
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

Point= Shape.makeSubclass();

Circle= Shape.makeSubclass();
Circle.prototype._init= function(x, y, r) {
    Shape.prototype._init.call(this, x, y);
    this.r= r;
};

...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass to take and remember a class name and provide a default toString using it. Maybe you want to make the constructor detect when it has accidentally been called without the new operator (which would otherwise often result in very annoying debugging):

Function.prototype.makeSubclass= function() {
    function Class() {
        if (!(this instanceof Class))
            throw('Constructor called without "new"');
        ...

Maybe you want to pass in all the new members and have makeSubclass add them to the prototype, to save you having to write Class.prototype... quite so much. A lot of class systems do that, eg:

Circle= Shape.makeSubclass({
    _init: function(x, y, z) {
        Shape.prototype._init.call(this, x, y);
        this.r= r;
    },
    ...
});

There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.


The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:

function Shape(x, y) {
    var that= this;

    this.x= x;
    this.y= y;

    this.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };
}

function Circle(x, y, r) {
    var that= this;

    Shape.call(this, x, y);
    this.r= r;

    var _baseToString= this.toString;
    this.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+that.r;
    };
};

var mycircle= new Circle();

Now every single instance of Shape will have its own copy of the toString method (and any other methods or other class members we add).

The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.

[Also because there is no inheritance here, the instanceof operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof working.]

The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this in method calls, which has the upshot that if you detach a method from its owner:

var ts= mycircle.toString;
alert(ts());

then this inside the method won't be the Circle instance as expected (it'll actually be the global window object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout, onclick or EventListener in general.

With the prototype way, you have to include a closure for every such assignment:

setTimeout(function() {
    mycircle.move(1, 1);
}, 1000);

or, in the future (or now if you hack Function.prototype) you can also do it with function.bind():

setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);

if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that or self, though personally I would advise against the latter as self already has another, different meaning in JavaScript). You don't get the arguments 1, 1 in the above snippet for free though, so you would still need another closure or a bind() if you need to do that.

There are lots of variants on the closure method too. You may prefer to omit this completely, creating a new that and returning it instead of using the new operator:

function Shape(x, y) {
    var that= {};

    that.x= x;
    that.y= y;

    that.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };

    return that;
}

function Circle(x, y, r) {
    var that= Shape(x, y);

    that.r= r;

    var _baseToString= that.toString;
    that.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+r;
    };

    return that;
};

var mycircle= Circle(); // you can include `new` if you want but it won't do anything

Which way is “proper”? Both. Which is “best”? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.

But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.

[This has been part 94 of Why JavaScript Is Not My Favourite Programming Language.]

How do I call a dynamically-named method in Javascript?

Try with this:

var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);

How to comment out particular lines in a shell script

You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):

:10,20 s/^/#

with 10 and 20 being the start and end line numbers of the lines you want to comment out

and to undo when you are complete:

:10,20 s/^#//

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

How to launch PowerShell (not a script) from the command line

Set the default console colors and fonts:

http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)

Set-StrictMode -Version Latest

Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'

New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location

How can I plot with 2 different y-axes?

update: Copied material that was on the R wiki at http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes, link now broken: also available from the wayback machine

Two different y axes on the same plot

(some material originally by Daniel Rajdl 2006/03/31 15:26)

Please note that there are very few situations where it is appropriate to use two different scales on the same plot. It is very easy to mislead the viewer of the graphic. Check the following two examples and comments on this issue (example1, example2 from Junk Charts), as well as this article by Stephen Few (which concludes “I certainly cannot conclude, once and for all, that graphs with dual-scaled axes are never useful; only that I cannot think of a situation that warrants them in light of other, better solutions.”) Also see point #4 in this cartoon ...

If you are determined, the basic recipe is to create your first plot, set par(new=TRUE) to prevent R from clearing the graphics device, creating the second plot with axes=FALSE (and setting xlab and ylab to be blank – ann=FALSE should also work) and then using axis(side=4) to add a new axis on the right-hand side, and mtext(...,side=4) to add an axis label on the right-hand side. Here is an example using a little bit of made-up data:

set.seed(101)
x <- 1:10
y <- rnorm(10)
## second data set on a very different scale
z <- runif(10, min=1000, max=10000) 
par(mar = c(5, 4, 4, 4) + 0.3)  # Leave space for z axis
plot(x, y) # first plot
par(new = TRUE)
plot(x, z, type = "l", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("z", side=4, line=3)

twoord.plot() in the plotrix package automates this process, as does doubleYScale() in the latticeExtra package.

Another example (adapted from an R mailing list post by Robert W. Baer):

## set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)

## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)

## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="", 
   type="b",col="black", main="Mike's test data")
axis(2, ylim=c(0,1),col="black",las=1)  ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()

## Allow a second plot on the same graph
par(new=TRUE)

## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15,  xlab="", ylab="", ylim=c(0,7000), 
    axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4) 
axis(4, ylim=c(0,7000), col="red",col.axis="red",las=1)

## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)  

## Add Legend
legend("topleft",legend=c("Beta Gal","Cell Density"),
  text.col=c("black","red"),pch=c(16,15),col=c("black","red"))

enter image description here

Similar recipes can be used to superimpose plots of different types – bar plots, histograms, etc..

URL encoding the space character: + or %20?

This confusion is because URLs are still 'broken' to this day.

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+
|      Part     |      Data         |
+---------------+-------------------+
|  Scheme       | http              |
|  Host         | www.google.com    |
+---------------+-------------------+

If we look at a more complex URL such as:

"https://bob:[email protected]:8080/file;p=1?q=2#third"

we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host             | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file;p=1           |
|  Path parameter   | p=1                 |
|  Query            | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

https://bob:[email protected]:8080/file;p=1?q=2#third
\___/   \_/ \___/ \______________/ \__/\_______/ \_/ \___/
  |      |    |          |          |      | \_/  |    |
Scheme User Password    Host       Port  Path |   | Fragment
        \_____________________________/       | Query
                       |               Path parameter
                   Authority

The reserved characters are different for each part.

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts:

"http://example.com/blue+light%20blue?blue%2Blight+blue".

From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

This boils down to:

You should have %20 before the ? and + after.

Source

In PHP with PDO, how to check the final SQL parametrized query?

So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.

Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database. Only on the database side the full query exists.

Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)

Workaround
This is where I elaborate on Kailash Badu's answer. By logging all SQL queries, we can see what is really run on the server. With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:

log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]

Just do not run this in production!!!

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

How do I fix "Expected to return a value at the end of arrow function" warning?

The problem seems to be that you are not returning something in the event that your first if-case is false.

The error you are getting states that your arrow function (comment) => { doesn't have a return statement. While it does for when your if-case is true, it does not return anything for when it's false.

return this.props.comments.map((comment) => {
  if (comment.hasComments === true) {
    return (
      <div key={comment.id}>
        <CommentItem className="MainComment" />
        {this.props.comments.map(commentReply => {
          if (commentReply.replyTo === comment.id) { 
            return (
              <CommentItem className="SubComment"/>
            )
          }
        })
        }
      </div>
    )
  } else {
     //return something here.
  }
});

edit you should take a look at Kris' answer for how to better implement what you are trying to do.

Execute action when back bar button of UINavigationController is pressed

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if self.isMovingToParent {

        //your code backView
    }
}

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Python Matplotlib figure title overlaps axes label when using twiny

I was having an issue with the x-label overlapping a subplot title; this worked for me:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 1)
ax[0].scatter(...)
ax[1].scatter(...)
plt.tight_layout()
.
.
.
plt.show()

before

enter image description here

after

enter image description here

reference:

Benefits of EBS vs. instance-store (and vice-versa)

EBS is like the virtual disk of a VM:

  • Durable, instances backed by EBS can be freely started and stopped (saving money)
  • Can be snapshotted at any point in time, to get point-in-time backups
  • AMIs can be created from EBS snapshots, so the EBS volume becomes a template for new systems

Instance storage is:

  • Local, so generally faster
  • Non-networked, in normal cases EBS I/O comes at the cost of network bandwidth (except for EBS-optimized instances, which have separate EBS bandwidth)
  • Has limited I/O per second IOPS. Even provisioned I/O maxes out at a few thousand IOPS
  • Fragile. As soon as the instance is stopped, you lose everything in instance storage.

Here's where to use each:

  • Use EBS for the backing OS partition and permanent storage (DB data, critical logs, application config)
  • Use instance storage for in-process data, noncritical logs, and transient application state. Example: external sort storage, tempfiles, etc.
  • Instance storage can also be used for performance-critical data, when there's replication between instances (NoSQL DBs, distributed queue/message systems, and DBs with replication)
  • Use S3 for data shared between systems: input dataset and processed results, or for static data used by each system when lauched.
  • Use AMIs for prebaked, launchable servers

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Open multiple Eclipse workspaces on the Mac

Instead of copying Eclipse.app around, create an automator that runs the shell script above.

Run automator, create Application.

choose Utilities->Run shell script, and add in the above script (need full path to eclipse)

Then you can drag this to your Dock as a normal app.

Repeat for other workspaces.

You can even simply change the icon - https://discussions.apple.com/message/699288?messageID=699288򪮘

Clear form after submission with jQuery

try this in your post methods callback function

$(':input','#myform')
 .not(':button, :submit, :reset, :hidden')
 .val('')
 .removeAttr('checked')
 .removeAttr('selected');

for more info read this

Java Interfaces/Implementation naming convention

TruckClass sounds like it were a class of Truck, I think that recommended solution is to add Impl suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List interface and implementations: ArrayList or LinkedList), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl is the solution.

How to validate phone number using PHP?

Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.

php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.

An example

$phone = '000-0000-0000';

if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
  // $phone is valid
}

How do I solve the "server DNS address could not be found" error on Windows 10?

There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.

  1. Go to Control Panel ? Network and Internet ? Network and Sharing Centre
  2. Click on Change Adapter settings.
  3. Right click on your connection icon (Wireless Network Connection or Local Area Connection) and select properties.
  4. Select Internet protocol version 4.
  5. Click on "Use the following DNS server address" and type either of the two DNS given below.

Google Public DNS

Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4

OpenDNS

Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220

Creating composite primary key in SQL Server

How about something like

CREATE TABLE testRequest (
        wardNo nchar(5),
        BHTNo nchar(5),
        testID nchar(5),
        reqDateTime datetime,
        PRIMARY KEY (wardNo, BHTNo, testID)
);

Have a look at this example

SQL Fiddle DEMO

Python list of dictionaries search

You can achieve this with the usage of filter and next methods in Python.

filter method filters the given sequence and returns an iterator. next method accepts an iterator and returns the next element in the list.

So you can find the element by,

my_dict = [
    {"name": "Tom", "age": 10},
    {"name": "Mark", "age": 5},
    {"name": "Pam", "age": 7}
]

next(filter(lambda obj: obj.get('name') == 'Pam', my_dict), None)

and the output is,

{'name': 'Pam', 'age': 7}

Note: The above code will return None incase if the name we are searching is not found.

How is CountDownLatch used in Java Multithreading?

Best real time Example for countDownLatch explained in this link CountDownLatchExample

Gradle version 2.2 is required. Current version is 2.10

Use ./gradlew instead of gradle to resolve this issue.

How to check if "Radiobutton" is checked?

        if(jRadioButton1.isSelected()){
            jTextField1.setText("Welcome");
        }
        else if(jRadioButton2.isSelected()){
            jTextField1.setText("Hello");
        }

Import CSV to SQLite

As some websites and other article specifies, its simple have a look to this one. https://www.sqlitetutorial.net/sqlite-import-csv/

We don't need to specify the separator for csv file, becayse csv means comma separated. sqlite> .separator , no need of this line.

sqlite> create table cities(name, population);
sqlite> .mode csv
sqlite> .import c:/sqlite/city_no_header.csv cities

This will work flawlessly :)

PS: My cities.csv with header.


name,population
Abilene,115930
Akron,217074
Albany,93994
Albuquerque,448607
Alexandria,128283
Allentown,106632
Amarillo,173627
Anaheim,328014

C# naming convention for constants?

First, Hungarian Notation is the practice of using a prefix to display a parameter's data type or intended use. Microsoft's naming conventions for says no to Hungarian Notation http://en.wikipedia.org/wiki/Hungarian_notation http://msdn.microsoft.com/en-us/library/ms229045.aspx

Using UPPERCASE is not encouraged as stated here: Pascal Case is the acceptable convention and SCREAMING CAPS. http://en.wikibooks.org/wiki/C_Sharp_Programming/Naming

Microsoft also states here that UPPERCASE can be used if it is done to match the the existed scheme. http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx

This pretty much sums it up.

One DbContext per web request... why?

I'm pretty certain it is because the DbContext is not at all thread safe. So sharing the thing is never a good idea.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

In my case, I got this problem because I had given the server a non-existent certificate, due to a typo in the config file. Instead of throwing an exception, the server proceeded like normal and sent an empty certificate to the client. So it might be worth checking to make sure that the server is providing the correct response.

I experienced this error while using the Jersey Client to connect to a server. The way I resolved it was by debugging the library and seeing that it actually did receive an EOF the moment it tried to read. I also tried connecting using a web browser and got the same results.

Just writing this here in case it ends up helping anyone.

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Why use the 'ref' keyword when passing an object?

Ref denotes whether the function can get its hands on the object itself, or only on its value.

Passing by reference is not bound to a language; it's a parameter binding strategy next to pass-by-value, pass by name, pass by need etc...

A sidenote: the class name TestRef is a hideously bad choice in this context ;).

Android refresh current activity

From dialog to activity that you want to refresh. If it not first activity!
Like this:mainActivity>>objectActivity>>dialog
In your dialog class:

  @Override
public void dismiss() {
    super.dismiss();
   getActivity().finish();
    Intent i = new Intent(getActivity(), objectActivity.class);  //your class
    startActivity(i);

}

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

Replace text inside td using jQuery having td containing other elements

Remove the textnode, and replace the <b> tag with whatever you need without ever touching the inputs :

$('#demoTable').find('tr > td').contents().filter(function() {
    return this.nodeType===3;
}).remove().end().end()
  .find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));

FIDDLE

ps1 cannot be loaded because running scripts is disabled on this system

Open terminal

Run the command: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

in terminal: yarn --version

Android Studio is slow (how to speed up)?

Click Help > Edit Custom properties and add this line:

sun.java2d.noddraw=false

... worked successfully for me to fix the speed issues (Windows 10 64-bit). It's absolute voodoo as far as I'm concerned (I haven't done any research on why that should work), and there is a warning above that property that it can cause blinking and fail to repaint on some graphics cards, but there you go. (Inspired by LairdPleng's comment, further information)

How to set dropdown arrow in spinner?

Set the Dropdown arrow image to spinner like this :

<Spinner
    android:id="@+id/Exam_Course"
    android:layout_width="320dp"
    android:background="@drawable/spinner_bg"
    android:layout_height="wrap_content"/>

Here android:background="@drawable/spinner_bg" the spinner_bg is the Dropdown arrow image.

Convert UTC date time to local date time

This is a simplified solution based on Adorjan Princ´s answer:

function convertUTCDateToLocalDate(date) {
    var newDate = new Date(date);
    newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return newDate;
}

Usage:

var date = convertUTCDateToLocalDate(new Date(date_string_you_received));

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

Seems you have installed express in root directory.Copy path of package.json and delete package json file and node_modules folder.

Jackson - best way writes a java list to a json array

I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:

public void writeListToJsonArray() throws IOException {  

    //your list
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));


    final StringWriter sw =new StringWriter();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, list);
    System.out.println(sw.toString());//use toString() to convert to JSON

    sw.close(); 
}

Or just use ObjectMapper#writeValueAsString:

    final ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(list));

Dialog with transparent background in Android

Try this in your code:

getWindow().setBackgroundDrawableResource(android.R.color.transparent);

it will definately working...in my case...! my frend

Subscript out of bounds - general definition and solution?

It just means that either alter > ncol( reach_mat ) or i > nrow( reach_mat ), in other words, your indices exceed the array boundary (i is greater than the number of rows, or alter is greater than the number of columns).

Just run the above tests to see what and when is happening.

Any way to exit bash script, but not quitting the terminal

This is just like you put a run function inside your script run2.sh. You use exit code inside run while source your run2.sh file in the bash tty. If the give the run function its power to exit your script and give the run2.sh its power to exit the terminator. Then of cuz the run function has power to exit your teminator.

    #! /bin/sh
    # use . run2.sh

    run()
    {
        echo "this is run"
        #return 0
        exit 0
    }

    echo "this is begin"
    run
    echo "this is end"

Anyway, I approve with Kaz it's a design problem.

How to return a custom object from a Spring Data JPA GROUP BY query

I do not like java type names in query strings and handle it with a specific constructor. Spring JPA implicitly calls constructor with query result in HashMap parameter:

@Getter
public class SurveyAnswerStatistics {
  public static final String PROP_ANSWER = "answer";
  public static final String PROP_CNT = "cnt";

  private String answer;
  private Long   cnt;

  public SurveyAnswerStatistics(HashMap<String, Object> values) {
    this.answer = (String) values.get(PROP_ANSWER);
    this.count  = (Long) values.get(PROP_CNT);
  }
}

@Query("SELECT v.answer as "+PROP_ANSWER+", count(v) as "+PROP_CNT+" FROM  Survey v GROUP BY v.answer")
List<SurveyAnswerStatistics> findSurveyCount();

Code needs Lombok for resolving @Getter

Parsing CSV files in C#, with header

Here is my KISS implementation...

using System;
using System.Collections.Generic;
using System.Text;

class CsvParser
{
    public static List<string> Parse(string line)
    {
        const char escapeChar = '"';
        const char splitChar = ',';
        bool inEscape = false;
        bool priorEscape = false;

        List<string> result = new List<string>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < line.Length; i++)
        {
            char c = line[i];
            switch (c)
            {
                case escapeChar:
                    if (!inEscape)
                        inEscape = true;
                    else
                    {
                        if (!priorEscape)
                        {
                            if (i + 1 < line.Length && line[i + 1] == escapeChar)
                                priorEscape = true;
                            else
                                inEscape = false;
                        }
                        else
                        {
                            sb.Append(c);
                            priorEscape = false;
                        }
                    }
                    break;
                case splitChar:
                    if (inEscape) //if in escape
                        sb.Append(c);
                    else
                    {
                        result.Add(sb.ToString());
                        sb.Length = 0;
                    }
                    break;
                default:
                    sb.Append(c);
                    break;
            }
        }

        if (sb.Length > 0)
            result.Add(sb.ToString());

        return result;
    }

}

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

I had the same problem using PHP and prepared statements on a VARCHAR2 column. My string didn't exceeed the VARCHAR2 size. The problem was that I used -1 as maxlength for binding, but the variable content changed later.

In example:

$sMyVariable = '';
$rParsedQuery = oci_parse($rLink, 'INSERT INTO MyTable (MyVarChar2Column) VALUES (:MYPLACEHOLDER)');
oci_bind_by_name($rParsedQuery, ':MYPLACEHOLDER', $sMyVariable, -1, SQLT_CHR);

$sMyVariable = 'a';
oci_execute($rParsedQuery, OCI_DEFAULT);
$sMyVariable = 'b';
oci_execute($rParsedQuery, OCI_DEFAULT);

If you replace the -1 with the max column width (i. e. 254) then this code works. With -1 oci_bind_by_param uses the current length of the variable content (in my case 0) as maximum length for this column. This results in ORA-01461 when executing.

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

I got the same error from IIS under windows 7. To fix this error i had to add full control permissions to IUSR account for sqlite database file. You don't need to change permissions if you use sqlite under webmatrix instead of IIS.

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

PHP Function Comments

Functions:

/**
 * Does something interesting
 *
 * @param Place   $where  Where something interesting takes place
 * @param integer $repeat How many times something interesting should happen
 * 
 * @throws Some_Exception_Class If something interesting cannot happen
 * @author Monkey Coder <[email protected]>
 * @return Status
 */ 

Classes:

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @copyright  2006 Zend Technologies
 * @license    http://www.zend.com/license/3_0.txt   PHP License 3.0
 * @version    Release: @package_version@
 * @link       http://dev.zend.com/package/PackageName
 * @since      Class available since Release 1.2.0
 */ 

Sample File:

<?php

/**
 * Short description for file
 *
 * Long description for file (if any)...
 *
 * PHP version 5.6
 *
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to [email protected] so we can mail you a copy immediately.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    SVN: $Id$
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      File available since Release 1.2.0
 * @deprecated File deprecated in Release 2.0.0
 */

/**
 * This is a "Docblock Comment," also known as a "docblock."  The class'
 * docblock, below, contains a complete description of how to write these.
 */
require_once 'PEAR.php';

// {{{ constants

/**
 * Methods return this if they succeed
 */
define('NET_SAMPLE_OK', 1);

// }}}
// {{{ GLOBALS

/**
 * The number of objects created
 * @global int $GLOBALS['_NET_SAMPLE_Count']
 */
$GLOBALS['_NET_SAMPLE_Count'] = 0;

// }}}
// {{{ Net_Sample

/**
 * An example of how to write code to PEAR's standards
 *
 * Docblock comments start with "/**" at the top.  Notice how the "/"
 * lines up with the normal indenting and the asterisks on subsequent rows
 * are in line with the first asterisk.  The last line of comment text
 * should be immediately followed on the next line by the closing asterisk
 * and slash and then the item you are commenting on should be on the next
 * line below that.  Don't add extra lines.  Please put a blank line
 * between paragraphs as well as between the end of the description and
 * the start of the @tags.  Wrap comments before 80 columns in order to
 * ease readability for a wide variety of users.
 *
 * Docblocks can only be used for programming constructs which allow them
 * (classes, properties, methods, defines, includes, globals).  See the
 * phpDocumentor documentation for more information.
 * http://phpdoc.org/tutorial_phpDocumentor.howto.pkg.html
 *
 * The Javadoc Style Guide is an excellent resource for figuring out
 * how to say what needs to be said in docblock comments.  Much of what is
 * written here is a summary of what is found there, though there are some
 * cases where what's said here overrides what is said there.
 * http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#styleguide
 *
 * The first line of any docblock is the summary.  Make them one short
 * sentence, without a period at the end.  Summaries for classes, properties
 * and constants should omit the subject and simply state the object,
 * because they are describing things rather than actions or behaviors.
 *
 * Below are the tags commonly used for classes. @category through @version
 * are required.  The remainder should only be used when necessary.
 * Please use them in the order they appear here.  phpDocumentor has
 * several other tags available, feel free to use them.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    Release: @package_version@
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      Class available since Release 1.2.0
 * @deprecated Class deprecated in Release 2.0.0
 */
class Net_Sample
{
    // {{{ properties

    /**
     * The status of foo's universe
     * Potential values are 'good', 'fair', 'poor' and 'unknown'.
     * @var string $foo
     */
    public $foo = 'unknown';

    /**
     * The status of life
     * Note that names of private properties or methods must be
     * preceeded by an underscore.
     * @var bool $_good
     */
    private $_good = true;

    // }}}
    // {{{ setFoo()

    /**
     * Registers the status of foo's universe
     *
     * Summaries for methods should use 3rd person declarative rather
     * than 2nd person imperative, beginning with a verb phrase.
     *
     * Summaries should add description beyond the method's name. The
     * best method names are "self-documenting", meaning they tell you
     * basically what the method does.  If the summary merely repeats
     * the method name in sentence form, it is not providing more
     * information.
     *
     * Summary Examples:
     *   + Sets the label              (preferred)
     *   + Set the label               (avoid)
     *   + This method sets the label  (avoid)
     *
     * Below are the tags commonly used for methods.  A @param tag is
     * required for each parameter the method has.  The @return
     * and @access tags are mandatory.  The @throws tag is required if
     * the method uses exceptions.  @static is required if the method can
     * be called statically.  The remainder should only be used when
     * necessary.  Please use them in the order they appear here.
     * phpDocumentor has several other tags available, feel free to use
     * them.
     *
     * The @param tag contains the data type, then the parameter's
     * name, followed by a description.  By convention, the first noun in
     * the description is the data type of the parameter.  Articles like
     * "a", "an", and  "the" can precede the noun.  The descriptions
     * should start with a phrase.  If further description is necessary,
     * follow with sentences.  Having two spaces between the name and the
     * description aids readability.
     *
     * When writing a phrase, do not capitalize and do not end with a
     * period:
     *   + the string to be tested
     *
     * When writing a phrase followed by a sentence, do not capitalize the
     * phrase, but end it with a period to distinguish it from the start
     * of the next sentence:
     *   + the string to be tested. Must use UTF-8 encoding.
     *
     * Return tags should contain the data type then a description of
     * the data returned.  The data type can be any of PHP's data types
     * (int, float, bool, string, array, object, resource, mixed)
     * and should contain the type primarily returned.  For example, if
     * a method returns an object when things work correctly but false
     * when an error happens, say 'object' rather than 'mixed.'  Use
     * 'void' if nothing is returned.
     *
     * Here's an example of how to format examples:
     * <code>
     * require_once 'Net/Sample.php';
     *
     * $s = new Net_Sample();
     * if (PEAR::isError($s)) {
     *     echo $s->getMessage() . "\n";
     * }
     * </code>
     *
     * Here is an example for non-php example or sample:
     * <samp>
     * pear install net_sample
     * </samp>
     *
     * @param string $arg1 the string to quote
     * @param int    $arg2 an integer of how many problems happened.
     *                     Indent to the description's starting point
     *                     for long ones.
     *
     * @return int the integer of the set mode used. FALSE if foo
     *             foo could not be set.
     * @throws exceptionclass [description]
     *
     * @access public
     * @static
     * @see Net_Sample::$foo, Net_Other::someMethod()
     * @since Method available since Release 1.2.0
     * @deprecated Method deprecated in Release 2.0.0
     */
    function setFoo($arg1, $arg2 = 0)
    {
        /*
         * This is a "Block Comment."  The format is the same as
         * Docblock Comments except there is only one asterisk at the
         * top.  phpDocumentor doesn't parse these.
         */
        if ($arg1 == 'good' || $arg1 == 'fair') {
            $this->foo = $arg1;
            return 1;
        } elseif ($arg1 == 'poor' && $arg2 > 1) {
            $this->foo = 'poor';
            return 2;
        } else {
            return false;
        }
    }

    // }}}
}

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */

?>

Source: PEAR Docblock Comment standards

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains "mysql_native_password". (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you've also verified the contents of authentication string matches the return from PASSWORD('mysecret'). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax? – spencer7593

So Basically Just make sure that the Plugin Column contains "mysql_native_password".

Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop

How to find topmost view controller on iOS

Simple extension for UIApplication in Swift:

NOTE:

It cares about moreNavigationController within UITabBarController

extension UIApplication {

    class func topViewController(baseViewController: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {

        if let navigationController = baseViewController as? UINavigationController {
            return topViewController(navigationController.visibleViewController)
        }

        if let tabBarViewController = baseViewController as? UITabBarController {

            let moreNavigationController = tabBarViewController.moreNavigationController

            if let topViewController = moreNavigationController.topViewController where topViewController.view.window != nil {
                return topViewController(topViewController)
            } else if let selectedViewController = tabBarViewController.selectedViewController {
                return topViewController(selectedViewController)
            }
        }

        if let splitViewController = baseViewController as? UISplitViewController where splitViewController.viewControllers.count == 1 {
            return topViewController(splitViewController.viewControllers[0])
        }

        if let presentedViewController = baseViewController?.presentedViewController {
            return topViewController(presentedViewController)
        }

        return baseViewController
    }
}

Simple usage:

if let topViewController = UIApplication.topViewController() {
    //do sth with top view controller
}

Software Design vs. Software Architecture

Architecture is high level, abstract and logical design whereas software design is low level,detailed and physical design.

How do I auto-hide placeholder text upon focus using css or jquery?

I like the css approach spiced with transitions. On Focus the placeholder fades out ;) Works also for textareas.

Thanks @Casey Chu for the great idea.

textarea::-webkit-input-placeholder, input::-webkit-input-placeholder { 
    color: #fff;
    opacity: 0.4;
    transition: opacity 0.5s;
    -webkit-transition: opacity 0.5s; 
}

textarea:focus::-webkit-input-placeholder, input:focus::-webkit-input-placeholder  { 
    opacity: 0;
}

Opening a folder in explorer and selecting a file

Samuel Yang answer tripped me up, here is my 3 cents worth.

Adrian Hum is right, make sure you put quotes around your filename. Not because it can't handle spaces as zourtney pointed out, but because it will recognize the commas (and possibly other characters) in filenames as separate arguments. So it should look as Adrian Hum suggested.

string argument = "/select, \"" + filePath +"\"";

Parsing jQuery AJAX response

Since you are using $.ajax, and not $.getJSON, your return type is plain text. you need to now convert data into a JSON object.

you can either do this by changing your $.ajax to $.getJSON (which is a shorthand for $.ajax, only preconfigured to fetch json).

Or you can parse the data string into JSON after you receive it, like so:

    success: function (data) {
         var obj = $.parseJSON(data);
         console.log(obj);
    },

Extract every nth element of a vector

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

Generate 'n' unique random numbers within a range

If you just need sampling without replacement:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sample takes a population and a sample size k and returns k random members of the population.

If you have to control for the case where k is larger than len(population), you need to be prepared to catch a ValueError:

>>> try:
...   random.sample(range(1, 2), 3)
... except ValueError:
...   print('Sample size exceeded population size.')
... 
Sample size exceeded population size

What is the difference between 'git pull' and 'git fetch'?

The Difference between GIT Fetch and GIT Pull can be explained with the following scenario: (Keeping in mind that pictures speak louder than words!, I have provided pictorial representation)

Let's take an example that you are working on a project with your team members. So there will be one main Branch of the project and all the contributors must fork it to their own local repository and then work on this local branch to modify/Add modules then push back to the main branch.

So, Initial State of the two Branches when you forked the main project on your local repository will be like this- (A, B and C are Modules already completed of the project)

enter image description here

Now, you have started working on the new module (suppose D) and when you have completed the D module you want to push it to the main branch, But meanwhile what happens is that one of your teammates has developed new Module E, F and modified C.
So now what has happened is that your local repository is lacking behind the original progress of the project and thus pushing of your changes to the main branch can lead to conflict and may cause your Module D to malfunction.

enter image description here

To avoid such issues and to work parallel with the original progress of the project there are Two ways:

1. Git Fetch- This will Download all the changes that have been made to the origin/main branch project which are not present in your local branch. And will wait for the Git Merge command to apply the changes that have been fetched to your Repository or branch.

enter image description here

So now You can carefully monitor the files before merging it to your repository. And you can also modify D if required because of Modified C.

enter image description here

2. Git Pull- This will update your local branch with the origin/main branch i.e. actually what it does is a combination of Git Fetch and Git merge one after another. But this may Cause Conflicts to occur, so it’s recommended to use Git Pull with a clean copy.

enter image description here

Java Try Catch Finally blocks without Catch

Inside try block we write codes that can throw an exception. The catch block is where we handle the exception. The finally block is always executed no matter whether exception occurs or not.

Now if we have try-finally block instead of try-catch-finally block then the exception will not be handled and after the try block instead of control going to catch block it will go to finally block. We can use try-finally block when we want to do nothing with the exception.

Viewing my IIS hosted site on other machines on my network

First of all, try to connect to the LAN IP of your server. If IIS is set up with only one web site, chances are that your site is going to pop up.

If you want to access it by name, you would have to add an entry in the HOSTS file of every client PC you want to view the site with (not to 127.0.0.1 obviously, but to the local IP address of your server).

Also, your Firewall needs to be configured to accept incoming calls on Port 80.

This is usually the point where it makes more sense to set up a DNS service that you can register names like "mysite.dev" with centrally, without having to dabble with hosts files. But that's a different story, and belongs to superuser.com or serverfault.com.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'

Print all properties of a Python Class

try ppretty:

from ppretty import ppretty


class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0


print ppretty(Animal(), seq_length=10)

Output:

__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

How to find a text inside SQL Server procedures / triggers?

There are much better solutions than modifying the text of your stored procedures, functions, and views each time the linked server changes. Here are some options:

  1. Update the linked server. Instead of using a linked server named with its IP address, create a new linked server with the name of the resource such as Finance or DataLinkProd or some such. Then when you need to change which server is reached, update the linked server to point to the new server (or drop it and recreate it).

  2. While unfortunately you cannot create synonyms for linked servers or schemas, you CAN make synonyms for objects that are located on linked servers. For example, your procedure [10.10.100.50].dbo.SPROCEDURE_EXAMPLE could by aliased. Perhaps create a schema datalinkprod, then CREATE SYNONYM datalinkprod.dbo_SPROCEDURE_EXAMPLE FOR [10.10.100.50].dbo.SPROCEDURE_EXAMPLE;. Then, write a stored procedure that accepts a linked server name, which queries all the potential objects from the remote database and (re)creates synonyms for them. All your SPs and functions get rewritten just once to use the synonym names starting with datalinkprod, and ever after that, to change from one linked server to another you just do EXEC dbo.SwitchLinkedServer '[10.10.100.51]'; and in a fraction of a second you're using a different linked server.

There may be even more options. I highly recommend using the superior techniques of pre-processing, configuration, or indirection rather than changing human-written scripts. Automatically updating machine-created scripts is fine, this is preprocessing. Doing things manually is awful.

Adding an onclicklistener to listview (android)

Try this:

    list.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3)
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

in this scenario:

DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));

aren't you missing the column you want to compare to? example:

DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));    

I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.

ORA-01438: value larger than specified precision allows for this column

The number you are trying to store is too big for the field. Look at the SCALE and PRECISION. The difference between the two is the number of digits ahead of the decimal place that you can store.

select cast (10 as number(1,2)) from dual
             *
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column

select cast (15.33 as number(3,2)) from dual
             *
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column

Anything at the lower end gets truncated (silently)

select cast (5.33333333 as number(3,2)) from dual;
CAST(5.33333333ASNUMBER(3,2))
-----------------------------
                         5.33

Command to run a .bat file

There are many possibilities to solve this task.

1. RUN the batch file with full path

The easiest solution is running the batch file with full path.

"F:\- Big Packets -\kitterengine\Common\Template.bat"

Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.

The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after @echo off as second line the following command line:

cd /D "%~dp0"

Run in a command prompt window cd /? for getting displayed the help of this command explaining parameter /D ... change to specified directory also on a different drive.

Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0 ... drive and path of argument 0 which is the name of the batch file.

2. CALL the batch file with full path

Another solution is calling the batch file with full path.

call "F:\- Big Packets -\kitterengine\Common\Template.bat"

The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.

For the current directory read above.

3. Change directory and RUN batch file with one command line

There are 3 operators for running multiple commands on one command line: &, && and ||.
For details see answer on Single line with multiple commands using Windows batch file

I suggest for this task the && operator.

cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat

As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.

4. Change directory and CALL batch file with one command line

This command line changes the directory and on success calls the batch file.

cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat

The difference to third solution is the return to current batch script on exiting processing of Template.bat.

5. Change directory and CALL batch file with keeping current environment with one command line

The four solutions above change the current directory and it is unknown what Template.bat does regarding

  1. current directory
  2. environment variables
  3. command extensions state
  4. delayed expansion state

In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal.

Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.

setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal

Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.


ONE MORE NOTE

If batch file Template.bat contains the command exit without parameter /B and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat contains exit /B or goto :EOF instead of just exit if there is exit used at all in this batch file.

vba error handling in loop

I do not want to craft special error handlers for every loop structure in my code so I have a way of finding problem loops using my standard error handler so that I can then write a special error handler for them.

If an error occurs in a loop, I normally want to know about what caused the error rather than just skip over it. To find out about these errors, I write error messages to a log file as many people do. However writing to a log file is dangerous if an error occurs in a loop as the error can be triggered for every time the loop iterates and in my case 80 000 iterations is not uncommon. I have therefore put some code into my error logging function that detects identical errors and skips writing them to the error log.

My standard error handler that is used on every procedure looks like this. It records the error type, procedure the error occurred in and any parameters the procedure received (FileType in this case).

procerr:
    Call NewErrorLog(Err.number, Err.Description, "GetOutputFileType", FileType)
    Resume exitproc

My error logging function which writes to a table (I am in ms-access) is as follows. It uses static variables to retain the previous values of error data and compare them to current versions. The first error is logged, then the second identical error pushes the application into debug mode if I am the user or if in other user mode, quits the application.

Public Function NewErrorLog(ErrCode As Variant, ErrDesc As Variant, Optional Source As Variant = "", Optional ErrData As Variant = Null) As Boolean
On Error GoTo errLogError

    'Records errors from application code
    Dim dbs As Database
    Dim rst As Recordset

    Dim ErrorLogID As Long
    Dim StackInfo As String
    Dim MustQuit As Boolean
    Dim i As Long

    Static ErrCodeOld As Long
    Static SourceOld As String
    Static ErrDataOld As String

    'Detects errors that occur in loops and records only the first two.
    If Nz(ErrCode, 0) = ErrCodeOld And Nz(Source, "") = SourceOld And Nz(ErrData, "") = ErrDataOld Then
        NewErrorLog = True
        MsgBox "Error has occured in a loop: " & Nz(ErrCode, 0) & Space(1) & Nz(ErrDesc, "") & ": " & Nz(Source, "") & "[" & Nz(ErrData, "") & "]", vbExclamation, Appname
        If Not gDeveloping Then  'Allow debugging
            Stop
            Exit Function
        Else
            ErrDesc = "[loop]" & Nz(ErrDesc, "")  'Flag this error as coming from a loop
            MsgBox "Error has been logged, now Quiting", vbInformation, Appname
            MustQuit = True  'will Quit after error has been logged
        End If
    Else
        'Save current values to static variables
        ErrCodeOld = Nz(ErrCode, 0)
        SourceOld = Nz(Source, "")
        ErrDataOld = Nz(ErrData, "")
    End If

    'From FMS tools pushstack/popstack - tells me the names of the calling procedures
    For i = 1 To UBound(mCallStack)
        If Len(mCallStack(i)) > 0 Then StackInfo = StackInfo & "\" & mCallStack(i)
    Next

    'Open error table
    Set dbs = CurrentDb()
    Set rst = dbs.OpenRecordset("tbl_ErrLog", dbOpenTable)

    'Write the error to the error table
    With rst
        .AddNew
        !ErrSource = Source
        !ErrTime = Now()
        !ErrCode = ErrCode
        !ErrDesc = ErrDesc
        !ErrData = ErrData
        !StackTrace = StackInfo
        .Update
        .BookMark = .LastModified
        ErrorLogID = !ErrLogID
    End With


    rst.Close: Set rst = Nothing
    dbs.Close: Set dbs = Nothing
    DoCmd.Hourglass False
    DoCmd.Echo True
    DoEvents
    If MustQuit = True Then DoCmd.Quit

exitLogError:
    Exit Function

errLogError:
    MsgBox "An error occured whilst logging the details of another error " & vbNewLine & _
    "Send details to Developer: " & Err.number & ", " & Err.Description, vbCritical, "Please e-mail this message to developer"
    Resume exitLogError

End Function

Note that an error logger has to be the most bullet proofed function in your application as the application cannot gracefully handle errors in the error logger. For this reason, I use NZ() to make sure that nulls cannot sneak in. Note that I also add [loop] to the second identical error so that I know to look in the loops in the error procedure first.

git ignore exception

If you're working with Visual Studio and your .dll happens to be in a bin folder, then you'll need to add an exception for the particular bin folder itself, before you can add the exception for the .dll file. E.g.

!SourceCode/Solution/Project/bin
!SourceCode/Solution/Project/bin/My.dll

This is because the default Visual Studio .gitignore file includes an ignore pattern for [Bbin]/

This pattern is zapping all bin folders (and consequently their contents), which makes any attempt to include the contents redundant (since the folder itself is already ignored).

I was able to find why my file wasn't being excepted by running

git check-ignore -v -- SourceCode/Solution/Project/bin/My.dll

from a Git Bash window. This returned the [Bbin]/ pattern.

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

Just a note for other users searching for answers for thie error. Another common issue is:

You generally cannot call an @transactional method from within the same class.

(There are ways and means using AspectJ but refactoring will be way easier)

So you'll need a calling class and class that holds the @transactional methods.

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

In my case it was because i was connecting to HTTP and it was running on HTTPS

Conditional operator in Python?

From Python 2.5 onwards you can do:

value = b if a > 10 else c

Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:

value = [c, b][a > 10]

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

Show space, tab, CRLF characters in editor of Visual Studio

For those who are looking for a button toggle:

The name of this command is View white space in GUI menu (Edit -> Advanced -> View white space).

Menu toggle

The name of this command in the Add command popup is Toggle Visual Space.

Button toggle.

Add (insert) a column between two columns in a data.frame

Add in your new column:

df$d <- list/data

Then you can reorder them.

df <- df[, c("a", "b", "d", "c")]

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

JavaScript or jQuery browser back button click detector

In my case I am using jQuery .load() to update DIVs in a SPA (single page [web] app) .

Being new to working with $(window).on('hashchange', ..) event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.

In summary - there is the variable globalCurrentHash that should be set each time you load a view.

Then when $(window).on('hashchange', ..) event listener runs, it checks the following:

  • If location.hash has the same value, it means Going Forward
  • If location.hash has different value, it means Going Back

I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated


Set Up:

  1. Define a global var :
    var globalCurrentHash = null;
  1. When calling .load() to update the DIV, update the global var as well :

    function loadMenuSelection(hrefVal) {
      $('#layout_main').load(nextView);
      globalCurrentHash = hrefVal;
    }
    
  2. On page ready, set up the listener to check the global var to see if Back Button is being pressed:

    $(document).ready(function(){
      $(window).on('hashchange', function(){
          console.log( 'location.hash: ' + location.hash );
          console.log( 'globalCurrentHash: ' + globalCurrentHash );
    
          if (location.hash == globalCurrentHash) {
              console.log( 'Going fwd' );
          }
          else {
    
              console.log( 'Going Back' );
              loadMenuSelection(location.hash);
          }
        });
    
    });
    

DB2 Date format

One more solution REPLACE (CHAR(current date, ISO),'-','')

Writing to an Excel spreadsheet

import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

# Insert an image.
worksheet.insert_image('B5', 'logo.png')

workbook.close()

How does the bitwise complement operator (~ tilde) work?

Basically action is a complement not a negation .

Here x= ~x produce results -(x+1) always .

x = ~2

-(2+1)

-3

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

Create auto-numbering on images/figures in MS Word

  • Select whole document (Ctrl+A)
  • Press F9
  • Save

Should update the figure caption automatically.

My question is tho, how can one also 'assign' referenced figures '(Fig.4)' in the text to do the same thing - aka change when an image is added above it?

EDIT: Figured it out.. In word go to Insert and Cross-ref and assign the ref. Then Ctrl+A and F9 and everything should sort itself out.

How to get File Created Date and Modified Date

Use :

FileInfo fInfo = new FileInfo('FilePath');
var fFirstTime = fInfo.CreationTime;
var fLastTime = fInfo.LastWriteTime;

How to print pthread_t

OK, seems this is my final answer. We have 2 actual problems:

  • How to get shorter unique IDs for thread for logging.
  • Anyway we need to print real pthread_t ID for thread (just to link to POSIX values at least).

1. Print POSIX ID (pthread_t)

You can simply treat pthread_t as array of bytes with hex digits printed for each byte. So you aren't limited by some fixed size type. The only issue is byte order. You probably like if order of your printed bytes is the same as for simple "int" printed. Here is example for little-endian and only order should be reverted (under define?) for big-endian:

#include <pthread.h>
#include <stdio.h>

void print_thread_id(pthread_t id)
{
    size_t i;
    for (i = sizeof(i); i; --i)
        printf("%02x", *(((unsigned char*) &id) + i - 1));
}

int main()
{
    pthread_t id = pthread_self();

    printf("%08x\n", id);
    print_thread_id(id);

    return 0;
}

2. Get shorter printable thread ID

In any of proposed cases you should translate real thread ID (posix) to index of some table. But there is 2 significantly different approaches:

2.1. Track threads.

You may track threads ID of all the existing threads in table (their pthread_create() calls should be wrapped) and have "overloaded" id function that get you just table index, not real thread ID. This scheme is also very useful for any internal thread-related debug an resources tracking. Obvious advantage is side effect of thread-level trace / debug facility with future extension possible. Disadvantage is requirement to track any thread creation / destruction.

Here is partial pseudocode example:

pthread_create_wrapper(...)
{
   id = pthread_create(...)
   add_thread(id);
}

pthread_destruction_wrapper()
{
   /* Main problem is it should be called.
      pthread_cleanup_*() calls are possible solution. */
   remove_thread(pthread_self());
}

unsigned thread_id(pthread_t known_pthread_id)
{
  return seatch_thread_index(known_pthread_id);
}

/* user code */
printf("04x", thread_id(pthread_self()));

2.2. Just register new thread ID.

During logging call pthread_self() and search internal table if it know thread. If thread with such ID was created its index is used (or re-used from previously thread, actually it doesn't matter as there are no 2 same IDs for the same moment). If thread ID is not known yet, new entry is created so new index is generated / used.

Advantage is simplicity. Disadvantage is no tracking of thread creation / destruction. So to track this some external mechanics is required.

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

Python read next()

You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

lines = f.readlines() # get all lines as a list (array)

# Iterate over each line, printing each line and then move to the next
for line in lines:
    print line

f.close()

What is the HTML tabindex attribute?

In Simple words, tabindex is used to focus on elements. Syntax: tabindex="numeric_value" This numeric_value is the weight of element. Lower value will be accessed first.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

The last parameter to the rgba() function is the "alpha" or "opacity" parameter. If you set it to 0 it will mean "completely transparent", and the first three parameters (the red, green, and blue channels) won't matter because you won't be able to see the color anyway.

With that in mind, I would choose rgba(0, 0, 0, 0) because:

  1. it's less typing,
  2. it keeps a few extra bytes out of your CSS file, and
  3. you will see an obvious problem if the alpha value changes to something undesirable.

You could avoid the rgba model altogether and use the transparent keyword instead, which according to w3.org, is equivalent to "transparent black" and should compute to rgba(0, 0, 0, 0). For example:

h1 {
    background-color: transparent;
}

This saves you yet another couple bytes while your intentions of using transparency are obvious (in case one is unfamiliar with RGBA).

As of CSS3, you can use the transparent keyword for any CSS property that accepts a color.

Ignore case in Python strings

When something isn't supported well in the standard library, I always look for a PyPI package. With virtualization and the ubiquity of modern Linux distributions, I no longer avoid Python extensions. PyICU seems to fit the bill: https://stackoverflow.com/a/1098160/3461

There now is also an option that is pure python. It's well tested: https://github.com/jtauber/pyuca


Old answer:

I like the regular expression solution. Here's a function you can copy and paste into any function, thanks to python's block structure support.

def equals_ignore_case(str1, str2):
    import re
    return re.match(re.escape(str1) + r'\Z', str2, re.I) is not None

Since I used match instead of search, I didn't need to add a caret (^) to the regular expression.

Note: This only checks equality, which is sometimes what is needed. I also wouldn't go so far as to say that I like it.

MySQL default datetime through phpmyadmin

I don't think you can achieve that with mysql date. You have to use timestamp or try this approach..

CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table`
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW());

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

Showing line numbers in IPython/Jupyter Notebooks

Select the Toggle Line Number Option from the View -> Toggle Line Number.

The menu looks like this

How do you change the value inside of a textfield flutter?

_mytexteditingcontroller.value = new TextEditingController.fromValue(new TextEditingValue(text: "My String")).value;

This seems to work if anyone has a better way please feel free to let me know.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

Quickfix

I had similar issue and I resolved it doing the following

  1. Navigate to jenkins > Manage jenkins > In-process Script Approval
  2. There was a pending command, which I had to approve.

In process approval link in Jenkins 2.61 Alternative 1: Disable sandbox

As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.

Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script: enter image description here

Alternative 2: Disable script security

As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:

-Dpermissive-script-security.enabled=true

So you jenkins.xml will look something like this:

<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>

Make sure you know what you are doing if you implement this!

Android Button setOnClickListener Design

You can use array to handle several button click listener in android like this: here i am setting button click listener for n buttons by using array as:

Button btn[] = new Button[n]; 

NOTE: n is a constant positive integer

Code example:

//class androidMultipleButtonActions 
package a.b.c.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class androidMultipleButtonActions extends Activity implements OnClickListener{
    Button btn[] = new Button[3];

    public void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        btn[0] = (Button) findViewById(R.id.Button1);
        btn[1] = (Button) findViewById(R.id.Button2);
        btn[2] = (Button) findViewById(R.id.Button3);
        for(int i=0; i<3; i++){
            btn[i].setOnClickListener(this);
        }           
    }

    public void onClick(View v) {
        if(v == findViewById(R.id.Button1)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button2)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button3)){
            //do here what u wanna do.
        }
    }
}

Note: First write an main.xml file if u dont know how to write please mail to: [email protected]

HTML - How to do a Confirmation popup to a Submit button and then send the request?

The most compact version:

<input type="submit" onclick="return confirm('Are you sure?')" />

The key thing to note is the return

-

Because there are many ways to skin a cat, here is another alternate method:

HTML:

<input type="submit" onclick="clicked(event)" />

Javascript:

<script>
function clicked(e)
{
    if(!confirm('Are you sure?')) {
        e.preventDefault();
    }
}
</script>

jQuery's .click - pass parameters to user function

Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.

//click handler
function add_event(event, paramA, paramB)
{
    //do something with your parameters
    alert(paramA ? 'paramA:' + paramA : '' + paramB ? '  paramB:' + paramB : '');
}

//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});

//or use variables
var a = 'first',
    b = 'second';

$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});

Best way to get the max value in a Spark dataframe column

Max value for a particular column of a dataframe can be achieved by using -

your_max_value = df.agg({"your-column": "max"}).collect()[0][0]

Set the maximum character length of a UITextField

Thank you august! (Post)

This is the code that I ended up with which works:

#define MAX_LENGTH 20

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length >= MAX_LENGTH && range.length == 0)
    {
        return NO; // return NO to not change text
    }
    else
    {return YES;}
}

How to get value of a div using javascript

First of all

<div id="demo" align="center"  value="1"></div>

that is not valid HTML. Read up on custom data attributes or use the following instead:

<div id="demo" align="center" data-value="1"></div>

Since "data-value" is an attribute, you have to use the getAttribute function to retrieve its value.

var cookieValue = document.getElementById("demo").getAttribute("data-value"); 

What type of hash does WordPress use?

MD5 worked for me changing my database manually. See: Resetting Your Password

Post to another page within a PHP script

index.php

$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);

$options = ['http' => [
    'method' => 'POST',
    'header' => 'Content-type:application/json',
    'content' => $json
]];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

test.php

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn

Convert a object into JSON in REST service by Spring MVC


The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:

<bean id="contentNegotiationManager"
      class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="useJaf" value="false" />
     <property name="defaultContentType" value="application/json" />

      <property name="mediaTypes">
         <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
         </map>
      </property>
   </bean>

   <mvc:annotation-driven
      content-negotiation-manager="contentNegotiationManager" />

   <context:annotation-config />

Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.

Bulk Insert to Oracle using .NET

I'm loading 50,000 records in 15 or so seconds using Array Binding in ODP.NET

It works by repeatedly invoking a stored procedure you specify (and in which you can do updates/inserts/deletes), but it passes the multiple parameter values from .NET to the database in bulk.

Instead of specifying a single value for each parameter to the stored procedure you specify an array of values for each parameter.

Oracle passes the parameter arrays from .NET to the database in one go, and then repeatedly invokes the stored procedure you specify using the parameter values you specified.

http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html

/Damian

Kendo grid date column not formatting

just need putting the datatype of the column in the datasource

dataSource: {
      data: empModel.Value,
      pageSize: 10,
      schema:  {
                model: {
                    fields: {
                        DOJ: { type: "date" }
                            }
                       }
               }  
           }

and then your statement column:

 columns: [
    {
        field: "Name",
        width: 90,
        title: "Name"
    },

    {
        field: "DOJ",
        width: 90,
        title: "DOJ",
        type: "date",
        format:"{0:MM-dd-yyyy}" 
    }
]

How do I get LaTeX to hyphenate a word that contains a dash?

multi\hskip0pt-\hskip0pt disciplinary

You can e.g. define like

\def\:{\hskip0pt}

and then write

multi\:-\:disciplinary

Note that the babel Russian language package has its own set of dashes that do not prohibit hyphenation, "~ (double quotation+tilde) for example.

Display last git commit comment

I just found out a workaround with shell by retrieving the previous command.

Press Ctrl-R to bring up reverse search command:

reverse-i-search

Then start typing git commit -m, this will add this as search command, and this brings the previous git commit with its message:

reverse-i-search`git commit -m`: git commit -m "message"

Enter. That's it!

(tested in Ubuntu shell)

Refresh a page using JavaScript or HTML

window.location.reload()

should work however there are many different options like:

window.location.href=window.location.href

How do I rename a column in a SQLite database table?

sqlite3 yourdb .dump > /tmp/db.txt
edit /tmp/db.txt change column name in Create line
sqlite2 yourdb2 < /tmp/db.txt
mv/move yourdb2 yourdb

How to get keyboard input in pygame?

You can get the events from pygame and then watch out for the KEYDOWN event, instead of looking at the keys returned by get_pressed()(which gives you keys that are currently pressed down, whereas the KEYDOWN event shows you which keys were pressed down on that frame).

What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.

events = pygame.event.get()
for event in events:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            location -= 1
        if event.key == pygame.K_RIGHT:
            location += 1

To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.

move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    if move_ticker == 0:
        move_ticker = 10
        location -= 1
        if location == -1:
            location = 0
if keys[K_RIGHT]:
    if move_ticker == 0:   
        move_ticker = 10     
        location+=1
        if location == 5:
            location = 4

Then somewhere during the game loop you would do something like this:

if move_ticker > 0:
    move_ticker -= 1

This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)

How to get a property value based on the name

return car.GetType().GetProperty(propertyName).GetValue(car, null);

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

How to make the first option of <select> selected with jQuery

$('#newType option:first').prop('selected', true);

What is the path that Django uses for locating and loading templates?

In django 2.2 this is explained here

https://docs.djangoproject.com/en/2.2/howto/overriding-templates/

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = [
    ...,
    'blog',
    ...,
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...
    },
]

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

Create a table without a header in Markdown

If you don't mind wasting a line by leaving it empty, consider the following hack (it is a hack, and use this only if you don't like adding any additional plugins).

| | | |
|-|-|-|
|__Bold Key__| Value1 |
| Normal Key | Value2 |

To view how the above one could look, copy the above and visit https://stackedit.io/editor

It worked with GitLab/GitHub's Markdown implementations.

Maven Install on Mac OS X

brew install maven31 (if you have homebrew)