function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def backup_ignore_patterns(self, value): if value is None: self._backup_ignore_patterns = None elif not isinstance(value, list): raise ValueError("Backup pattern must be in list format") else: self._backup_ignore_patterns = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def check_interval(self): return (self._check_interval_enabled, self._check_interval_months, self._check_interval_days, self._check_interval_hours, self._check_interval_minutes)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def current_version(self): return self._current_version
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def current_version(self, tuple_values): if tuple_values is None: self._current_version = None return elif type(tuple_values) is not tuple: try: tuple(tuple_values) except: raise ValueError( "current_version must be a tuple of integers") for i in tuple_values: if type(i) is not int: raise ValueError( "current_version must be a tuple of integers") self._current_version = tuple(tuple_values)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def engine(self): return self._engine.name
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def engine(self, value): engine = value.lower() if engine == "github": self._engine = GithubEngine() elif engine == "gitlab": self._engine = GitlabEngine() elif engine == "bitbucket": self._engine = BitbucketEngine() else: raise ValueError("Invalid engine selection")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def error(self): return self._error
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def error_msg(self): return self._error_msg
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def fake_install(self): return self._fake_install
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def fake_install(self, value): if not isinstance(value, bool): raise ValueError("fake_install must be a boolean value") self._fake_install = bool(value)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def include_branch_auto_check(self): return self._include_branch_auto_check
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def include_branch_auto_check(self, value): try: self._include_branch_auto_check = bool(value) except: raise ValueError("include_branch_autocheck must be a boolean")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def include_branch_list(self): return self._include_branch_list
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def include_branch_list(self, value): try: if value is None: self._include_branch_list = ['master'] elif not isinstance(value, list) or len(value) == 0: raise ValueError( "include_branch_list should be a list of valid branches") else: self._include_branch_list = value except: raise ValueError( "include_branch_list should be a list of valid branches")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def include_branches(self): return self._include_branches
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def include_branches(self, value): try: self._include_branches = bool(value) except: raise ValueError("include_branches must be a boolean value")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def json(self): if len(self._json) == 0: self.set_updater_json() return self._json
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def latest_release(self): if self._latest_release is None: return None return self._latest_release
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def manual_only(self): return self._manual_only
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def manual_only(self, value): try: self._manual_only = bool(value) except: raise ValueError("manual_only must be a boolean value")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def overwrite_patterns(self): return self._overwrite_patterns
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def overwrite_patterns(self, value): if value is None: self._overwrite_patterns = ["*.py", "*.pyc"] elif not isinstance(value, list): raise ValueError("overwrite_patterns needs to be in a list format") else: self._overwrite_patterns = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def private_token(self): return self._engine.token
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def private_token(self, value): if value is None: self._engine.token = None else: self._engine.token = str(value)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def remove_pre_update_patterns(self): return self._remove_pre_update_patterns
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def remove_pre_update_patterns(self, value): if value is None: self._remove_pre_update_patterns = list() elif not isinstance(value, list): raise ValueError( "remove_pre_update_patterns needs to be in a list format") else: self._remove_pre_update_patterns = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def repo(self): return self._repo
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def repo(self, value): try: self._repo = str(value) except: raise ValueError("repo must be a string value")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def select_link(self): return self._select_link
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def select_link(self, value): # ensure it is a function assignment, with signature: # input self, tag; returns link name if not hasattr(value, "__call__"): raise ValueError("select_link must be a function") self._select_link = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def stage_path(self): return self._updater_path
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def stage_path(self, value): if value is None: self.print_verbose("Aborting assigning stage_path, it's null") return elif value is not None and not os.path.exists(value): try: os.makedirs(value) except: self.print_verbose("Error trying to staging path") self.print_trace() return self._updater_path = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def subfolder_path(self): return self._subfolder_path
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def subfolder_path(self, value): self._subfolder_path = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def tags(self): if len(self._tags) == 0: return list() tag_names = list() for tag in self._tags: tag_names.append(tag["name"]) return tag_names
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def tag_latest(self): if self._tag_latest is None: return None return self._tag_latest["name"]
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def update_link(self): return self._update_link
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def update_ready(self): return self._update_ready
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def update_version(self): return self._update_version
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def use_releases(self): return self._use_releases
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def use_releases(self, value): try: self._use_releases = bool(value) except: raise ValueError("use_releases must be a boolean value")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def user(self): return self._user
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def user(self, value): try: self._user = str(value) except: raise ValueError("User must be a string value")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def verbose(self): return self._verbose
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def verbose(self, value): try: self._verbose = bool(value) self.print_verbose("Verbose is enabled") except: raise ValueError("Verbose must be a boolean value")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def use_print_traces(self): return self._use_print_traces
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def use_print_traces(self, value): try: self._use_print_traces = bool(value) except: raise ValueError("use_print_traces must be a boolean value")
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def version_max_update(self): return self._version_max_update
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def version_max_update(self, value): if value is None: self._version_max_update = None return if not isinstance(value, tuple): raise ValueError("Version maximum must be a tuple") for subvalue in value: if type(subvalue) is not int: raise ValueError("Version elements must be integers") self._version_max_update = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def version_min_update(self): return self._version_min_update
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def version_min_update(self, value): if value is None: self._version_min_update = None return if not isinstance(value, tuple): raise ValueError("Version minimum must be a tuple") for subvalue in value: if type(subvalue) != int: raise ValueError("Version elements must be integers") self._version_min_update = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def website(self): return self._website
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def website(self, value): if not self.check_is_url(value): raise ValueError("Not a valid URL: " + value) self._website = value
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def check_is_url(url): if not ("http://" in url or "https://" in url): return False if "." not in url: return False return True
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def set_check_interval(self, enabled=False, months=0, days=14, hours=0, minutes=0): """Set the time interval between automated checks, and if enabled. Has enabled = False as default to not check against frequency, if enabled, default is 2 weeks. """ if type(enabled) is not bool: raise ValueError("Enable must be a boolean value") if type(months) is not int: raise ValueError("Months must be an integer value") if type(days) is not int: raise ValueError("Days must be an integer value") if type(hours) is not int: raise ValueError("Hours must be an integer value") if type(minutes) is not int: raise ValueError("Minutes must be an integer value") if not enabled: self._check_interval_enabled = False else: self._check_interval_enabled = True self._check_interval_months = months self._check_interval_days = days self._check_interval_hours = hours self._check_interval_minutes = minutes
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def __str__(self): return "Updater, with user: {a}, repository: {b}, url: {c}".format( a=self._user, b=self._repo, c=self.form_repo_url())
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def form_repo_url(self): return self._engine.form_repo_url(self)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def form_branch_url(self, branch): return self._engine.form_branch_url(branch, self)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def get_raw(self, url): """All API calls to base url.""" request = urllib.request.Request(url) try: context = ssl._create_unverified_context() except: # Some blender packaged python versions don't have this, largely # useful for local network setups otherwise minimal impact. context = None # Setup private request headers if appropriate. if self._engine.token is not None: if self._engine.name == "gitlab": request.add_header('PRIVATE-TOKEN', self._engine.token) else: self.print_verbose("Tokens not setup for engine yet") # Always set user agent. request.add_header( 'User-Agent', "Python/" + str(platform.python_version())) # Run the request. try: if context: result = urllib.request.urlopen(request, context=context) else: result = urllib.request.urlopen(request) except urllib.error.HTTPError as e: if str(e.code) == "403": self._error = "HTTP error (access denied)" self._error_msg = str(e.code) + " - server error response" print(self._error, self._error_msg) else: self._error = "HTTP error" self._error_msg = str(e.code) print(self._error, self._error_msg) self.print_trace() self._update_ready = None except urllib.error.URLError as e: reason = str(e.reason) if "TLSV1_ALERT" in reason or "SSL" in reason.upper(): self._error = "Connection rejected, download manually" self._error_msg = reason print(self._error, self._error_msg) else: self._error = "URL error, check internet connection" self._error_msg = reason print(self._error, self._error_msg) self.print_trace() self._update_ready = None return None else: result_string = result.read() result.close() return result_string.decode()
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def stage_repository(self, url): """Create a working directory and download the new files""" local = os.path.join(self._updater_path, "update_staging") error = None # Make/clear the staging folder, to ensure the folder is always clean. self.print_verbose( "Preparing staging folder for download:\n" + str(local)) if os.path.isdir(local): try: shutil.rmtree(local) os.makedirs(local) except: error = "failed to remove existing staging directory" self.print_trace() else: try: os.makedirs(local) except: error = "failed to create staging directory" self.print_trace() if error is not None: self.print_verbose("Error: Aborting update, " + error) self._error = "Update aborted, staging path error" self._error_msg = "Error: {}".format(error) return False if self._backup_current: self.create_backup() self.print_verbose("Now retrieving the new source zip") self._source_zip = os.path.join(local, "source.zip") self.print_verbose("Starting download update zip") try: request = urllib.request.Request(url) context = ssl._create_unverified_context() # Setup private token if appropriate. if self._engine.token is not None: if self._engine.name == "gitlab": request.add_header('PRIVATE-TOKEN', self._engine.token) else: self.print_verbose( "Tokens not setup for selected engine yet") # Always set user agent request.add_header( 'User-Agent', "Python/" + str(platform.python_version())) self.url_retrieve(urllib.request.urlopen(request, context=context), self._source_zip) # Add additional checks on file size being non-zero. self.print_verbose("Successfully downloaded update zip") return True except Exception as e: self._error = "Error retrieving download, bad link?" self._error_msg = "Error: {}".format(e) print("Error retrieving download, bad link?") print("Error: {}".format(e)) self.print_trace() return False
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def restore_backup(self): """Restore the last backed up addon version, user initiated only""" self.print_verbose("Restoring backup, backing up current addon folder") backuploc = os.path.join(self._updater_path, "backup") tempdest = os.path.join( self._addon_root, os.pardir, self._addon + "_updater_backup_temp") tempdest = os.path.abspath(tempdest) # Move instead contents back in place, instead of copy. shutil.move(backuploc, tempdest) shutil.rmtree(self._addon_root) os.rename(tempdest, self._addon_root) self._json["backup_date"] = "" self._json["just_restored"] = True self._json["just_updated"] = True self.save_updater_json() self.reload_addon()
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def deep_merge_directory(self, base, merger, clean=False): """Merge folder 'merger' into 'base' without deleting existing""" if not os.path.exists(base): self.print_verbose("Base path does not exist:" + str(base)) return -1 elif not os.path.exists(merger): self.print_verbose("Merger path does not exist") return -1 # Path to be aware of and not overwrite/remove/etc. staging_path = os.path.join(self._updater_path, "update_staging") # If clean install is enabled, clear existing files ahead of time # note: will not delete the update.json, update folder, staging, or # staging but will delete all other folders/files in addon directory. error = None if clean: try: # Implement clearing of all folders/files, except the updater # folder and updater json. # Careful, this deletes entire subdirectories recursively... # Make sure that base is not a high level shared folder, but # is dedicated just to the addon itself. self.print_verbose( "clean=True, clearing addon folder to fresh install state") # Remove root files and folders (except update folder). files = [f for f in os.listdir(base) if os.path.isfile(os.path.join(base, f))] folders = [f for f in os.listdir(base) if os.path.isdir(os.path.join(base, f))] for f in files: os.remove(os.path.join(base, f)) self.print_verbose( "Clean removing file {}".format(os.path.join(base, f))) for f in folders: if os.path.join(base, f) is self._updater_path: continue shutil.rmtree(os.path.join(base, f)) self.print_verbose( "Clean removing folder and contents {}".format( os.path.join(base, f))) except Exception as err: error = "failed to create clean existing addon folder" print(error, str(err)) self.print_trace() # Walk through the base addon folder for rules on pre-removing # but avoid removing/altering backup and updater file. for path, dirs, files in os.walk(base): # Prune ie skip updater folder. dirs[:] = [d for d in dirs if os.path.join(path, d) not in [self._updater_path]] for file in files: for pattern in self.remove_pre_update_patterns: if fnmatch.filter([file], pattern): try: fl = os.path.join(path, file) os.remove(fl) self.print_verbose("Pre-removed file " + file) except OSError: print("Failed to pre-remove " + file) self.print_trace() # Walk through the temp addon sub folder for replacements # this implements the overwrite rules, which apply after # the above pre-removal rules. This also performs the # actual file copying/replacements. for path, dirs, files in os.walk(merger): # Verify structure works to prune updater sub folder overwriting. dirs[:] = [d for d in dirs if os.path.join(path, d) not in [self._updater_path]] rel_path = os.path.relpath(path, merger) dest_path = os.path.join(base, rel_path) if not os.path.exists(dest_path): os.makedirs(dest_path) for file in files: # Bring in additional logic around copying/replacing. # Blender default: overwrite .py's, don't overwrite the rest. dest_file = os.path.join(dest_path, file) srcFile = os.path.join(path, file) # Decide to replace if file already exists, and copy new over. if os.path.isfile(dest_file): # Otherwise, check each file for overwrite pattern match. replaced = False for pattern in self._overwrite_patterns: if fnmatch.filter([file], pattern): replaced = True break if replaced: os.remove(dest_file) os.rename(srcFile, dest_file) self.print_verbose( "Overwrote file " + os.path.basename(dest_file)) else: self.print_verbose( "Pattern not matched to {}, not overwritten".format( os.path.basename(dest_file))) else: # File did not previously exist, simply move it over. os.rename(srcFile, dest_file) self.print_verbose( "New file " + os.path.basename(dest_file)) # now remove the temp staging folder and downloaded zip try: shutil.rmtree(staging_path) except: error = ("Error: Failed to remove existing staging directory, " "consider manually removing ") + staging_path self.print_verbose(error) self.print_trace()
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def clear_state(self): self._update_ready = None self._update_link = None self._update_version = None self._source_zip = None self._error = None self._error_msg = None
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def version_tuple_from_text(self, text): """Convert text into a tuple of numbers (int). Should go through string and remove all non-integers, and for any given break split into a different section. """ if text is None: return () segments = list() tmp = '' for char in str(text): if not char.isdigit(): if len(tmp) > 0: segments.append(int(tmp)) tmp = '' else: tmp += char if len(tmp) > 0: segments.append(int(tmp)) if len(segments) == 0: self.print_verbose("No version strings found text: " + str(text)) if not self._include_branches: return () else: return (text) return tuple(segments)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def check_for_update_now(self, callback=None): self._error = None self._error_msg = None self.print_verbose( "Check update pressed, first getting current status") if self._async_checking: self.print_verbose("Skipping async check, already started") return # already running the bg thread elif self._update_ready is None: self.start_async_check_update(True, callback) else: self._update_ready = None self.start_async_check_update(True, callback)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def set_tag(self, name): """Assign the tag name and url to update to""" tg = None for tag in self._tags: if name == tag["name"]: tg = tag break if tg: new_version = self.version_tuple_from_text(self.tag_latest) self._update_version = new_version self._update_link = self.select_link(self, tg) elif self._include_branches and name in self._include_branch_list: # scenario if reverting to a specific branch name instead of tag tg = name link = self.form_branch_url(tg) self._update_version = name # this will break things self._update_link = link if not tg: raise ValueError("Version tag not found: " + name)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def past_interval_timestamp(self): if not self._check_interval_enabled: return True # ie this exact feature is disabled if "last_check" not in self._json or self._json["last_check"] == "": return True now = datetime.now() last_check = datetime.strptime( self._json["last_check"], "%Y-%m-%d %H:%M:%S.%f") offset = timedelta( days=self._check_interval_days + 30 * self._check_interval_months, hours=self._check_interval_hours, minutes=self._check_interval_minutes) delta = (now - offset) - last_check if delta.total_seconds() > 0: self.print_verbose("Time to check for updates!") return True self.print_verbose("Determined it's not yet time to check for updates") return False
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def set_updater_json(self): """Load or initialize JSON dictionary data for updater state""" if self._updater_path is None: raise ValueError("updater_path is not defined") elif not os.path.isdir(self._updater_path): os.makedirs(self._updater_path) jpath = self.get_json_path() if os.path.isfile(jpath): with open(jpath) as data_file: self._json = json.load(data_file) self.print_verbose("Read in JSON settings from file") else: self._json = { "last_check": "", "backup_date": "", "update_ready": False, "ignore": False, "just_restored": False, "just_updated": False, "version_text": dict() } self.save_updater_json()
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def json_reset_postupdate(self): self._json["just_updated"] = False self._json["update_ready"] = False self._json["version_text"] = dict() self.save_updater_json()
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def ignore_update(self): self._json["ignore"] = True self.save_updater_json()
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def start_async_check_update(self, now=False, callback=None): """Start a background thread which will check for updates""" if self._async_checking: return self.print_verbose("Starting background checking thread") check_thread = threading.Thread(target=self.async_check_update, args=(now, callback,)) check_thread.daemon = True self._check_thread = check_thread check_thread.start()
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def stop_async_check_update(self): """Method to give impression of stopping check for update. Currently does nothing but allows user to retry/stop blocking UI from hitting a refresh button. This does not actually stop the thread, as it will complete after the connection timeout regardless. If the thread does complete with a successful response, this will be still displayed on next UI refresh (ie no update, or update available). """ if self._check_thread is not None: self.print_verbose("Thread will end in normal course.") # however, "There is no direct kill method on a thread object." # better to let it run its course # self._check_thread.stop() self._async_checking = False self._error = None self._error_msg = None
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def __init__(self): self.api_url = 'https://api.bitbucket.org' self.token = None self.name = "bitbucket"
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def form_tags_url(self, updater): return self.form_repo_url(updater) + "/refs/tags?sort=-name"
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def get_zip_url(self, name, updater): return "https://bitbucket.org/{user}/{repo}/get/{name}.zip".format( user=updater.user, repo=updater.repo, name=name)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def __init__(self): self.api_url = 'https://api.github.com' self.token = None self.name = "github"
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def form_tags_url(self, updater): if updater.use_releases: return "{}/releases".format(self.form_repo_url(updater)) else: return "{}/tags".format(self.form_repo_url(updater))
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def form_branch_url(self, branch, updater): return "{}/zipball/{}".format(self.form_repo_url(updater), branch)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def __init__(self): self.api_url = 'https://gitlab.com' self.token = None self.name = "gitlab"
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def form_tags_url(self, updater): return "{}/repository/tags".format(self.form_repo_url(updater))
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def form_branch_url(self, branch, updater): # Could clash with tag names and if it does, it will download TAG zip # instead of branch zip to get direct path, would need. return "{}/repository/archive.zip?sha={}".format( self.form_repo_url(updater), branch)
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def parse_tags(self, response, updater): if response is None: return list() return [ { "name": tag["name"], "zipball_url": self.get_zip_url(tag["commit"]["id"], updater) } for tag in response]
TheDuckCow/MCprep
[ 213, 21, 213, 63, 1383027728 ]
def get_content(): vh_title = "czx.to" list_li = [] response = tools.get_response(URL + '/' + str(_kp_id_) + '/', HEADERS, VALUES, 'GET')
dandygithub/kodi
[ 54, 41, 54, 5, 1483968122 ]
def __init__(self, bot: commands.Bot): self.bot = bot self.surveys_path = "data/survey/surveys.json" self.surveys = dataIO.load_json(self.surveys_path) self.tasks = defaultdict(list) self.bot.loop.create_task(self._resume_running_surveys())
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _member_has_role(self, member: discord.Member, role: discord.Role): return role in member.roles
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _deadline_string_to_datetime(self, deadline: str, adjust: bool = True) -> datetime: dl = dp.parse(deadline, tzinfos=tzd) if dl.tzinfo is None: dl = dl.replace(tzinfo=pytz.utc) to = self._get_timeout(dl) if adjust and -86400 < to < 0: dl += timedelta(days=1) elif to < -86400: raise PastDeadlineError() return dl
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _mark_as_closed(self, survey_id: str): if not self.surveys["closed"]: self.surveys["closed"] = [] closed = self.surveys["closed"] if survey_id not in closed: closed.append(survey_id) dataIO.save_json(self.surveys_path, self.surveys)
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _save_deadline(self, server_id: str, survey_id: str, deadline: str): self.surveys[server_id][survey_id]["deadline"] = deadline dataIO.save_json(self.surveys_path, self.surveys)
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _save_question(self, server_id: str, survey_id: str, question: str): self.surveys[server_id][survey_id]["question"] = question dataIO.save_json(self.surveys_path, self.surveys)
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _save_asked(self, server_id: str, survey_id: str, users: List[discord.User]): asked = [u.id for u in users] self.surveys[server_id][survey_id]["asked"] = asked dataIO.save_json(self.surveys_path, self.surveys)
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _save_answer(self, server_id: str, survey_id: str, user: discord.User, answer: str, change: bool) -> bool: answers = self.surveys[server_id][survey_id]["answers"] asked = self.surveys[server_id][survey_id]["asked"] options = self.surveys[server_id][survey_id]["options"] if change: for a in answers.values(): if user.id in a: a.remove(user.id) if options != "any": limit = options[answer]["limit"] if answer not in answers: answers[answer] = [] if answer in options and limit and len(answers[answer]) >= int(limit): return False answers[answer].append(user.id) if user.id in asked: asked.remove(user.id) dataIO.save_json(self.surveys_path, self.surveys) return True
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _check_reprompt(self, server_id: str, survey_id: str, option_name: str, link_name: str = None): answers = self.surveys[server_id][survey_id]["answers"] options = self.surveys[server_id][survey_id]["options"] if (link_name and len(answers[link_name]) == int(options[link_name]["limit"])): return for uid in answers[option_name]: user = self.bot.get_server(server_id).get_member(uid) new_task = self.bot.loop.create_task( self._send_message_and_wait_for_message( server_id, survey_id, user, change=True, rp_opt=option_name)) self.tasks[survey_id].append(new_task)
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _make_answer_table(self, server_id: str, survey_id: str) -> str: server = self.bot.get_server(server_id) answers = sorted(self.surveys[server_id][survey_id]["answers"].items()) rows = list(zip_longest( *[[server.get_member(y).display_name for y in x[1] if server.get_member(y) is not None] for x in answers])) headers = [x[0] for x in answers] return tabulate(rows, headers, tablefmt="orgtbl")
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def _get_server_id_from_survey_id(self, survey_id): for server_id, survey_ids in [ (ser, sur) for (ser, sur) in self.surveys.items() if ser not in ["next_id", "closed"]]: if survey_id in survey_ids: return server_id return None
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def check_folders(): if not os.path.exists("data/survey"): print("Creating data/survey directory...") os.makedirs("data/survey")
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def setup(bot: commands.Bot): check_folders() check_files() if dateutil_available: if pytz_available: if tabulate_available: bot.add_cog(Survey(bot)) else: raise RuntimeError( "You need to install `tabulate`: `pip install tabulate`.") else: raise RuntimeError( "You need to install `pytz`: `pip install pytz`.") else: raise RuntimeError( "You need to install `python-dateutil`:" " `pip install python-dateutil`.")
dealien/Red-Magician
[ 3, 6, 3, 12, 1497719436 ]
def received_message(self, message): if isinstance(message, TextMessage): # Data is always returned in bytes through the websocket, so convert it first to unicode message_dict = from_json(b2u(message.data)) self.handle_message(message_dict) else: log.warning('Unsupported message received on websocket server: %r', message)
h3llrais3r/Auto-Subliminal
[ 43, 7, 43, 6, 1387396745 ]
def check_message_structure(self, message): try: MESSAGE_SCHEMA.validate(message) return True except SchemaError: return False
h3llrais3r/Auto-Subliminal
[ 43, 7, 43, 6, 1387396745 ]
def run(self): # Check for messages on the websocket queue and pop it if len(autosubliminal.WEBSOCKETMESSAGEQUEUE) > 0: message = autosubliminal.WEBSOCKETMESSAGEQUEUE.pop(0) log.debug('Broadcasting websocket message: %r', message) # The message on the websocket queue is a dict, so convert it to a json string cherrypy.engine.publish('websocket-broadcast', to_json(message))
h3llrais3r/Auto-Subliminal
[ 43, 7, 43, 6, 1387396745 ]
def forwards(self, orm): "Write your forwards methods here." new_default = orm.Extension._meta.get_field_by_name('icon')[0].default for ext in orm.Extension.objects.filter(icon=""): ext.icon = new_default ext.save()
magcius/sweettooth
[ 7, 1, 7, 2, 1306982638 ]