text:
package com.github.tonivade.claudb.replication;

import static com.github.tonivade.resp.protocol.RedisToken.array;
import static com.github.tonivade.resp.protocol.RedisToken.string;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.tonivade.claudb.DBServerContext;
import com.github.tonivade.claudb.DBServerState;
import com.github.tonivade.purefun.type.Option;
import com.github.tonivade.resp.protocol.AbstractRedisToken.ArrayRedisToken;
import com.github.tonivade.resp.protocol.AbstractRedisTokenVisitor;
import com.github.tonivade.resp.protocol.RedisToken;
import com.github.tonivade.resp.protocol.SafeString;

public class MasterReplication implements Runnable {

  private static final Logger LOGGER = LoggerFactory.getLogger(MasterReplication.class);

  private static final String SELECT_COMMAND = "SELECT";
  private static final String PING_COMMAND = "PING";
  private static final int TASK_DELAY = 2;

  private final DBServerContext server;
  private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

  public MasterReplication(DBServerContext server) {
    this.server = requireNonNull(server);
  }

  public void start() {
    executor.scheduleWithFixedDelay(this, TASK_DELAY, TASK_DELAY, TimeUnit.SECONDS);
  }

  public void stop() {
    executor.shutdown();
  }

  public void addSlave(String id) {
    getServerState().addSlave(id);
    LOGGER.info("new slave: {}", id);
  }

  public void removeSlave(String id) {
    getServerState().removeSlave(id);
    LOGGER.info("slave revomed: {}", id);
  }

  @Override
  public void run() {
    List<RedisToken> commands = createCommands();

    for (SafeString slave : getServerState().getSlaves()) {
      for (RedisToken command : commands) {
        server.publish(slave.toString(), command);
      }
    }
  }

  private List<RedisToken> createCommands() {
    List<RedisToken> commands = new LinkedList<>();
    commands.add(pingCommand());
    commands.addAll(commandsToReplicate());
    return commands;
  }

  private List<RedisToken> commandsToReplicate() {
    List<RedisToken> commands = new LinkedList<>();

    for (RedisToken command : server.getCommandsToReplicate()) {
      command.accept(new AbstractRedisTokenVisitor<Void>() {
        @Override
        public Void array(ArrayRedisToken token) {
          commands.add(selectCommand(token));
          commands.add(command(token));
          return null;
        }
      });
    }
    return commands;
  }

  private RedisToken selectCommand(ArrayRedisToken token) {
    return array(string(SELECT_COMMAND),
        token.getValue().stream().findFirst().orElse(string("0")));
  }

  private RedisToken pingCommand() {
    return array(string(PING_COMMAND));
  }

  private RedisToken command(ArrayRedisToken token) {
    return array(token.getValue().stream().skip(1).collect(toList()));
  }

  private DBServerState getServerState() {
    return serverState().getOrElseThrow(() -> new IllegalStateException("missing server state"));
  }

  private Option<DBServerState> serverState() {
    return server.getValue("state");
  }
}


text:
New window (noopener)
New window

redpajama_set_name: RedPajamaGithub


text:
@protocol AdvancedFilterViewControllerDelegate;
@class CTSearchFilters;

@interface AdvancedFilterViewController : UIViewController <UITableViewDataSource, UITableViewDataSource> {
	id <AdvancedFilterViewControllerDelegate> delegate;

	UITableView *filterTable;
	UISegmentedControl *peopleSegCtrl;
	UISegmentedControl *fuelSegCtrl;
	UISegmentedControl *transmissionSegCtrl;
	UISegmentedControl *airConSegCtrl;

	CTSearchFilters *ctSearchFilters;
}

@property (nonatomic, assign) id delegate;
@property (nonatomic,retain) CTSearchFilters *ctSearchFilters;
@property (nonatomic,retain) IBOutlet UITableView *filterTable;
@property (nonatomic,retain) UISegmentedControl *peopleSegCtrl;
@property (nonatomic,retain) UISegmentedControl *fuelSegCtrl;
@property (nonatomic,retain) UISegmentedControl *transmissionSegCtrl;
@property (nonatomic,retain) UISegmentedControl *airConSegCtrl;

- (IBAction) dismissView:(id)sender;
- (IBAction) saveFilters:(id)sender;
- (IBAction) resetForm:(id)sender;
- (void) loadFilters:(id)sender;
- (void) setDefaultValues;
- (void) resetUIElements;

@end

@protocol AdvancedFilterViewControllerDelegate <NSObject>
-(void)advancedFilterViewController:(AdvancedFilterViewController *)advancedFilterViewController didSaveFilterSettings:(CTSearchFilters*)ctSearchFilters;
@end


text:
<!DOCTYPE html>

        <meta property="og:title" content="TruvéeWines" />
        <meta property="og:type" content/>
        <meta property="og:url" content="http://www.truveewines.com" />
        <meta property="og:image" content="http://www.truveewines.com/images/TruveeWines.png" />
        <meta property="og:description" content='Marrying 10 plus years of experience in the wine industry as négociants, and creators of eco.love Wines from New Zealand, we have crafted another authentic, but affordable luxury wine, this time from select vineyards within the Central Coast of California. Our vision for Truvée is to make delicious wines everyone can enjoy and inspire people "to find" what matters most to them.' />

        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <title>Sisters Story — Truvée Wines</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <link rel="stylesheet" type="text/css" href="styles/bootstrap.min.css">
        <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/>

        <link rel="stylesheet" type="text/css" href="styles/single.css">
        <link rel="stylesheet" type="text/css" href="styles/content.css">


text:
import { TemplateRef } from '@angular/core';
export declare class TourStepTemplateService {
    template: TemplateRef<{
        content: string;
    }>;
}


text:
package org.javalite.conversion;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Converts instances of {@link java.util.Date} to {@link String}. This class is thread-safe.
 *
 * @author Eric Nielsen
 */
public class DateToStringConverter implements Converter<java.util.Date, String> {

    private final DateFormat format;
    // Calendar and DateFormat are not thread safe: http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html
    private final ThreadLocal<DateFormat> threadLocalFormat = new ThreadLocal<DateFormat>() {
        @Override protected DateFormat initialValue() {
            return (DateFormat) format.clone();
        }
    };

    /**
     * @param pattern pattern to use for conversion
     */
    public DateToStringConverter(String pattern) {
        this(new SimpleDateFormat(pattern));
    }
    /**
     * @param format DateFormat to use for conversion
     */
    public DateToStringConverter(DateFormat format) {
        this.format = format;
    }

    /**
     * @param sourceClass source Class
     * @param destinationClass destination Class
     * @return true if sourceClass is java.util.Date, or a subclass of it, and destinationClass is String
     */
    @Override
    public boolean canConvert(Class sourceClass, Class destinationClass) {
        return java.util.Date.class.isAssignableFrom(sourceClass) && String.class.equals(destinationClass);
    }

    /**
     * @param source instance of java.util.Date, or subclasses of it, for example:
     * java.sql.Date, java.sql.Time, java.sql.Timestamp
     * @return source converted to String
     */
    @Override
    public String convert(java.util.Date source) {
        return threadLocalFormat.get().format(source);
    }
}


text:
package com.example.ruslan.towncare.Models.Case;

import android.util.Log;

import com.example.ruslan.towncare.Models.Enums.DataStateChange;
import com.example.ruslan.towncare.Models.MasterInterface;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Ruslan on 16/06/2017.
 */

public class CaseFireBase {
    public static final String SORT_CASE_LAST_UPDATE = "caseLastUpdateDate";

    private static FirebaseDatabase database = FirebaseDatabase.getInstance();
    private static DatabaseReference myRef = database.getReference(CaseSql.CASE_TABLE);

    /* --- Public Methods --- */

    public static void addCase(Case c) {
        Map<String, Object> value = new HashMap<>();
        value.put("caseLastUpdateDate", ServerValue.TIMESTAMP);
        value.put("caseId", c.getCaseId());
        value.put("caseTitle", c.getCaseTitle());
        value.put("caseDate", c.getCaseDate());
        value.put("caseLikeCount", c.getCaseLikeCount());
        value.put("caseType", c.getCaseType());
        value.put("caseStatus", c.getCaseStatus());
        value.put("caseOpenerPhone", c.getCaseOpenerPhone());
        value.put("caseOpenerId", c.getCaseOpenerId());
        value.put("caseTown", c.getCaseTown());
        value.put("caseAddress", c.getCaseAddress());
        value.put("caseDesc", c.getCaseDesc());
        value.put("caseImageUrl", c.getCaseImageUrl());

        myRef.child("" + c.getCaseId()).setValue(value);
    }

    public static void removeCase(String id, final MasterInterface.GetCaseCallback callback) {
        myRef.child(id).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                dataSnapshot.getRef().removeValue();
                callback.onComplete();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                callback.onCancel();
            }
        });
    }

    // using the same method as add sense it can handle insert or edit
    public static void updateCase(Case aCase) {
        addCase(aCase);
    }

    public static void syncAndRegisterCaseData(long lastUpdate, final MasterInterface.RegisterCasesEvents callback) {
        Log.d("TAG", "syncAndRegisterCaseData - CaseFireBase - pulling data from firebase");
        myRef.orderByChild(SORT_CASE_LAST_UPDATE).startAt(lastUpdate).addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Case aCase = dataSnapshot.getValue(Case.class);
                Log.d("TAG", "syncAndRegisterCaseData - CaseFireBase - onChildAdded " + aCase.getCaseTitle());
                callback.onCaseUpdate(aCase, DataStateChange.ADDED);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Case aCase = dataSnapshot.getValue(Case.class);
                Log.d("TAG", "syncAndRegisterCaseData - CaseFireBase - onChildChanged " + aCase.getCaseTitle());
                callback.onCaseUpdate(aCase, DataStateChange.CHANGED);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Case aCase = dataSnapshot.getValue(Case.class);
                Log.d("TAG", "syncAndRegisterCaseData - CaseFireBase - onChildRemoved " + aCase.getCaseTitle());
                callback.onCaseUpdate(aCase, DataStateChange.REMOVED);
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Case aCase = dataSnapshot.getValue(Case.class);
                Log.d("TAG", "syncAndRegisterCaseData - CaseFireBase - onChildMoved " + aCase.getCaseTitle());
                callback.onCaseUpdate(aCase, DataStateChange.CHANGED);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}


text:
import json
import requests
import pprint                         # Allows Pretty Print of JSON
import os                             # Allows for the clearing of the Terminal Window
import csv                            # Allows outputting to CSV file
import time, datetime

from Classes import SharedFolder      # Object to represent a single shared folder, and all it's sharing.

