Development and Programming How To

From KnowWiki
Jump to: navigation, search

Contents

[edit] How to configure pydev to ignore "Undefined variable from import” errors

Window -> Preferences -> PyDev -> Editor -> Code Analysis -> Undefined -> Undefined Variable From Import -> Ignore

[edit] How to remove non-ascii characters from a file

Use a linux or a cygwin 'tr' command:

tr -cd '\11\12\15\40-\176' < infile > outfile

[edit] How to check password strength with regular expressions

Use look-ahead constructs from the extended version of the regular expressions:

^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$
^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$
^.{6,}$

[edit] How to roll back a committed SVN file

to roll back to the previous revision do this:

svn merge -r COMMITTED:PREV file.py

or if you want to use a specific revision

svn merge -c -[revision_number] file.py

[edit] How to revert local changes to an SVN file

Either run

svn revert <filename>

or delete the file and run

svn up

[edit] How to reflect an SVN revision number in an ANT build

So you want to use ANT to build your files and use the SVN version either in the build or inside of a files. Use SVNANT. One caveat though. This is well suitable for a server-driven build, but if you are building off your local copy of the files that you edit, there is a chance that you are building off non-committed files. In this case the SVN version used by ANT is NOT truly indicative of what was code used to build the files. Just be careful or add "svn commit" as the first step.

<!-- The if statement requires ant-contrib to be linked in properly, like this:-->
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
  <classpath>
    <pathelement location="../Tools/ant-contrib/ant-contrib-1.0b3.jar"/>
  </classpath>
</taskdef>
<!-- prep the svnant lib-->
<path id="svnant.libs.path">
  <fileset dir="../Tools/ant-contrib/">
    <include name="svnant.jar"/>
    <include name="svnClientAdapter.jar"/>
    <include name="svnjavahl.jar"/>
  </fileset>
</path>
<!-- Load SvnAnt -->
<typedef resource="org/tigris/subversion/svnant/svnantlib.xml" classpathref="svnant.libs.path" />
<property name="curdir" location="."/>
<svn>
  <info target="${curdir}"/>
  <wcVersion path="." prefix="svn.version."/>
</svn>
<if>
    <equals arg1="${svn.version.modified}" arg2="true" />
  <then>
    <echo message="The code you are building has not been committed." />
    <echo message="Make sure to re-build once it has been committed to have the version correctly reflected in the build" />
  </then>
</if>
<echo>Revision: ${svn.info.lastRev} ${svn.info.lastDate}</echo>
<replace file="RELEASE.txt" token="$Revision$" value="Rev:${svn.info.lastRev} (${svn.info.lastDate})" />
<jar jarfile="${projectDescription.name}.rev${svn.info.lastRev}.jar" basedir="Runtime-${projectDescription.name}" includes="${projectDescription.name}/*" />

Look here for more info on how to build ITDI files with ANT.

[edit] How to configure SVN to update Rev and Date tags

If you want tags like the following automatically updated in the text of the files in SVN:

$Rev: 11 $ $LastChangedDate: 2011-11-11 11:11:11 -1100 (Fri, 11 Nov 2011) $

For a single file run this:

svn:keywords "Author Date Id Revision HeadURL" file

For many do this (Linux):

find . \( -name "*.php" -o -name "*.js" \) -exec svn propset svn:keywords "Author Date Id Revision HeadURL" {} \; && commit -m "Added svn keywords"

Or

find . -type f | grep -v '/\.svn/' | egrep "\.(inc|install|info|module|theme|php|txt|sh)$" | xargs svn propset svn:keywords "Date Revision"

Or this (Windows+Cygwin):

c:\cygwin\bin\find . -name "*.py" | grep -v '/\.svn/' | xargs svn propset svn:keywords "Date Revision"

And then commit all changes to svn

svn commit -m "Added svn keywords"

[edit] How to run PyDoc as a windows service

The trick is that PyDoc does not exit after being started Try this

sc create PyDoc binpath= "F:\python\bin\python -c \"import pydoc;pydoc.cli()\" -p 8000"

or this

sc create PyDoc binpath= "start F:\python\bin\python -c \"import pydoc;pydoc.cli()\" -p 8000"

Jython's PyDoc is a bit trickier since the executable started is not python but java One could try to build a clever batch and try setting it up like this:

sc create PyDoc binpath= "start F:\apiscript\bin\jythonscript.bat -c \"import pydoc;pydoc.cli()\" -p 8000"

[edit] How to use SED regexp with a non-greedy qualifier

sed does not have it. Use an exclusion format [^ ] to terminate match early like this

echo "http://dada.do/dadad" | sed -rne 's|\/[^/]*\/|\1|gp'

or use perl that supports it

echo "http://dada.do/dadad" | perl -pe 's|\/.*?\/|\1\|'

or awk using a split

 string="http://www.dada.da/baba/16/"
 echo $string | awk -F"/" '{print $1,$2,$3}' OFS="/"

[edit] How to convert text to lower or upper case

cat instances-stage | tr [:lower:] [:upper:]

[edit] How to configure or reconfigure CPAN

perm -MCPAN -e shell
o conf make_install_arg UNINGS=1
o conf prerequisites_policy follow
o conf commit
quit

