code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def lookup_users(self, user_ids=None, screen_names=None, include_entities=None, tweet_mode=None):
post_data = {}
if include_entities is not None:
include_entities = 'true' if include_entities else 'false'
post_data['include_entities'] = include_entities
if user_ids:
... | Perform bulk look up of users from user ID or screen_name |
def _set_scroll(self, *args):
self._canvas_scroll.xview(*args)
self._canvas_ticks.xview(*args) | Set horizontal scroll of scroll container and ticks Canvas |
def salt_syndic():
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15) | Start the salt syndic. |
def bisine_wahwah_wave(frequency):
waves_a = bisine_wave(frequency)
waves_b = tf.reverse(waves_a, axis=[2])
iterations = 4
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
thetas = xs / _samples() * iterations
ts = (tf.sin(math.pi * 2 * thetas) + 1) / 2
wave = ts * waves_a + (1.... | Emit two sine waves with balance oscillating left and right. |
def safe_import(self, name):
module = None
if name not in self._modules:
self._modules[name] = importlib.import_module(name)
module = self._modules[name]
if not module:
dist = next(iter(
dist for dist in self.base_working_set if dist.project_name =... | Helper utility for reimporting previously imported modules while inside the env |
def add_tags(self, tags):
if isinstance(tags, (str, unicode)):
tags = [tags]
objs = object_session(self)
tmps = [FeedTag(tag=t, feed=self) for t in tags]
objs.add_all(tmps)
objs.commit() | add a tag or tags to a Feed |
def timeout(self, value):
if not self.params:
self.params = dict(timeout=value)
return self
self.params['timeout'] = value
return self | Specifies a timeout on the search query |
def info(cls, name, get_state=True, get_pid=True):
command = ['lxc-info', '-n', name]
response = subwrap.run(command)
lines = map(split_info_line, response.std_out.splitlines())
return dict(lines) | Retrieves and parses info about an LXC |
def Output(self):
self.Open()
self.Header()
self.Body()
self.Footer() | Output all sections of the page. |
def _ensure_content_type():
from django.contrib.contenttypes.models import ContentType
try:
row = ContentType.objects.get(app_label=PERM_APP_NAME)
except ContentType.DoesNotExist:
row = ContentType(name=PERM_APP_NAME, app_label=PERM_APP_NAME, model=PERM_APP_NAME)
row.save()
retur... | Add the bulldog content type to the database if it's missing. |
def ir_instrs(self):
ir_instrs = []
for asm_instr in self._instrs:
ir_instrs += asm_instr.ir_instrs
return ir_instrs | Get gadgets IR instructions. |
def _fall(self):
a = self._array
for column in [a[:, c] for c in range(a.shape[1])]:
target_p = column.shape[0] - 1
fall_distance = 1
while target_p - fall_distance >= 0:
if column[target_p].is_blank():
blank = column[target_p]
... | Cause tiles to fall down to fill blanks below them. |
def clean_descriptor(self, number):
self.descriptors[number]['stdout'].close()
self.descriptors[number]['stderr'].close()
if os.path.exists(self.descriptors[number]['stdout_path']):
os.remove(self.descriptors[number]['stdout_path'])
if os.path.exists(self.descriptors[number][... | Close file descriptor and remove underlying files. |
def raise_api_error(resp, state=None):
error_code = resp.status_code
if error_code == 402:
error_message = (
"Please add a payment method to upload more samples. If you continue to "
"experience problems, contact us at help@onecodex.com for assistance."
)
elif error_c... | Raise an exception with a pretty message in various states of upload |
def codestr2rst(codestr, lang='python', lineno=None):
if lineno is not None:
if LooseVersion(sphinx.__version__) >= '1.3':
blank_lines = codestr.count('\n', 0, -len(codestr.lstrip()))
lineno = ' :lineno-start: {0}\n'.format(lineno + blank_lines)
else:
lineno = '... | Return reStructuredText code block from code string |
def _xmlTextReaderErrorFunc(xxx_todo_changeme,msg,severity,locator):
(f,arg) = xxx_todo_changeme
return f(arg,msg,severity,xmlTextReaderLocator(locator)) | Intermediate callback to wrap the locator |
def dumb_property_dict(style):
return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]); | returns a hash of css attributes |
def plot_trunc_gr_model(
aval, bval, min_mag, max_mag, dmag,
catalogue=None, completeness=None, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval)
if not catalogue:
annual_rates, cumulative_rates ... | Plots a Gutenberg-Richter model |
def manage_config(cmd, *args):
if cmd == "file":
print(config.config_file)
elif cmd == "show":
with open(config.config_file) as f:
print(f.read())
elif cmd == "generate":
fname = os.path.join(
user_config_dir("genomepy"), "{}.yaml".format("genomepy")
... | Manage genomepy config file. |
def new( self, min, max ):
assert MIN <= min <= max <= MAX
self.min = min
self.max = max
self.offsets = offsets_for_max_size( max )
self.bin_count = bin_for_range( max - 1, max, offsets = self.offsets ) + 1
self.bins = [ [] for i in range( self.bin_count ) ] | Create an empty index for intervals in the range min, max |
def validate_parent_id(self, key, parent_id):
id_ = getattr(self, 'id', None)
if id_ is not None and parent_id is not None:
assert id_ != parent_id, 'Can not be attached to itself.'
return parent_id | Parent has to be different from itself. |
def command(results_dir, result_id):
campaign = sem.CampaignManager.load(results_dir)
result = campaign.db.get_results(result_id=result_id)[0]
click.echo("Simulation command:")
click.echo(sem.utils.get_command_from_result(campaign.db.get_script(),
result)... | Print the command that needs to be used to reproduce a result. |
def newEntry(self, ident = "", seq = "", plus = "", qual = "") :
e = FastqEntry()
self.data.append(e)
return e | Appends an empty entry at the end of the CSV and returns it |
def register_scf_task(self, *args, **kwargs):
kwargs["task_class"] = ScfTask
return self.register_task(*args, **kwargs) | Register a Scf task. |
def _token_to_subwords(self, token):
subwords = []
start = 0
while start < len(token):
subword = None
for end in range(
min(len(token), start + self._max_subword_len), start, -1):
candidate = token[start:end]
if (candidate in self._subword_to_id or
candidate... | Greedily split token into subwords. |
def _extract_docs_other(self):
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
lst = self.dst.numpydoc.get_list_key(data, 'also')
lst = self.dst.numpydoc.get_list_key... | Extract other specific sections |
def getPart(ID, chart):
obj = GenericObject()
obj.id = ID
obj.type = const.OBJ_ARABIC_PART
obj.relocate(partLon(ID, chart))
return obj | Returns an Arabic Part. |
def _get_style_of_faulting_term(self, C, rup):
if (rup.rake > 30.0) and (rup.rake < 150.):
frv = 1.0
fnm = 0.0
elif (rup.rake > -150.0) and (rup.rake < -30.0):
fnm = 1.0
frv = 0.0
else:
fnm = 0.0
frv = 0.0
fflt_f = (... | Returns the style-of-faulting scaling term defined in equations 4 to 6 |
def _set_attribute(self, name, value):
setattr(self, name, value)
self.namespace.update({name: getattr(self, name)}) | Make sure namespace gets updated when setting attributes. |
def total_level(source_levels):
sums = 0.0
for l in source_levels:
if l is None:
continue
if l == 0:
continue
sums += pow(10.0, float(l) / 10.0)
level = 10.0 * math.log10(sums)
return level | Calculates the total sound pressure level based on multiple source levels |
def joint_hex(x, y, **kwargs):
return sns.jointplot(
x, y, kind='hex', stat_func=None, marginal_kws={'kde': True}, **kwargs
) | Seaborn Joint Hexplot with marginal KDE + hists. |
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None):
if (fit_key is None) ^ (h5file is None):
raise ValueError("Either specify both fit_key and h5file, or"
" neither")
if not ((fit_key is None) ^ (fit_data is None)):
raise ValueError("Specify exac... | Loads a single fit |
def _rectangular(n):
for i in n:
if len(i) != len(n[0]):
return False
return True | Checks to see if a 2D list is a valid 2D matrix |
def interval_lengths( bits ):
end = 0
while 1:
start = bits.next_set( end )
if start == bits.size: break
end = bits.next_clear( start )
yield end - start | Get the length distribution of all contiguous runs of set bits from |
def execute_with_client(quiet=False,
bootstrap_server=False,
create_client=True):
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
quiet=quiet,
bootstrap_server=bootstrap_server,
... | Decorator that gets a client and performs an operation on it. |
def _set_covars(self, covars):
covars = np.asarray(covars)
_validate_covars(covars, self.covariance_type, self.n_components)
self.covars_ = covars | Provide values for covariance |
def update_result_ctrl(self, event):
if not self:
return
printLen = 0
self.result_ctrl.SetValue('')
if hasattr(event, 'msg'):
self.result_ctrl.AppendText(event.msg)
printLen = len(event.msg)
if hasattr(event, 'err'):
errLen = len(ev... | Update event result following execution by main window |
def b58encode(v):
long_value = 0
for c in v:
long_value = long_value * 256 + c
result = ""
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
nPad = 0
... | encode v, which is a string of bytes, to base58. |
def _transform(xsl_filename, xml, **kwargs):
xslt = _make_xsl(xsl_filename)
xml = xslt(xml, **kwargs)
return xml | Transforms the xml using the specifiec xsl file. |
def call(function, args, pseudo_type=None):
if not isinstance(function, Node):
function = local(function)
return Node('call', function=function, args=args, pseudo_type=pseudo_type) | A shortcut for a call with an identifier callee |
def _parse_g_dir(repo, gdirpath):
for f in repo.get_contents(gdirpath):
if f.type == "dir":
for sf in repo.get_contents(f.path):
yield sf
else:
yield f | parses a repo directory two-levels deep |
async def _handle_job_queue_update(self, message: BackendGetQueue):
self._logger.debug("Received job queue update")
self._queue_update_last_attempt = 0
self._queue_cache = message
new_job_queue_cache = {}
for (job_id, is_local, _, _2, _3, _4, max_end) in message.jobs_running:
... | Handles a BackendGetQueue containing a snapshot of the job queue |
def transform(self, m):
if len(m) != 6:
raise ValueError("bad sequ. length")
self.x, self.y = TOOLS._transform_point(self, m)
return self | Replace point by its transformation with matrix-like m. |
def _format_param_value(key, value):
if isinstance(value, str):
value = "'{}'".format(value)
return "{}={}".format(key, value) | Wraps string values in quotes, and returns as 'key=value'. |
def tree_to_dict(cls, tree):
specs = {}
for k in tree.keys():
spec_key = '.'.join(k)
specs[spec_key] = {}
for grp in tree[k].groups:
kwargs = tree[k].groups[grp].kwargs
if kwargs:
specs[spec_key][grp] = kwargs
... | Given an OptionTree, convert it into the equivalent dictionary format. |
def install (self):
outs = super(MyInstallLib, self).install()
infile = self.create_conf_file()
outfile = os.path.join(self.install_dir, os.path.basename(infile))
self.copy_file(infile, outfile)
outs.append(outfile)
return outs | Install the generated config file. |
def download(self, protocol, host, user, password,
file_name, rbridge='all'):
urn = "{urn:brocade.com:mgmt:brocade-firmware}"
request_fwdl = self.get_firmware_download_request(protocol, host,
user, password,
... | Download firmware to device |
def FindUniqueId(dic):
name = str(len(dic))
while name in dic:
name = str(random.randint(1000000, 999999999))
return name | Return a string not used as a key in the dictionary dic |
def _render_corpus_row(self, label, ngrams):
row = ('<tr>\n<td>{label}</td>\n<td>{first}</td>\n<td>{only}</td>\n'
'<td>{last}</td>\n</tr>')
cell_data = {'label': label}
for period in ('first', 'only', 'last'):
cell_data[period] = ', '.join(ngrams[label][period])
... | Returns the HTML for a corpus row. |
def _file_chunks(self, data, chunk_size):
for i in xrange(0, len(data), chunk_size):
yield self.compressor(data[i:i+chunk_size]) | Yield compressed chunks from a data array |
def agent_updated(self, context, payload):
try:
if payload['admin_state_up']:
pass
except KeyError as e:
LOG.error("Invalid payload format for received RPC message "
"`agent_updated`. Error is %(error)s. Payload is "
"%(... | Deal with agent updated RPC message. |
def execute_sql(self, sql, commit=False):
logger.info("Running sqlite query: \"%s\"", sql)
self.connection.execute(sql)
if commit:
self.connection.commit() | Log and then execute a SQL query |
def date_range(self):
try:
days = int(self.days)
except ValueError:
exit_after_echo(QUERY_DAYS_INVALID)
if days < 1:
exit_after_echo(QUERY_DAYS_INVALID)
start = datetime.today()
end = start + timedelta(days=days)
return (
da... | Generate date range according to the `days` user input. |
def parse_hpxregion(region):
m = re.match(r'([A-Za-z\_]*?)\((.*?)\)', region)
if m is None:
raise Exception('Failed to parse hpx region string.')
if not m.group(1):
return re.split(',', m.group(2))
else:
return [m.group(1)] + re.split(',', m.group(2)) | Parse the HPX_REG header keyword into a list of tokens. |
def _validate_information(self):
needed_variables = ["ModuleName", "ModuleVersion", "APIVersion"]
for var in needed_variables:
if var not in self.variables:
raise DataError("Needed variable was not defined in mib file.", variable=var)
if len(self.variables["ModuleName... | Validate that all information has been filled in |
def finish (self):
if not self.urlqueue.empty():
self.cancel()
for t in self.threads:
t.stop() | Wait for checker threads to finish. |
def sha(self):
if self._sha is None:
self._sha = compute_auth_key(self.userid, self.password)
return self._sha | Return sha, lazily compute if not done yet. |
def _get_conn(ret=None):
_options = _get_options(ret)
dsn = _options.get('dsn')
user = _options.get('user')
passwd = _options.get('passwd')
return pyodbc.connect('DSN={0};UID={1};PWD={2}'.format(
dsn,
user,
passwd)) | Return a MSSQL connection. |
def iter_halfs_double(graph):
edges = graph.edges
for index1, (atom_a1, atom_b1) in enumerate(edges):
for atom_a2, atom_b2 in edges[:index1]:
try:
affected_atoms1, affected_atoms2, hinge_atoms = graph.get_halfs_double(atom_a1, atom_b1, atom_a2, atom_b2)
yield ... | Select two random non-consecutive bonds that divide the molecule in two |
def targetword(self, index, targetwords, alignment):
if alignment[index]:
return targetwords[alignment[index]]
else:
return None | Return the aligned targetword for a specified index in the source words |
def _build_url(self, resource, **kwargs):
return urljoin(self.api_root, API_PATH[resource].format(**kwargs)) | Build the correct API url. |
def write_chunk(self, x, z, nbt_file):
data = BytesIO()
nbt_file.write_file(buffer=data)
self.write_blockdata(x, z, data.getvalue()) | Pack the NBT file as binary data, and write to file in a compressed format. |
def new_empty(self, name):
if name in self:
raise KeyError("Already have rule {}".format(name))
new = Rule(self.engine, name)
self._cache[name] = new
self.send(self, rule=new, active=True)
return new | Make a new rule with no actions or anything, and return it. |
def _process_failures(self, key):
if self.settings['RETRY_FAILURES']:
self.logger.debug("going to retry failure")
failkey = self._get_fail_key(key)
current = self.redis_conn.get(failkey)
if current is None:
current = 0
else:
... | Handles the retrying of the failed key |
def _rand_init(x_bounds, x_types, selection_num_starting_points):
return [lib_data.rand(x_bounds, x_types) for i \
in range(0, selection_num_starting_points)] | Random sample some init seed within bounds. |
def rotation_matrix_to_quaternion(rotation_matrix):
invert = (np.linalg.det(rotation_matrix) < 0)
if invert:
factor = -1
else:
factor = 1
c2 = 0.25*(factor*np.trace(rotation_matrix) + 1)
if c2 < 0:
c2 = 0.0
c = np.sqrt(c2)
r2 = 0.5*(1 + factor*np.diagonal(rotation_mat... | Compute the quaternion representing the rotation given by the matrix |
def create_table(clas,pool_or_cursor):
"uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model"
def mkfield((name,tp)): return name,(tp if isinstance(tp,basestring) else 'jsonb')
fields = ','.join(map(' '.join,map(mkfield,clas.FIELDS)))
base = 'create table if not exists %s... | uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model |
def tchar(tree_style, cur_level, level, item, size):
if (cur_level == level):
i1 = '1' if level == 0 else 'x'
i2 = '1' if item == 0 else 'x'
i3 = 'x'
if size == 1:
i3 = '1'
elif item == (size - 1):
i3 = 'l'
... | Retrieve tree character for particular tree node. |
def register_callback(self, sensorid, callback, user_data=None):
if sensorid not in self._registry:
self._registry[sensorid] = list()
self._registry[sensorid].append((callback, user_data)) | Register a callback for the specified sensor id. |
def _kput(url, data):
headers = {"Content-Type": "application/json"}
ret = http.query(url,
method='PUT',
header_dict=headers,
data=salt.utils.json.dumps(data))
if ret.get('error'):
return ret
else:
return salt.utils.json.load... | put any object in kubernetes based on URL |
def compute_file_metrics(processors, language, key, token_list):
tli = itertools.tee(token_list, len(processors))
metrics = OrderedDict()
for p in processors:
p.reset()
for p, tl in zip(processors, tli):
p.process_file(language, key, tl)
for p in processors:
metrics.update(p.... | use processors to compute file metrics. |
def getChild(self, suffix):
if suffix is None:
return self
if self.root is not self:
if suffix.startswith(self.name + "."):
suffix = suffix[len(self.name + "."):]
suf_parts = suffix.split(".")
if len(suf_parts) > 1 and suf_parts[-1]... | Taken from CPython 2.7, modified to remove duplicate prefix and suffixes |
def point_mutate(self,p_i,func_set,term_set):
x = self.random_state.randint(len(p_i))
arity = p_i[x].arity[p_i[x].in_type]
reps = [n for n in func_set+term_set
if n.arity[n.in_type]==arity and n.out_type==p_i[x].out_type
and n.in_type==p_i[x].in_type]
tmp ... | point mutation on individual p_i |
def indent(text, n=4):
_indent = ' ' * n
return '\n'.join(_indent + line for line in text.split('\n')) | Indent each line of text by n spaces |
def find_config_files():
config_files = []
for config_dir in _get_config_dirs():
path = os.path.join(config_dir, "rapport.conf")
if os.path.exists(path):
config_files.append(path)
return list(filter(bool, config_files)) | Return a list of default configuration files. |
def recent_comments(context):
latest = context["settings"].COMMENTS_NUM_LATEST
comments = ThreadedComment.objects.all().select_related("user")
context["comments"] = comments.order_by("-id")[:latest]
return context | Dashboard widget for displaying recent comments. |
def normalize_bboxes(bboxes, rows, cols):
return [normalize_bbox(bbox, rows, cols) for bbox in bboxes] | Normalize a list of bounding boxes. |
def include_library(libname):
if exclude_list:
if exclude_list.search(libname) and not include_list.search(libname):
return False
else:
return True
else:
return True | Check if a dynamic library should be included with application or not. |
def upload_mission(aFileName):
missionlist = readmission(aFileName)
print("\nUpload mission from a file: %s" % aFileName)
print(' Clear mission')
cmds = vehicle.commands
cmds.clear()
for command in missionlist:
cmds.add(command)
print(' Upload mission')
vehicle.commands.upload() | Upload a mission from a file. |
def _and(ctx, *logical):
for arg in logical:
if not conversions.to_boolean(arg, ctx):
return False
return True | Returns TRUE if and only if all its arguments evaluate to TRUE |
def available_styles(self):
styles = self._schema_item.get("styles", [])
return list(map(operator.itemgetter("name"), styles)) | Returns a list of all styles defined for the item |
def _load_from_tar(self, dtype_out_time, dtype_out_vert=False):
path = os.path.join(self.dir_tar_out, 'data.tar')
utils.io.dmget([path])
with tarfile.open(path, 'r') as data_tar:
ds = xr.open_dataset(
data_tar.extractfile(self.file_name[dtype_out_time])
)
... | Load data save in tarball form on the file system. |
def parallel_assimilate(self, rootpath):
logger.info('Scanning for valid paths...')
valid_paths = []
for (parent, subdirs, files) in os.walk(rootpath):
valid_paths.extend(self._drone.get_valid_paths((parent, subdirs,
files))... | Assimilate the entire subdirectory structure in rootpath. |
def _call_method(self, request):
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough... | Calls given method with given params and returns it value. |
def loadImageData(filename, spacing=()):
if not os.path.isfile(filename):
colors.printc("~noentry File not found:", filename, c=1)
return None
if ".tif" in filename.lower():
reader = vtk.vtkTIFFReader()
elif ".slc" in filename.lower():
reader = vtk.vtkSLCReader()
if n... | Read and return a ``vtkImageData`` object from file. |
def numericalize(self, t:Collection[str]) -> List[int]:
"Convert a list of tokens `t` to their ids."
return [self.stoi[w] for w in t] | Convert a list of tokens `t` to their ids. |
def zoom(self, factor):
camera = self.ren.GetActiveCamera()
camera.Zoom(factor)
self.ren_win.Render() | Zoom the camera view by a factor. |
def data_changed(self, change):
index = self.index
if index:
self.view.model.dataChanged.emit(index, index) | Notify the model that data has changed in this cell! |
def stop_listener_thread(self):
if self.sync_thread:
self.should_listen = False
self.sync_thread.join()
self.sync_thread = None | Stop listener thread running in the background |
def plugin_valid(self, filename):
filename = os.path.basename(filename)
for regex in self.regex_expressions:
if regex.match(filename):
return True
return False | Checks if the given filename is a valid plugin for this Strategy |
def _f90repr(self, value):
if isinstance(value, bool):
return self._f90bool(value)
elif isinstance(value, numbers.Integral):
return self._f90int(value)
elif isinstance(value, numbers.Real):
return self._f90float(value)
elif isinstance(value, numbers.Co... | Convert primitive Python types to equivalent Fortran strings. |
def stack(datasets):
base = datasets[0].copy()
for dataset in datasets[1:]:
base = base.where(dataset.isnull(), dataset)
return base | First dataset at the bottom. |
def availability(self):
if not hasattr(self, '_availability'):
self._availability = conf.lib.clang_getCursorAvailability(self)
return AvailabilityKind.from_id(self._availability) | Retrieves the availability of the entity pointed at by the cursor. |
def _handle_request_exception(request):
try:
data = request.json()
except:
data = {}
code = request.status_code
if code == requests.codes.bad:
raise BadRequestException(response=data)
if code == requests.codes.unauthorized:
raise Un... | Raise the proper exception based on the response |
def target_query(plugin, port, location):
return ((r.row[PLUGIN_NAME_KEY] == plugin) &
(r.row[PORT_FIELD] == port) &
(r.row[LOCATION_FIELD] == location)) | prepared ReQL for target |
def groups_set_description(self, room_id, description, **kwargs):
return self.__call_api_post('groups.setDescription', roomId=room_id, description=description, kwargs=kwargs) | Sets the description for the private group. |
def verb_chain_starts(self):
if not self.is_tagged(VERB_CHAINS):
self.tag_verb_chains()
return self.starts(VERB_CHAINS) | The start positions of ``verb_chains`` elements. |
def raw_shell(s):
'Not a member of ShellQuoted so we get a useful error for raw strings'
if isinstance(s, ShellQuoted):
return s.do_not_use_raw_str
raise RuntimeError('{0} should have been ShellQuoted'.format(s)) | Not a member of ShellQuoted so we get a useful error for raw strings |
def convert_all(folder, dest_path='.', force_all=False):
"Convert modified notebooks in `folder` to html pages in `dest_path`."
path = Path(folder)
changed_cnt = 0
for fname in path.glob("*.ipynb"):
fname_out = Path(dest_path)/fname.with_suffix('.html').name
if not force_all and fname_ou... | Convert modified notebooks in `folder` to html pages in `dest_path`. |
def make_connection(self):
"Make a fresh connection."
connection = self.connection_class(**self.connection_kwargs)
self._connections.append(connection)
return connection | Make a fresh connection. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.