working on it ...

Filters

Explore Public Snippets

Sort by

Found 25k snippets matching: find

    public by lbottaro modified Mar 24, 2014  406477  1  7  9

    Simple CORBA java server

    This code shows an example of simple corba server in java. A CORBA server needs a local ORB object. The server instantiates an ORB and registers its servant objects so that the ORB can find the server when it receives an invocation for it. the server is a process that instantiates one or more servant objects. Each servant implements the
    // The package containing our stubs.
    import HelloApp.*;
    
    // HelloServer will use the naming service.
    import org.omg.CosNaming.*;
    
    // The package containing special exceptions thrown by the name service.
    import org.omg.CosNaming.NamingContextPackage.*;
    
    // All CORBA applications need these classes.
    import org.omg.CORBA.*;
    
    public class HelloServer 
    {
      public static void main(String args[])
      {
        try{
           // Create and initialize the ORB
          ORB orb = ORB.init(args, null);
          
          // Create the servant and register it with the ORB
          HelloServant helloRef = new HelloServant();
          orb.connect(helloRef);
          
          // Get the root naming context
        org.omg.CORBA.Object objRef = 
    orb.resolve_initial_references("NameService");
          NamingContext ncRef = NamingContextHelper.narrow(objRef);
          
          // Bind the object reference in naming
          NameComponent nc = new NameComponent("Hello", "");
          NameComponent path[] = {nc};
          ncRef.rebind(path, helloRef);
          
          // Wait for invocations from clients
          java.lang.Object sync = new java.lang.Object();
          synchronized(sync){
            sync.wait();
          }
              } catch(Exception e) {
            System.err.println("ERROR: " + e);
            e.printStackTrace(System.out);
          }  
      }
    }
    
    class HelloServant extends _HelloImplBase
    {
      public String sayHello()
      {
        return "\nHello world!!\n";
        }
    }
        

    public by skaggej modified Jan 10, 2013  336375  3  6  0

    SharePoint 2010 - Disable the "New" icon for newly added content

    This is another easy and useful one; I find it helpful when I'm recording content and adding it as I'm going. I don't really want the word "New" next to some things and not next to others. The finalized recordings look better if that's never there. Here's the simple PowerShell script that you can run per web application to disable the "New" icon
    $webApp = Get-SPWebApplication http://sharepoint2010
    $webApp.DaysToShowNewIndicator = "0"
    $webApp.Update()

    public by dave83 modified Apr 26, 2015  223880  8  7  0

    How to run methods in class marked with specific Java annotation

    The snippet shows how to invoke only methods of a class marked with specific annotation. The list of methods class (MyTest) is returned using reflection. Annotations are returned via getAnnotation() method. The method is executed via invoke() method.
    import java.lang.reflect.Method;
    
    public class MyTest {
    
        @MyAnnotation
        public void method1() {
          System.out.println("method1");
        }
    
        public void method2() {
          System.out.println("method2");
        }
        
        @MyAnnotation
        public void method3() {
          System.out.println("method3");
        }
        
        public static void main(String[] args) {
    
            MyTest runner = new MyTest();
            Method[] methods = runner.getClass().getMethods();
    
            for (Method method : methods) {
                MyAnnotation annos = method.getAnnotation(MyAnnotation.class);
                if (annos != null) {
                    try {
                        method.invoke(runner);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    } 
                            

    public by ejmurray modified Jan 22, 2016  249923  16  3  0

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; se...

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; see here: http://www.leancrew.com/all-this/2013/10/photo-management-via-the-finder/ You can see mor
    #!/usr/bin/python
    
    import sys
    import os, shutil
    import subprocess
    import os.path
    from datetime import datetime
    
    ######################## Functions #########################
    
    def photoDate(f):
      "Return the date/time on which the given photo was taken."
    
      cDate = subprocess.check_output(['sips', '-g', 'creation', f])
      cDate = cDate.split('\n')[1].lstrip().split(': ')[1]
      return datetime.strptime(cDate, "%Y:%m:%d %H:%M:%S")
    
    
    ###################### Main program ########################
    
    # Where the photos are and where they're going.
    sourceDir = os.environ['HOME'] + '/Pictures/iPhone Incoming'
    destDir = os.environ['HOME'] + '/Pictures/iPhone'
    errorDir = destDir + '/Unsorted/'
    
    # The format for the new file names.
    fmt = "%Y-%m-%d %H-%M-%S"
    
    # The problem files.
    problems = []
    
    # Get all the JPEGs in the source folder.
    photos = os.listdir(sourceDir)
    photos = [ x for x in photos if x[-4:] == '.jpg' or x[-4:] == '.JPG' ]
    
    # Prepare to output as processing occurs
    lastMonth = 0
    lastYear = 0
    
    # Create the destination folder if necessary
    if not os.path.exists(destDir):
      os.makedirs(destDir)
    if not os.path.exists(errorDir):
      os.makedirs(errorDir)
    
    # Copy photos into year and month subfolders. Name the copies according to
    # their timestamps. If more than one photo has the same timestamp, add
    # suffixes 'a', 'b', etc. to the names. 
    for photo in photos:
      # print "Processing %s..." % photo
      original = sourceDir + '/' + photo
      suffix = 'a'
      try:
        pDate = photoDate(original)
        yr = pDate.year
        mo = pDate.month
    
        if not lastYear == yr or not lastMonth == mo:
          sys.stdout.write('\nProcessing %04d-%02d...' % (yr, mo))
          lastMonth = mo
          lastYear = yr
        else:
          sys.stdout.write('.')
        
        newname = pDate.strftime(fmt)
        thisDestDir = destDir + '/%04d/%02d' % (yr, mo)
        if not os.path.exists(thisDestDir):
          os.makedirs(thisDestDir)
    
        duplicate = thisDestDir + '/%s.jpg' % (newname)
        while os.path.exists(duplicate):
          newname = pDate.strftime(fmt) + suffix
          duplicate = destDir + '/%04d/%02d/%s.jpg' % (yr, mo, newname)
          suffix = chr(ord(suffix) + 1)
        shutil.copy2(original, duplicate)
      except Exception:
        shutil.copy2(original, errorDir + photo)
        problems.append(photo)
      except:
        sys.exit("Execution stopped.")
    
    # Report the problem files, if any.
    if len(problems) > 0:
      print "\nProblem files:"
      print "\n".join(problems)
      print "These can be found in: %s" % errorDir
    
    
    

    public by sukhjinderkahlon modified Mar 9, 2016  247618  2  4  0

    Selenium IsElementExists

    This code will find whether the element is present or not
    public static boolean isExistsElement(WebDriver driver, By by){
    		
    		    try {
    		        driver.findElement(by);
    		    } catch (NoSuchElementException e) {
    		        return false;
    		    }
    		    return true;
    			}            

    public by strykerraven modified Sep 22, 2016  188225  6  5  1

    WordPress safely defining and executing functions

    Handy safe way to include functions in your WordPress Themes functions.php file. This is even more useful if you are using a child theme and don't want to conflict with functions already defined by the parent theme. Even better; These functions can be executed within the same if(function_exists()) block that defines them creating a neater to manage
    <?php
    
    // Lets get rid of the versioning on static .js and .css files.
    // It looks tacky anyway for static files.
    
    	/**
    	 * Strips Version query strings
    	 * @param type $src
    	 * @return type
    	 */
    	if(!function_exists('remove_css_js_versions')){ // if the function doesnt exist then...
    		function remove_css_js_versions($src){ // define the function
    			return remove_query_arg('ver', $src); // call built-in wordpress function to remove query named "ver" from whatever is passed as $src
    		}
    		add_filter('script_loader_src', 'remove_css_js_versions'); // Pass a hook as $src for js to function listed above named "remove_css_js_versions"
    		add_filter('style_loader_src', 'remove_css_js_versions'); // Pass a hook as $src for css to function listed above named "remove_css_js_versions"
    	} // All scripts and styles will be filtered to have ?ver=1.2.3 stripped from urls. Function defined and executed in same if() statement.
    
      /**
      * Need to debug? Instead of just using print_r($array) you just do preprint_r($array)
      * the array will be output neatly instead of wrapped and messy.
      */
    	if(!function_exists('preprint_r')){
    		function preprint_r($val){
    			echo '<pre>' . PHP_EOL;
    			print_r($val) . PHP_EOL;
    			echo '</pre>' . PHP_EOL;
    		}
    	}
    	
    	/** Remove the WP Icon (Menu) from profile and admin pages. */
    		if(!function_exists('remove_wp_logo')){
      		function remove_wp_logo($wp_admin_bar){
      			$wp_admin_bar->remove_node('wp-logo');
      		}
      		add_action('admin_bar_menu', 'remove_wp_logo', 33);
      	}
      	
    /**
    	 * Wordpress Login Page fixes. By default WordPress shows its logo on your login pages and links to its own site.
    	 * A visitor logging into your site don't need this potential roadblock so lets show WordPress that we mean business!
    	 */
    	# Fix Login Page WordPress URL
    	if(!function_exists('fix_wp_login_img_url')){
    		function fix_wp_login_img_url($url){
    			return get_bloginfo('url');
    		}
    		add_filter('login_headerurl', 'fix_wp_login_img_url');
    	}
    
    	# Fix Login Page WordPress Title (Text displayed on hover defaults to Powered By WordPress)
    	if(!function_exists('fix_wp_login_img_title')){
    		function fix_wp_login_img_title($title){
    			return get_bloginfo('description');
    		}
    		add_filter('login_headertitle', 'fix_wp_login_img_title');
    	}
    
    	/**
    		Change Login Page WordPress Logo, You will need to update path and point to a valid image.
    		WordPress adds this with a CSS background image for your anchor link. It first applys a PNG and then a SVG override if your browser is modern and supports svg
    		In your themes custom stylesheet you can change default Wordpress image by supplying a new background image:
    
    		.login h1 a {
    			background-image: none,url(images/your_image.png);
    		}
    
    		Hint: WordPress uses an 64x64 image but you can adapt size to your need. You might want to use SVG like WordPress did because it will scale best at any resolution.
    
    	 */
    
    	/**
    	 * Simple Actions that use wp_head hook to cleanup WP header Junk/Bloat
    	 * that is included with WordPress by default.
    	 */
    	remove_action('wp_head', 'wp_generator');
    	remove_action('wp_head', 'rsd_link');
    	remove_action('wp_head', 'wlwmanifest_link');
    	remove_action('wp_head', 'wp_shortlink_wp_head');            
    	
    	
    	?>

    public by maindog modified Dec 18, 2013  15588  1436  8  17

    javascript cheat for A Dark Room v1.3

    (can be used on chrome using the javascript console) After you get a hut and someone joins your village (not the builder) this code will provide you with a lot of wood, allowing you to build more huts, traps and other buildings once you have the resources. (does not purchase the buildings and for the mines you still have to find them on the map)
    /**
     * Module that registers the outdoors functionality
     */
    var Outside = {
    	name: "Outside",
    	
    	_GATHER_DELAY: 60,
    	_TRAPS_DELAY: 90,
    	_POP_DELAY: [0.5, 3],
    	
    	_INCOME: {
    		'gatherer': {
    			delay: 1,
    			stores: {
    				'wood': 10000
    			}
    		},
    		'hunter': {
    			delay: 1,
    			stores: {
    				'fur': 10000,
    				'meat': 10000,
    				'alien alloy': 10000,
    				'medicine': 10000
    			}
    		},
    		'trapper': {
    			delay: 1,
    			stores: {
    				'meat': 10000,
    				'bait': 10000,
    				'teeth': 10000,
    				'scales': 10000
    			}
    		},
    		'tanner': {
    			delay: 1,
    			stores: {
    				'fur': 100000,
    				'leather': 100000
    			}
    		},
    		'charcutier': {
    			delay: 1,
    			stores: {
    				'meat': 100000,
    				'wood': 100000,
    				'cured meat': 100000
    			}
    		},
    		'iron miner': {
    			delay: 1,
    			stores: {
    				'cured meat': 100000,
    				'iron': 100000
    			}
    		},
    		'coal miner': {
    			delay: 1,
    			stores: {
    				'cured meat': 100000,
    				'coal': 100000
    			}
    		},
    		'sulphur miner': {
    			delay: 1,
    			stores: {
    				'cured meat': 100000,
    				'sulphur': 100000
    			}
    		},
    		'steelworker': {
    			delay: 1,
    			stores: {
    				'iron': 100000,
    				'coal': 100000,
    				'steel': 100000
    			}
    		},
    		'armourer': {
    			delay: 1,
    			stores: {
    				'steel': 100000,
    				'sulphur': 10000,
    				'bullets': 100000
    			}
    		}
    	},
    	
    	TrapDrops: [
    		{
    			rollUnder: 0.5,
    			name: 'fur',
    			message: 'scraps of fur'
    		},
    		{
    			rollUnder: 0.75,
    			name: 'meat',
    			message: 'bits of meat'
    		},
    		{
    			rollUnder: 0.85,
    			name: 'scales',
    			message: 'strange scales'
    		},
    		{
    			rollUnder: 0.93,
    			name: 'teeth',
    			message: 'scattered teeth'
    		},
    		{
    			rollUnder: 0.995,
    			name: 'cloth',
    			message: 'tattered cloth'
    		},
    		{
    			rollUnder: 1.0,
    			name: 'charm',
    			message: 'a crudely made charm'
    		}
    	],
    	
    	init: function(options) {
    		this.options = $.extend(
    			this.options,
    			options
    		);
    		
    		if(Engine._debug) {
    			this._GATHER_DELAY = 0;
    			this._TRAPS_DELAY = 0;
    		}
    		
    		// Create the outside tab
    		this.tab = Header.addLocation("A Silent Forest", "outside", Outside);
    		
    		// Create the Outside panel
    		this.panel = $('<div>').attr('id', "outsidePanel")
    			.addClass('location')
    			.appendTo('div#locationSlider');
    		
    		//subscribe to stateUpdates
    		$.Dispatch('stateUpdate').subscribe(Outside.handleStateUpdates);
    		
    		if(typeof $SM.get('features.location.outside') == 'undefined') {
    			$SM.set('features.location.outside', true);
    			if(!$SM.get('game.buildings')) $SM.set('game.buildings', {});
    			if(!$SM.get('game.population')) $SM.set('game.population', 0);
    			if(!$SM.get('game.workers')) $SM.set('game.workers', {});
    		}
    		
    		this.updateVillage();
    		Outside.updateWorkersView();
    		
    		Engine.updateSlider();
    		
    		// Create the gather button
    		new Button.Button({
    			id: 'gatherButton',
    			text: "gather wood",
    			click: Outside.gatherWood,
    			cooldown: Outside._GATHER_DELAY,
    			width: '80px'
    		}).appendTo('div#outsidePanel');
    	},
    	
    	getMaxPopulation: function() {
    		return $SM.get('game.buildings["hut"]', true) * 4;
    	},
    	
    	increasePopulation: function() {
    		var space = Outside.getMaxPopulation() - $SM.get('game.population');
    		if(space > 0) {
    			var num = Math.floor(Math.random()*(space/2) + space/2);
    			if(num == 0) num = 1;
    			if(num == 1) {
    				Notifications.notify(null, 'a stranger arrives in the night');
    			} else if(num < 5) {
    				Notifications.notify(null, 'a weathered family takes up in one of the huts.');
    			} else if(num < 10) {
    				Notifications.notify(null, 'a small group arrives, all dust and bones.');
    			} else if(num < 30) {
    				Notifications.notify(null, 'a convoy lurches in, equal parts worry and hope.');
    			} else {
    				Notifications.notify(null, "the town's booming. word does get around.");
    			}
    			Engine.log('population increased by ' + num);
    			$SM.add('game.population', num);
    		}
    		Outside.schedulePopIncrease();
    	},
    	
    	killVillagers: function(num) {
    		$SM.add('game.population', num * -1);
    		if($SM.get('game.population') < 0) {
    			$SM.set('game.population', 0);
    		}
    		var remaining = Outside.getNumGatherers();
    		if(remaining < 0) {
    			var gap = -remaining;
    			for(var k in $SM.get('game.workers')) {
    				var num = $SM.get('game.workers["'+k+'"]');
    				if(num < gap) {
    					gap -= num;
    					$SM.set('game.workers["'+k+'"]', 0);
    				} else {
    					$SM.add('game.workers["'+k+'"]', gap * -1);
    					break;
    				}
    			}
    		}
    	},
    	
    	schedulePopIncrease: function() {
    		var nextIncrease = Math.floor(Math.random()*(Outside._POP_DELAY[1] - Outside._POP_DELAY[0])) + Outside._POP_DELAY[0];
        	Engine.log('next population increase scheduled in ' + nextIncrease + ' minutes');
        	Outside._popTimeout = setTimeout(Outside.increasePopulation, nextIncrease * 60 * 1000);
    	},
    	
    	updateWorkersView: function() {
    		var workers = $('div#workers');
    
    		// If our population is 0 and we don't already have a workers view,
    		// there's nothing to do here.
    		if(!workers.length && $SM.get('game.population') == 0) return;
    
    		var needsAppend = false;
    		if(workers.length == 0) {
    			needsAppend = true;
    			workers = $('<div>').attr('id', 'workers').css('opacity', 0);
    		}
    		
    		var numGatherers = $SM.get('game.population');
    		var gatherer = $('div#workers_row_gatherer', workers);
    		
    		for(var k in $SM.get('game.workers')) {
    			var workerCount = $SM.get('game.workers["'+k+'"]');
    			var row = $('div#workers_row_' + k.replace(' ', '-'), workers);
    			if(row.length == 0) {
    				row = Outside.makeWorkerRow(k, workerCount);
    				
    				var curPrev = null;
    				workers.children().each(function(i) {
    					var child = $(this);
    					var cName = child.attr('id').substring(12).replace('-', ' ');
    					if(cName != 'gatherer') {
    						if(cName < k && (curPrev == null || cName > curPrev)) {
    							curPrev = cName;
    						}
    					}
    				});
    				if(curPrev == null && gatherer.length == 0) {
    					row.prependTo(workers);
    				} 
    				else if(curPrev == null)
    				{
    					row.insertAfter(gatherer);
    				} 
    				else 
    				{
    					row.insertAfter(workers.find('#workers_row_' + curPrev.replace(' ', '-')));
    				}
    				
    			} else {
    				$('div#' + row.attr('id') + ' > div.row_val > span', workers).text(workerCount);
    			}
    			numGatherers -= workerCount;
    			if(workerCount == 0) {
    				$('.dnBtn', row).addClass('disabled');
    				$('.dnManyBtn', row).addClass('disabled');
    			} else {
    				$('.dnBtn', row).removeClass('disabled');
    				$('.dnManyBtn', row).removeClass('disabled');
    			}
    		}
    		
    		if(gatherer.length == 0) {
    			gatherer = Outside.makeWorkerRow('gatherer', numGatherers);
    			gatherer.prependTo(workers);
    		} else {
    			$('div#workers_row_gatherer > div.row_val > span', workers).text(numGatherers);
    		}
    		
    		if(numGatherers == 0) {
    			$('.upBtn', '#workers').addClass('disabled');
    			$('.upManyBtn', '#workers').addClass('disabled');
    		} else {
    			$('.upBtn', '#workers').removeClass('disabled');
    			$('.upManyBtn', '#workers').removeClass('disabled');
    		}
    		
    		
    		if(needsAppend && workers.children().length > 0) {
    			workers.appendTo('#outsidePanel').animate({opacity:1}, 300, 'linear');
    		}
    	},
    	
    	getNumGatherers: function() {
    		var num = $SM.get('game.population'); 
    		for(var k in $SM.get('game.workers')) {
    			num -= $SM.get('game.workers["'+k+'"]');
    		}
    		return num;
    	},
    	
    	makeWorkerRow: function(name, num) {
    		var row = $('<div>')
    			.attr('id', 'workers_row_' + name.replace(' ','-'))
    			.addClass('workerRow');
    		$('<div>').addClass('row_key').text(name).appendTo(row);
    		var val = $('<div>').addClass('row_val').appendTo(row);
    		
    		$('<span>').text(num).appendTo(val);
    		
    		if(name != 'gatherer') {
    		  $('<div>').addClass('upManyBtn').appendTo(val).click([10], Outside.increaseWorker);
    			$('<div>').addClass('upBtn').appendTo(val).click([1], Outside.increaseWorker);
    			$('<div>').addClass('dnBtn').appendTo(val).click([1], Outside.decreaseWorker);
    			$('<div>').addClass('dnManyBtn').appendTo(val).click([10], Outside.decreaseWorker);
    		}
    		
    		$('<div>').addClass('clear').appendTo(row);
    		
    		var tooltip = $('<div>').addClass('tooltip bottom right').appendTo(row);
    		var income = Outside._INCOME[name];
    		for(var s in income.stores) {
    			var r = $('<div>').addClass('storeRow');
    			$('<div>').addClass('row_key').text(s).appendTo(r);
    			$('<div>').addClass('row_val').text(Engine.getIncomeMsg(income.stores[s], income.delay)).appendTo(r);
    			r.appendTo(tooltip);
    		}
    		
    		return row;
    	},
    	
    	increaseWorker: function(btn) {
    		var worker = $(this).closest('.workerRow').children('.row_key').text();
    		if(Outside.getNumGatherers() > 0) {
    		  var increaseAmt = Math.min(Outside.getNumGatherers(), btn.data);
    			Engine.log('increasing ' + worker + ' by ' + increaseAmt);
    			$SM.add('game.workers["'+worker+'"]', increaseAmt);
    		}
    	},
    	
    	decreaseWorker: function(btn) {
    		var worker = $(this).closest('.workerRow').children('.row_key').text();
    		if($SM.get('game.workers["'+worker+'"]') > 0) {
    		  var decreaseAmt = Math.min($SM.get('game.workers["'+worker+'"]') || 0, btn.data);
    			Engine.log('decreasing ' + worker + ' by ' + decreaseAmt);
    			$SM.add('game.workers["'+worker+'"]', decreaseAmt * -1);
    		}
    	},
    	
    	updateVillageRow: function(name, num, village) {
    		var id = 'building_row_' + name.replace(' ', '-');
    		var row = $('div#' + id, village);
    		if(row.length == 0 && num > 0) {
    			row = $('<div>').attr('id', id).addClass('storeRow');
    			$('<div>').addClass('row_key').text(name).appendTo(row);
    			$('<div>').addClass('row_val').text(num).appendTo(row);
    			$('<div>').addClass('clear').appendTo(row);
    			var curPrev = null;
    			village.children().each(function(i) {
    				var child = $(this);
    				if(child.attr('id') != 'population') {
    					var cName = child.attr('id').substring(13).replace('-', ' ');
    					if(cName < name && (curPrev == null || cName > curPrev)) {
    						curPrev = cName;
    					}
    				}
    			});
    			if(curPrev == null) {
    				row.prependTo(village);
    			} else {
    				row.insertAfter('#building_row_' + curPrev.replace(' ', '-'));
    			}
    		} else if(num > 0) {
    			$('div#' + row.attr('id') + ' > div.row_val', village).text(num);
    		} else if(num == 0) {
    			row.remove();
    		}
    	},
    	
    	updateVillage: function(ignoreStores) {
    		var village = $('div#village');
    		var population = $('div#population');
    		var needsAppend = false;
    		if(village.length == 0) {
    			needsAppend = true;
    			village = $('<div>').attr('id', 'village').css('opacity', 0);
    			population = $('<div>').attr('id', 'population').appendTo(village);
    		}
    		
    		for(var k in $SM.get('game.buildings')) {
    			if(k == 'trap') {
    				var numTraps = $SM.get('game.buildings["'+k+'"]');
    				var numBait = $SM.get('stores.bait', true);
    				var traps = numTraps - numBait;
    				traps = traps < 0 ? 0 : traps;
    				Outside.updateVillageRow(k, traps, village);
    				Outside.updateVillageRow('baited trap', numBait > numTraps ? numTraps : numBait, village);
    			} else {
    				if(Outside.checkWorker(k)) {
    					Outside.updateWorkersView();
    				}
    				Outside.updateVillageRow(k, $SM.get('game.buildings["'+k+'"]'), village);
    			}
    		}
    		
    		population.text('pop ' + $SM.get('game.population') + '/' + this.getMaxPopulation());
    		
    		var hasPeeps;
    		if($SM.get('game.buildings["hut"]', true) == 0) {
    			hasPeeps = false;
    			village.addClass('noHuts');
    		} else {
    			hasPeeps = true;
    			village.removeClass('noHuts');
    		}
    		
    		if(needsAppend && village.children().length > 1) {
    			village.appendTo('#outsidePanel');
    			village.animate({opacity:1}, 300, 'linear');
    		}
    		
    		if(hasPeeps && typeof Outside._popTimeout == 'undefined') {
    			Outside.schedulePopIncrease();
    		}
    		
    		this.setTitle();
    
    		if(!ignoreStores && Engine.activeModule === Outside && village.children().length > 1) {
    			$('#storesContainer').css({top: village.height() + 26 + 'px'});
    		}
    	},
    	
    	checkWorker: function(name) {
    		var jobMap = {
    			'lodge': ['hunter', 'trapper'],
    			'tannery': ['tanner'],
    			'smokehouse': ['charcutier'],
    			'iron mine': ['iron miner'],
    			'coal mine': ['coal miner'],
    			'sulphur mine': ['sulphur miner'],
    			'steelworks': ['steelworker'],
    			'armoury' : ['armourer']
    		};
    		
    		var jobs = jobMap[name];
    		var added = false;
    		if(typeof jobs == 'object') {
    			for(var i = 0, len = jobs.length; i < len; i++) {
    				var job = jobs[i];
    				if(typeof $SM.get('game.buildings["'+name+'"]') == 'number' && 
    						typeof $SM.get('game.workers["'+job+'"]') != 'number') {
    					Engine.log('adding ' + job + ' to the workers list');
    					$SM.set('game.workers["'+job+'"]', 0);
    					added = true;
    				}
    			}
    		}
    		return added;
    	},
    	
    	updateVillageIncome: function() {		
    		for(var worker in Outside._INCOME) {
    			var income = Outside._INCOME[worker];
    			var num = worker == 'gatherer' ? Outside.getNumGatherers() : $SM.get('game.workers["'+worker+'"]');
    			if(typeof num == 'number') {
    				var stores = {};
    				if(num < 0) num = 0;
    				var tooltip = $('.tooltip', 'div#workers_row_' + worker.replace(' ', '-'));
    				tooltip.empty();
    				var needsUpdate = false;
    				var curIncome = $SM.getIncome(worker);
    				for(var store in income.stores) {
    					stores[store] = income.stores[store] * num;
    					if(curIncome[store] != stores[store]) needsUpdate = true;
    					var row = $('<div>').addClass('storeRow');
    					$('<div>').addClass('row_key').text(store).appendTo(row);
    					$('<div>').addClass('row_val').text(Engine.getIncomeMsg(stores[store], income.delay)).appendTo(row);
    					row.appendTo(tooltip);
    				}
    				if(needsUpdate) {
    					$SM.setIncome(worker, {
    						delay: income.delay,
    						stores: stores
    					});
    				}
    			}
    		}
    		Room.updateIncomeView();
    	},
    	
    	updateTrapButton: function() {
    		var btn = $('div#trapsButton');
    		if($SM.get('game.buildings["trap"]', true) > 0) {
    			if(btn.length == 0) {
    				new Button.Button({
    					id: 'trapsButton',
    					text: "check traps",
    					click: Outside.checkTraps,
    					cooldown: Outside._TRAPS_DELAY,
    					width: '80px'
    				}).appendTo('div#outsidePanel');
    			} else {
    				Button.setDisabled(btn, false);
    			}
    		} else {
    			if(btn.length > 0) {
    				Button.setDisabled(btn, true);
    			}
    		}
    	},
    	
    	setTitle: function() {
    		var numHuts = $SM.get('game.buildings["hut"]', true);
    		var title;
    		if(numHuts == 0) {
    			title = "A Silent Forest";
    		} else if(numHuts == 1) {
    			title = "A Lonely Hut";
    		} else if(numHuts <= 4) {
    			title = "A Tiny Village";
    		} else if(numHuts <= 8) {
    			title = "A Modest Village";
    		} else if(numHuts <= 14) {
    			title = "A Large Village";
    		} else {
    			title = "A Raucous Village";
    		}
    		
    		if(Engine.activeModule == this) {
    			document.title = title;
    		}
    		$('#location_outside').text(title);
    	},
    	
    	onArrival: function(transition_diff) {
    		Outside.setTitle();
    		if(!$SM.get('game.outside.seenForest')) {
    			Notifications.notify(Outside, "the sky is grey and the wind blows relentlessly");
    			$SM.set('game.outside.seenForest', true);
    		}
    		Outside.updateTrapButton();
    		Outside.updateVillage(true);
    
    		Engine.moveStoresView($('#village'), transition_diff);
    	},
    	
    	gatherWood: function() {
    		Notifications.notify(Outside, "dry brush and dead branches litter the forest floor");
    		var gatherAmt = $SM.get('game.buildings["cart"]', true) > 0 ? 50 : 10;
    		$SM.add('stores.wood', gatherAmt);
    	},
    	
    	checkTraps: function() {
    		var drops = {};
    		var msg = [];
    		var numTraps = $SM.get('game.buildings["trap"]', true);
    		var numBait = $SM.get('stores.bait', true);
    		var numDrops = numTraps + (numBait < numTraps ? numBait : numTraps);
    		for(var i = 0; i < numDrops; i++) {
    			var roll = Math.random();
    			for(var j in Outside.TrapDrops) {
    				var drop = Outside.TrapDrops[j];
    				if(roll < drop.rollUnder) {
    					var num = drops[drop.name];
    					if(typeof num == 'undefined') {
    						num = 0;
    						msg.push(drop.message);
    					}
    					drops[drop.name] = num + 1;
    					break;
    				}
    			}
    		}
    		var s = 'the traps contain ';
    		for(var i = 0, len = msg.length; i < len; i++) {
    			if(len > 1 && i > 0 && i < len - 1) {
    				s += ", ";
    			} else if(len > 1 && i == len - 1) {
    				s += " and ";
    			}
    			s += msg[i];
    		}
    		
    		var baitUsed = numBait < numTraps ? numBait : numTraps;
    		drops['bait'] = -baitUsed;
    		
    		Notifications.notify(Outside, s);
    		$SM.addM('stores', drops);
    	},
    	
    	handleStateUpdates: function(e){
    		if(e.category == 'stores'){
    			Outside.updateVillage();
    		} else if(e.stateName.indexOf('game.workers') == 0
    		          || e.stateName.indexOf('game.population') == 0){
    			Outside.updateVillage();
    			Outside.updateWorkersView();
    			Outside.updateVillageIncome();
    		};
    	}
    };

    public by lbottaro modified Oct 17, 2013  4408  0  7  0

    How to find and remove directories in windows batch command

    The script will search for a given path and returns the name of folders found. The script may remove the directory found (with or without prompt)
    @echo off
    set m_path="C:\Users"
    if exist %m_path% (
    cd %m_path%
    echo FOUND %m_path%
    REM pippo
    for /F %%i in ('dir obj /s /b') do (
    echo "dir %%i"
    REM Remove dir without prompt
    rmdir %%i /s /q
    REM Remove dir with prompt
    REM rmdir %%i /s
    )
    )
    
    pause

    public by Geometry modified Aug 7, 2016  1245  0  6  0

    FindQuadrilateralCorners: Find corners of quadrilateral or triangular area, which contains the specified collection of points.

    Find corners of quadrilateral or triangular area, which contains the specified collection of points. Collection of points to search quadrilateral for. Returns a list of 3 or 4 points, which are corners of the quadrilateral or triangular area filled by specified collection of point. The first point in the list is the point with lowest X coordin
    private static float quadrilateralRelativeDistortionLimit = 0.1f;
    
    /// <summary>
    /// Find corners of quadrilateral or triangular area, which contains the specified collection of points.
    /// </summary>
    /// 
    /// <param name="cloud">Collection of points to search quadrilateral for.</param>
    /// 
    /// <returns>Returns a list of 3 or 4 points, which are corners of the quadrilateral or
    /// triangular area filled by specified collection of point. The first point in the list
    /// is the point with lowest X coordinate (and with lowest Y if there are several points
    /// with the same X value). The corners are provided in counter clockwise order
    /// (<a href="http://en.wikipedia.org/wiki/Cartesian_coordinate_system">Cartesian
    /// coordinate system</a>).</returns>
    /// 
    /// <remarks><para>The method makes an assumption that the specified collection of points
    /// form some sort of quadrilateral/triangular area. With this assumption it tries to find corners
    /// of the area.</para>
    /// 
    /// <para><note>The method does not search for <b>bounding</b> quadrilateral/triangular area,
    /// where all specified points are <b>inside</b> of the found quadrilateral/triangle. Some of the
    /// specified points potentially may be outside of the found quadrilateral/triangle, since the
    /// method takes corners only from the specified collection of points, but does not calculate such
    /// to form true bounding quadrilateral/triangle.</note></para>
    /// 
    /// <para>See <see cref="QuadrilateralRelativeDistortionLimit"/> property for additional information.</para>
    /// </remarks>
    /// 
    public static List<IntPoint> FindQuadrilateralCorners( IEnumerable<IntPoint> cloud )
    {
        // quadrilateral's corners
        List<IntPoint> corners = new List<IntPoint>( );
    
        // get bounding rectangle of the points list
        IntPoint minXY, maxXY;
        PointsCloud.GetBoundingRectangle( cloud, out minXY, out maxXY );
        // get cloud's size
        IntPoint cloudSize = maxXY - minXY;
        // calculate center point
        IntPoint center = minXY + cloudSize / 2;
        // acceptable deviation limit
        float distortionLimit = quadrilateralRelativeDistortionLimit * ( cloudSize.X + cloudSize.Y ) / 2;
    
        // get the furthest point from (0,0)
        IntPoint point1 = PointsCloud.GetFurthestPoint( cloud, center );
        // get the furthest point from the first point
        IntPoint point2 = PointsCloud.GetFurthestPoint( cloud, point1 );
    
        corners.Add( point1 );
        corners.Add( point2 );
    
        // get two furthest points from line
        IntPoint point3, point4;
        float distance3, distance4;
    
        PointsCloud.GetFurthestPointsFromLine( cloud, point1, point2,
            out point3, out distance3, out point4, out distance4 );
    
        // ideally points 1 and 2 form a diagonal of the
        // quadrilateral area, and points 3 and 4 form another diagonal
    
        // but if one of the points (3 or 4) is very close to the line
        // connecting points 1 and 2, then it is one the same line ...
        // which means corner was not found.
        // in this case we deal with a trapezoid or triangle, where
        // (1-2) line is one of it sides.
    
        // another interesting case is when both points (3) and (4) are
        // very close the (1-2) line. in this case we may have just a flat
        // quadrilateral.
    
        if (
             ( ( distance3 >= distortionLimit ) && ( distance4 >= distortionLimit ) ) ||
    
             ( ( distance3 < distortionLimit ) && ( distance3 != 0 ) &&
               ( distance4 < distortionLimit ) && ( distance4 != 0 ) ) )
        {
            // don't add one of the corners, if the point is already in the corners list
            // (this may happen when both #3 and #4 points are very close to the line
            // connecting #1 and #2)
            if ( !corners.Contains( point3 ) )
            {
                corners.Add( point3 );
            }
            if ( !corners.Contains( point4 ) )
            {
                corners.Add( point4 );
            }
        }
        else
        {
            // it seems that we deal with kind of trapezoid,
            // where point 1 and 2 are on the same edge
    
            IntPoint tempPoint = ( distance3 > distance4 ) ? point3 : point4;
    
            // try to find 3rd point
            PointsCloud.GetFurthestPointsFromLine( cloud, point1, tempPoint,
                out point3, out distance3, out point4, out distance4 );
    
            bool thirdPointIsFound = false;
    
            if ( ( distance3 >= distortionLimit ) && ( distance4 >= distortionLimit ) )
            {
                if ( point4.DistanceTo( point2 ) > point3.DistanceTo( point2 ) )
                    point3 = point4;
    
                thirdPointIsFound = true;
            }
            else
            {
                PointsCloud.GetFurthestPointsFromLine( cloud, point2, tempPoint,
                    out point3, out distance3, out point4, out distance4 );
    
                if ( ( distance3 >= distortionLimit ) && ( distance4 >= distortionLimit ) )
                {
                    if ( point4.DistanceTo( point1 ) > point3.DistanceTo( point1 ) )
                        point3 = point4;
    
                    thirdPointIsFound = true;
                }
            }
    
            if ( !thirdPointIsFound )
            {
                // failed to find 3rd edge point, which is away enough from the temp point.
                // this means that the clound looks more like triangle
                corners.Add( tempPoint );
            }
            else
            {
                corners.Add( point3 );
    
                // try to find 4th point
                float tempDistance;
    
                PointsCloud.GetFurthestPointsFromLine( cloud, point1, point3,
                    out tempPoint, out tempDistance, out point4, out distance4 );
    
                if ( ( distance4 >= distortionLimit ) && ( tempDistance >= distortionLimit ) )
                {
                    if ( tempPoint.DistanceTo( point2 ) > point4.DistanceTo( point2 ) )
                        point4 = tempPoint;
                }
                else
                {
                    PointsCloud.GetFurthestPointsFromLine( cloud, point2, point3,
                        out tempPoint, out tempDistance, out point4, out distance4 );
    
                    if ( ( tempPoint.DistanceTo( point1 ) > point4.DistanceTo( point1 ) ) &&
                         ( tempPoint != point2 ) && ( tempPoint != point3 ) )
                    {
                        point4 = tempPoint;
                    }
                }
    
                if ( ( point4 != point1 ) && ( point4 != point2 ) && ( point4 != point3 ) )
                    corners.Add( point4 );
            }
        }
    
        // put the point with lowest X as the first
        for ( int i = 1, n = corners.Count; i < n; i++ )
        {
            if ( ( corners[i].X < corners[0].X ) ||
                 ( ( corners[i].X == corners[0].X ) && ( corners[i].Y < corners[0].Y ) ) )
            {
                IntPoint temp = corners[i];
                corners[i] = corners[0];
                corners[0] = temp;
            }
        }
    
    
        // sort other points in counter clockwise order
        float k1 = ( corners[1].X != corners[0].X ) ?
            ( (float) ( corners[1].Y - corners[0].Y ) / ( corners[1].X - corners[0].X ) ) :
            ( ( corners[1].Y > corners[0].Y ) ? float.PositiveInfinity : float.NegativeInfinity );
    
        float k2 = ( corners[2].X != corners[0].X ) ?
            ( (float) ( corners[2].Y - corners[0].Y ) / ( corners[2].X - corners[0].X ) ) :
            ( ( corners[2].Y > corners[0].Y ) ? float.PositiveInfinity : float.NegativeInfinity );
    
        if ( k2 < k1 )
        {
            IntPoint temp = corners[1];
            corners[1] = corners[2];
            corners[2] = temp;
    
            float tk = k1;
            k1 = k2;
            k2 = tk;
        }
    
        if ( corners.Count == 4 )
        {
            float k3 = ( corners[3].X != corners[0].X ) ?
                ( (float) ( corners[3].Y - corners[0].Y ) / ( corners[3].X - corners[0].X ) ) :
                ( ( corners[3].Y > corners[0].Y ) ? float.PositiveInfinity : float.NegativeInfinity );
    
            if ( k3 < k1 )
            {
                IntPoint temp = corners[1];
                corners[1] = corners[3];
                corners[3] = temp;
    
                float tk = k1;
                k1 = k3;
                k3 = tk;
            }
            if ( k3 < k2 )
            {
                IntPoint temp = corners[2];
                corners[2] = corners[3];
                corners[3] = temp;
    
                float tk = k2;
                k2 = k3;
                k3 = tk;
            }
        }
    
        return corners;
    }

    public by qxshower modified Apr 21, 2015  1953  2  6  0

    FindVisualChild: Attempts to find a visual child of the specified type.

    Attempts to find a visual child of the specified type. (source from CodeMaid: http://www.codemaid.net/)
    using System.Windows;
    using System.Windows.Media;
    
    /// <summary>
    /// Attempts to find a visual child of the specified type.
    /// </summary>
    /// <typeparam name="T">The type of the child.</typeparam>
    /// <param name="obj">The object to search.</param>
    /// <returns>A matching visual child, otherwise null.</returns>
    public static T FindVisualChild<T>(this DependencyObject obj)
        where T : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            var child = VisualTreeHelper.GetChild(obj, i);
            if (child is T)
            {
                return (T)child;
            }
    
            var descendant = FindVisualChild<T>(child);
            if (descendant != null)
            {
                return descendant;
            }
        }
    
        return null;
    }            
    • Public Snippets
    • Channels Snippets