"""

Written using Python 2.6

BE WARNED:
* Use with discression.
* Not testing in anger so accuracy of reporting TBC.
* Not threaded so will be slow for larger Teams / complex folder structures

An example script to iterate over all members of a team, for each member pull out a list of their shared folders.
If you provide a CSV file of users emails, it will start by analyzing only those users.
NOTE: You won't see that users full collaboration without analyzing rest of company.

If the user is the owner of a folder... iterate over and list all the groups and users with accesss ( or invited ).
If the user is not the owner, but the owner is a member of our team, we'll ignore the folder as it'll be captured when we iterate over that users folders.
If the user is not the owner, and the owner is not a member of our team. Note the folder details but flip it so external user is the folder owner and the user we're iterating over is the collaborator.

Note: Assumes default of 1000 results acceptible for querying folder members

The following output files are created.
YY-MM-DD-paths.csv   			-> List of user and the paths to publicly shared files.

"""

"""
Set your OAuth Tokens here
"""

aTokenTMFA = ''     # Team Member File Access
aTokenTMM =  ''    	# Team Member Management
aTokenTI =   ''     # Team Information Access

sourceMembersToReportOn = 'config.csv'

"""
DO NOT EDIT BELOW THIS POINT
"""

fileName = 'collaboration.csv'
totalTimeStart = datetime.datetime.fromtimestamp(time.time())

#############################################
# Function to return current Timestamp
#############################################
def getTimeYMDHM():
  lRightNow = datetime.datetime.fromtimestamp(time.time()).strftime('%y%m%d-%H-%M')
  return lRightNow;

#############################################
# Function to print Message to console in a tidy box
#############################################
def printmessageblock( str ):
  print "\n*********************************************************"
  print "* %s" % (str)
  print "*********************************************************\n"
  return;

#############################################
# Function to print Message to console in a tidy box
#############################################
def printTimeInHoursMinutesSeconds( sec ):
    sec = int(sec)
    hrs = sec / 3600
    sec -= 3600*hrs

    mins = sec / 60
    sec -= 60*mins

    return '%s hrs, %s mins, %s sec' % ( hrs, mins, sec);

"""
#############################################
# Step 0
# Clear the terminal window, not essential but makes it easier to read this way.
#############################################
"""

os.system('cls' if os.name=='nt' else 'clear')

"""
#############################################
# Step 1
# 1. Check if we have the necessary Tokens.
# 2. If not, ask the user to enter it.
#############################################
"""
if (aTokenTMFA == ''):
  aTokenTMFA = raw_input('Enter your Dropbox Business API App token (Team Member File Access permission): ')

if (aTokenTMM == ''):
  aTokenTMM = raw_input('Enter your Dropbox Business API App token (Team Member Management permission): ')

if (aTokenTI == ''):
  aTokenTI = raw_input('Enter your Dropbox Business API App token (Team Information permission): ')

"""
#############################################
# Step 2
# 1. Get the Team ID
#############################################
"""
aHeaders = {'Authorization': 'Bearer %s' % aTokenTI}
aURL = 'https://api.dropboxapi.com/2/team/get_info'
aData = json.dumps({})

print (">>> API call")
""" Make the API call """
aResult = requests.post(aURL, headers=aHeaders, data=aData)

print ("<<< Results")

# If we don't get a 200 HTML response code, we didn't get a result.
if( aResult.status_code != 200 ):
	print ('>>> Failed to get a response to call for /2/team/get_info')
	print (aResult.text)
	exit();

# Note the JSON response
teamInfo = aResult.json()
teamID = teamInfo['team_id'] # This tells us what Team we are, any folder not owned by this is EXTERNALLY owned.

"""
#############################################
# Step 3
# 1. Load CSV of users we want to report on
#############################################
"""
gUsersToAnalyze = []
bAnalyzeAll = False

# Check we have a Domains file
bHaveCSV = os.path.isfile( sourceMembersToReportOn )

if (not bHaveCSV):
	print('We could not find a file listing users to report on. ')
	print('Would you like to analyze ALL users on the team. Note this could be a very *VERY* slow process.')
	lsAnswer = raw_input("Type 'y' to process ALL or 'n' to cancel this script: ")

	if ( lsAnswer == 'y' or lsAnswer == 'Y'):
		bAnalyzeAll = True
	elif ( lsAnswer == 'n' or lsAnswer == 'N'):
		print( '\nExiting script\n')
		exit()
	else:
		print("\n\nUser did not enter a 'n' or a 'y' input. Ending script.")
		exit();

if ( not bAnalyzeAll ):
	# Open file of users to analyze
	with open( sourceMembersToReportOn, 'rb') as csvfileRead:
		# Open file to read from
		reader = csv.reader(csvfileRead)

		#Iterate through each row of the CSV.
		for row in reader:
			gUsersToAnalyze.append( row[0].lower() ) # Lower case so we can compare to Dropbox ( always lowercase )

		if ( len(gUsersToAnalyze) <= 0 ):

			# Check that we have users
			print("We could not any users in file '%s' to report on. " % sourceMembersToReportOn)
			print('Would you like to analyze ALL users on the team. Note this could be a very *VERY* slow process.')
			lsAnswer = raw_input("Type 'y' to process ALL or 'n' to cancel this script: ")

			if ( lsAnswer == 'y' or lsAnswer == 'Y'):
				bAnalyzeAll = True
			elif ( lsAnswer == 'n' or lsAnswer == 'N'):
				print( '\nExiting script\n')
				exit()
			else:
				print("\n\nUser did not enter a 'n' or a 'y' input. Ending script.")
				exit();

"""
#############################################
# Step 4
# 1. Setup the necessary variables to get list of members.
#############################################
"""
aHeaders = {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % aTokenTMM}
aURL = 'https://api.dropboxapi.com/2/team/members/list'
aData = json.dumps({'limit': 300})

"""
#############################################
# Step 5
# 1. Get list of all Dropbox Team Members
# 2. Create in memory list of them.
# 3. If they match variable 'filterOut', skip them and move to skipped list.
#############################################
"""
hasMore = True;      # Controls how long we stay in while loop loading users.
loopCounter = 0      # Count of how many times we hit the API
dbxUsers = []        # List of Dropbox Users
dbxEmailLookup = {}  # A quick reference list of key-pair values of team-member-ids and email addressses

print ("> Retrieving Dropbox Users via API")
timestart = datetime.datetime.fromtimestamp(time.time())			# Used to note start and calculare total time script took to run.

while hasMore:

	print (">>> API call")
	""" Make the API call """
	aResult = requests.post(aURL, headers=aHeaders, data=aData)

	print ("<<< Results")

	# If we don't get a 200 HTML response code, we didn't get a result.
	if( aResult.status_code != 200 ):
		print ('>>> Failed to get a response to call for /team/members/list')
		print (aResult.text)
		exit();

	# Note the JSON response
	members = aResult.json()

	# Iterate over the Members in the JSON
	for aMember in members['members']:
		dbxUsers.append( aMember )
		dbxEmailLookup[ aMember['profile']['team_member_id'] ] = aMember['profile']['email']

	hasMore = members['has_more']            # Note if there's another cursor call to make.

	# If it's the first run, from this point onwards the API call is the /continue version.
	if ( loopCounter >= 0 ):
		aURL = 'https://api.dropboxapi.com/2/team/members/list/continue'
		aData = json.dumps({'cursor': members['cursor']})
		loopCounter += 1

# How long did the APIs take?
timestop = datetime.datetime.fromtimestamp(time.time())
print (" We have the Dropbox users in memory from %s API Calls. it took %s seconds.") % (loopCounter,(timestop-timestart).total_seconds())

"""
#############################################
# Step 5
# 1. Iterate over list of members
# 2. For each member:
#       Get the list of Shared Folders
#       Note the details
#############################################
"""
# Open a file to write to
newFileName = ("%s-" + fileName) % getTimeYMDHM()