might need to clean the old configs by

o conf init

[edit] How to get cpan modules under cygwin

open the cygwin setup program and make sure you have

run

perl -MCPAN -eshell
configure

point to /cygdrive/c/Windows/system32/ftp for the ftp

refresh CPAN if needed:

intall Bundle::CPAN
reload cpan

[edit] How to install CPAN module

if not configured - configure first via

perl -MCPAN -e shell

then

perl -MCPAN -e 'install Convert/Cyrillic'

[edit] How to run a file from a browser

The following technique uses xul

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="xxx" title="Process launcher" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml">
<script type="application/x-javascript">
<![CDATA[
      function getFile() {
              try {
                      // 1. Turn off the security. For the local files it should work.
                      netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                      // 2. Get the file to be executed via file picker. File picker is not the only way to get the local file object,
                      const nsIFilePicker = Components.interfaces.nsIFilePicker;
                      var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
                      fp.init(window, "Open Executable file", nsIFilePicker.modeOpen);
                      var rv = fp.show();
                      if (rv == nsIFilePicker.returnOK) {
                              // So far so good...
                              var file = fp.file;
                              // Now create the process, itit and launch it
                              var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
                              process.init(file);
                              // The process will not block the browser (1st arg), no command line options (2nd and 3rd args)
                              process.run(false, {array: {}, size_iz: function() {return 0;}}, 0);
                      }
              } catch(e) {
                      alert('!!! Bad news - "Exception, Sir!" ["+e+"]');
              }
              return;
      }
]]>
</script>
<groupbox>
<description>Make sure that the browser's preference <html:code><html:b>signed.applets.codebase_principal_support</html:b></html:code> is set to <html:b>true</html:b>.
(Complete set of FF preferences is accessable via <html:u>about:config</html:u> in the browser's URL bar).
This approach to bypass FF's security is pretty fine for the development, especially when you run the developed code in the dedicated isolated FF profile.
Just don't forget to set it back to <html:b>false</html:b> when you are done with this sample.
Otherwise the page must be signed to have access to the browser's internals and then to the local resources.<html:br/><html:br/></description>
<button id="btnFile" label="OpenFile" oncommand="getFile();" />
</groupbox>
</window>

[edit] How to correct C code indentation, remove blank lines and line breaks

sudo apt-get install indent
indent -nbc -br -brs -c33 -cd33 -ncdb -ce -ci4 -cli0 -cp33 -cs -d0 -di1 -nfc1 -nfca -hnl -i4 -ip0 -lp -npcs -nprs -npsl -saf -sai -saw -nsc -nbap -nbad -cdw -nss -npcs -nbc -brs -sob -l800 File.in -o File.out

Remove blank lines

sed '/^\s*$/d' File.in > File.out

[edit] How to correct HTML/XML indentations and syntax

tidy < infile > outfile

For XML do this:

tidy -mi -xml file-name

[edit] How to replace all occurences of a string using the IBM JS engine

function replaceAll(text, strA, strB) {
   sidx=0; restext="";
   while ((eidx=text.indexOf(strA,sidx)) != -1) {
      restext += text.substring(sidx,eidx)+strB;
      sidx=eidx+strA.length;
   }
   return restext+text.substring(sidx,text.length);
}

[edit] How to get any webpage source

copy and paste into the browaser's url prompt

javascript:window.open( , , '' ).document.write( '<textarea cols=80 rows=40>' + document.body.parentNode.innerHTML + '</textarea>' );

[edit] How to gray out images using css alone

Use the following css

.footerinc a img{opacity:0.5;border:0}
.footerinc a:hover img{opacity:1;}

[edit] How to read a file from jar

Read a text file from a jar

import java.applet.*;
import java.io.*;
 
public class ReadFromJar extends Applet{
 
public void init(){
  readTextFromJar("datafile1.txt"); 
  readTextFromJar("test/datafile2.txt");  
  }
 
  public void readTextFromJar(String s) {
    String thisLine;
    try {
      InputStream is = getClass().getResourceAsStream(s);
      BufferedReader br = new BufferedReader
         (new InputStreamReader(is));
      while ((thisLine = br.readLine()) != null) {  
         System.out.println(thisLine);
         }
      }
    catch (Exception e) {
      e.printStackTrace();
      }
  }
}

Create 2 datafiles. datafile1.txt in the same directory as ReadfromJar.class and datafile2.txt in a subdirectory called test

[datafile1.txt]
datafile1  line 1
datafile1  line 2
datafile1  line 3
datafile1  line 4
datafile1  line 5
[test\datafile2.txt]
datafile2  line 1
datafile2  line 2
datafile2  line 3
datafile2  line 4
datafile2  line 5

Create the jar with

jar cf readjar.jar ReadFromJar.class datafile1.txt test\datafile2.txt

Try with the follwing HTML page

<HTML><HEAD></HEAD>
  <BODY>
    <APPLET CODE=ReadFromJar.class width=1 height=1 archive=readjar.jar></APPLET>
    See java console for output
  </BODY>
</HTML>

NOTE: In Applet, there is some restrictions about the file extension that can be used

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox