Filename arrays in bash

I want to make a filename array to use with ffmpeg under BASH.  For example there are six video files named video_1.h264, video_2.h264, video_3.h264, video_4.h264, video_5.h264 and video_6.h264.
I want to then concat them using ffmpeg
ffmpeg -i "concat:video_1.h264|video_2.h264|video_3.h264|video_4.h264|video_5.h264|video_6.h264" -c copy final.h264
Now I use the current code to do it with 1.h264, 2.h264, 3.h264, etc.
eval segments=\({1..$segments_variable}.h264\)
ifs=$IFS
IFS="|"
ffmpeg -i "concat:${segments[*]}" -c copy video.h264
$segments_variable is the amount of h264 files in the directory.
Now I want the code to automatically detect how many .h264 files in the directory and instead of just being number they have a title in them eg (video_1.h264)
I know how to create an array.  For example
arr=( $(ls $project_*.h264) )
segments_variable=$(echo ${#arr[@]})
$project would equal in this case "video" and segments_variable finds how many files are called video_*.h264.
Any ideas

rockin turtle wrote:
I think this will do what you want.  The files will be sorted lexically according to your locale (I believe).  If you don't want the file sorted in that order, I think you have to explicitly sort them as you wish.
#!/bin/bash
project="$1"
printf -v files "%s|" $project_*.h264
[[ $files =~ [*] ]] || ffmpeg -i "concat:${files%|}" -c copy output.h264
You don't really mean to check for "*" in the variable, but to avoid the case where the path expansion fails. Your check breaks when there is any "*" in the actual filenames. I suggest the `failglob` shopt for your purpose here.
I would also substitute `$project_*.h264` with `"$@"` to let the user pass the filenames, a trivial effort in exchange for much flexibility.

Similar Messages

  • [SOLVED] How to create array in bash from some lines in config file

    I have config file for small script and it looks like this:
    local_directory="$HOME/etc"
    excluded_directory="$HOME/etc1"
    excluded_directory2="$HOME/etc2"
    excluded_directory3="$HOME/etc3"
    I would like to place all "excluded_directoryXX" config options into array that can be parsed to program. This way i have to hardcode it and it is not practical at all.
    Can somebody help me out?
    Last edited by kuraku (2013-09-24 20:45:42)

    @jasonwryan
    Thank you, i was not aware of that builtin. At first i wanted to use this in combination with "grep --after-context=XX" and then i realized that i can use it this way:
    mapfile -s XX -t configs </etc; echo "${configs[@]}"
    Thank you very much.

  • Multiple MovieClips Loading SWF From Same Array (Posted Code)

    Hey there,
    I'm currently working on a project that has eight separate movieclips (for loading content) on separate layers.  I have placed code in these mc's to randomly draw from the same array of 61 different swf's.  Each mc randomizes the array just fine, but here's the problem.  The code works great for one instance, but as soon as I add the code (including renaming) to the other mc's, the swf won't load/play.  I am not getting an compiler errors, and am kinda stuck as to what the problem may be.  Here's an example of the code I'm using.  It is the same for each mc, except I'm renaming the variables as well as the instances for each mc.  Thanks for any suggestions.
    Mike
    //filename = new Array("screen1.swf","screen2.swf","screen3.swf","screen4.swf","screen5.swf","screen6.swf" ,"screen7.swf","screen8.swf","screen9.swf","screen10.swf","screen11.swf","screen12.swf","s creen13.swf","screen14.swf","screen15.swf","screen16.swf","screen17.swf","screen18.swf","s creen19.swf","screen20.swf","screen21.swf","screen22.swf","screen23.swf","screen24.swf","s creen25.swf","screen26.swf","screen27.swf","screen28.swf","screen29.swf","screen30.swf","s creen31.swf","screen32.swf","screen33.swf","screen34.swf","screen35.swf","screen36.swf","s creen37.swf","screen38.swf","screen39.swf","screen40.swf","screen41.swf","screen42.swf","s creen43.swf","screen44.swf","screen45.swf","screen46.swf","screen47.swf","screen48.swf","s creen49.swf","screen50.swf","screen51.swf","screen52.swf","screen53.swf","screen54.swf","s creen55.swf","screen56.swf","screen57.swf","screen58.swf","screen59.swf","screen60.swf","s creen61.swf");
    //i = filename.length;
    //k=random(i)
    //_root.movieTarget.loadMovie(filename[k]);
    //movieTarget._xscale=80;
    //movieTarget._yscale=80;
    var fileNames:Array = ["screen1.swf","screen2.swf","screen3.swf","screen4.swf","screen5.swf","screen6.swf","scr een7.swf","screen8.swf","screen9.swf","screen10.swf","screen11.swf","screen12.swf","screen 13.swf","screen14.swf","screen15.swf","screen16.swf","screen17.swf","screen18.swf","screen 19.swf","screen20.swf","screen21.swf","screen22.swf","screen23.swf","screen24.swf","screen 25.swf","screen26.swf","screen27.swf","screen28.swf","screen29.swf","screen30.swf","screen 31.swf","screen32.swf","screen33.swf","screen34.swf","screen35.swf","screen36.swf","screen 37.swf","screen38.swf","screen39.swf","screen40.swf","screen41.swf","screen42.swf","screen 43.swf","screen44.swf","screen45.swf","screen46.swf","screen47.swf","screen48.swf","screen 49.swf","screen50.swf","screen51.swf","screen52.swf","screen53.swf","screen54.swf","screen 55.swf","screen56.swf","screen57.swf","screen58.swf","screen59.swf","screen60.swf","screen 61.swf"]
    fileNames.sort(function () {
        return Math.round(Math.random());
    trace("Random array: " + fileNames);
    var currentMovieNum:Number = 0    ;
    this.createEmptyMovieClip("container", _root.getNextHighestDepth());
    var mcl:MovieClipLoader = new MovieClipLoader();
    var mclListener:Object = new Object();
    mcl.addListener(mclListener);
    mclListener.onLoadInit = function(movieTarget:MovieClip) {
        trace("Preparing to play: " + fileNames[currentMovieNum]);
    movieTarget.loadClip(fileNames[currentMovieNum], container);
    movieTarget._xscale=80;
    movieTarget._yscale=80;
    this.onEnterFrame = function() {
        if (currentMovieNum == fileNames.length) {
            currentMovieNum = 0;
        } else {
            if (movieTarget._currentframe == movieTarget._totalframes) {
                mcl.loadClip(fileNames[currentMovieNum], movieTarget);
                currentMovieNum++;

    Thanks for taking a look at this.  The randomizer seems to work just fine, as here is a sample output from the trace:
    Random array: screen47.swf,screen2.swf,screen57.swf,screen21.swf,screen9.swf,screen49.swf,screen36.swf, screen17.swf,screen6.swf,screen59.swf,screen15.swf,screen12.swf,screen33.swf,screen25.swf, screen42.swf,screen22.swf,screen24.swf,screen40.swf,screen11.swf,screen19.swf,screen32.swf ,screen35.swf,screen7.swf,screen39.swf,screen23.swf,screen4.swf,screen1.swf,screen48.swf,s creen31.swf,screen45.swf,screen29.swf,screen18.swf,screen51.swf,screen14.swf,screen34.swf, screen10.swf,screen38.swf,screen26.swf,screen16.swf,screen13.swf,screen55.swf,screen37.swf ,screen44.swf,screen61.swf,screen43.swf,screen20.swf,screen28.swf,screen30.swf,screen56.sw f,screen50.swf,screen54.swf,screen53.swf,screen46.swf,screen58.swf,screen41.swf,screen8.sw f,screen5.swf,screen52.swf,screen3.swf,screen60.swf,screen27.swf
    Might you be able to lead me down a better path?  I'm currently unable to get this to function for multiple symbols.  The previous is the code that I've placed on the first keyframe of a movieclip with an instance name of movieTarget.  Works swimmingly for one, but once the code is placed on the other symbols on different layers, it seems to only work on the lowest layer in the project.
    M

  • Bash - open file with

    Hello guys,
    I'd like to type in just the filename in a bash shell and the file should then be opened with the program I'd defined previously.
    Example
    Instead of zathura name.pdf, the pdf should be opened with zathura when I only type in name.pdf.
    Is that possible?
    It's not directly an alias so I don't come up with a solution yet.
    Regards

    I also have a xdg-open independent solution, in .bashrc i have
    . ~/.bash_suffix
    add_filetype 'pdf|ps|djvu|dvi' evince
    add_filetype 'jpg|JPG|jpeg|JPEG|png|PNG' gqview
    prompt_command() {
    if [ $? -eq 127 ]; then
    local -a FILES=( $(history 1) )
    local FILE=${FILES[1]}
    local COMMAND="$(get_program ${FILE})"
    if [ -f "${FILE}" ] && [ "${COMMAND}" ]; then
    echo -en "\e[1A\e[2K" # Erase error message
    "${COMMAND}" "${FILE}"
    fi
    fi
    PROMPT_COMMAND=prompt_command
    and ~/.bash_suffix:
    #!/bin/bash
    declare -A MIMETYPES
    add_filetype() {
    OLD_IFS="$IFS"
    IFS="|"
    local COMMAND="$2"
    set $1 #EDIT
    for SUFFIX in $@; do
    MIMETYPES["$SUFFIX"]="${COMMAND}"
    done
    IFS=$OLD_IFS
    get_program() {
    local SUFFIX="${1##*.}"
    if [ "${SUFFIX}" ]; then
    local COMMAND="${MIMETYPES[$SUFFIX]}"
    [ "$COMMAND" ] && echo $COMMAND
    fi
    hbekel wrote:On a related note, does anyone know how to teach bash to complete a bare path down to a non-executable file?
    In vi-mode "\" will complete filenames even if the filename is the first token or you can bind complete-filename to a key (default is M-/).
    Last edited by portix (2010-05-22 16:15:46)

  • Looping around an arraylist of strings to find matches(more complicated!)

    Total Posts: 1
    Help developing an algortim
    Posted: 03-05-2006 07:11 AM
    Hi,
    I have been bashing my head with this for a while, so any help is much appreciated!
    I bascially have ONE arraylist which contains filenames as strings (e.g. file.txt, file1.xml, file2.doc, file2.xml, file2.txt)
    The arraylist bascially contains a document name with there associated metadata document names. For example file1.doc (document file), file1.xml (metedata file).
    There will be siuations where for example file1.doc may not have an associated file1.xml file with it. And there may be situations where there are 2 documents and only one associated metadata file (e.g. file.doc, file1.txt, file1.xml)
    I basiclaly need to loop arond the arraylist identifying only files names that:
    - have an associated metadatafile (once identified put the document name in an arraylist of matches)
    -this arraylist cannot contain duplicate documents with an associated file name (e.g. file.doc, file1.txt, file1.xml), if this particualr situations occurs I want to put these filenames in an arraylist of errors.
    Please help! thanks in advance

    I'm a little lost as to how
    >(e.g. file.doc, file1.txt, file1.xml)
    contains duplicate documents with an associated filename. Either the .txt and .xml are both metadata files, and you are saying that there should never exist two metadata documents of the same name, or else you meant to say
    (e.g. file1.doc, file1.txt, file1.xml)in which case you meant that two data files (the .doc and the .txt) with the same name (file1) cannot exist together if there exists a metadata .xml of the same name.
    Assuming the latter is true, try something like this: (hot off the grill ;)
    import java.util.*;
    public class Blah {
       public static void main(String[] args) {
          List<String> fileNames = Arrays.asList( new String[] {
             "File1.txt", "File2.txt", "File1.xml", "File1.doc", "File1.blah", "File3.doc",
             "File4.xml", "File4.txt", "File5.doc", "File6.doc", "File6.xml", "File7.csv",
             "File7.xsl", "File7.xml", "File8.xml", "File9.doc", "File90.txt"
          String metadataExtension = "xml";
          Map<String, Set<String>> pendingFileNames = new TreeMap<String, Set<String>>();
          Set<String> metadataNamesFound = new TreeSet<String>();
          Map<String, String> verifiedMetadataFileNamePair = new TreeMap<String, String>();
          Map<String, Set<String>> verifiedBadFileNames = new TreeMap<String, Set<String>>();
          Set<String> verifiedFileNamesWithoutMetadata = new TreeSet<String>();
          Set<String> verifiedMetadataWithoutFileName = new TreeSet<String>();
          for (String fileName: fileNames) {
             String[] halves = fileName.split("\\.");
             System.out.println(halves[0]+" "+halves[1]);
             String nameOnly = halves[0];
             String extension = halves[1];
             Set<String> associatedExtensions = pendingFileNames.get(nameOnly);
             if (associatedExtensions == null) {
                associatedExtensions = new TreeSet<String>();
                pendingFileNames.put(nameOnly, associatedExtensions);
             if (extension.equals(metadataExtension)) {
                metadataNamesFound.add(nameOnly);
             } else {
                associatedExtensions.add(extension);
          for (String name: pendingFileNames.keySet()) {
               Set<String> fileExtensions = pendingFileNames.get(name);
               boolean metaNameWasFound = metadataNamesFound.contains(name);
               String fullMetaName = name+"."+metadataExtension;
               if (fileExtensions == null || fileExtensions.size() == 0) {
                 if (metaNameWasFound)
                     verifiedMetadataWithoutFileName.add( fullMetaName );
               } else if (fileExtensions.size() == 1) {
                  String fullFileName = name+"."+fileExtensions.iterator().next();
                  if (metaNameWasFound)
                     verifiedMetadataFileNamePair.put(fullFileName, fullMetaName);
                  else
                     verifiedFileNamesWithoutMetadata.add(fullFileName);
               } else {
                 if (metaNameWasFound)
                     verifiedBadFileNames.put( name, fileExtensions );
                  else {
                    for(String extName: fileExtensions) {
                        verifiedFileNamesWithoutMetadata.add(name+"."+extName);
          System.out.println();
          System.out.println();
          // System.out.println(pendingFileNames);
          System.out.println("Verified one-to-one file/metadata pairs: \n"+verifiedMetadataFileNamePair);
          System.out.println("\nVerified errors (more than one document to one metadata): \n"+verifiedBadFileNames);
          System.out.println("\nVerified metadataless files: \n"+verifiedFileNamesWithoutMetadata);
          System.out.println("\nVerified fileless metadata: \n"+verifiedMetadataWithoutFileName);
    }

  • Error Cluster Propagation Issue

    Consider the following diagram:
    This VI is intended to be used in a chain of VIs.
    This VI copies a file to a folder, and in case of error, tries with another path of the file (located in a "backup" location)
    Due to the intrinsic dataflow programming model, how can I manage the error in the arrow place????
    The behaviour I want is this:
    if (error in == true) --> skips all and propagates error_in to error_out
    else { try to copy, and in case of error try with backup copy. If errors again then report the error (custom error code) }
    Is it possible???
    thanks
    Solved!
    Go to Solution.

    thanks all,
    the note about the "lost warning" was really interesting, I never noticed it because I never used warning.
    I discovered another source of bug.
    Consider the following:
    If error_in is true, the error_out would be false.
    The reason is that the filename array is EMPTY and the for case is never executed, so error_out takes a default value.
    As a consequence the error is not correctly propagated.
    I think this is not trivial to see at a first glance.

  • GetFirstFile() and non-english chars

    Hi,
    When using GetFirstFile() / GetNextFile(), if a file is encountered with Chinese chars in it's filename, each of these chars is replaced with a "?".
    As a result, I cant open the file as I dont know its full name.
    Does anyone know of a way around this? Some Windows SDK function maybe?
    cheers,
    Darrin.

    Hi Diz@work,
    Thanks for posting on the NI Discusson Forums. 
    I have a couple questions for you in order to troubleshoot this issue:
    Which language is your Windows operating system set to? Chinese or English?
    When you say that the filename returned contains '?' characters instead of the Chinese characters, do you mean you see this when you output to a message popup panel or print to the console? Are you looking at the values in fileName as you're debugging? Can you take a look at the actual numerical values in the fileName array and see which characters they map to? It's possible that the Chinese characters are being returned correctly, but the function you're using to output them doesn't understand the codes they use.
    Which function are you using to open the file with the fileName you get from GetFirstFile()? Can you take a look at what's being passed to it?
    CVI does include support for multi-byte characters. Take a look at this introduction:
    http://zone.ni.com/reference/en-XX/help/370051V-01/cvi/programmerref/programmingmultibytechars/
    As far as the Windows SDK goes, I did find that the GetFirstFile() and GetNextFile() functions are based on the Windows functions, FindFirstFile() and FindNextFile(). According to MSDN, these functions are capable of handling Unicode characters as well as ASCII:
    http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx
    There may be a discrepancy between how these functions are being called and/or what they're returning to the CVI wrapper functions.
    Frank L.
    Software Product Manager
    National Instruments

  • How Do You View PHP in DW and Safari with a MAMP Server?

    It almost works! I have just installed and set up MAMP. I haven't made a MySQL database and user account yet, (I'm not sure if it will make any difference if I do) but I followed the instructions - http://www.adobe.com/devnet/dreamweaver/articles/setup_php.html - up to that point. And I have had a problem!
    The test file in the exercise is a php file which tells you the time, it works in dreamweaver (when you select live view) But when you put the file into a browser it does not work! What is going wrong here? Can anybody help?
    Also, my other php files display in Dreamweaver live view but not in either browser (Safari or Firefox)!! Annoying!

    Here is the code …
    <!doctype html> 
    <html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Gallery_Test</title> 
    <!--[if lt IE 9]> 
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
    <![endif]--> 
    <!--LATEST JQUERY CORE LIBRARY--> 
    <script src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <!--FANCYBOX plugins--> 
    <link href="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/jquery.fancybox.css" rel="stylesheet" media="screen"> 
    <script src="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/jquery.fancybox.pack.js"></script> 
    <style> 
        padding: 0; 
        -moz-box-sizing: border-box; 
        -webkit-box-sizing: border-box; 
        box-sizing: border-box; 
    h1{
        font-family: Georgia, "Times New Roman",Times, Serif;
      text-align:center;
        font-size: 18px;
        font-weight: bold;
    h2 {
        font-family: Georgia, "Times New Roman", Times, Serif;
      text-align:center;
        font-size: 13px;
        font-weight: normal;
    body {
      margin: 0;
      padding: 0;
      background: #6C9;
      color: #333;
      font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", "DejaVu Sans", Verdana, sans-serif;
      font-siz: 100%;
      background-color: #003;
    #wrapper { 
        width: 1000px; /**adjust width in px or %**/ 
        margin: 0 auto; /**with width, this is centered**/ 
    header { 
        background: #355DA0; 
        width: 100%; 
        margin: 0 auto; 
        color: #FFF; 
    #inner_wrapper { 
        background: #3366FF; 
        overflow: hidden; /**float containment**/ 
    aside { 
        float: left; 
        width: 11%; 
    section { 
        background: #FFF; 
        width: 78%; 
        float: left; 
        margin: 0 auto; 
    /**Begin image gallery styles**/ 
    .thumbs { /*divs that hold gallery pictures*/ 
        float: left; 
        margin: 0.5%; /*space between thumbnails*/ 
        border: 1px dotted #CCC; 
        /**same size images**/ 
        width: 90px; 
        height: 99px;
    .thumbs a { /* in every .thumbs div there is a hyperlink exactly the size of the container */ 
        width: 90px; 
        height: 99px; 
        text-indent: -99999px; /*move text links off screen*/ 
        display: block; 
        outline: none; 
    /**end gallery styles**/ 
    footer { 
        clear: both; 
        background: #222; 
        width: 100%; 
        color: #FFF; 
        margin: 0 auto 
    </style> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head> 
    <body link="#FFFFFF" vlink="#FFFFFF" alink="#FF0066"> 
    <div id="wrapper"> 
    <header> <h1><a href="index_01.html">Return to Index</a></h1> 
    <h2>My Photos - [72 images 2000 x 1330] - 5th of September  2014</h2> 
    </header> 
    <div id="inner_wrapper"> 
    <aside> </aside> 
    <section>
      <?php 
    $directory = 'gallery/thumbs_1'; //path to your thumbnails 
    $link = 'gallery/slides_1'; //path to your full-sized images 
    $allowed_types = array('jpg','jpeg','gif','png'); 
    $aFiles = array(); 
    $dir_handle = @opendir($directory) or die("There is an error with your image directory!"); 
    while ($file = readdir($dir_handle)) //traverse through files 
    if($file=='.' || $file == '..') continue; //skip links to parent directories 
    $file_parts = explode('.',$file); //split filenames and put each part in an array 
    $ext = strtolower(array_pop($file_parts)); //last element is the file extension 
    $title = implode('.',$file_parts); //what's left is the filename 
    if(in_array($ext,$allowed_types)) 
    $aFiles[] = $file; //filename array 
    closedir($dir_handle); //close directory 
    natsort($aFiles); // natural sort by filename 01, 02, 10, 20 
    $i=0; 
    foreach ($aFiles as $file) { 
    $file_parts = explode('.',$file); //split filenames and put each part in an array 
    $ext = strtolower(array_pop($file_parts)); //last element is the file extension 
    $title = implode('.',$file_parts); //what's left is the filename 
    $title = htmlspecialchars($title); //make it html-safe 
    echo '<div class="thumbs" style="background:url('.$directory.'/'.$file.') no-repeat 50% 50%"> 
    <a class="fancybox" data-fancybox-group="gallery" href="Gallery/slides/'.$file.'" title="'.$title.'">'.$title.'</a> 
    </div>'; 
    $i++; //increment the image counter 
    ?> 
    <!--end gallery-->  
    </section> 
    <aside> </aside> 
    <!--end inner_wrapper--></div> 
    <footer> </footer> 
    <!--end wrapper--></div> 
    <!--FancyBox function code-->  
    <script> 
    $(document).ready(function() { 
        $('.fancybox').fancybox(); 
    </script> 
    </body> 
    </html>

  • Playlist creator for mp3s and wma's

    I wrote the following pretty quickly this morning to traverse a directory and it's child directories to look for any mp3/wma files in that directory and make a windows media m3u playlist (basically, the file names separated by newlines).
    I thought I'd post it if anyone needs it or if anyone can find something I'm overlooking. It seems to work correctly, but it's hardly tested well.
    -Chuck
    // PlaylistCreator.java source file
    // By Chuck Reed
    // Usage: Creates a folder playlist for any folder or subfolder containing mp3 files
    // This program will need the java file IO utilities
    import java.io.*;
    // The main class for the playlist creator
    public class PlaylistCreator
      private static String CurrentDirectory;          // A member to keep track of the current directory
      private static File WorkingFilePointer;          // The location of the working file's pointer
      private static String[] FileNames;               // Array of file names read in from directory
      // The main class to drive the playlist creator
      public static void main(String args[])
        try
           // Find our directory name and pointers, then run the recursive directory processor
               WorkingFilePointer = new File(System.getProperty("user.dir"));
               ProcessAllDirs(WorkingFilePointer);
          } catch (Exception e)
          // If something fails, catch the exception
            System.err.println(e);
      // This is the method that actually creates a playlist file in the current directory
      private static void CreatePlaylist(File CurFilePointer)
        try
          // Store the file names and initialize the mp3 counter
            int Mp3Count = 0;
          FileNames = CurFilePointer.list();
          // If we don't have anything in the folder, return doing nothing
          if (FileNames == null)
            return;
          // Loop through all of the files returned in this directory
            for (int i = 0; i < FileNames.length; i++)
                if ( IsMp3File(FileNames) )
    Mp3Count++;
    // If we don't have any mp3s to make a list of, bail
    if (Mp3Count < 1)
              return;
    // Create the output stream and format it properly
              PrintStream OutputStream = new PrintStream(
              new BufferedOutputStream(
                                                                new FileOutputStream(CurFilePointer.getAbsolutePath() + "\\00 - FolderPlaylist.m3u")));
    // Loop through all of the files we have in the directory
    for (int i = 0; i < FileNames.length; i++)
         // See if mp3 is at the index of length - 4
              if ( IsMp3File(FileNames[i]) )
    // Print out the mp3 file name to the next line of the playlist
              OutputStream.println(FileNames[i]);
    // Close the playlist file
    OutputStream.close();
    } catch (Exception e)
    // Catch and report any exceptions we get
         System.err.println(e);
    // Recursive function to visit each subdirectory in the directory structure and create playlists
    private static void ProcessAllDirs(File dir)
    // If our current location is a directory, lets check it for subdirectories or mp3s
    if (dir.isDirectory())
    // Call create playlist on our current directory in case we have mp3 files here
    CreatePlaylist(dir);
    // Get a list of all subdirectories
    String[] children = dir.list();
    // Loop through the child directories
    for (int i=0; i < children.length; i++)
    // Call this function recursively on the child directory
    ProcessAllDirs(new File(dir, children[i]));
    // A method to determine if a file ends in .mp3 or .MP3 or .WMA or .wma
    private static boolean IsMp3File(String name)
    // We can't have anything valid with a length of under 4
    if (name.length() < 4)
         return false;
    // If we have the correct file suffix
    if ( (name.indexOf(".mp3") == (name.length() - 4)) || (name.indexOf(".MP3") == (name.length() - 4)) ||
         (name.indexOf(".wma") == (name.length() - 4)) || (name.indexOf(".WMA") == (name.length() - 4)))
    // We return true
         return true;
    // Otherwise, this isn't a valid mp3 file
         return false;

    I have also Paid this morning, approximately 3-4 hours ago, and cannot play from my phone, or play ad free on my mac.
    This quite frankly pisses me off and this is unacceptable. I paid money for your service which doesn't even work. Sooo give me a free month or fix your problems. I don't pay your company money for **bleep** that doesnt work.
    I've recevied my Receipt of payment already, and it's processed through my bank account. This does not make me very happy at all. 

  • Publishing pages with non-ASCII characters to folder

    There is a weirdness/anachronism in exported file names from iWeb'08.
    I have a page "Mökin katto" (that is Finnish).
    "ls" in Terminal shows the exported folder ok, like
    Mökin_katto.html
    Mökinkattofiles/
    Tarring and uploading to show on my Apache web server did not work so good, though. I changed the server to operate in UTF-8 locale and also use UTF-8 as the default character set. Still no success. At this point, I wanted to check the exported folder in the source (my MacBook). Tab completion didn't work:
    % Mö<TAB>
    didn't give any results. At this point, I wrote a simple Python script to dump the filenames. I created pages with different Scandinavian characters and capitalizations to demonstrate (I have cleaned the output a bit to remove unnecessary filenames):
    % ls
    MäkiÄn_katto.html MökiÖn_katto.html feed.xml
    MäkiÄnkattofiles/ MökiÖnkattofiles/ index.html
    MåkiÅn_katto.html Mökin_katto.html
    MåkiÅnkattofiles/ Mökinkattofiles/
    % ~/repos/scripts/misc/dirdump.py
    MäkiÄn_katto.html 'M(4d)' 'a(61)' cc88 'k(6b)' 'i(69)' 'A(41)'cc 88 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '.(2e)' 'h(68)' 't(74)' 'm(6d)' 'l(6c)'
    MäkiÄnkattofiles 'M(4d)' 'a(61)' cc88 'k(6b)' 'i(69)' 'A(41)'cc 88 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '_(5f)' 'f(66)' 'i(69)' 'l(6c)' 'e(65)' 's(73)'
    MåkiÅn_katto.html 'M(4d)' 'a(61)' cc8a 'k(6b)' 'i(69)' 'A(41)'cc 8a 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '.(2e)' 'h(68)' 't(74)' 'm(6d)' 'l(6c)'
    MåkiÅnkattofiles 'M(4d)' 'a(61)' cc8a 'k(6b)' 'i(69)' 'A(41)'cc 8a 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '_(5f)' 'f(66)' 'i(69)' 'l(6c)' 'e(65)' 's(73)'
    Media 'M(4d)' 'e(65)' 'd(64)' 'i(69)' 'a(61)'
    Mökin_katto.html 'M(4d)' 'o(6f)' cc88 'k(6b)' 'i(69)' 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '.(2e)' 'h(68)' 't(74)' 'm(6d)' 'l(6c)'
    Mökinkattofiles 'M(4d)' 'o(6f)' cc88 'k(6b)' 'i(69)' 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '_(5f)' 'f(66)' 'i(69)' 'l(6c)' 'e(65)' 's(73)'
    MökiÖn_katto.html 'M(4d)' 'o(6f)' cc88 'k(6b)' 'i(69)' 'O(4f)'cc 88 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '.(2e)' 'h(68)' 't(74)' 'm(6d)' 'l(6c)'
    MökiÖnkattofiles 'M(4d)' 'o(6f)' cc88 'k(6b)' 'i(69)' 'O(4f)'cc 88 'n(6e)' '_(5f)' 'k(6b)' 'a(61)' 't(74)' 't(74)' 'o(6f)' '_(5f)' 'f(66)' 'i(69)' 'l(6c)' 'e(65)' 's(73)'
    Scripts 'S(53)' 'c(63)' 'r(72)' 'i(69)' 'p(70)' 't(74)' 's(73)'
    Apparently Ö and ö are translated to the sequences '"O" 0xcc 0x88' and '"o" 0xcc 0x88', Ä and ä to '"A" 0xcc 0x88' and '"a" 0xcc 0x88' and finally Å and å to the sequences '"A" 0xcc 0x8a' and '"a" 0xcc 0x8a'. Looking into this a bit more, those ("0xcc 0x88" and "0xcc 0x8a") are the UTF-8 encodings of COMBINING DIAERESIS (U+308) (http://www.fileformat.info/info/unicode/char/0308/index.htm) and COMBINING RING ABOVE (U+030A) (http://www.fileformat.info/info/unicode/char/030a/index.htm).
    The generated links in the pages are in the short (Latin1 equivalent) form, but the filenames are in this format. The meaning of the strings is the same, but e.g. Apache doesn't internally canonicalize the paths, which results in broken URLs. I think iWeb should export the filenames and the URLs in identical UTF-8 strings (which quite likely should be the Latin1-equivalent Unicode code points). Especially as e.g. Terminal and bash only work with the short forms.
    Is there an option to make iWeb behave this way?

    I tried checking whether changing my keyboard layout (I've created the current one with Ukelele) to one which wrote decomposed characters changed things; it didn't. The filenames and generated html-files contained identical entries; I could use tab-completion for the generated filenames, though. (Bash was otherwise a bit confused about the change, so I can't recommend this)
    By canonicalizing the filenames with a script on the server (a Debian GNU/Linux system) end I can now make it work; the root cause of the discrefence between the file name and the URLs in the generated HTML is still a mystery. This would've worked if iWeb wrote decomposed UTF-8 characters to the URLs, also.

  • Parse files in directory newer than MM/DD/YYYY

    In the attached VI I am trying to figure out how to pull in and parse all .txt log files in Folder path newer than a particular date instead of just the *.txt (all text files) as it is set to now. The date I will be entering from a sub VI is a string in the format MM/DD/YYYY. The date & time are included in the file names. The comma delimited .txt file names are broken down into "TesterID UUTSerial# Date TimeTested.txt". I have attached one of the comma delimited .txt files that the path contains. Anyone have any suggestions? I am running LV2009 SP1.
    Thanks!
    Solved!
    Go to Solution.
    Attachments:
    Concatenate Files.vi ‏12 KB
    2 123456789 Jun 24 2010 124729.txt ‏1 KB

    Extracting the date from the filename and comparing it to an input date seemed like a fun thing to write.  So I wrote a VI to do that.  Here it is.  Just wire in the filenames array and the desired date to compare.  The output is a list of files that are greater than or equal to the specified date.  You can change the compare function if you want something different.  The filename must have a 3-letter month followed by a space, followed by a date, another space, the year, a space then whatever else.  The compare date must be in the form mm/dd/yyyy.
    - tbob
    Inventor of the WORM Global
    Attachments:
    File_GTEQ_Date.vi ‏22 KB

  • Lion: Connecting to legacy (pre-Lion) AFP services - and Mac OS X (server)

    After upgrading to MacOS X Lion, it was discovered that it was not possible to logon to Novell-shares and NAS-boxes (e.g. Qnap).
    Here is a recipe that has been tested OK with the following combinations:
    * Mac OS X Lion -> Novell shares
    * Mac OS X Lion -> Mac OS X 10.5 server
    * Mac OS X Lion -> Mac OS X Lion
    Please note that the command-lines themselves must not have CR/NL-characters. Copy the commands to a text-editor and remove format-inserted CR/NL-characters.
    Another note: Your logon will be less secure with these changes. Later when e.g. Novell and/or your NAS-box support native Lion-logon, then please remove the AppleShareClient-parameter changes again with the first block.
    Recipe:
    The following block can be skipped if you have not previously changed AppleShareClient-parameters:
    sudo -s
    chmod o+w /Library/Preferences
    cd  /Library/Preferences/
    rm com.apple.AppleShareClient.plist*
    ! Restart
    The following block makes it possible to logon to: (1) Novell-shares (2) Pre Lion Mac-OS-X-volumes - and possibly non-native Lion logon NAS-shares:
    sudo -s
    chmod o+w /Library/Preferences
    defaults write /Library/Preferences/com.apple.AppleShareClient afp_host_prefs_version -int 1
    ! Restart
    You now have to logon a real account (non-guest) on another Mac OS X Lion volume
    to catalyst a creation of AppleShareClient-files. (See Apple-support-link) (Is this necessary?)
    ! instead?:
    /bin/sleep 60
    chmod o+w /Library/Preferences
    defaults write /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams -array "Cleartxt Passwrd" "MS2.0" "2-Way Randnum exchange"
    defaults write /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams -array "DHX2"
    defaults write /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams -array "DHCAST128"
    chmod o-w /Library/Preferences
    PS:
    Possibly all volume-links may be deletes and recreated to use the new logon-parameters?
    Sources for command-bricks:
    OS X Lion: Connecting to legacy AFP services:
    http://support.apple.com/kb/HT4700
    AFP changes in OSX Lion:
    http://www.novell.com/communities/node/13155/afp-changes-osx-lion
    AFP support for DHX2 authentication mechanism on OES:
    http://www.novell.com/support/search.do?cmd=displayKC&docType=kc&externalId=7008 683&sliceId=1&docTypeID=DT_TID_1_1
    "/bin/sleep 60":
    Making My NAS Work in Lion:
    http://krypted.com/mac-os-x/making-my-nas-work-in-lion/
    Example:
    bash-3.2# chmod o+w /Library/Preferences
    bash-3.2# cd  /Library/Preferences/
    bash-3.2# rm /Library/Preferences/com.apple.AppleShareClient.plist*
    bash-3.2# chmod o-w /Library/Preferences
    bash-3.2#
    ! Restart
    Last login: Fri Aug 12 14:41:58 on console
    $ sudo -s
    Password:
    bash-3.2# chmod o+w /Library/Preferences
    bash-3.2# defaults read /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams
    2011-08-12 14:42:31.172 defaults[188:707]
    The domain/default pair of (com.apple.AppleShareClient, afp_disabled_uams) does not exist
    bash-3.2#
    ! Restart
    Last login: Fri Aug 12 14:47:31 on console
    $ sudo -s
    Password:
    bash-3.2# chmod o+w /Library/Preferences
    bash-3.2# defaults write /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams -array "Cleartxt Passwrd" "MS2.0" "2-Way Randnum exchange"
    bash-3.2# defaults read /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams(
        "Cleartxt Passwrd",
        "MS2.0",
        "2-Way Randnum exchange"
    bash-3.2# defaults write /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams -array "DHX2"
    bash-3.2# defaults read /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams
        DHX2
    bash-3.2# defaults write /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams -array "DHCAST128"
    bash-3.2# defaults read /Library/Preferences/com.apple.AppleShareClient afp_disabled_uams
        DHCAST128
    bash-3.2# chmod o-w /Library/Preferences
    bash-3.2#
    Also posted here:
    Lion: Connecting to legacy (pre-Lion) AFP services - and Mac OS X (server):
    http://forum.qnap.com/viewtopic.php?f=30&t=48143
    http://forums.macrumors.com/showthread.php?p=13166617

    hammer58 wrote:
    Thanks for your response, but this all looks pretty complicated to me.  I am not sure from this which lines I need to use and what I don't need.
    What are CR/NL characters?
    In plain text files carriage-return (CR) and new-line (NL) has:
    LF, NL: decimal 10, hexadecimal 0x0A
    CR: decimal 13, hexadecimal 0x0D
    References:
    http://en.wikipedia.org/wiki/Carriage_return
    http://en.wikipedia.org/wiki/Line_feed
    http://www.asciitable.com/
    Especially:
    http://en.wikipedia.org/wiki/Line_feed#Representations
    Quote: "...
    CR+LF: Microsoft Windows, DEC TOPS-10, RT-11 and most other early non-Unix and non-IBM OSes, CP/M, MP/M, DOS (MS-DOS, PC-DOS, etc.), Atari TOS, OS/2, Symbian OS, Palm OS
    LF+CR: Acorn BBC spooled text output.
    CR:   Commodore 8-bit machines, Acorn BBC, TRS-80, Apple II family, Mac OS up to version 9 and OS-9
    LF:   Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others.
    RS:   QNX pre-POSIX implementation.
    http://en.wikipedia.org/wiki/Newline#Unicode
    Quote:"...
    The Unicode standard defines a large number of characters that conforming applications should recognize as line terminators:[3]
    LF:   Line Feed, U+000A
    VT:   Vertical Tab, U+000B
    FF:   Form Feed, U+000C
    CR:   Carriage Return, U+000D
    CR+LF: CR (U+000D) followed by LF (U+000A)
    NEL:  Next Line, U+0085
    LS:   Line Separator, U+2028
    PS:   Paragraph Separator, U+2029
    If you have Linux, classic Mac or Windows/DOS text files, and you want to convert their LF/CR-flavor to another, then TextWrangler can do it for you; choose new LF/CR-combination via bottom button of the text file window. TextWrangler can be downloaded for free - also via App Store.
    TextWrangler:
    http://www.barebones.com/products/textwrangler/

  • Automatically layout large # of images, and rollovers?

    Hello:
    I have about 400 images that I'd like to put in a simple grid layout, and I'm wondering if there's any way to do it that doesn't involve typing in all 400 filenames into the HTML. All the files are located in a single directory and are uniformly named (filename1, filename2...). Is there a way to batch place a large number of images? I'm happy to place them in a table, or using CSS, or whatever works.
    On a related note, I'd also like to learn how to set up the grid so that when the user rolls over an image, that image is displayed larger and, notably, doesn't screw up the layout of the rest of the images -- for example, display the image centered in a new layer superimposed over the grid. I've already got preview and full-size images of all 400 files. I'm sure there's already a thread about this somewhere, but I've searched the forums and I suspect I don't know enough about Dreamweaver yet to know what to look for in the responses.
    Any help would be greatly appreciated. I'm obviously new to all this, but am having a great deal of fun learning. Thank you!
    -Stephen

    Be aware that Java is not the same as JavaScript.  Which are you referring to?  If the former, then I don't think it's much of a practical solution.
    The approach I suggested would work either as a static one (i.e., showing you the code locally which you copy and paste into a real page) or a dynamic one (i.e., the PHP actually builds the matrix of images on the live page), as does Nancy's solution.  In either event, you would need to know enough PHP to be able to build the filename array, and loop through the filenames while you build the matrix of images (and their links to a lightbox-type display).  If you are indeed fluent in Java then PHP should be something you can cobble together - it's very C-like.
    The good news is that if you take Nancy's suggested approach, then any new images would automatically be added to the matrix since each time you create the matrix, you do so from the filenames that are found in that image directory.

  • Using sockets to relay video stream

    Hi there,
    I've been working with java for 4 years now, and I never had troubles making the applications I wanted with it...since my last project :(
    I hope you, gurus from the java community forum, can help me sort this out, but let me explain it to you:
    I'd like to stream video content (let's say from a webcam) to several spectators. But my upload bandwidth (ADSL line) is limited to 512kbps, which is far from enough to send a video streaming (with a bitrate of ~400kbps) to 10 or more viewers.
    That's why I decided to rent a distant server (with a bandwidth of 5Mbps download/upload), and make a java application run on it, which would be able to broadcast the stream to all the viewers.
    So my computer (connected to adsl) captures the video from the webcam, sends it via socket to the rented server, which broadcasts the video to all the spectators. If no video is sent to the rented server, then it should broadcast local files to the spectators.
    Here is a schema of the project so you understand easily (my english is not as good as I'd like it to be, so you may not understand with words only):
    http://www.bf-stream.com/schema1.gif
    My application runs quite well with 5 spectators, but as soon as more viewers come to see the video, it starts hanging, and all the viewers suffer lags and buffering, which is not exactly what I expected...
    Of course, I checked the administration interface on the rented server to see if this was due to a cpu/ram/bandwitdh problem. With no success: with 10 viewers connected, the app uses less than 1% of the cpu power, something like 200kb of RAM, and a bandwidth of 3-4Mbps (which is still under the actual bandwidth capacity of the server).
    That's why I came to the conclusion that my java app was not as good as I thought, and decided to show it to you, so you can help me make it better.
    So here is a schema showing the classes and their interactions:
    http://www.bf-stream.com/schema2.gif
    And here are the sources of the classes:
    StreamRelay.java:
    package com.RR4;
    import java.net.Socket;
    import java.util.Vector;
    import java.util.Observable;
    import java.util.Observer;
    * StreamRelay:
    *  Main class controlling every aspects of the stream
    *  (live content, or files read from hard disk)
    public class StreamRelay extends Observable implements Observer  {
         static public String VERSION = "0.5";
         static public int BUFFER_SIZE = 16;
         private StreamServer streamServer;
         private LiveServer liveServer;
         LocalFile localFile;
         Vector clients;
         boolean streamFromSocket;
         public StreamRelay(int livePort, int relayPort) {
              streamFromSocket = false;
              // clients: vector containing every StreamClient connected
              clients = new Vector();
              // localFile: class reading local files when no live is sent to the relay
              localFile = new LocalFile(this);
              new Thread(localFile).start();
              // streamServer: server listening for new StreamClient
              streamServer = new StreamServer(this, relayPort);
              new Thread(streamServer).start();
              // liveServer: server listening for new sources for live content
              liveServer = new LiveServer(this, livePort);
              new Thread(liveServer).start();
         * addClient: adds new StreamClient to 'clients' vector (a StreamClient is a 'spectator')
         public void addClient(Socket clientSocket) {
             StreamClient client = new StreamClient(this, clientSocket);
         * removeClient: removes a StreamClient from 'clients' vector
         public void removeClient(int index) {
              clients.remove(index);
         * update: updates every StreamClient (which are all Observers of StreamRelay)
         public void update(Observable observable, Object obj) {
              if ((observable.getClass().toString().indexOf("LocalFile")!=-1&&!streamFromSocket)||(observable.getClass().toString().indexOf("LiveStream")!=-1)) {
                   this.notifyObservers( (byte[]) obj);
                   this.setChanged();
         public static void main(String[] args) {
              new StreamRelay(8000, 8080);
    LocalFile.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    * LocalFile: class reading local file when no live content is sent to the relay
    public class LocalFile extends Observable implements Runnable {
         // filenames is an array containing a list of files to be read when no live content is sent
         private String[] filenames = {
              "file1",
              "file2"
         private InputStream stream;
         boolean streamOpened;
         private StreamRelay parent;
         int fileIndex;
         // Constructor: initialises LocalFile
         //  sets fileIndex to 0, and sets main StreamRelay as Observer
         public LocalFile(StreamRelay parent) {
              this.parent = parent;
              fileIndex = 0;
              this.addObserver(parent);
              initStream();
          * initStream: initialises stream to read the next file in 'filenames' array
         public void initStream() {
              try {
                   stream = new BufferedInputStream(new FileInputStream(filenames[fileIndex]), StreamRelay.BUFFER_SIZE);
                   streamOpened = true;
                   fileIndex++;
                   if (fileIndex==filenames.length)
                        fileIndex = 0;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
          * run: main loop of the class.
          *     the file is actually read: a buffer of BUFFER_SIZE is filled and sent to
          *     the observer (StreamRelay)
         public void run() {
              byte[] buffer = new byte[StreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              boolean quit = false;
              int actualBufferSize = 0;
              while (!quit) {
                   try {
                        this.setChanged();
                        // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                        // Only then is it sent to the observer...
                        while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, StreamRelay.BUFFER_SIZE)) > 0)) {
                             if (parent.clients.size()>0 && (!parent.streamFromSocket)) {
                                  if (actualBufferSize<StreamRelay.BUFFER_SIZE) {
                                       bufferToSend = new byte[actualBufferSize];
                                       System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                       this.notifyObservers(bufferToSend);
                                  } else
                                       this.notifyObservers(buffer);
                                  this.setChanged();
                             } else {
                                  try { Thread.sleep(100); } catch (Exception exp) {}
                   } catch (Exception exp) {
                        exp.printStackTrace();
                   try { stream.close(); } catch (Exception exp) {}
                   initStream();
    StreamServer.java:
    package com.RR4;
    import java.net.ServerSocket;
    public class StreamServer extends Thread {
         private ServerSocket serverSocket;
         private boolean socketOpened;
         private StreamRelay parent;
         * StreamServer: server listening for new StreamClient
         public StreamServer(StreamRelay parent, int relayPort) {
              this.parent = parent;
              try {
                   serverSocket = new ServerSocket(relayPort);
                   socketOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   socketOpened = false;
         public void run() {
              try {
                   while (socketOpened) {
                        parent.addClient(serverSocket.accept());
              } catch (Exception exp) {
                   exp.printStackTrace();
    StreamClient.java:
    package com.RR4;
    import java.net.Socket;
    import java.util.Observer;
    import java.util.Observable;
    import java.io.*;
    * StreamClient: class representing spectators connected to view the video content
    *     whether it is live content, or local files
    public class StreamClient implements Observer {
         private Socket socket;
         private OutputStream outStream;
         private boolean connected = true;
         private StreamRelay parent;
         public StreamClient(StreamRelay parent, Socket socket) {
              this.parent = parent;
              this.socket = socket;
              try {
                   // initialises OutputStream from socket
                   outStream = socket.getOutputStream();
              } catch (Exception exp) {
                   try { outStream.close(); } catch (Exception e) {}
                   try { socket.close(); } catch (Exception e) {}
                   exp.printStackTrace();
                   connected = false;
              if (connected) {
                   // if initializing of OutputStream didn't fail
                   // add this class to StreamBroadcast 'clients' vector
                   // and add this class to StreamRelay observers
                   parent.clients.add(this);
                   parent.addObserver(this);
          * update: actually send read bytes to the client
         public void update(Observable observable, Object obj) {
             try {
                   outStream.write( (byte[]) obj);
                   outStream.flush();
              } catch (Exception exp) {
                   // if read bytes couldn't be sent
                   // remove this client from clients list and observers of StreamRelay
                   // and try to close OutputStream and Socket
                   connected = false;
                   try { parent.deleteObserver(this); } catch (Exception e) {}
                   try { parent.clients.remove(this); } catch (Exception e) {}
                   try { outStream.close(); } catch (Exception e) {}
                   try { socket.close(); } catch (Exception e) {}
    LiveServer.java:
    package com.RR4;
    import java.net.ServerSocket;
    * LiveServer:
    *     SocketServer listening to new 'Live streams'
    public class LiveServer extends Thread {
         private ServerSocket liveSocket;
         private boolean liveServerOpened;
         private StreamRelay parent;
         public LiveServer(StreamRelay parent, int livePort) {
              this.parent = parent;
              try {
                   liveSocket = new ServerSocket(livePort);
                   liveServerOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   liveServerOpened = false;
         public void run() {
              LiveStream liveStream;
              try {
                   while (liveServerOpened) {
                        liveStream = new LiveStream(parent, liveSocket.accept());
                        new Thread(liveStream).start();
              } catch (Exception exp) {
                   exp.printStackTrace();
    LiveStream.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    import java.net.Socket;
    *     LiveStream:
    *          Socket receiving live content from another distant computer
    *          to display it instead of the local files.
    public class LiveStream extends Observable implements Runnable {
         private InputStream stream;
         boolean streamOpened;
         private StreamRelay parent;
         public LiveStream(StreamRelay parent, Socket socket) {
              this.parent = parent;
              this.addObserver(parent);
              try {
                   stream = new BufferedInputStream(socket.getInputStream(), StreamRelay.BUFFER_SIZE);
                   streamOpened = true;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
         public void run() {
              byte[] buffer = new byte[StreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              int actualBufferSize = 0;
              try {
                   this.setChanged();
                   // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                   // Only then is it sent to the observer...
                   while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, StreamRelay.BUFFER_SIZE)) > 0)) {
                        if (!parent.streamFromSocket)
                             parent.streamFromSocket = true;
                        if (parent.clients.size() > 0) {
                             if (actualBufferSize<StreamRelay.BUFFER_SIZE) {
                                  bufferToSend = new byte[actualBufferSize];
                                  System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                  this.notifyObservers(bufferToSend);
                             } else
                                  this.notifyObservers(buffer);
                             this.setChanged();
                        } else
                             try { Thread.sleep(100); } catch (Exception exp) {}
              } catch (Exception exp) {
                   exp.printStackTrace();
              } finally {
                   try { stream.close(); } catch (Exception exp) {}
                   this.deleteObserver(parent);
                   parent.streamFromSocket = false;
    }For your information, I uses NSV/VP6 vbr as video codec (but this should have no incidence on it, since the app only takes the video stream from a socket and broadcasts it to other sockets, without analysing it or modifying it). And the java app is hosted on a Celeron 2.6 GHz, 128MB RAM.
    I really hope you'll be able to help me with this project, as it is really important to me...
    I've been trying several Stream types available with the JDK but I hadn't any success... I've also been playing with the BUFFER_SIZE parameter, unsuccessfully too...
    Anyway, thanks in advance for reading me so far... and I hope, for helping me... I know the java community is strong, and I hope I won't have to make it with C or C++ :(

    Hi again :)
    I've been focusing on the local part of the stream (no live video, just playing local files and sending them to clients) using NIO.
    NIOStreamRelay.java:
    package com.RR4;
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.net.*;
    import java.util.*;
    public class NIOStreamRelay {
         static int BUFFER_SIZE = 1024;
         LocalFile localFile;
         Vector clients;
         public NIOStreamRelay() throws IOException {
              localFile = new LocalFile(this);
              new Thread(localFile).start();
              clients = new Vector();
              acceptConnections();
         public void acceptConnections() throws IOException {          
              // Selector for incoming requests
              Selector acceptSelector = SelectorProvider.provider().openSelector();
              // Create a new server socket and set to non blocking mode
              ServerSocketChannel ssc = ServerSocketChannel.open();
              ssc.configureBlocking(false);
              // Bind the server socket to the local host and port
              InetAddress lh = InetAddress.getLocalHost();
              InetSocketAddress isa = new InetSocketAddress(lh, 8080);
              ssc.socket().bind(isa);
              // Register accepts on the server socket with the selector. This
              // step tells the selector that the socket wants to be put on the
              // ready list when accept operations occur, so allowing multiplexed
              // non-blocking I/O to take place.
              SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
              int keysAdded = 0;
              // Here's where everything happens. The select method will
              // return when any operations registered above have occurred, the
              // thread has been interrupted, etc.
              while ((keysAdded = acceptSelector.select()) > 0) {
                  // Someone is ready for I/O, get the ready keys
                  Set readyKeys = acceptSelector.selectedKeys();
                  Iterator i = readyKeys.iterator();
                  // Walk through the ready keys collection and process date requests.
                  while (i.hasNext()) {
                        SelectionKey sk = (SelectionKey)i.next();
                        i.remove();
                        // The key indexes into the selector so you
                        // can retrieve the socket that's ready for I/O
                        ServerSocketChannel nextReady = (ServerSocketChannel)sk.channel();
                        // Accept the date request and send back the date string
                        Socket s = nextReady.accept().socket();
                        OutputStream socketStream = s.getOutputStream();
                        StreamClient newClient = new StreamClient(socketStream, this);
                        localFile.addObserver(newClient);
                        clients.add(newClient);
         public static void main(String[] args) {
              try {
                   NIOStreamRelay streamRelay = new NIOStreamRelay();
              } catch (Exception e) {
                   e.printStackTrace();
    LocalFile.java:
    package com.RR4;
    import java.util.Observable;
    import java.io.*;
    * LocalFile: class reading local file when no live content is sent to the relay
    public class LocalFile extends Observable implements Runnable {
         // filenames is an array containing a list of files to be read when no live content is sent
         private String[] filenames = {
              "test.nsv",
              "test2.nsv"
         private InputStream stream;
         boolean streamOpened;
         int fileIndex;
         NIOStreamRelay parent;
         // Constructor: initialises LocalFile
         //  sets fileIndex to 0, and sets main StreamRelay as Observer
         public LocalFile(NIOStreamRelay parent) {
              this.parent = parent;
              fileIndex = 0;
              initStream();
          * initStream: initialises stream to read the next file in 'filenames' array
         public void initStream() {
              try {
                   stream = new BufferedInputStream(new FileInputStream(filenames[fileIndex]), NIOStreamRelay.BUFFER_SIZE);
                   streamOpened = true;
                   fileIndex++;
                   if (fileIndex==filenames.length)
                        fileIndex = 0;
              } catch (Exception exp) {
                   exp.printStackTrace();
                   streamOpened = false;
          * run: main loop of the class.
          *     the file is actually read: a buffer of BUFFER_SIZE is filled and sent to
          *     the observer (StreamRelay)
         public void run() {
              byte[] buffer = new byte[NIOStreamRelay.BUFFER_SIZE];
              byte[] bufferToSend;
              boolean quit = false;
              int actualBufferSize = 0;
              while (!quit) {
                   try {
                        this.setChanged();
                        // Bytes are read until the buffer is actually filled with BUFFER_SIZE bytes
                        // Only then is it sent to the observer...
                        while (streamOpened && ((actualBufferSize = stream.read(buffer, 0, NIOStreamRelay.BUFFER_SIZE)) > 0)) {
                             if (parent.clients.size() > 0) {
                                  if (actualBufferSize<NIOStreamRelay.BUFFER_SIZE) {
                                       bufferToSend = new byte[actualBufferSize];
                                       System.arraycopy(buffer, 0, bufferToSend, 0, actualBufferSize);
                                       this.notifyObservers(bufferToSend);
                                  } else
                                       this.notifyObservers(buffer);
                                  this.setChanged();
                             } else {
                                  try { Thread.sleep(100); } catch (Exception exp) {}
                   } catch (Exception exp) {
                        exp.printStackTrace();
                   try { stream.close(); } catch (Exception exp) {}
                   initStream();
    StreamClient.java:
    package com.RR4;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class StreamClient implements Observer {
         OutputStream out;
         NIOStreamRelay parent;
         public StreamClient(OutputStream out, NIOStreamRelay parent) {
              this.out = out;
              this.parent = parent;
         public void update(Observable observable, Object obj) {
             try {
                   out.write( (byte[]) obj);
                   out.flush();
              } catch (Exception exp) {
                   // if read bytes couldn't be sent
                   // remove this client from clients list and observers of StreamRelay
                   // and try to close OutputStream and Socket
                   try { parent.localFile.deleteObserver(this); } catch (Exception e) {}
                   try { parent.clients.remove(this); } catch (Exception e) {}
                   try { out.close(); } catch (Exception e) {}
    }Does it look better to you?
    I know I'm still using single threading, but as the IO should be non-blocking, I guess it should be better.
    Furthermore, I tried it locally, and was able to launch 30+ clients without buffering problems (huh, ok, my cpu here is only a 1.6GHz, so the display was a bit lagguy, but it didn't seem to buffer at all)

  • Bringing in Multiple Images Together?

    Hi everybody. Is there any way of bringing in multiple images at the same time into a HTML page in Dreamweaver? I am trying to place about 70 small thumb nails on the same page. At the moment I have to bring them all in, one at a time, which takes forever! If you could just select a folder and bring all the images in that folder in to your page together, ordered as they are in the folder that would be a lot quicker. Thanks for your help.

    Copy & paste this code into a new, blank document.  SaveAs gallery_test.php.  Change php code to point to your Gallery/thumbs and Gallery/slides.  If you don't have a local testing server, upload to your remote site to test.
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>HTML5 Document</title>
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <!--LATEST JQUERY CORE LIBRARY-->
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <!--FANCYBOX plugins-->
    <link href="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/jquery.fancybox.css" rel="stylesheet" media="screen">
    <script src="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/jquery.fancybox.pack.js"></script>
    <style>
        padding: 0;
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    body {
        margin: 0;
        padding: 0;
        background: #08035F;
        color: #333;
        font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", "DejaVu Sans", Verdana, sans-serif;
        font-siz: 100%;
    #wrapper {
        width: 1000px; /**adjust width in px or %**/
        margin: 0 auto; /**with width, this is centered**/
    header {
        background: #355DA0;
        width: 100%;
        margin: 0 auto;
        color: #FFF;
    #inner_wrapper {
        background: #CCC7B3;
        overflow: hidden; /**float containment**/
    aside {
        float: left;
        width: 14%;
    section {
        background: #FFF;
        width: 72%;
        float: left;
        margin: 0 auto;
    /**Begin image gallery styles**/
    .thumbs { /*divs that hold gallery pictures*/
        float: left;
        margin: 0.5%; /*space between thumbnails*/
        border: 1px dotted #CCC;
        /**same size images**/
        width: 135px;
        height: 99px;
        opacity: .70
    .thumbs a { /* in every .thumbs div there is a hyperlink exactly the size of the container */
        width: 135px;
        height: 99px;
        text-indent: -99999px; /*move text links off screen*/
        display: block;
        outline: none;
    /**on mouse over**/
    .thumbs:hover { opacity: 1.0 }
    /**end gallery styles**/
    footer {
        clear: both;
        background: #222;
        width: 100%;
        color: #FFF;
        margin: 0 auto
    </style>
    </head>
    <body>
    <div id="wrapper">
    <header> <h1>Header</h1>
    <nav>Navigtion</nav>
    </header>
    <div id="inner_wrapper">
    <aside> LEFT ASIDE </aside>
    <section> <h2>Dynamic Thumbnails go here</h2>
    <?php
    $directory = 'GALLERY/thumbs'; //path to your thumbnails
    $link = 'GALLERY/slides'; //path to your full-sized images
    $allowed_types = array('jpg','jpeg','gif','png');
    $aFiles = array();
    $dir_handle = @opendir($directory) or die("There is an error with your image directory!");
    while ($file = readdir($dir_handle)) //traverse through files
    if($file=='.' || $file == '..') continue; //skip links to parent directories
    $file_parts = explode('.',$file); //split filenames and put each part in an array
    $ext = strtolower(array_pop($file_parts)); //last element is the file extension
    $title = implode('.',$file_parts); //what's left is the filename
    if(in_array($ext,$allowed_types))
    $aFiles[] = $file; //filename array
    closedir($dir_handle); //close directory
    natsort($aFiles); // natural sort by filename 01, 02, 10, 20
    $i=0;
    foreach ($aFiles as $file) {
    $file_parts = explode('.',$file); //split filenames and put each part in an array
    $ext = strtolower(array_pop($file_parts)); //last element is the file extension
    $title = implode('.',$file_parts); //what's left is the filename
    $title = htmlspecialchars($title); //make it html-safe
    echo '<div class="thumbs" style="background:url('.$directory.'/'.$file.') no-repeat 50% 50%">
    <a class="fancybox" data-fancybox-group="gallery" href="GALLERY/slides/'.$file.'" title="'.$title.'">'.$title.'</a>
    </div>';
    $i++; //increment the image counter
    ?>
    <!--end gallery-->
    </section>
    <aside> RIGHT ASIDE </aside>
    <!--end inner_wrapper--></div>
    <footer>Footer</footer>
    <!--end wrapper--></div>
    <!--FancyBox function code-->
    <script>
    $(document).ready(function() {
        $('.fancybox').fancybox();
    </script>
    </body>
    </html>
    Nancy O.

Maybe you are looking for

  • Error when attaching file in document tab page (content management)

    Hello When I'm importing file in document tab page (in activity, BP, etc) I get error "operation not allowed", and nothing more :/ Why it can happen? I have never had any problems with documents, since now. Do you think this is because of I'm connect

  • Receiver JDBC: Error while doing the Deleting and Inserting new records

    Hi All,           I am doing Idoc to JDBC scenario. In this I am collecting & bundling different type of Idocs and then sending to the JDBC receiver. My requirement is to delete the existing records in the database and insert the new records. I have

  • Problem with cron due to TERM

    I used to work on HP-UX and schedule jobs using cronjob. TERM was initialized in .profile using following - if [ "$TERM" = "" ] then eval ` tset -s -Q -m ':?hp' ` else eval ` tset -s -Q ` fi In cron, while executing a job, I used to call .profile to

  • User_tab_cols - nullable column?

    Dear All, check the workflow: C:\>sqlplus scott/tiger SQL*Plus: Release 10.2.0.1.0 - Production on Fri Apr 4 16:20:48 2008 Copyright (c) 1982, 2005, Oracle. All rights reserved. Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.1.0

  • ITunes 9: No Playback of Video Previews

    In iTunes 9, when I click on a movie or TV show to preview it, I get a blank black window, no content, no control bar, nada. What's the problem? I just upgraded to OS X 10.6.1.