with open( newFileName, 'wt') as csvfile:
	# Define the delimiter
	writer = csv.writer(csvfile, delimiter=',')
	# Write the Column Headers

	writer.writerow(['Owner email', 'Owner Name','Folder Name', 'Folder Path', 'Folder ID', 'Collaborator Email', 'Collaborator Permissions',
		'Collaborator on Team', 'Folder Mount Status', 'Group Name', 'Group Members', 'Group Permissions', 'Group Type',
		'Team Owned Folder' ])

	#############################################
    # Iterate over the members
    ############################################
	for aMember in dbxUsers:

		# check if Analyze all is true
	    if ( not bAnalyzeAll ):

	    	# Check if aMember is in our list of
	    	if ( aMember['profile']['email'] not in gUsersToAnalyze ):

	    		continue;

	    lHeadersTMFA = {'Content-Type': 'application/json',
	        'Authorization': 'Bearer %s' % aTokenTMFA,
	        'Dropbox-API-Select-User': '%s' % str(aMember['profile']['team_member_id'])}

	    hasMore = True;
	    loopCounter = 0
	    aMemberCSV = []

	    timestart = datetime.datetime.fromtimestamp(time.time())

        #############################################
        # Loop Through all the folders the member has
        #############################################

	    aURL = 'https://api.dropboxapi.com/2/sharing/list_folders'
	    aData = json.dumps({'limit': 300})

	    while hasMore:

	    	print ('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
	    	print ('Account: %s' % aMember['profile']['email'])
	    	print ('\n+')
	    	aResult = requests.post(aURL, headers=lHeadersTMFA, data=aData)  # List_Folders
	    	print ("+++")

	    	# If we don't get a 200 HTML response code, we didn't get a result.
	    	if( aResult.status_code != 200 ):
	     		printmessageblock ('* Failed to get a response to call for list_folders. \nWe got an error [%s] with text "%s"' % (aResult.status_code, aResult.text))
	     		next;

	    	# Note the JSON response
	    	userFolders = aResult.json()

	        # Note: Unmounted Shared Folders can be identified by the absense of 'path_lower'

	    	###########################################
	    	# Iterate over the users folders
	    	###########################################
	    	for userFolder in userFolders['entries']:
	    		# Reset the variable to note the file details
	    		aMemberCSVBody = []

	    		mySharedFolder = SharedFolder()
	    		mySharedFolder.team_member_id = aMember['profile']['team_member_id']
	    		mySharedFolder.team_member_name = aMember['profile']['name']['display_name']
	    		mySharedFolder.team_member_email = aMember['profile']['email']
	    		mySharedFolder.email_is_verified = aMember['profile']['email_verified']
	    		mySharedFolder.account_status = aMember['profile']['status']['.tag']

	    		try:
	    			path_lower = userFolder['path_lower']
	    		except KeyError:
	    			path_lower = None

	    		mySharedFolder.is_team_folder = True if (userFolder['is_team_folder'] == 'true' ) else False
	    		mySharedFolder.path_lower = path_lower
	    		mySharedFolder.share_folder_id = userFolder['shared_folder_id']   # Preview URL
	    		mySharedFolder.folder_name = userFolder['name']                   # Folder Name

	    		if ( path_lower == None ):
	    			mySharedFolder.mount_status = 'UNMOUNTED' # It's an UNMOUNTED folder if path_lower is empty
	    		else:
	    			mySharedFolder.mount_status = 'MOUNTED' # It's an UNMOUNTED folder if path_lower is empty

	    		mySharedFolder.preview_url = userFolder['preview_url'] # Preview URL
	    		mySharedFolder.folder_permission = userFolder['access_type']['.tag']                                         ### So we know if user owns the folder!!!

	    		#############################################
	    		# Loop through all the members of the folder
	    		#############################################
	    		#pprint.pprint( userFolder )
	    		aSubURL = 'https://api.dropboxapi.com/2/sharing/list_folder_members'
	    		aSubData = json.dumps({'shared_folder_id': userFolder['shared_folder_id'], 'actions': [], 'limit': 1000})
	    		#pprint.pprint( aSubData )

	    		aResult = requests.post(aSubURL, headers=lHeadersTMFA, data=aSubData)
	    		# If we don't get a 200 HTML response code, we didn't get a result.
	    		if( aResult.status_code != 200 ):
	    			printmessageblock ('* Failed to get a response to call for list_folder_members. \nWe got an error [%s] with text "%s"' % (aResult.status_code, aResult.text))
	    			continue;

	    		# Note the JSON response
	    		userFolderMembers = aResult.json()

	    		#########################################
	    		#
	    		# Decision time.
	    		# We only want to record to file details from a folder owners point of view.
	    		# If this user is NOT the folder owner, we need to work out who is because if it's owned by an external party we do need
	    		# to record the fact that THIS user is a member of an externally owned/shared folder.
	    		#
	    		# So, if folder is owned by a team member, don't write anything to file and move on to next folder ( we'll catch that later )
	    		#
	    		# However if folder owned by external resource then we print ONE line showing who the external owner is, and this user as contrib.
	    		#
	    		#########################################

	    		printRowAnyways = True # If no groups / invitees / users

	    		print ( 'Folder: %s' % mySharedFolder.folder_name)
	    		groupcnt = 0
	    		inviteescnt = 0
	    		usercnt = 0

	    		##########################################
	    		# Loop over all the Groups of the folder
	    		##########################################
	    		if len(userFolderMembers['groups'] ) > 0 :
	    			groupcnt = len(userFolderMembers['groups'] )

	    			printRowAnyways = False
	    			for userGroups in userFolderMembers['groups']:

		    			mySharedFolder.addGroup( userGroups['group']['group_name'],
		    				userGroups['group']['member_count'],
		    				userGroups['access_type']['.tag'],
		    				userGroups['group']['group_type']['.tag'])

		    	# Invitees
		    	inviteescnt = len(userFolderMembers['invitees'] )
		    	#if len(userFolderMembers['invitees'] ) > 0 :
		    		# TO FIGURE OUT

		    	##########################################
	    		# Loop over all the Users of the folder
	    		##########################################
		    	if len(userFolderMembers['users'] ) > 0 :
		    		usercnt = len(userFolderMembers['users'] )
    				printRowAnyways = False
    				for folderUser in userFolderMembers['users']:

    					userEmailAddress = ''
    					userName = mySharedFolder.team_member_name

    					# Check for email address
    					if (folderUser['user']['same_team'] == True):
    						userEmailAddress = dbxEmailLookup.get( folderUser['user']['team_member_id'] )   # Get team members email address
    					else:
    						# We have to do an API call on the Account ID to get the name
    						aUserAccURL = 'https://api.dropboxapi.com/2/users/get_account'
    						aUserAccData = json.dumps({'account_id': folderUser['user']['account_id']})

    						aResult = requests.post(aUserAccURL, headers=lHeadersTMFA, data=aUserAccData)

    						# If we don't get a 200 HTML response code, we didn't get a result.
    						if( aResult.status_code != 200 ):
    							printmessageblock ('* Failed to get user account. \nWe got an error [%s] with text "%s"' % (aResult.status_code, aResult.text))
    							userEmailAddress = folderUser['user']['same_team']   # Account ID, as we couldn't load account to get email address
    							userName = ''
    						else:
    							# Note the JSON response
    							userAccount = aResult.json()
    							userEmailAddress = userAccount['email']  # Email address of the account
    							userName = userAccount['name']['display_name']

    					mySharedFolder.addUser( folderUser['access_type']['.tag'],
    						folderUser['is_inherited'],
    						userEmailAddress,
    						folderUser['user']['same_team'],
    						userName)
    			print ( '    Groups: %d  |  Invitees: %d  |  Users: %d' % (groupcnt, inviteescnt, usercnt))

    			##########################################
	    		# We should now have a folder object with list of
	    		# Groups / Invitees / Users.
	    		# Decision time!!!
	    		#
	    		##########################################

	    		if ( mySharedFolder.isOwnedByUser() ):
	    			#pprint.pprint( 'Folder owned by User')
	    			rows = mySharedFolder.getOwnerOwnedFolderRows()
	    			for row in rows:
	    				#pprint.pprint ( row )
	    				writer.writerow( row )
	    		elif ( mySharedFolder.isOwnedByTeamMember() ):
	    			print("    This folder is owned by another team member. This will be reflected when we parse their owned folders. ")
	    		else:
	    			writer.writerow ( mySharedFolder.getExternallyOwnedFolderRow() )

	        try:
	            myCursor = userFolder['cursor']
	            aData = json.dumps({'cursor': myCursor})
	        except KeyError:
	    	    hasMore = False

	    	# How long did this one account take?
	    	accTimestop = datetime.datetime.fromtimestamp(time.time())

	    	accTime = (accTimestop-timestart).total_seconds()
	    	soFar = (accTimestop-totalTimeStart).total_seconds()

	    	print ('\nTime for account listing:                                                                              %s' % (printTimeInHoursMinutesSeconds(accTime)))
	    	print ('Total so far:                                                                                %s' % (printTimeInHoursMinutesSeconds(soFar)))
	    	print ('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')

"""
#############################################
# Step 5
# 1. Output how long the script took to run.
#############################################
"""
totalTimeStop = datetime.datetime.fromtimestamp(time.time())
totalTimeInSeconds = (totalTimeStop-totalTimeStart).total_seconds()
timeAsStr = printTimeInHoursMinutesSeconds( totalTimeInSeconds )
printmessageblock( " Script finished running, it took %s seconds." % ( timeAsStr ) )


text:
srcdir = .
top_srcdir = ..

pkgdatadir = $(datadir)/ml-pnet
pkglibdir = $(libdir)/ml-pnet
pkgincludedir = $(includedir)/ml-pnet
top_builddir = ..
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
INSTALL = /usr/bin/install -c
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
subdir = tests
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/configure.in
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
	$(ACLOCAL_M4)
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_CLEAN_FILES =
depcomp =
am__depfiles_maybe =
SOURCES =
DIST_SOURCES =
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/missing --run aclocal-1.9
AMDEP_FALSE = #
AMDEP_TRUE =
AMTAR = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/missing --run tar
AUTOCONF = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/missing --run autoconf
AUTOHEADER = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/missing --run autoheader
AUTOMAKE = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/missing --run automake-1.9
AWK = gawk
CC = gcc
CCDEPMODE = depmode=none
CFLAGS = -g -O2
CPPFLAGS =
CSANT = /usr/local/bin/csant
CSANT_FLAGS = --compiler cscc -Dcscc="$(CSHARP_COMPILER)" -Dcscc.plugins.cs="$(CSHARP_PLUGIN)" --profile "$(top_srcdir)/profiles/$(PROFILE_NAME)" -Ddebug.flag="$(DEBUG_FLAG)" -Dilgac="$(CYG_ILGAC)" --assembly-cache "$(DESTDIR)$(CYG_CACHE)" -DFRAMEWORK_VERSION="$(FRAMEWORK_VERSION)" -DSECONDARY_VERSION="$(SECONDARY_VERSION)"
CSCC_FLAGS =
CSHARP_COMPILER = /usr/local/bin/cscc
CSHARP_COMPILER_CYGWIN = /usr/local/bin/cscc
CSHARP_PLUGIN =
CYGPATH =
CYGPATH_W = echo
CYG_CACHE = ${exec_prefix}/lib/cscc/lib
CYG_ILGAC = /usr/local/bin/ilgac
DEBUG_FLAG = true
DEFS = -DPACKAGE_NAME=\"\" -DPACKAGE_TARNAME=\"\" -DPACKAGE_VERSION=\"\" -DPACKAGE_STRING=\"\" -DPACKAGE_BUGREPORT=\"\" -DPACKAGE=\"ml-pnet\" -DVERSION=\"0.8.1\"
DEPDIR = .deps
ECHO_C =
ECHO_N = -n
ECHO_T =
EXEEXT =
FRAMEWORK_VERSION = 0.0.0.0
ILDD = /usr/local/bin/ildd
ILGAC = /usr/local/bin/ilgac
ILRUN = /usr/local/bin/ilrun
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
LDFLAGS =
LIBOBJS =
LIBS =
LN_S = ln -s
LTLIBOBJS =
MAINT = #
MAINTAINER_MODE_FALSE =
MAINTAINER_MODE_TRUE = #
MAKEINFO = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/missing --run makeinfo
ML_PNET_PATH = /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1
MONO_SOURCE_PATH = /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/mcs-sources
OBJEXT = o
PACKAGE = ml-pnet
PACKAGE_BUGREPORT =
PACKAGE_NAME =
PACKAGE_STRING =
PACKAGE_TARNAME =
PACKAGE_VERSION =
PATH_SEPARATOR = :
PNETLIB_PATH = /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/../pnetlib
PNET_PATH = /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/../pnet
PROFILE_NAME = framework1.1
SECONDARY_VERSION = 0.0.0.0
SET_MAKE =
SHELL = /bin/bash
STRIP =
TREECC = /usr/local/bin/treecc
TREECC_VERSION = 0.3.4
VERSION = 0.8.1
ac_ct_CC = gcc
am__fastdepCC_FALSE =
am__fastdepCC_TRUE = #
am__include = include
am__leading_dot = .
am__quote =
am__tar = ${AMTAR} chof - "$$tardir"
am__untar = ${AMTAR} xf -
bindir = ${exec_prefix}/bin
build_alias =
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE}
dvidir = ${docdir}
exec_prefix = ${prefix}
host_alias =
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = /home/jeff/dev/dev_apps/sand/qca_designer/lib/ml-pnet-0.8.1/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = mkdir -p --
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /usr/local
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
sysconfdir = ${prefix}/etc
target_alias =
CLEANFILES = Testcorlib.System.dll Testcorlib.System.Collections.dll \
		Testcorlib.System.Diagnostics.dll Testcorlib.System.Globalization.dll \
		Testcorlob.System.IO.dll Testcorlib.System.Reflection.dll \
		Testcorlib.System.Reflection.Emit.dll Testcorlib.System.Resources.dll \
		Testcorlib.System.Runtime.CompilerServices.dll \
		Testcorlib.System.Runtime.InteropServices.dll \
		Testcorlib.System.Runtime.Remoting.dll \
		Testcorlib.System.Runtime.Serialization.dll \
		Testcorlib.System.Security.dll Testcorlib.System.Security.Cryptography.dll \
		Testcorlib.System.Security.Permissions.dll \
		Testcorlib.System.Security.Policy.dll \
		Testcorlib.System.Security.Principal.dll Testcorlib.System.Text.dll \
		Testcorlib.System.Threading.dll TestSystem.dll TestSystem.Xml.dll \
		TestSystem.Runtime.Serialization.Formatters.Soap.dll \
		TestSystem.Security.dll TestMono.Security.dll TestSystem.Data.dll \
		TestSystem.Web.Services.dll TestSystem.Runtime.Remoting.dll

TESTS = Testcorlib.System.dll Testcorlib.System.Collections.dll \
		Testcorlib.System.Diagnostics.dll Testcorlib.System.Globalization.dll \
		Testcorlib.System.IO.dll Testcorlib.System.Reflection.dll \
		Testcorlib.System.Reflection.Emit.dll Testcorlib.System.Resources.dll \
		Testcorlib.System.Runtime.CompilerServices.dll \
		Testcorlib.System.Runtime.InteropServices.dll \
		Testcorlib.System.Runtime.Remoting.dll \
		Testcorlib.System.Runtime.Serialization.dll \
		Testcorlib.System.Security.dll Testcorlib.System.Security.Cryptography.dll \
		Testcorlib.System.Security.Permissions.dll \
		Testcorlib.System.Security.Policy.dll \
		Testcorlib.System.Security.Principal.dll Testcorlib.System.Text.dll \
		Testcorlib.System.Threading.dll TestSystem.dll TestSystem.Xml.dll \
		TestSystem.Runtime.Serialization.Formatters.Soap.dll \
		TestSystem.Security.dll TestMono.Security.dll TestSystem.Data.dll \
		TestSystem.Web.Services.dll TestSystem.Runtime.Remoting.dll

TESTS_ENVIRONMENT = $(SHELL) $(top_builddir)/tools/run_test.sh $(top_builddir)
all: all-am

.SUFFIXES:
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am  $(am__configure_deps)
	@for dep in $?; do \
	  case '$(am__configure_deps)' in \
	    *$$dep*) \
	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
		&& exit 0; \
	      exit 1;; \
	  esac; \
	done; \
	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu  --ignore-deps tests/Makefile'; \
	cd $(top_srcdir) && \
	  $(AUTOMAKE) --gnu  --ignore-deps tests/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
	@case '$?' in \
	  *config.status*) \
	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
	  *) \
	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
	esac;

$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh

$(top_srcdir)/configure: # $(am__configure_deps)
	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
uninstall-info-am:
tags: TAGS
TAGS:

ctags: CTAGS
CTAGS:

check-TESTS: $(TESTS)
	@failed=0; all=0; xfail=0; xpass=0; skip=0; \
	srcdir=$(srcdir); export srcdir; \
	list='$(TESTS)'; \
	if test -n "$$list"; then \
	  for tst in $$list; do \
	    if test -f ./$$tst; then dir=./; \
	    elif test -f $$tst; then dir=; \
	    else dir="$(srcdir)/"; fi; \
	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
	      all=`expr $$all + 1`; \
	      case " $(XFAIL_TESTS) " in \
	      *" $$tst "*) \
		xpass=`expr $$xpass + 1`; \
		failed=`expr $$failed + 1`; \
		echo "XPASS: $$tst"; \
	      ;; \
	      *) \
		echo "PASS: $$tst"; \
	      ;; \
	      esac; \
	    elif test $$? -ne 77; then \
	      all=`expr $$all + 1`; \
	      case " $(XFAIL_TESTS) " in \
	      *" $$tst "*) \
		xfail=`expr $$xfail + 1`; \
		echo "XFAIL: $$tst"; \
	      ;; \
	      *) \
		failed=`expr $$failed + 1`; \
		echo "FAIL: $$tst"; \
	      ;; \
	      esac; \
	    else \
	      skip=`expr $$skip + 1`; \
	      echo "SKIP: $$tst"; \
	    fi; \
	  done; \
	  if test "$$failed" -eq 0; then \
	    if test "$$xfail" -eq 0; then \
	      banner="All $$all tests passed"; \
	    else \
	      banner="All $$all tests behaved as expected ($$xfail expected failures)"; \
	    fi; \
	  else \
	    if test "$$xpass" -eq 0; then \
	      banner="$$failed of $$all tests failed"; \
	    else \
	      banner="$$failed of $$all tests did not behave as expected ($$xpass unexpected passes)"; \
	    fi; \
	  fi; \
	  dashes="$$banner"; \
	  skipped=""; \
	  if test "$$skip" -ne 0; then \
	    skipped="($$skip tests were not run)"; \
	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
	      dashes="$$skipped"; \
	  fi; \
	  report=""; \
	  if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \
	    report="Please report to $(PACKAGE_BUGREPORT)"; \
	    test `echo "$$report" | wc -c` -le `echo "$$banner" | wc -c` || \
	      dashes="$$report"; \
	  fi; \
	  dashes=`echo "$$dashes" | sed s/./=/g`; \
	  echo "$$dashes"; \
	  echo "$$banner"; \
	  test -z "$$skipped" || echo "$$skipped"; \
	  test -z "$$report" || echo "$$report"; \
	  echo "$$dashes"; \
	  test "$$failed" -eq 0; \
	else :; fi

distdir: $(DISTFILES)
	@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
	list='$(DISTFILES)'; for file in $$list; do \
	  case $$file in \
	    $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
	    $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
	  esac; \
	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
	  dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
	  if test "$$dir" != "$$file" && test "$$dir" != "."; then \
	    dir="/$$dir"; \
	    $(mkdir_p) "$(distdir)$$dir"; \
	  else \
	    dir=''; \
	  fi; \
	  if test -d $$d/$$file; then \
	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
	    fi; \
	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
	  else \
	    test -f $(distdir)/$$file \
	    || cp -p $$d/$$file $(distdir)/$$file \
	    || exit 1; \
	  fi; \
	done
check-am: all-am
	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
check: check-am
all-am: Makefile all-local
installdirs:
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am

install-am: all-am
	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am

