rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if create_time == os.stat(path).st_mtime: | if create_time and create_time == os.stat(path).st_mtime: | def edit_doc(self, doc_entry, editor, file_format): """Edit a document. Keyword arguments: doc_entry: DocEntry of the document to edit. editor: Name of the editor to use. Should be executable from the user's working directory. file_format: Suffix of the file to download. For example, "txt", "csv", "xcl". """ import s... |
self.Put(mediasource, doc_entry.GetEditMediaLink().href) | self.Put(mediasource, doc_entry_or_title.GetEditMediaLink().href) | def edit_doc(self, doc_entry, editor, file_format): """Edit a document. Keyword arguments: doc_entry: DocEntry of the document to edit. editor: Name of the editor to use. Should be executable from the user's working directory. file_format: Suffix of the file to download. For example, "txt", "csv", "xcl". """ import s... |
except ConfigParser.ParsingError, err: | else: raise UnknownDoctype(doctype_label) except ConfigParser.NoOptionError, err: | def get_extension(doctype_label): """Return file extension based on document type and preferences file.""" try: if doctype_label == SPREADSHEET_LABEL: return googlecl.CONFIG.get(SECTION_HEADER, 'spreadsheet_format') elif doctype_label == DOCUMENT_LABEL: return googlecl.CONFIG.get(SECTION_HEADER, 'document_format') elif... |
try: return googlecl.CONFIG.get(SECTION_HEADER, 'format') except ConfigParser.ParsingError, err2: print err2 return None | except UnknownDoctype, err: if doctype_label is not None: print err try: return googlecl.CONFIG.get(SECTION_HEADER, 'format') except ConfigParser.NoOptionError, err: print err return None | def get_extension(doctype_label): """Return file extension based on document type and preferences file.""" try: if doctype_label == SPREADSHEET_LABEL: return googlecl.CONFIG.get(SECTION_HEADER, 'spreadsheet_format') elif doctype_label == DOCUMENT_LABEL: return googlecl.CONFIG.get(SECTION_HEADER, 'document_format') elif... |
except ConfigParser.NoOptionError: try: return googlecl.CONFIG.get(SECTION_HEADER, 'editor') except ConfigParser.NoOptionError: return os.getenv('EDITOR') | else: raise UnknownDoctype(doctype_label) except ConfigParser.NoOptionError, err: print err except UnknownDoctype, err: if doctype_label is not None: print err try: return googlecl.CONFIG.get(SECTION_HEADER, 'editor') except ConfigParser.NoOptionError, err: print err return os.getenv('EDITOR') | def get_editor(doctype_label): """Return editor for file based on entry type and preferences file. Editor is determined in an order of preference: 1) Try to load the editor for the specific type (spreadsheet, document, etc.) 2) If no specification, try to load the "editor" option from config file. 3) If no default edi... |
if not doc_entry: print 'No matching documents found! Creating it.' new_entry = gdata.docs.DocumentListEntry() new_entry.title = gdata.atom.Title(text=options.title or 'GoogleCL doc') category = _make_kind_category(DOCUMENT_LABEL) new_entry.category.append(category) folder_entries = client.get_folder(options.folder) fo... | if doc_entry: doc_entry_or_title = doc_entry doc_type = get_document_type(doc_entry) else: doc_entry_or_title = options.title doc_type = None print 'No matching documents found! Will create one.' folder_entry = client.get_single_entry(folder_entry_list) if not folder_entry and options.folder: print 'No matching folde... | def _run_edit(client, options, args): if not hasattr(client, 'Export'): print 'Editing documents is not supported' +\ ' for gdata-python-client < 2.0' return folder_entry_list = client.get_folder(options.folder) doc_entry = client.get_single_doc(options.title, folder_entry_list) if not doc_entry: print 'No matching doc... |
client.edit_doc(doc_entry, editor, format_ext) | if not format_ext: print 'No format defined!' print 'Define a "format" option in your config file, or pass in a format' +\ ' with --format' return client.edit_doc(doc_entry_or_title, editor, format_ext, folder_entry_or_path=folder_entry or options.folder) | def _run_edit(client, options, args): if not hasattr(client, 'Export'): print 'Editing documents is not supported' +\ ' for gdata-python-client < 2.0' return folder_entry_list = client.get_folder(options.folder) doc_entry = client.get_single_doc(options.title, folder_entry_list) if not doc_entry: print 'No matching doc... |
print googlecl.base.compile_entry_string( googlecl.base.BaseEntryToStringWrapper(entry), options.fields.split(','), delimiter=options.delimiter) | print googlecl.base.compile_entry_string(PhotoEntryToStringWrapper(entry), options.fields.split(','), delimiter=options.delimiter) | def _run_list(client, options, args): titles_list = googlecl.build_titles_list(options.title, args) entries = client.build_entry_list(user=options.owner or options.user, titles=titles_list, query=options.encoded_query, force_photos=True) for entry in entries: print googlecl.base.compile_entry_string( googlecl.base.Base... |
if len(args) == 3: file_glob = args[2] | if len(args) >= 3: | def run_once(options, args): """Run one command. Keyword arguments: options -- the options class as built and returned by optparse. args -- the arguments to google-cl, also as returned by optparse. """ service = args[0] if not is_supported_service(service): print 'Service %s is not supported' % service return task =... |
for file in glob.glob(file_glob): print 'Loading file', file photo = client.InsertPhotoSimple(album_url, file, '', file) | if len(args) == 3: insert_photos(client, album_url, glob.glob(args[2])) elif len(args) > 3: insert_photos(client, album_url, args[2:]) | def run_once(options, args): """Run one command. Keyword arguments: options -- the options class as built and returned by optparse. args -- the arguments to google-cl, also as returned by optparse. """ service = args[0] if not is_supported_service(service): print 'Service %s is not supported' % service return task =... |
print 'Could not delete event: ' + err[0]['body'] | print 'Could not delete ' + entry_type + ': ' + str(err) | def delete(self, entries, entry_type, delete_default): """Extends Delete to handle a list of entries. Keyword arguments: entries: List of entries to delete. entry_type: String describing the thing being deleted (e.g. album, post). delete_default: Whether or not the default action should be deletion. """ if delete_def... |
if converter: feed = self.GetFeed(uri, converter=converter) else: feed = self.GetFeed(uri) | try: if converter: feed = self.GetFeed(uri, converter=converter) else: feed = self.GetFeed(uri) except gdata.service.RequestError, err: print 'Failed to get entries: ' + str(err) return [] | def get_entries(self, uri, title=None, converter=None): """Get a list of entries from a feed uri. Keyword arguments: uri: URI to get the feed from. title: String to use when looking for entries to return. Will be compared to entry.title.text, using regular expressions if self.use_regex. (Default None for all entries f... |
print '==WARNING: Leaving data that matches query on server.==' print ' Increase max-results or set cap_results to False.' | warnings.warn('Leaving data that matches query on server.' + ' Increase max_results or set cap_results to False.', LeftoverData, stacklevel=2) | def get_entries(self, uri, title=None, converter=None): """Get a list of entries from a feed uri. Keyword arguments: uri: URI to get the feed from. title: String to use when looking for entries to return. Will be compared to entry.title.text, using regular expressions if self.use_regex. (Default None for all entries f... |
LOG.error('Failed to upload video: ' + err_str | LOG.error('Failed to upload video: ' + err_str) | def post_videos(self, paths, category, title=None, desc=None, tags=None, devtags=None): """Post video(s) to YouTube. Keyword arguments: paths: List of paths to videos. category: YouTube category for the video. title: Title of the video. (Default is the filename of the video). desc: Video summary (Default None). tags: ... |
return [entry for entry in all_entries if entry.title.text and re.match(title,entry.title.text)] | entries = [entry for entry in all_entries if entry.title.text and re.match(title,entry.title.text)] | def get_entries(self, uri, title=None, converter=None, desired_class=None): """Get a list of entries from a feed uri. Keyword arguments: uri: URI to get the feed from. title: String to use when looking for entries to return. Will be compared to entry.title.text, using regular expressions if self.use_regex. (Default No... |
return [entry for entry in all_entries if title == entry.title.text] | entries = [entry for entry in all_entries if title == entry.title.text] LOG.debug('Retrieved ' + str(len(all_entries)) + ' entries, returning ' + str(len(entries)) + ' of them') return entries | def get_entries(self, uri, title=None, converter=None, desired_class=None): """Get a list of entries from a feed uri. Keyword arguments: uri: URI to get the feed from. title: String to use when looking for entries to return. Will be compared to entry.title.text, using regular expressions if self.use_regex. (Default No... |
gdata.service.GDataService.Delete(self, item.GetEditLink().href) | try: gdata.service.GDataService.Delete(self, item.GetEditLink().href) except gdata.service.RequestError, e: print 'Could not delete event: ' + e[0]['body'] | def Delete(self, entries, entry_type, delete_default): """Extends Delete to handle a list of entries. Keyword arguments: entries: List of entries to delete. entry_type: String describing the thing being deleted (e.g. album, post). delete_default: Whether or not the default action should be deletion. """ if delete_def... |
request_token.verifier = raw_input('Please enter the verification code on' + ' the success page: ') | request_token.verifier = raw_input('Please enter the verification code on' ' the success page: ').strip() | def request_access(self, domain, hostid, scopes=None): """Do all the steps involved with getting an OAuth access token. Keyword arguments: domain: Domain to request access for. (Sets the hd query parameter for the authorization step). hostid: string Descriptor for the machine doing the requesting. e.g. 'username@host'... |
if extension.lower() in ['csv', 'tsv', 'tab', 'ods', 'xls']: | if hasattr(self, 'Upload'): entry = self.Upload(media, title) elif extension.lower() in ['csv', 'tsv', 'tab', 'ods', 'xls']: | def upload_docs(self, paths, title=None): """Upload a document. Keyword arguments: paths: Paths of files to upload. title: Title to give the files once uploaded. (Default None for the names of the files). |
default_hostid = getpass.getuser() + '@' + os.uname()[1] | default_hostid = getpass.getuser() + '@' + socket.gethostname() | def set_options(): """Set the most basic options in the config file.""" import googlecl import getpass # These may be useful to define at the module level, but for now, # keep them here. # REMEMBER: updating these means you need to update the CONFIG readme. default_hostid = getpass.getuser() + '@' + os.uname()[1] _you... |
editor = config_parser.get(SECTION_HEADER, 'spreadsheet_editor') | editor = config_parser.safe_get(SECTION_HEADER, 'spreadsheet_editor') | def get_editor(doctype_label, config_parser): """Return editor for file based on entry type and preferences file. Editor is determined in an order of preference: 1) Try to load the editor for the specific type (spreadsheet, document, etc.) 2) If no specification, try to load the "editor" option from config file. 3) If... |
editor = config_parser.get(SECTION_HEADER, 'document_editor') | editor = config_parser.safe_get(SECTION_HEADER, 'document_editor') | def get_editor(doctype_label, config_parser): """Return editor for file based on entry type and preferences file. Editor is determined in an order of preference: 1) Try to load the editor for the specific type (spreadsheet, document, etc.) 2) If no specification, try to load the "editor" option from config file. 3) If... |
editor = config_parser.get(SECTION_HEADER, 'pdf_editor') | editor = config_parser.safe_get(SECTION_HEADER, 'pdf_editor') | def get_editor(doctype_label, config_parser): """Return editor for file based on entry type and preferences file. Editor is determined in an order of preference: 1) Try to load the editor for the specific type (spreadsheet, document, etc.) 2) If no specification, try to load the "editor" option from config file. 3) If... |
editor = config_parser.get(SECTION_HEADER, 'presentation_editor') | editor = config_parser.safe_get(SECTION_HEADER, 'presentation_editor') | def get_editor(doctype_label, config_parser): """Return editor for file based on entry type and preferences file. Editor is determined in an order of preference: 1) Try to load the editor for the specific type (spreadsheet, document, etc.) 2) If no specification, try to load the "editor" option from config file. 3) If... |
def get_docs(self, base_path, entries, default_format='txt'): | def get_docs(self, base_path, entries, file_format=None): | def get_docs(self, base_path, entries, default_format='txt'): """Download documents. Keyword arguments: base_path: The path to download files to. This plus an entry's title plus its format-specific extension will form the complete path. entries: List of DocEntry items representing the files to download. default_format... |
default_format: The extension to use if the type of the entry is not defined or unknown. (Default 'txt'). | file_format: Suffix to give the file when downloading. For example, "txt", "csv", "xcl". Default None to let get_extension decide the extension. | def get_docs(self, base_path, entries, default_format='txt'): """Download documents. Keyword arguments: base_path: The path to download files to. This plus an entry's title plus its format-specific extension will form the complete path. entries: List of DocEntry items representing the files to download. default_format... |
file_format = get_extension(get_document_type(entry)) or default_format | if not file_format: file_format = get_extension(get_document_type(entry)) or default_format | def get_docs(self, base_path, entries, default_format='txt'): """Download documents. Keyword arguments: base_path: The path to download files to. This plus an entry's title plus its format-specific extension will form the complete path. entries: List of DocEntry items representing the files to download. default_format... |
client.get_docs(path, entries) | client.get_docs(path, entries, file_format=options.format) | def _run_get(client, options, args): if not hasattr(client, 'Export'): print 'Downloading documents is not supported for gdata-python-client < 2.0' return if not args: path = os.getcwd() else: path = args[0] if not os.path.exists(path): print 'Path ' + path + ' does not exist!' return entries = client.get_doclist(optio... |
start, junk, end = date.partition(',') | start, is_range, end = date.partition(',') | def get_start_and_end(date): """Split a string representation of a date or range of dates. Ranges should be designated via a comma. For example, '2010-06-01,2010-06-20' will set return ('2010-06-01', '2010-06-20', ...) Returns: Tuple of (start, end, utc_start, utc_end) where start is either the starting date or None,... |
entries = [entry for entry in all_entries if entry.title.text and re.match(title,entry.title.text)] | entries = [entry for entry in all_entries if entry.title.text and re.match(title,entry.title.text.decode('utf-8'))] | def get_entries(self, uri, title=None, converter=None, desired_class=None): """Get a list of entries from a feed uri. Keyword arguments: uri: URI to get the feed from. title: String to use when looking for entries to return. Will be compared to entry.title.text, using regular expressions if self.use_regex. (Default No... |
entries = [entry for entry in all_entries if title == entry.title.text] | entries = [entry for entry in all_entries if title == entry.title.text.decode('utf-8')] | def get_entries(self, uri, title=None, converter=None, desired_class=None): """Get a list of entries from a feed uri. Keyword arguments: uri: URI to get the feed from. title: String to use when looking for entries to return. Will be compared to entry.title.text, using regular expressions if self.use_regex. (Default No... |
self.developer_key = 'AI39si4d9dBo0dX7TnGyfQ68bNiKfEeO7wORCfY3HAgSStFboTgTgAi9nQwJMfMSizdGIs35W9wVGkygEw8ei3_fWGIiGSiqnQ' | def __init__(self, regex=False, tags_prompt=False, delete_prompt=True): """Constructor. Keyword arguments: regex: Indicates if regular expressions should be used for matching strings, such as video titles. (Default False) tags_prompt: Indicates if while inserting videos, instance should prompt for tags for each video.... | |
print ('Category update failed, probably because ' + category + ' is not a category.') | if e.args[0]['body'].find('invalid_value') != -1: print 'Category update failed, ' + category + ' is not a category.' else: raise | def categorize_videos(self, video_entries, category): """Change the categories of a list of videos to a single category. If the update fails with a request error, a message is printed to screen. Usually, valid category strings are the first word of the category as seen on YouTube (e.g. "Film" for "Film & Animation") ... |
def login(self, email, password): """Try to use programmatic login to log into YouTube. Keyword arguments: email: Email account to log in with. If no domain is specified, gmail.com is inferred. password: Un-encrypted password to log in with. Returns: Nothing, but sets self.logged_in to True if login was a success. "... | def is_token_valid(self): """Check that the token being used is valid.""" return util.BaseServiceCL.IsTokenValid(self, '/feeds/api/users/default') | |
description=Description(text=desc), | description=Description(text=desc or 'A video'), | def post_videos(self, paths, category, title=None, desc=None, tags=None, devtags=None): """Post video(s) to YouTube. Keyword arguments: paths: List of paths to videos. category: YouTube category for the video. title: Title of the video. (Default is the filename of the video). desc: Video summary (Default None). tags: ... |
tasks = {'post': util.Task('Post a video', callback=_run_post, | tasks = {'post': util.Task('Post a video.', callback=_run_post, | def _run_delete(client, options, args): entries = client.GetVideos(title=options.title) client.Delete(entries, 'video', util.config.get('GENERAL', 'delete_by_default')) |
'list': util.Task('List videos by user', callback=_run_list, | 'list': util.Task('List videos by user.', callback=_run_list, | def _run_delete(client, options, args): entries = client.GetVideos(title=options.title) client.Delete(entries, 'video', util.config.get('GENERAL', 'delete_by_default')) |
'tag': util.Task('Add tags to a video', callback=_run_tag, | 'tag': util.Task('Add tags to a video and/or change its category.', callback=_run_tag, | def _run_delete(client, options, args): entries = client.GetVideos(title=options.title) client.Delete(entries, 'video', util.config.get('GENERAL', 'delete_by_default')) |
'delete': util.Task('Delete videos', callback=_run_delete, | 'delete': util.Task('Delete videos.', callback=_run_delete, | def _run_delete(client, options, args): entries = client.GetVideos(title=options.title) client.Delete(entries, 'video', util.config.get('GENERAL', 'delete_by_default')) |
val = getattr(wrapped_entry, attr.replace('-','_') or missing_field_value | val = getattr(wrapped_entry, attr.replace('-','_')) or missing_field_value | def compile_entry_string(wrapped_entry, attribute_list, delimiter, missing_field_value=None, newline_replacer=' '): """Return a useful string describing a gdata.data.GDEntry. Keyword arguments: wrapped_entry: BaseEntryToStringWrapper or subclass to display. attribute_list: List of attributes to access delimiter: Strin... |
LOG.debug('valid_token evaulates to false,') | LOG.debug('Could not retrieve valid access token') | def authenticate(auth_manager, options, config, section_header): """Set a (presumably valid) OAuth token for the client to use. Args: auth_manager: Object handling the authentication process. options: Parsed command line options. config: Configuration file parser. section_header: Section header to look in for the conf... |
if not _md5_hash_file(SCRIPT_TO_INSTALL) == _md5_hash_file(SCRIPT_TO_RENAME): | if os.path.exists(SCRIPT_TO_RENAME) and\ not _md5_hash_file(SCRIPT_TO_INSTALL) == _md5_hash_file(SCRIPT_TO_RENAME): | def _md5_hash_file(path, read_size=2560): """Return a binary md5 checksum of file at path.""" import hashlib hash_function = hashlib.md5() with open(path, 'r') as my_file: data = my_file.read(read_size) while data: hash_function.update(data) data = my_file.read(read_size) return hash_function.digest() |
package = __import__('googlecl.' + service, fromlist=['SECTION_HEADER', 'TASKS']) | package = import_at_runtime('googlecl.' + service) | def import_service(service, config_file_path): """Import vital information about a service. The goal of this function is to allow expansion to other "service" classes in the future. In the same way that the v2 and v3 API python library uses a module called "client", googlecl will do the same. Keyword arguments: servi... |
service_module = __import__('googlecl.' + service + '.service', globals(), locals(), -1) | service_module = import_at_runtime('googlecl.' + service + '.service') | def import_service(service, config_file_path): """Import vital information about a service. The goal of this function is to allow expansion to other "service" classes in the future. In the same way that the v2 and v3 API python library uses a module called "client", googlecl will do the same. Keyword arguments: servi... |
service_module = __import__('googlecl.' + service + '.client', globals(), locals(), -1) | service_module = import_at_runtime('googlecl.' + service + '.client') | def import_service(service, config_file_path): """Import vital information about a service. The goal of this function is to allow expansion to other "service" classes in the future. In the same way that the v2 and v3 API python library uses a module called "client", googlecl will do the same. Keyword arguments: servi... |
service_package = __import__('googlecl.' + service, fromlist=['TASKS']) | service_package = import_at_runtime('googlecl.' + service) | def setup_parser(loading_usage): """Set up the parser. Returns: optparse.OptionParser with options configured. """ available_services = '[' + '|'.join(AVAILABLE_SERVICES) + ']' # NOTE: Usage string formatted to work with help2man. After changing it, # please run: # 'help2man -N -n "command-line access to (some) Goog... |
def upload_docs(self, paths, title=None): | def upload_docs(self, paths, title=None, folder=None): | def upload_docs(self, paths, title=None): """Upload a document. Keyword arguments: paths: Paths of files to upload. title: Title to give the files once uploaded. (Default None for the names of the files). |
entry = self.Upload(media, title) | if folder_entry: entry = self.Upload(media, title, folder_or_uri=folder_entry) else: entry = self.Upload(media, title) | def upload_docs(self, paths, title=None): """Upload a document. Keyword arguments: paths: Paths of files to upload. title: Title to give the files once uploaded. (Default None for the names of the files). |
client.upload_docs(args, options.title) | client.upload_docs(args, title=options.title, folder=options.folder) | def _run_upload(client, options, args): if not args: print 'Need to tell me what to upload!' return client.upload_docs(args, options.title) |
return [entry for entry in all_entries if entry.title.text and re.match(title,entry.title.text)] | try: return [entry for entry in all_entries if entry.title.text and re.match(title,entry.title.text)] except re.error, err: LOG.error('Regular expression error: ' + str(err) + '!') LOG.debug('regex provided: ' + title) return [] | def get_entries(self, uri, title=None, converter=None): """Get a list of entries from a feed uri. Keyword arguments: uri: URI to get the feed from. title: String to use when looking for entries to return. Will be compared to entry.title.text, using regular expressions if self.use_regex. (Default None for all entries f... |
entries.append(entryDict) | if doFilter: entryDict = self.filterEntry(entryDict) if entryDict: entries.append(entryDict) | def build(self): import codecs |
class StrokeOrderBuilder(CSVFileLoader): | class NarrowBuildCSVFileLoader(CSVFileLoader): """ A CSVFileLoader that ignores entries for Unicode characters outside the BMP. """ @classmethod def getDefaultOptions(cls): options = super(NarrowBuildCSVFileLoader, cls).getDefaultOptions() options.update({'wideBuild': True}) return options @classmethod def getOptionM... | def build(self): import codecs |
class CharacterDecompositionBuilder(CSVFileLoader): | class CharacterDecompositionBuilder(NarrowBuildCSVFileLoader): | def build(self): import codecs |
class LocaleCharacterGlyphBuilder(CSVFileLoader): | def filterEntry(self, entryDict): entryDict = NarrowBuildCSVFileLoader.filterEntry(self, entryDict) if entryDict and 'Decomposition' in entryDict: decompositionChars = getCharacterList(entryDict['Decomposition']) for i in range(len(decompositionChars)): if decompositionChars[i] > u'\U00010000': decompositionChars[... | def build(self): import codecs |
for url in self._findAttachableDatabases(attach): | searchPaths = self.engine.name == 'sqlite' for url in self._findAttachableDatabases(attach, searchPaths): | def __init__(self, configuration): """ Constructs the DatabaseConnector object and connects to the database specified by the options given in databaseSettings. |
def _findAttachableDatabases(self, attachList): | def _findAttachableDatabases(self, attachList, searchPaths=False): | def _findAttachableDatabases(self, attachList): """ Returns URLs for databases that can be attached to a given database. """ attachable = [] for name in attachList: if '://' in name: # database url attachable.append(name) elif os.path.isabs(name): # path if not os.path.exists(name): continue |
attach.extend(getSearchPaths(name)) attachable.extend(self._findAttachableDatabases(attach)) | if searchPaths: attach.extend(getSearchPaths(name)) attachable.extend(self._findAttachableDatabases(attach, searchPaths)) | def _findAttachableDatabases(self, attachList): """ Returns URLs for databases that can be attached to a given database. """ attachable = [] for name in attachList: if '://' in name: # database url attachable.append(name) elif os.path.isabs(name): # path if not os.path.exists(name): continue |
raise ValueError("Invalid database reference '%s'" % name) | raise ValueError(("Invalid database reference '%s'." " Check your 'attach' settings!") % name) | def _findAttachableDatabases(self, attachList): """ Returns URLs for databases that can be attached to a given database. """ attachable = [] for name in attachList: if '://' in name: # database url attachable.append(name) elif os.path.isabs(name): # path if not os.path.exists(name): continue |
raise ValueError("Incompatible engines") | raise ValueError( ("Unable to attach database '%s': Incompatible engines." " Check your 'attach' settings!") % databaseUrl) | def attachDatabase(self, databaseUrl): """ Attaches a database to the main database. |
@classmethod def listBuildGroups(cls): cls.printFormattedLine("Generic groups:\n" \ | def listBuildGroups(self): self.printFormattedLine("Generic groups:\n" \ | def buildParser(self): usage = "%prog [options] [build | list]" description = self.DESCRIPTION version = """%%prog %s |
cls.printFormattedLine("Standard groups:") groupList = cls.BUILD_GROUPS.keys() groupList = [group for group in groupList if (group != 'fullDictionaries' and group not in cls.BUILD_GROUPS['fullDictionaries'])] | self.printFormattedLine("Standard groups:") groupList = self.BUILD_GROUPS.keys() | def listBuildGroups(cls): cls.printFormattedLine("Generic groups:\n" \ + "all, for all tables understood by the build script\n" \ + "allAvail, for all data available to the build script\n") cls.printFormattedLine("Standard groups:") groupList = cls.BUILD_GROUPS.keys() # TODO deprecated groupList = [group for group in g... |
for member in cls.BUILD_GROUPS[groupName]: if cls.BUILD_GROUPS.has_key(member): | for member in self.BUILD_GROUPS[groupName]: if member in deprecated: continue if self.BUILD_GROUPS.has_key(member): | def listBuildGroups(cls): cls.printFormattedLine("Generic groups:\n" \ + "all, for all tables understood by the build script\n" \ + "allAvail, for all data available to the build script\n") cls.printFormattedLine("Standard groups:") groupList = cls.BUILD_GROUPS.keys() # TODO deprecated groupList = [group for group in g... |
cls.printFormattedLine(groupName + ": " + ', '.join(content), | self.printFormattedLine(groupName + ": " + ', '.join(content), | def listBuildGroups(cls): cls.printFormattedLine("Generic groups:\n" \ + "all, for all tables understood by the build script\n" \ + "allAvail, for all data available to the build script\n") cls.printFormattedLine("Standard groups:") groupList = cls.BUILD_GROUPS.keys() # TODO deprecated groupList = [group for group in g... |
cls.printFormattedLine("\nBoth group names and table names can be " \ | self.printFormattedLine("\nBoth group names and table names can be " | def listBuildGroups(cls): cls.printFormattedLine("Generic groups:\n" \ + "all, for all tables understood by the build script\n" \ + "allAvail, for all data available to the build script\n") cls.printFormattedLine("Standard groups:") groupList = cls.BUILD_GROUPS.keys() # TODO deprecated groupList = [group for group in g... |
_, default_encoding = locale.getdefaultlocale() | output_encoding = sys.stdout.encoding or locale.getpreferredencoding() \ or 'ascii' | def run(self): charCount = 0 charFullCount = 0 |
print ''.join(missingSingleCharacters).encode(default_encoding) | print ''.join(missingSingleCharacters).encode(output_encoding, 'replace') | def run(self): charCount = 0 charFullCount = 0 |
.encode(default_encoding) | .encode(output_encoding, 'replace') | def run(self): charCount = 0 charFullCount = 0 |
for builder in build.DatabaseBuilder.getTableBuilderClasses(): | for builder in build.DatabaseBuilder.getTableBuilderClasses( resolveConflicts=False): | def getBuilderConfigSettings(cls): """ Gets the builder settings from the section C{Builder} from cjklib.conf. |
in parentheses and allows for multiple entries in one record separated by punctuation marks. | in parentheses. """ def getMatchFunction(self, searchStr): regex = re.compile('/' + '(\s+|\([^\)]+\))*' + re.escape(searchStr) + '(\s+|\([^\)]+\))*' + '/') return lambda translation: regex.search(translation) is not None class HanDeDictTranslationSearchStrategy(ExactTranslationSearchStrategy): """ HanDeDict trans... | def getMatchFunction(self, searchStr): """ Gets a function that returns C{True} if the entry's translation matches the search string. |
regex = re.compile('/((\([^\)]+\)|[^\(])+[\,\;\.\?\!])?' + '(\s+|\([^\)]+\))*' + re.escape(searchStr) + '(\s+|\([^\)]+\))*' + '[/\,\;\.\?\!]') return lambda translation: regex.search(translation) is not None class HanDeDictTranslationSearchStrategy(SimpleTranslationSearchStrategy): """ HanDeDict translation based se... | def getMatchFunction(self, searchStr): # start with a slash '/', make sure any opening parenthesis is # closed, end any other entry with a punctuation mark, and match # search string. Finish with other content in parantheses and # a slash or punctuation mark regex = re.compile('/((\([^\)]+\)|[^\(])+[\,\;\.\?\!])?... | |
class CFDICT(CEDICT): | class CFDICT(HanDeDict): | def __init__(self, entryFactory=None, readingFormatStrategy=None, translationFormatStrategy=None, readingSearchStrategy=None, translationSearchStrategy=None, databaseUrl=None, dbConnectInst=None, headword='b'): if not translationSearchStrategy: translationSearchStrategy = HanDeDictTranslationSearchStrategy() super(HanD... |
ZVARIANT_REGEX = re.compile(ur"\s*U\+([0-9A-F]+)(?:\:\S+)?\s*$") | def generator(self): """Provides one entry per radical and character.""" for character, radicalStroke in self.rsEntries: matchObj = self.RADICAL_REGEX.match(radicalStroke) if matchObj: radical = matchObj.group(1) yield(character, radical) elif not self.quiet: warn("unable to read radical information of character '" \ +... | |
'Z': (ZVARIANT_REGEX, ZVARIANT_REGEX)} | 'Z': (SEMANTIC_REGEX, SEMANTIC_FIND_REGEX)} | def generator(self): """Provides one entry per radical and character.""" for character, radicalStroke in self.rsEntries: matchObj = self.RADICAL_REGEX.match(radicalStroke) if matchObj: radical = matchObj.group(1) yield(character, radical) elif not self.quiet: warn("unable to read radical information of character '" \ +... |
attach = config['attach'] if isinstance(attach, basestring): attach = attach.split('\n') options['attach'] = attach | options['attach'] = config['attach'] | def getDefaultOptions(cls): """ Gets default options that always overwrite those specified in the build module. Boolean options of the L{DatabaseBuilder} can not be changed here as they are hardcoded in the given command line options. """ options = {} # dataPath options['dataPath'] = ['.', getDataPath()] # prefer optio... |
configuration['attach'] = options.pop('databaseUrl', configuration.get('attach', [])) db = DatabaseConnector(configuration) | configuration['attach'] = [attach for attach in options.pop('attach', configuration.get('attach', [])) if attach] try: db = DatabaseConnector(configuration) except ValueError, e: print >> sys.stderr, "Error: %s" % e return False | def runBuild(self, buildGroupList, options): if not buildGroupList: return buildGroupList = set(buildGroupList) # by default fail if a table couldn't be built options['noFail'] = False if 'all' in buildGroupList or 'allAvail' in buildGroupList: if 'allAvail' in buildGroupList: if len(buildGroupList) == 1: # don't fail ... |
regexString = '(?ui)^' + regexString else: regexString = '(?u)^' + regexString | regexString = '(?ui)' + regexString else: regexString = '(?u)' + regexString | def _compileRegex(self, regexString): if self._caseInsensitive: regexString = '(?ui)^' + regexString else: regexString = '(?u)^' + regexString return re.compile(regexString) |
class PlainReadingFactory(object): """Default reading formatting factory, doing nothing.""" | class PlainReadingStrategy(object): """Default reading formatting strategy, doing nothing.""" | def getEntries(self, results): for row in results: if len(row) != len(self.columnNames): raise ValueError("Incompatible element counts %d for result: %d" % (len(self.columnNames), len(row))) |
class ReadingConversionFactory(object): | class ReadingConversionStrategy(object): | def getReading(self, plainReading): return plainReading |
def __init__(self, toReading, targetOptions=None): | def __init__(self, toReading=None, targetOptions=None): | def __init__(self, toReading, targetOptions=None): self.toReading = toReading if targetOptions: self.targetOptions = targetOptions else: self.targetOptions = {} |
raise ValueError('Factory not initialized properly.' ' Probably incompatible to dictionary.') | raise ValueError('Strategy instance not initialized properly.' ' Probably incompatible to dictionary class.') toReading = self.toReading or self.fromReading | def getReading(self, plainReading): if not hasattr(self, 'fromReading'): raise ValueError('Factory not initialized properly.' ' Probably incompatible to dictionary.') |
self.toReading, sourceOptions=self.sourceOptions, | toReading, sourceOptions=self.sourceOptions, | def getReading(self, plainReading): if not hasattr(self, 'fromReading'): raise ValueError('Factory not initialized properly.' ' Probably incompatible to dictionary.') |
class StandardPinyinReadingFactory(ReadingConversionFactory): """Converts the entries' reading string to standard I{Pinyin}.""" def __init__(self): super(StandardPinyinReadingFactory, self).__init__('Pinyin') | def getReading(self, plainReading): if not hasattr(self, 'fromReading'): raise ValueError('Factory not initialized properly.' ' Probably incompatible to dictionary.') | |
class PlainTranslationFactory(object): """Default translation formatting factory, doing nothing.""" | class PlainTranslationStrategy(object): """Default translation formatting strategy, doing nothing.""" | def __init__(self): super(StandardPinyinReadingFactory, self).__init__('Pinyin') |
def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): | PROVIDES = None """Name of dictionary that is provided by this class.""" def __init__(self, entryFactory=None, readingFormatStrategy=None, translationFormatStrategy=None, translationSearchStrategy=None, databaseUrl=None, dbConnectInst=None): | def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): """ Initialises the BaseDictionary instance. |
@type readingFormatFactory: instance @param readingFormatFactory: reading formatting factory instance @type translationFormatFactory: instance @param translationFormatFactory: translation formatting factory instance | @type readingFormatStrategy: instance @param readingFormatStrategy: reading formatting strategy instance @type translationFormatStrategy: instance @param translationFormatStrategy: translation formatting strategy instance @type translationSearchStrategy: instance @param translationSearchStrategy: translation search str... | def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): """ Initialises the BaseDictionary instance. |
if readingFormatFactory: self.readingFormatFactory = readingFormatFactory else: self.readingFormatFactory = PlainReadingFactory() """Factory for formatting reading.""" if hasattr(self.readingFormatFactory, 'setReadingFactory'): self.readingFormatFactory.setReadingFactory(self._readingFactory) if translationFormatFacto... | if readingFormatStrategy: self.readingFormatStrategy = readingFormatStrategy else: self.readingFormatStrategy = PlainReadingStrategy() """Strategy for formatting readings.""" if hasattr(self.readingFormatStrategy, 'setReadingFactory'): self.readingFormatStrategy.setReadingFactory(self._readingFactory) if translationFo... | def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): """ Initialises the BaseDictionary instance. |
DICTIONARY_TABLE = 'EDICT' | DICTIONARY_TABLE = None | def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): """ Initialises the BaseDictionary instance. |
def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): super(EDICT, self).__init__(entryFactory, readingFormatFactory, translationFormatFactory, databaseUrl, dbConnectInst) | def __init__(self, entryFactory=None, readingFormatStrategy=None, translationFormatStrategy=None, translationSearchStrategy=None, databaseUrl=None, dbConnectInst=None): super(EDICTStyleDictionary, self).__init__(entryFactory, readingFormatStrategy, translationFormatStrategy, translationSearchStrategy, databaseUrl, dbCo... | def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): super(EDICT, self).__init__(entryFactory, readingFormatFactory, translationFormatFactory, databaseUrl, dbConnectInst) |
if not self.db.has_table(self.DICTIONARY_TABLE): | if not self.available(self.db): | def __init__(self, entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): super(EDICT, self).__init__(entryFactory, readingFormatFactory, translationFormatFactory, databaseUrl, dbConnectInst) |
def _search(self, whereClause, orderBy, limit): | @classmethod def available(cls, dbConnectInst): return (cls.DICTIONARY_TABLE and dbConnectInst.has_table(cls.DICTIONARY_TABLE)) def _search(self, whereClause, orderBy, limit, filterResult=None): | def _search(self, whereClause, orderBy, limit): dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] |
results = [(headword, self.readingFormatFactory.getReading(reading), | results = [(headword, self.readingFormatStrategy.getReading(reading), | def _search(self, whereClause, orderBy, limit): dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] |
self.translationFormatFactory.getTranslation(translation)) | self.translationFormatStrategy.getTranslation(translation)) | def _search(self, whereClause, orderBy, limit): dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] |
class CEDICT(EDICT): | def getForTranslation(self, translationStr, limit=None, orderBy=None): def filterResult(headword, reading, translation): return self.translationSearchStrategy.isMatch(translationStr, translation) return self._search( self.translationSearchStrategy.getWhereClause(translationStr), limit, orderBy, filterResult) def getF... | def getForReading(self, readingStr, limit=None, orderBy=None): dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] |
CEDICT dictionary access. The CEDICT dictionary class extends L{EDICT} by: - support for reading conversion, understanding reading format factories L{ReadingConversionFactory} and more specifically L{StandardPinyinReadingFactory}, - flexible searching for reading strings, - simplified and traditional headword for each... | EDICT dictionary access with enhanced reading support. The EDICTStyleEnhancedReadingDictionary dictionary class extends L{EDICT} by: - support for reading conversion, understanding reading format strategy L{ReadingConversionStrategy}, - flexible searching for reading strings. """ READING = None """Reading.""" READING_... | def getForReading(self, readingStr, limit=None, orderBy=None): dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] |
DICTIONARY_TABLE = 'CEDICT' COLUMNS = ['HeadwordSimplified', 'HeadwordTraditional', 'Reading', 'Translation'] def __init__(self, headword='s', entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, | def __init__(self, entryFactory=None, readingFormatStrategy=None, translationFormatStrategy=None, translationSearchStrategy=None, | def getForReading(self, readingStr, limit=None, orderBy=None): dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] |
if not readingFormatFactory: readingFormatFactory = StandardPinyinReadingFactory() super(CEDICT, self).__init__(entryFactory, readingFormatFactory, translationFormatFactory, databaseUrl, dbConnectInst) if hasattr(self.readingFormatFactory, 'setReadingOptions'): self.readingFormatFactory.setReadingOptions('Pinyin', | if not readingFormatStrategy: readingFormatStrategy = ReadingConversionStrategy() super(EDICTStyleEnhancedReadingDictionary, self).__init__(entryFactory, readingFormatStrategy, translationFormatStrategy, translationSearchStrategy, databaseUrl, dbConnectInst) if hasattr(self.readingFormatStrategy, 'setReadingOptions'):... | def __init__(self, headword='s', entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): if not readingFormatFactory: readingFormatFactory = StandardPinyinReadingFactory() super(CEDICT, self).__init__(entryFactory, readingFormatFactory, translationFormatFactor... |
if headword in ('s', 't'): self.headword = headword else: raise ValueError("Invalid type for headword '%s'." % headword \ + " Needs to be either 's' (simplified) or 't' (traditional)") def _search(self, whereClause, orderBy, limit): dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] if orderBy is None: orderBy =... | def _getReadingStrings(self, readingStr, fromReading, **options): | def __init__(self, headword='s', entryFactory=None, readingFormatFactory=None, translationFormatFactory=None, databaseUrl=None, dbConnectInst=None): if not readingFormatFactory: readingFormatFactory = StandardPinyinReadingFactory() super(CEDICT, self).__init__(entryFactory, readingFormatFactory, translationFormatFactor... |
fromReading, 'Pinyin', sourceOptions=options, | fromReading, self.READING, sourceOptions=options, | def _getReadingClause(self, readingStr, fromReading, **options): decompositions = self._readingFactory.getDecompositions(readingStr, fromReading, **options) # convert all possible decompositions decompEntities = [] e = None for entities in decompositions: try: decompEntities.append( self._readingFactory.convertEntities... |
dictionaryTable = self.db.tables[self.DICTIONARY_TABLE] clauses = [] | strings = [] | def _getReadingClause(self, readingStr, fromReading, **options): decompositions = self._readingFactory.getDecompositions(readingStr, fromReading, **options) # convert all possible decompositions decompEntities = [] e = None for entities in decompositions: try: decompEntities.append( self._readingFactory.convertEntities... |
clauses.append(dictionaryTable.c.Reading == ' '.join( | strings.append(' '.join( | def _getReadingClause(self, readingStr, fromReading, **options): decompositions = self._readingFactory.getDecompositions(readingStr, fromReading, **options) # convert all possible decompositions decompEntities = [] e = None for entities in decompositions: try: decompEntities.append( self._readingFactory.convertEntities... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.