installcheck: installcheck-am
install-strip:
	$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
	  install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
	  `test -z '$(STRIP)' || \
	    echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:

clean-generic:
	-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)

distclean-generic:
	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)

maintainer-clean-generic:
	@echo "This command is intended for maintainers to use"
	@echo "it deletes files that may require special tools to rebuild."
clean: clean-am

clean-am: clean-generic mostlyclean-am

distclean: distclean-am
	-rm -f Makefile
distclean-am: clean-am distclean-generic

dvi: dvi-am

dvi-am:

html: html-am

info: info-am

info-am:

install-data-am:

install-exec-am:

install-info: install-info-am

install-man:

installcheck-am:

maintainer-clean: maintainer-clean-am
	-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic

mostlyclean: mostlyclean-am

mostlyclean-am: mostlyclean-generic

pdf: pdf-am

pdf-am:

ps: ps-am

ps-am:

uninstall-am: uninstall-info-am

.PHONY: all all-am all-local check check-TESTS check-am clean \
	clean-generic distclean distclean-generic distdir dvi dvi-am \
	html html-am info info-am install install-am install-data \
	install-data-am install-exec install-exec-am install-info \
	install-info-am install-man install-strip installcheck \
	installcheck-am installdirs maintainer-clean \
	maintainer-clean-generic mostlyclean mostlyclean-generic pdf \
	pdf-am ps ps-am uninstall uninstall-am uninstall-info-am

all-local:
	"$(CSANT)" $(CSANT_FLAGS) -Dmono.sources="$(MONO_SOURCE_PATH)" \
			-Dpnet.libdir="$(PNETLIB_PATH)" \
			-b "$(srcdir)" -B . -f "$(srcdir)/Test.build" all
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:


text:
import accessor
import decimal
import json as json_
import message
import MySQLdb, MySQLdb.cursors
import os.path
import Queue
import re
import socket
import sys
import threading

################################################################################

CURSOR=MySQLdb.cursors.Cursor # this is the default
DICT_CURSOR=MySQLdb.cursors.DictCursor
host = socket.gethostname()

class cursor(object) :
  HAS_UPDATE=True
  LAST_SQL='SELECT last_insert_id() AS rowid;'
  def __init__(self, connection, factory) :
    self.factory = factory
    self.connection = connection
    self.create()

  def retry(self, fn0, fn1=None) :
    for attempt in range(0, connection.RETRIES) :
      try :
        return fn0()
      except MySQLdb.OperationalError :
        if sys.exc_info()[1].args == (2006, 'MySQL server has gone away') :
          message.warning('MySQL connection lost; retrying')
          self.reconnect()
          if fn1 :
            fn1()
        else :
          raise
    message.warning('retried %(n)d times', n=connection.RETRIES)
    raise

  def _create(self) :
    self.db = self.connection.cursor(self.factory) if self.factory else self.connection.cursor()
  def create(self) :
    self.retry(self._create)

  def _execute(self, *args) :
    def exe() :
      return self.db.execute(self.formatter(args[0]), *args[1:])
    return self.retry(exe, self._create) # don't retry the create

  def _executemany(self, *args) :
    def exe() :
      return self.db.executemany(self.formatter(args[0]), *args[1:])
    return self.retry(exe, self._create) # don't retry the create

  def formatter(self, fmt) :
    return re.sub(r'MIN(?=\((?=[^)]*,).+\))', 'LEAST', re.sub(r'MAX(?=\((?=[^)]*,).+\))', 'GREATEST', str(fmt)))

  def split(self, field) :
    return 'SUBSTRING_INDEX('+field+', "-", 1)'

  def info(self) :
    return self.connection.info()
  def warning_count(self) :
    return self.connection.warning_count()

class row_cursor(DICT_CURSOR) :
  def __init__(self, *args) :
    self.row_factory = self._row_factory # default row factory can be replaced
    DICT_CURSOR.__init__(self, *args)

  def __enter__(self) :
    return self

  def __exit__(self, exc_type, exc_value, traceback) :
    try :
      self.close()
    except :
      message.warning('cursor close raised exception %(exc)s', exc=sys.exc_info()[1])

  def __iter__(self) :
    self._check_executed()
    for row in self._rows[self.rownumber:] :
      yield self.row_factory(**row)
      self.rownumber += 1

  def fetchall(self) :
    return [self.row_factory(**row) for row in DICT_CURSOR.fetchall(self)]

  def fetchone(self) :
    try :
      return self.row_factory(**DICT_CURSOR.fetchone(self))
    except :
      return None

  @staticmethod
  def _row_factory(**kwargs) :
    return accessor.accessor(**kwargs)

class connection(object) :
  RETRIES=5
  default_host   = host
  default_port   = 3307
  default_user   = 'mdb'
  default_passwd = 'mdb'
  default_db     = 'mdb'
  def connect(self, *args, **kwargs) :
    try :
      self.db = kwargs['db']
    except KeyError:
      self.db = self.default_db
    try :
      instance = MySQLdb.connect(
        host=self.default_host,
        port=self.default_port,
        db=self.default_db,
        user=self.default_user,
        passwd=self.default_passwd
      )
      instance.autocommit(False)
    except :
      message.warning('Unable to connect to mysql db %(db)s at %(host)s:%(port)d because %(exc)s', db=self.db, host=self.default_host, port=self.default_port, exc=sys.exc_info()[0])
      return
    message.note("Connected to mysql db %(db)s at %(host)s:%(port)d for %(thread)s", db=self.default_db, host=self.default_host, port=self.default_port, thread=self.id())
    # this should be keyed on db too - but we don't used multiple databases currently
    self.instance[self.id()] = instance

  def row_cursor(self) :
    return self.cursor(row_cursor)

  @classmethod
  def set_default_db(cls, **args) :
    message.warning('set default db on mysql')

class json(json_.JSONEncoder) :
  'Serialize Decimal objects as integers'
  def default(self, obj):
    if isinstance(obj, decimal.Decimal):
      return int(obj)
    # Let the base class default method raise the TypeError
    return json_.JSONEncoder.default(self, obj)
  @classmethod
  def dump(cls, obj, f) :
    json_.dump(obj, f, cls=cls)
  @classmethod
  def dumps(cls, obj) :
    return json_.dumps(obj, cls=cls)


text:
module Grenade.Layers (
    module Grenade.Layers.Concat
  , module Grenade.Layers.Convolution
  , module Grenade.Layers.Crop
  , module Grenade.Layers.Deconvolution
  , module Grenade.Layers.Elu
  , module Grenade.Layers.FullyConnected
  , module Grenade.Layers.Inception
  , module Grenade.Layers.Logit
  , module Grenade.Layers.Merge
  , module Grenade.Layers.Pad
  , module Grenade.Layers.Pooling
  , module Grenade.Layers.Reshape
  , module Grenade.Layers.Relu
  , module Grenade.Layers.Softmax
  , module Grenade.Layers.Tanh
  , module Grenade.Layers.Trivial
  ) where

import           Grenade.Layers.Concat
import           Grenade.Layers.Convolution
import           Grenade.Layers.Crop
import           Grenade.Layers.Deconvolution
import           Grenade.Layers.Elu
import           Grenade.Layers.Pad
import           Grenade.Layers.FullyConnected
import           Grenade.Layers.Inception
import           Grenade.Layers.Logit
import           Grenade.Layers.Merge
import           Grenade.Layers.Pooling
import           Grenade.Layers.Reshape
import           Grenade.Layers.Relu
import           Grenade.Layers.Softmax
import           Grenade.Layers.Tanh
import           Grenade.Layers.Trivial


text:
You can see below the API reference of this module.

### `parsePath(url)`
Parses the input url.

#### Params

- **String** `url`: The input url.

#### Return
- **Object** An object containing the following fields:
   - `protocols` (Array): An array with the url protocols (usually it has one element).
   - `protocol` (String): The first protocol or `"file"`.
   - `port` (String): The domain port (default: `""`).
   - `resource` (String): The url domain/hostname.
   - `host` (String): The url domain (including subdomain and port).
   - `user` (String): The authentication user (default: `""`).
   - `password` (String): The authentication password (default: `""`).
   - `pathname` (String): The url pathname.
   - `hash` (String): The url hash.
   - `search` (String): The url querystring value (excluding `?`).
   - `href` (String): The normalized input url.
   - `query` (Object): The url querystring, parsed as object.
   - `parse_failed` (Boolean): Whether the parsing failed or not.


text:
const int SUCCESS_CODE = 12345;

static void cb_CanCreateIcosahedron()
{
    RendMesh *mesh = rend_new_icosahedron_mesh();
    EXPECT_NE(nullptr, mesh);
    rend_mesh_destroy(mesh);
    rend_exit(SUCCESS_CODE);
}
TEST(MeshTest, CanCreateIcosahedron)
{
    rend_set_start_callback(&cb_CanCreateIcosahedron);
    EXPECT_EQ(SUCCESS_CODE, rend_exec());
    rend_set_start_callback(nullptr);
}


text:
<link href="<?=base_url()?>/assets/css/admin_add_style.css" rel="stylesheet">

<?php
/**
 * Created by PhpStorm.
 * User: psion
 * Date: 10/26/2016
 * Time: 9:06 PM
 */
?>

<?php
include 'a_navbar.php';
?>

Admin

Account Management

<?php if($_SESSION['admin_typeid'] == 1): ?>

                            List of Admins

                                    <button type ="button"data-toggle="modal" data-target="#AddNewAdminModal" class="btn btn-default btn-block add-room-btn" >+ Add Accounts</button>

                                    <button class="btn btn-default btn-block" type="button" onclick="changeViewToEdit('admintable','admintable_buttons', 'AddNewAdminModal')">Edit Accounts</button>

                        <form>

                                        First Name
                                        Last Name
                                        Email
                                        Department

                                    <?php foreach($administrators as $admin):?>

                                            <?=$admin->first_name?>
                                            <?=$admin->last_name?>
                                            <?=$admin->email?>
                                            <?=$admin->name?>

                                    <?php endforeach;?>

                        </form>

<?php else:?>

                            List of Moderators

                            <button type ="button"data-toggle="modal" data-target="#AddNewModeratorModal" class="btn btn-default btn-block  col-md-2"> +Add Moderators</button>

                               <button class="btn btn-default btn-block col-md-2 col-md-offset-0" type="button" onclick="changeViewToEdit('modtable','modtable_buttons', 'AddNewModeratorModal')">Edit Accounts</button>

                        <form>

                                        First Name
                                        Last Name
                                        Email
                                        Department
                                        Area Assignment

                                    <?php foreach($moderators as $mod):?>

                                            <?=$mod->first_name?>
                                            <?=$mod->last_name?>
                                            <?=$mod->email?>
                                            <?=$mod->name?>
                                            <?=$mod->room?>

                                    <?php endforeach;?>

                        </form>

<?php endif;?>

                <button type="button" class="close" data-dismiss="modal">×</button>

Add Moderator Account/s

            <form>

                    <button type = "button" class = "btn btn-default btn-block  " onclick = "addAccountModerator('add_table')">Add Another Moderator</button>

                            First Name
                            Last Name
                            Email
                            Department
                            Area Assignment
                            Delete

                            <input type="text" class="form-control" placeholder="Enter first name">
                            <input type="text" class="form-control" placeholder="Enter last name">
                            <input type="text" class="form-control" placeholder="Enter email">
                            <?php echo $departments[0]->name ?>
                            <select type='text' class='form-control' placeholder='Choose Area' onchange="changeAreaMod('add_table')"><option value='0' selected>No Area</option>
                                    <?php foreach($freeRooms as $room):?>
                                        <option value=<?=$room->roomid?> ><?=$room->name?></option>
                                    <?php endforeach;?>

                                </select>

                            <button type ="button" onclick="deleteRow('add_table', 1)" class="btn btn-default clearmod-btn">×</button>

                    <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="cancelAddAccount('add_table')">Cancel</button>
                    <button type="button" class="btn btn-success" onclick="submitModerator('add_table')">Confirm</button>

            </form>

                <button type="button" class="close" data-dismiss="modal">×</button>

Add Admin Account/s

            <form>

                    <button type = "button" class = "btn btn-default btn-block  " onclick = "addAccountAdmin('add_tableA')">Add Another Admin</button>

                            First Name
                            Last Name
                            Email
                            Department
                            Delete

                            <input type="text" class="form-control" placeholder="Enter first name">
                            <input type="text" class="form-control" placeholder="Enter last name">
                            <input type="text" class="form-control" placeholder="Enter email">

                            <select type='text' class='form-control' placeholder='Enter Department'>
                                    <option value='0' disabled selected>Choose a Department</option>
                                    <?php foreach($departments as $dep):?>
                                        <option value=<?=$dep->departmentid?>><?=$dep->name?></option>
                                    <?php endforeach;?>
                                </select>

                            <button type ="button" onclick="deleteRow('add_tableA', 1)" class="btn btn-default clearmod-btn">×</button>

                    <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="cancelAddAccount('add_tableA')">Cancel</button>
                    <button type="button" class="btn btn-success" onclick="submitAdmins('add_tableA')" >Confirm</button>

            </form>


text:
package ar.edu.unju.fi.negocio;

import javax.inject.Named;

/**
 * Clase java ejemplo para probar el contexto de spring
 *
 * @author Jose
 *
 */
@Named
public class Ejemplo {
	private String nombre;

	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

}


text:
/**
 * Annotation action.
 *
 * @class
 * @extends ve.ui.Action
 * @constructor
 * @param {ve.ui.Surface} surface Surface to act on
 */
ve.ui.AnnotationAction = function VeUiAnnotationAction( surface ) {
	// Parent constructor
	ve.ui.Action.call( this, surface );
};

/* Inheritance */

OO.inheritClass( ve.ui.AnnotationAction, ve.ui.Action );

/* Static Properties */

ve.ui.AnnotationAction.static.name = 'annotation';

/**
 * List of allowed methods for the action.
 *
 * @static
 * @property
 */
ve.ui.AnnotationAction.static.methods = [ 'set', 'clear', 'toggle', 'clearAll' ];

/* Methods */

/**
 * Set an annotation.
 *
 * @method
 * @param {string} name Annotation name, for example: 'textStyle/bold'
 * @param {Object} [data] Additional annotation data
 */
ve.ui.AnnotationAction.prototype.set = function ( name, data ) {
	var i,
		fragment = this.surface.getModel().getFragment(),
		annotationClass = ve.dm.annotationFactory.lookup( name ),
		removes = annotationClass.static.removes;

	for ( i = removes.length - 1; i >= 0; i-- ) {
		fragment.annotateContent( 'clear', removes[i] );
	}
	fragment.annotateContent( 'set', name, data );
};

/**
 * Clear an annotation.
 *
 * @method
 * @param {string} name Annotation name, for example: 'textStyle/bold'
 * @param {Object} [data] Additional annotation data
 */
ve.ui.AnnotationAction.prototype.clear = function ( name, data ) {
	this.surface.getModel().getFragment().annotateContent( 'clear', name, data );
};

/**
 * Toggle an annotation.
 *
 * If the selected text is completely covered with the annotation already the annotation will be
 * cleared. Otherwise the annotation will be set.
 *
 * @method
 * @param {string} name Annotation name, for example: 'textStyle/bold'
 * @param {Object} [data] Additional annotation data
 */
ve.ui.AnnotationAction.prototype.toggle = function ( name, data ) {
	var i, existingAnnotations, insertionAnnotations, removesAnnotations,
		surfaceModel = this.surface.getModel(),
		fragment = surfaceModel.getFragment(),
		annotation = ve.dm.annotationFactory.create( name, data ),
		removes = annotation.constructor.static.removes;

	if ( !fragment.getRange().isCollapsed() ) {
		if ( !fragment.getAnnotations().containsComparable( annotation ) ) {
			for ( i = removes.length - 1; i >= 0; i-- ) {
				fragment.annotateContent( 'clear', removes[i] );
			}
			fragment.annotateContent( 'set', name, data );
		} else {
			fragment.annotateContent( 'clear', name );
		}
	} else {
		insertionAnnotations = surfaceModel.getInsertionAnnotations();
		existingAnnotations = insertionAnnotations.getAnnotationsByName( annotation.name );
		if ( existingAnnotations.isEmpty() ) {
			removesAnnotations = insertionAnnotations.filter( function ( annotation ) {
				return ve.indexOf( annotation.name, removes ) !== -1;
			} );
			surfaceModel.removeInsertionAnnotations( removesAnnotations );
			surfaceModel.addInsertionAnnotations( annotation );
		} else {
			surfaceModel.removeInsertionAnnotations( existingAnnotations );
		}
	}
};

/**
 * Clear all annotations.
 *
 * @method
 */
ve.ui.AnnotationAction.prototype.clearAll = function () {
	var i, len, arr,
		surfaceModel = this.surface.getModel(),
		fragment = surfaceModel.getFragment(),
		annotations = fragment.getAnnotations( true );

	arr = annotations.get();
	// TODO: Allow multiple annotations to be set or cleared by ve.dm.SurfaceFragment, probably
	// using an annotation set and ideally building a single transaction
	for ( i = 0, len = arr.length; i < len; i++ ) {
		fragment.annotateContent( 'clear', arr[i].name, arr[i].data );
	}
	surfaceModel.setInsertionAnnotations( null );
};

/* Registration */

ve.ui.actionFactory.register( ve.ui.AnnotationAction );


text:
#import <UIKit/UIKit.h>

#import "ENManager.h"

#define DEFAULT_IMAGE_LIST_WIDTH	640
#define TITLE_INPUT_FIELD_HEIGHT	44

@interface CreateNoteViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
	NSMutableArray *imageViews;

    IBOutlet UITextView *bodyView;
	IBOutlet UIView *titleHeaderView;
	IBOutlet UITextField *titleField;
	EDAMGuid notebookGUID;
}
@property (nonatomic, retain) EDAMGuid notebookGUID;

#pragma mark - Instance method

- (void)sendOnlyText;
- (void)sendTextAndImage;
- (void)updateHeader;
- (void)addImageToArrayWithInfo:(NSDictionary*)info;

@end


text:
package com.socialize.demo.implementations.twitter;

import android.app.Activity;
import com.socialize.LocationUtils;
import com.socialize.api.SocializeSession;
import com.socialize.demo.SDKDemoActivity;
import com.socialize.error.SocializeException;
import com.socialize.listener.SocializeAuthListener;
import com.socialize.networks.PostData;
import com.socialize.networks.SocialNetwork;
import com.socialize.networks.SocialNetworkListener;
import com.socialize.networks.twitter.Tweet;
import com.socialize.networks.twitter.TwitterUtils;
import org.json.JSONObject;

/**
 * @author Jason Polites
 *
 */
public class TweetActivity extends SDKDemoActivity {

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#executeDemo()
	 */
	@Override
	public void executeDemo(final String text) {

		TwitterUtils.link(this, new SocializeAuthListener() {

			@Override
			public void onError(SocializeException error) {
				handleError(TweetActivity.this, error);
			}

			@Override
			public void onCancel() {
				handleCancel();
			}

			@Override
			public void onAuthSuccess(SocializeSession session) {

				Tweet tweet = new Tweet();

				tweet.setText(text);
				tweet.setLocation(LocationUtils.getLastKnownLocation(TweetActivity.this));
				tweet.setShareLocation(true);

				TwitterUtils.tweet(TweetActivity.this, tweet, new SocialNetworkListener() {

					@Override
					public boolean onBeforePost(Activity parent, SocialNetwork socialNetwork, PostData postData) {
						// Nothing to see here.. move along.
						return false;
					}

					@Override
					public void onNetworkError(Activity context, SocialNetwork network, Exception error) {
						handleError(TweetActivity.this, error);
					}

					@Override
					public void onCancel() {
						handleCancel();
					}

					@Override
					public void onAfterPost(Activity parent, SocialNetwork socialNetwork, JSONObject responseObject) {
						handleResult(responseObject.toString());
					}
				});
			}

			@Override
			public void onAuthFail(SocializeException error) {
				handleError(TweetActivity.this, error);
			}
		});
	}

	@Override
	public boolean isTextEntryRequired() {
		return true;
	}

	/* (non-Javadoc)
	 * @see com.socialize.demo.DemoActivity#getButtonText()
	 */
	@Override
	public String getButtonText() {
		return "Tweet!";
	}
}


text:
(function(wc) {
    'use strict';
    var version = 'v1.0.1',
        logEle, el, color,
        container,
        myNav = navigator.userAgent.toLowerCase(),
        config = {
            warn: '#FFA500;',
            error: '#FF0000;',
            info: '#FFFF00;',
            log: '#7FFF00;',
            def: '#00FFFF;',
            sLog: 'log info warn error'.split(' '),
            top_left: {
                'top': 0,
                'left': 0,
                'right': '',
                'bottom': ''
            },
            top_right: {
                'top': 0,
                'left': '',
                'right': 0,
                'bottom': ''
            },
            bottom_left: {
                'top': '',
                'left': 0,
                'right': '',
                'bottom': 0
            },
            bottom_right: {
                'top': '',
                'left': '',
                'right': 0,
                'bottom': 0
            },
            mainCon_css: 'background:#000;position:fixed;min-width:200px;max-height:50vh;font-family:Helvetica,Arial,sans-serif;font-size:10px;border:2px solid tomato;font-weight:bold;padding:5px;text-align:left;'
        },
        defOptions = {
            direction: 'top_left',
            bgColor: '#000000;',
            css: 'opacity:0.8; eeoverflow:auto;'
        },
        /**
         * @return {function} Creating instance
         **/
        DOM = {},
        Logger = function() {},
        d = wc.log,
        fn = d,
        log = function(a, l) {
            if (!wc) return; /* return or call your custom function here */
            fn = (l === undefined) ? d : (_console[l] || d);
            if (container) DOM.paintLog(l, a[0]);
            fn.apply(wc, a);
        },
        _console = {
            log: wc.log,
            debug: wc.debug,
            info: wc.info,
            warn: wc.warn,
            error: wc.error,
            assert: wc.assert,
            clear: wc.clear,
            dir: wc.dir,
            dirxml: wc.dirxml,
            trace: wc.trace,
            group: wc.group,
            groupCollapsed: wc.groupCollapsed,
            groupEnd: wc.groupEnd,
            time: wc.time,
            timeEnd: wc.timeEnd,
            timeStamp: wc.timeStamp,
            profile: wc.profile,
            profileEnd: wc.profileEnd,
            count: wc.count,
            exception: wc.exception,
            table: wc.table
        };
    /**
     * @return {boolean} Is browser is IE or not
     **/
    function isIE() {
        return myNav.indexOf('msie') !== -1 ? parseInt(myNav.split('msie')[1], 10) : false;
    }
    /**
     * @return {boolean} Is object or not
     **/
    function isObject(a) {
        return (a instanceof Object || typeof a === 'object');
    }
    /**
     * @return {object} Merging two objects
     **/
    function extend(obj, src) {
        if (!isIE()) {
            /*this is too fast compare to other, but this is not working in IE8 and less*/
            Object.keys(src).forEach(function(key) {
                obj[key] = src[key];
            });
        } else {
            /*this is slow compare to above, this is for IE*/
            for (var key in src) {
                if (src.hasOwnProperty(key)) obj[key] = src[key];
            }
        }
        return obj;
    }
    /**
     * Destroy the screen console
     **/
    function destroy() {
        if (logger.loggerInitialized) {
            logger.loggerInitialized = !1;
            container.remove();
            container = '';
        } else {
            throw 'You need to call `logger.init()` for show logger screen.';
        }
    }
    DOM = {
        /**
         * Creata a screen console container
         * @param {object} options
         * @return {object} screen console container
         **/
        createContainer: function(options) {

            var butt, mainCon = this.createElement(config.mainCon_css);

            butt = this.createButton('Clear', function() {
                logEle.innerHTML = '';
            });
            mainCon.appendChild(butt);

            butt = this.createButton('Close', destroy);
            butt.style.cssText = 'float:right;';
            mainCon.appendChild(butt);

            logEle = this.createElement(options.css);
            mainCon.appendChild(logEle);
            return mainCon;
        },
        /**
         * Creates a DOM element
         * @param {String} scc
         * @return {Object} DOM element
         **/
        createElement: function(css) {
            var element = document.createElement('div');
            element.style.cssText = css;
            return element;
        },
        /**
         * creates a button for clean/destroy button
         * @param {string} button name
         * @param {function} button event
         * @return {object} button DOM element
         **/
        createButton: function(name, event) {
            var element = document.createElement('button');
            element.innerHTML = name;
            element.addEventListener("click", event);
            return element;
        },
        /**
         * Print the console log into the browser screen
         * @param {string} console name
         * @param {string} console message
         **/
        paintLog: function(l, msg) {
            msg = config.sLog.indexOf(l) > -1 ? msg : 'Please, see the browser console';
            color = config[l] ? config[l] : config.def;
            el = this.createElement('color:' + color + 'line-height:18px;background:' + (logEle.children.length % 2 ? 'rgba(255,255,255,0.1)' : ''));
            el.textContent = msg;
            logEle.appendChild(el);
        },
        /**
         * Set the screen console positon - top_left, top_right, bottom_left, bottom_right
         * @param {object} positions
         **/
        setPosition: function(styles) {
            if (container) {
                styles = config[styles];
                for (var property in styles)
                    container.style[property] = styles[property];
            } else {
                throw 'You need to call `logger.init()` for show logger screen.';
            }
        }
    };

    Logger = Logger.prototype = {
        /**
         * @return {String} Logger version
         **/
        version: version,
        /**
         * Load the logger window once DOM ready
         * @param {function} callback function
         **/
        ready: function(callBack) {
            // in case the document is already rendered
            if (document.readyState != 'loading') {
                this.init();
                if (callBack) callBack(this);
            } else if (document.addEventListener) {
                document.addEventListener('DOMContentLoaded', function() {
                    this.init();
                    if (callBack) callBack(this);
                }.bind(this));
            } else document.attachEvent('onreadystatechange', function() {
                if (document.readyState == 'complete') {
                    this.init();
                    if (callBack) callBack(this);
                }
            });
        },
        /**
         * initializing the logger screen window
         * @param {Object} options for logger
         **/
        init: function(options) {
            if (this.loggerInitialized) return;
            this.loggerInitialized = !0;
            defOptions = isObject(options) ? extend(defOptions, options) : defOptions;
            container = DOM.createContainer(defOptions);
            DOM.setPosition(defOptions.direction);
            document.body.appendChild(container);
        },
        /**
         * show the logger screen window if turned off
         **/
        on: function() {
            if (container) {
                container.style.display = 'block';
            } else {
                throw 'You need to call `logger.init()` for show logger screen.';
            }
        },
        /**
         * hide the displaying logger screen window
         **/
        off: function() {
            if (this.loggerInitialized) container.style.display = 'none';
        },
        /**
         * kill the the logger screen window
         **/
        kill: destroy,
        /**
         * set positon the logger screen window
         * @param {Object} options for logger pisition
         **/
        position: function(a) {
            if (a && a.direction !== undefined) {
                DOM.setPosition(a.direction);
            }
        },
        /**
         * Clears the console.
         **/
        clear: function() {
            log(arguments, 'clear');
        },
        /**
         * Writes a message to the console with the visual "info" icon and color coding and a hyperlink to the line where it was called.
         **/
        info: function() {
            log(arguments, 'info');
        },
        /**
         * Writes a message to the console. You may pass as many arguments as you'd like, and they will be joined together in a space-delimited line.
         **/
        log: function() {
            log(arguments, 'log');
        },
        /**
         * Tests that an expression is true. If not, it will write a message to the console and throw an exception.
         **/
        assert: function() {
            log(arguments, 'assert');
        },
        /**
         * Writes the number of times that the line of code where count was called was executed.
         **/
        count: function() {
            log(arguments, 'count');
        },
        /**
         * Writes a message to the console, including a hyperlink to the line where it was called.
         **/
        debug: function() {
            log(arguments, 'debug');
        },
        /**
         * Prints an interactive listing of all properties of the object. This looks identical to the view that you would see in the DOM Panel.
         **/
        dir: function() {
            log(arguments, 'dir');
        },
        /**
         * Prints the XML source tree of an HTML or XML element. This looks identical to the view that you would see in the HTML Panel. You can click on any node to inspect it in the HTML Panel.
         **/
        dirxml: function() {
            log(arguments, 'dirxml');
        },
        /**
         * Writes a message to the console with the visual "error" icon and color coding and a hyperlink to the line where it was called.
         **/
        error: function() {
            log(arguments, 'error');
        },
        /**
         * Writes a message to the console and opens a nested block to indent all future messages sent to the console. Call console.groupEnd() to close the block.
         **/
        group: function() {
            log(arguments, 'group');
        },
        /**
         * Like console.group(), but the block is initially collapsed.
         **/
        groupCollapsed: function() {
            log(arguments, 'groupCollapsed');
        },
        /**
         * Closes the most recently opened block created by a call to console.group() or console.groupCollapsed()
         **/
        groupEnd: function() {
            log(arguments, 'groupEnd');
        },
        /**
         * Turns on the JavaScript profiler.
         **/
        profile: function() {
            log(arguments, 'profile');
        },
        /**
         * Turns off the JavaScript profiler and prints its report.
         **/
        profileEnd: function() {
            log(arguments, 'profileEnd');
        },
        /**
         * Creates a new timer under the given name. Call console.timeEnd() with the same name to stop the timer and print the time elapsed.
         **/
        time: function() {
            log(arguments, 'time');
        },
        /**
         * Stops a timer created by a call to console.time(name) and writes the time elapsed.
         **/
        timeEnd: function() {
            log(arguments, 'timeEnd');
        },
        /**
         * Creates a time stamp, which can be used together with HTTP traffic timing to measure when a certain piece of code was executed.
         **/
        timeStamp: function() {
            log(arguments, 'timeStamp');
        },
        /**
         * Prints an interactive stack trace of JavaScript execution at the point where it is called.
         **/
        trace: function() {
            log(arguments, 'trace');
        },
        /**
         * Writes a message to the console with the visual "warning" icon and color coding and a hyperlink to the line where it was called.
         **/
        warn: function() {
            log(arguments, 'warn');
        },
        /**
         * Prints an error message together with an interactive stack trace of JavaScript execution at the point where the exception occurred.
         **/
        exception: function() {
            log(arguments, 'exception');
        },
        /**
         * Allows to log provided data using tabular layout.
         **/
        table: function() {
            log(arguments, 'table');
        }
    };
    /**
     * initializing the logger screen window
     **/
    Logger.ready();
    /* AMD/RequireJS */
    if (typeof define !== 'undefined' && define.amd) {
        define([], function() {
            return Logger;
        });
    }
    /* CommonJS */
    else if (typeof module !== 'undefined' && module.exports) {
        module.exports = Logger;
    } else { /*Plain javascript library*/
        window.logger = window.Logger = Logger;
    }

})(window.console);


text:
import sys
class config(object):
    import yaml, uuid, os, logging
    """
        Magical config class that allows for real-time updating of config variables.
        Every attribute access to this class (i.e.: config.config.thumbnail_size) will
        check the fmod time of the config YAML file, and read the file if necessary.

        Fast, although it does an os.stat on every attribute access. Worth it.
    """

    # Format of track identifiers (currently UUIDs)
    uid = lambda(self): str( object.__getattribute__(self, 'uuid').uuid4() ).replace( '-', '' )
    uid_re = r'[a-f0-9]{32}'

    last_updated = 0
    config_file = 'config.yml'

    def __init__(self):
        # Variables to be passed through to javascript.
        self.javascript = {
            'socket_io_port': self.socket_io_port,
            'remember_transport': False,
            'monitor_resource': self.monitor_resource,
            'progress_resource': self.progress_resource,
            'socket_extra_sep': self.socket_extra_sep,
            'allowed_file_extensions': [x[1:] for x in self.allowed_file_extensions],
            'drop_text': 'Drop a song here to remix!',
            'upload_text': 'Click here (or drag in a song) to create a remix.',
            'soundcloud_consumer': self.soundcloud_consumer,
            'soundcloud_redirect': self.soundcloud_redirect,
        }

    def update(self, filename=None):
        """
            Update the object's attributes.
        """
        object.__getattribute__(self, 'logging').getLogger().info("Config file has changed, updating...")
        if not filename:
            filename = object.__getattribute__(self, 'config_file')
        for k, v in object.__getattribute__(self, 'yaml').load(open(filename)).iteritems():
            setattr(self, k, v)

    def __getattribute__(self, name):
        """
            When trying to access an attribute, check if the underlying file has changed first.
        """
        if name in ['update', 'javascript', 'uid', 'uid_re']:
            return object.__getattribute__(self, name)
        else:
            last_updated = object.__getattribute__(self, 'last_updated')
            fmod_time = object.__getattribute__(self, 'os').stat(object.__getattribute__(self, 'config_file'))[9]
            if last_updated < fmod_time:
                self.last_updated = fmod_time
                self.update()
            return object.__getattribute__(self, name)

# This is a dirty, dirty hack, but lets you just do:
#   import config
# and have access to an instantiated config object.
sys.modules[__name__] = config()


text:
        Dropdown
        Dropdown is used to select an item from a collection of options. Custom content support and filtering are the notable features.

Single

Selected City: {{selectedCity||'none'}}

Content with Filter

        <template let-car>

{{car.label}}

        </template>

Selected Car: {{selectedCar||'none'}}

Import

import {Dropdown} from 'primeng/primeng';

Getting Started

Two-way value binding is defined using ngModel and dropdown requires a collection of options
                where each option should follow the SelectItem interface that defines label-value properties.

<p-dropdown [options]="cities" [(ngModel)]="selectedCity"></p-dropdown>

import {SelectItem} from 'primeng/primeng';

export class MyModel {

    cities: SelectItem[];

    selectedCity: string;

    constructor() {
        this.cities = [];
        this.cities.push({label:'New York', value:'New York'});
        this.cities.push({label:'Rome', value:'Rome'});
        this.cities.push({label:'London', value:'London'});
        this.cities.push({label:'Istanbul', value:'Istanbul'});
        this.cities.push({label:'Paris', value:'Paris'});
    }

}

Model Driven Forms

Dropdown can be used in a model driven form as well by defining ngFormControl or ngControl.

<p-dropdown [options]="cities" ngControl="selectedCity"></p-dropdown>

Filtering

Options can be filtered using an input field in the overlay by enabling the filter property.

<p-dropdown [options]="cities" [(ngModel)]="selectedCity" [filter]="true"></p-dropdown>

Custom Content

Label of an option is used as the display text of an item by default, for custom content support define a template having a li item having .ui-dropdown-item style class
                as a wrapper for the content. The list item should have data-value attribute defined as the value of the select item. The local template variable refers to an option in the options collection.

<p-dropdown [options]="cars" [(ngModel)]="selectedCar" [filter]="true" style="width:100px">
    <template let-car>
        <li class="ui-dropdown-list-item ui-helper-clearfix" style="position: relative" [attr.data-value]="car.value">
            <img src="showcase/resources/demo/images/car/{{car.label}}.gif" style="width:24px;position:absolute;top:1px;left:10px"/>
            <div style="font-size:14px;float:right;margin-top:2px">{{car.label}}</div>
        </li>
    </template>
</p-dropdown>

import {SelectItem} from 'primeng/primeng'

export class MyModel {

    cars: SelectItem[];

    selectedCar: string;

    constructor() {
        this.cars = [];
        this.cars.push({label: 'Audi', value: 'Audi'});
        this.cars.push({label: 'BMW', value: 'BMW'});
        this.cars.push({label: 'Fiat', value: 'Fiat'});
        this.cars.push({label: 'Ford', value: 'Ford'});
        this.cars.push({label: 'Honda', value: 'Honda'});
        this.cars.push({label: 'Jaguar', value: 'Jaguar'});
        this.cars.push({label: 'Mercedes', value: 'Mercedes'});
        this.cars.push({label: 'Renault', value: 'Renault'});
        this.cars.push({label: 'VW', value: 'VW'});
        this.cars.push({label: 'Volvo', value: 'Volvo'});
    }
}

Attributes

                            Name
                            Type
                            Default
                            Description

                            options
                            array
                            null
                            An array of selectitems to display as the available options.

                            scrollHeight
                            string
                            200px
                            Height of the viewport in pixels, a scrollbar is defined if height of list exceeds this value.

                            style
                            string
                            null
                            Inline style of the element.

                            styleClass
                            string
                            null
                            Style class of the element.

                            filter
                            boolean
                            false
                            When specified, displays an input field to filter the items on keyup.

                            autoWidth
                            boolean
                            true
                            Calculates the width based on options width, set to false for custom width.

                            required
                            boolean
                            false
                            When present, it specifies that an input field must be filled out before submitting the form.

Events

                        Name
                        Parameters
                        Description

                        onChange
                        event.originalEvent: Browser event

                            event.value: Single value or an array of values that are selected

                        Callback to invoke when value of dropdown changes.

Styling

Following is the list of structural style classes, for theming classes visit theming page.

                            Name
                            Element

                            ui-dropdown
                            Container element.

                            ui-dropdown-label
                            Element to display label of selected option.

                            ui-dropdown-trigger
                            Icon element.

                            ui-dropdown-panel
                            Icon element.

                            ui-dropdown-items-wrapper
                            Wrapper element of items list.

                            ui-dropdown-items
                            List element of items.

                            ui-dropdown-item
                            An item in the list.

                            ui-dropdown-filter-container
                            Container of filter input.

                            ui-dropdown-filter
                            Filter element.

Dependencies

Native component that requires the css of PrimeUI Dropdown.

<h3 class="first">Single</h3>
<p-dropdown [options]="cities" [(ngModel)]="selectedCity"></p-dropdown>
<p>Selected City: {{selectedCity||'none'}}</p>

<h3>Content with Filter</h3>
<p-dropdown [options]="cars" [(ngModel)]="selectedCar" [filter]="true" style="width:150px">
    <template let-car>
        <li class="ui-helper-clearfix" style="position: relative">
            <img src="showcase/resources/demo/images/car/{{car.label}}.gif" style="width:24px;position:absolute;top:1px;left:10px"/>
            <div style="font-size:14px;float:right;margin-top:2px">{{car.label}}</div>
        </li>
    </template>
</p-dropdown>
<p>Selected Car: {{selectedCar||'none'}}</p>

export class DropdownDemo {

    cities: SelectItem[];

    selectedCity: string;

    cars: SelectItem[];

    selectedCar: string = 'BMW';

    constructor() {
        this.cities = [];
        this.cities.push({label:'Select City', value:''});
        this.cities.push({label:'New York', value:'New York'});
        this.cities.push({label:'Rome', value:'Rome'});
        this.cities.push({label:'London', value:'London'});
        this.cities.push({label:'Istanbul', value:'Istanbul'});
        this.cities.push({label:'Paris', value:'Paris'});

        this.cars = [];
        this.cars.push({label: 'Audi', value: 'Audi'});
        this.cars.push({label: 'BMW', value: 'BMW'});
        this.cars.push({label: 'Fiat', value: 'Fiat'});
        this.cars.push({label: 'Ford', value: 'Ford'});
        this.cars.push({label: 'Honda', value: 'Honda'});
        this.cars.push({label: 'Jaguar', value: 'Jaguar'});
        this.cars.push({label: 'Mercedes', value: 'Mercedes'});
        this.cars.push({label: 'Renault', value: 'Renault'});
        this.cars.push({label: 'VW', value: 'VW'});
        this.cars.push({label: 'Volvo', value: 'Volvo'});
    }

}


text:
import path from 'path'

export function createLogger(filename) {
  const label = path.relative(path.join(__dirname, '../../..'), filename)

  return new Proxy(
    {},
    {
      get(_, level) {
        return (message, meta) =>
          console.log(`[${label}] ${level}: ${message} %j`, meta)
      },
    }
  )
}

export const useLogger = filename => {
  return createLogger(filename)
}


text:
local xml = require('app/xml')
local tap = require('util/tap')
local assert = require('assert')

describe('test xml - parse', function()
    local data, err = xml.parse()
    console.log(data, err)

    data, err = xml.parse(1)
    console.log(data, err)

    data, err = xml.parse({})
    console.log(data, err)

    data, err = xml.parse('')
    console.log(data, err)

    data, err = xml.parse(' ')
    assert.equal(#data:children(), 0)

    data, err = xml.parse('{}')
    assert.equal(#data:children(), 0)

    data, err = xml.parse('<root/>')
    assert.equal(#data:children(), 1)

    data, err = xml.parse('<root></root>')
    assert.equal(#data:children(), 1)
end)

describe('test xml - onvif', function()

    local message = [[
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/>
    </s:Body>
</s:Envelope>
]]

    local data = xml.parse(message)

    -- root
    local root = data['s:Envelope']
    assert.equal(root:name(), 's:Envelope')

    -- body
    local body = root['s:Body']
    assert.equal(body:name(), 's:Body')

    -- GetSystemDateAndTime
    local element = body.GetSystemDateAndTime
    assert.equal(element:name(), 'GetSystemDateAndTime')
    assert.equal(element['@xmlns'], 'http://www.onvif.org/ver10/device/wsdl')

    -- properties
    local properties = element:properties()
    local property = properties[1]
    assert.equal(property.name, 'xmlns')

    -- xmlToTable
    local _, object = xml.xmlToTable(data)
    -- console.log(object)
    local Envelope = object.Envelope
    local Body = Envelope.Body
    local GetSystemDateAndTime = Body.GetSystemDateAndTime
    assert.equal(GetSystemDateAndTime['@xmlns'], 'http://www.onvif.org/ver10/device/wsdl')
end)


text:
<!DOCTYPE html>

        <title>Self Check</title>
        <meta http-equiv='X-UA-Compatible' content='IE=edge'>

        <link href='https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.min.css' rel='stylesheet' type='text/css'>

        <link href='https://cdn.jsdelivr.net/semantic-ui/2.1.8/semantic.min.css' rel='stylesheet' type='text/css'>

        <link href='./css/selfcheck.css' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="./css/codemirror.css">

SelfCheck

                    <button class='green circular ui icon button' onclick='addCheckModal();'>

                    </button>

                        Settings

                            <input class='timepicker' type='text' value=''/>

                            <input type='hidden' name=''>

                            <textarea id='codetextarea' class='tt'></textarea>

                    Github
                    Copyright/Licence


text:
/**
 * @license Highcharts JS v8.2.0 (2020-08-20)
 * @module highcharts/modules/histogram-bellcurve
 * @requires highcharts
 *
 * (c) 2010-2019 Highsoft AS
 * Author: Sebastian Domas
 *
 * License: www.highcharts.com/license
 */
'use strict';
import '../../Series/HistogramSeries.js';
import '../../Series/BellcurveSeries.js';


text:
/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Jaume Nin <jnin@cttc.es>
 */

#ifndef MAC_STATS_CALCULATOR_H_
#define MAC_STATS_CALCULATOR_H_

#include "ns3/lte-stats-calculator.h"
#include "ns3/nstime.h"
#include "ns3/uinteger.h"
#include <string>
#include <fstream>

namespace ns3 {

/**
 * Takes care of storing the information generated at MAC layer. Metrics saved are:
 *   - Timestamp (in seconds)
 *   - Frame index
 *   - Subframe index
 *   - C-RNTI
 *   - MCS for transport block 1
 *   - Size of transport block 1
 *   - MCS for transport block 2 (0 if not used)
 *   - Size of transport block 2 (0 if not used)
 */
class MacStatsCalculator : public LteStatsCalculator
{
public:
  /**
   * Constructor
   */
  MacStatsCalculator ();

  /**
   * Destructor
   */
  virtual ~MacStatsCalculator ();

  /**
   * Inherited from ns3::Object
   */
  static TypeId GetTypeId (void);

  /**
   * Set the name of the file where the uplink statistics will be stored.
   *
   * \param outputFilename string with the name of the file
   */
  void SetUlOutputFilename (std::string outputFilename);

  /**
   * Get the name of the file where the uplink statistics will be stored.
   */
  std::string GetUlOutputFilename (void);

  /**
   * Set the name of the file where the downlink statistics will be stored.
   *
   * @param outputFilename string with the name of the file
   */
  void SetDlOutputFilename (std::string outputFilename);

  /**
   * Get the name of the file where the downlink statistics will be stored.
   */
  std::string GetDlOutputFilename (void);

  /**
   * Notifies the stats calculator that an downlink scheduling has occurred.
   * @param cellId Cell ID of the attached Enb
   * @param imsi IMSI of the scheduled UE
   * @param frameNo Frame number
   * @param subframeNo Subframe number
   * @param rnti C-RNTI scheduled
   * @param mcsTb1 MCS for transport block 1
   * @param sizeTb1 Size of transport block 1
   * @param mcsTb2 MCS for transport block 2 (0 if not used)
   * @param sizeTb2 Size of transport block 2 (0 if not used)
   */
  void DlScheduling (uint16_t cellId, uint64_t imsi, uint32_t frameNo, uint32_t subframeNo,
                     uint16_t rnti, uint8_t mcsTb1, uint16_t sizeTb1, uint8_t mcsTb2, uint16_t sizeTb2);

  /**
   * Notifies the stats calculator that an uplink scheduling has occurred.
   * @param cellId Cell ID of the attached Enb
   * @param imsi IMSI of the scheduled UE
   * @param frameNo Frame number
   * @param subframeNo Subframe number
   * @param rnti C-RNTI scheduled
   * @param mcsTb MCS for transport block
   * @param sizeTb Size of transport block
   */
  void UlScheduling (uint16_t cellId, uint64_t imsi,uint32_t frameNo, uint32_t subframeNo,
                     uint16_t rnti, uint8_t mcs, uint16_t sizeTb);

private:

  bool m_dlFirstWrite;
  bool m_ulFirstWrite;

};

} // namespace ns3

#endif /* MAC_STATS_CALCULATOR_H_ */