Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
13,200 | def attach_mock(self, mock, attribute):
mock._mock_parent = None
mock._mock_new_parent = None
mock._mock_name =
mock._mock_new_name = None
setattr(self, attribute, mock) | Attach a mock as an attribute of this one, replacing its name and
parent. Calls to the attached mock will be recorded in the
`method_calls` and `mock_calls` attributes of this one. |
13,201 | def _jars_to_directories(self, target):
files = set()
jar_import_products = self.context.products.get_data(JarImportProducts)
imports = jar_import_products.imports(target)
for coordinate, jar in imports:
files.add(self._extract_jar(coordinate, jar))
return files | Extracts and maps jars to directories containing their contents.
:returns: a set of filepaths to directories containing the contents of jar. |
13,202 | def update_factor(self, name, body):
url = self._url(.format(name))
return self.client.put(url, data=body) | Update Guardian factor
Useful to enable / disable factor
Args:
name (str): Either push-notification or sms
body (dict): Attributes to modify.
See: https://auth0.com/docs/api/management/v2#!/Guardian/put_factors_by_name |
13,203 | def connect(self):
if ( in os.environ) and (sys.platform != ):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
retry_on_signal(lambda: conn.connect(os.environ[]))
except:
return
elif sys.platform ... | Method automatically called by the run() method of the AgentProxyThread |
13,204 | def verify_high(self, high):
errors = []
if not isinstance(high, dict):
errors.append()
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith():
continue
if not isinstance(name, six.string_types):
... | Verify that the high data is viable and follows the data structure |
13,205 | def register_activity_type(domain=None, name=None, version=None, description=None, defaultTaskStartToCloseTimeout=None, defaultTaskHeartbeatTimeout=None, defaultTaskList=None, defaultTaskPriority=None, defaultTaskScheduleToStartTimeout=None, defaultTaskScheduleToCloseTimeout=None):
pass | Registers a new activity type along with its configuration settings in the specified domain.
Access Control
You can use IAM policies to control this action's access to Amazon SWF resources as follows:
If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outsi... |
13,206 | def pdf_from_post(self):
html = self.request.form.get("html")
style = self.request.form.get("style")
reporthtml = "<html><head>{0}</head><body>{1}</body></html>"
reporthtml = reporthtml.format(style, html)
reporthtml = safe_unicode(reporthtml).encode("utf-8")
pdf... | Returns a pdf stream with the stickers |
13,207 | def _launch_editor(starting_text=):
"Launch editor, let user write text, then return that text."
editor = os.environ.get(, )
with tempfile.TemporaryDirectory() as dirname:
filename = pathlib.Path(dirname) /
with filename.open(mode=) as handle:
handle.write(starting_te... | Launch editor, let user write text, then return that text. |
13,208 | def to_python(self, value):
if value in self.empty_values:
try:
return self.empty_value
except AttributeError:
return u
return bleach.clean(value, **self.bleach_options) | Strips any dodgy HTML tags from the input |
13,209 | def compute_return(self, start_date, end_date, rate="MID"):
if rate not in ["MID", "ASK", "BID"]:
raise ValueError("Unknown rate type (%s)- must be , or " % str(rate))
if end_date <= start_date:
raise ValueError("End date must be on or after start date")
df = ... | Compute the return of the currency between two dates |
13,210 | def merge_pot1_files(self, delete_source=True):
natom = len(self[0].input.structure)
max_pertcase = 3 * natom
pot1_files = []
for task in self:
if not isinstance(task, DfptTask): continue
paths = task.outdir.list_filepaths(wildcard="*_POT*")
... | This method is called when all the q-points have been computed.
It runs `mrgdvdb` in sequential on the local machine to produce
the final DVDB file in the outdir of the `Work`.
Args:
delete_source: True if POT1 files should be removed after (successful) merge.
Returns:
... |
13,211 | def writeB1logfile(filename, data):
allkeys = list(data.keys())
f = open(filename, , encoding=)
for ld in _logfile_data:
linebegin = ld[0]
fieldnames = ld[1]
if len(ld) < 3:
formatter = str
elif ld[2] is None:
formatter = str
el... | Write a header structure into a B1 logfile.
Inputs:
filename: name of the file.
data: header dictionary
Notes:
exceptions pass through to the caller. |
13,212 | def transform_api_header_authorization(param, value):
try:
username, password = value.split(":", 1)
except ValueError:
raise click.BadParameter(
"Authorization header needs to be Authorization=username:password",
param=param,
)
value = "%s:%s" % (usernam... | Transform a username:password value into a base64 string. |
13,213 | def add_mip_obj(model):
if len(model.variables) > 1e4:
LOGGER.warning("the MIP version of minimal media is extremely slow for"
" models that large :(")
exchange_rxns = find_boundary_types(model, "exchange")
big_m = max(abs(b) for r in exchange_rxns for b in r.bounds)
... | Add a mixed-integer version of a minimal medium to the model.
Changes the optimization objective to finding the medium with the least
components::
minimize size(R) where R part of import_reactions
Arguments
---------
model : cobra.model
The model to modify. |
13,214 | def file_type(self, file):
try:
magic_text = magic.from_file(file)
if (isinstance(magic_text, bytes)):
magic_text = magic_text.decode()
except (TypeError, IOError):
return
if (re.search(, magic_text)):
retu... | Use python-magic to determine file type.
Returns 'png' or 'jpg' on success, nothing on failure. |
13,215 | def get_limits(self, coord=):
limits = self.t_[]
if limits is None:
image = self.get_image()
if image is not None:
wd, ht = image.get_size()
limits = ((self.data_off, self.data_off),
(fl... | Get the bounding box of the viewer extents.
Returns
-------
limits : tuple
Bounding box in coordinates of type `coord` in the form of
``(ll_pt, ur_pt)``. |
13,216 | def zoom_in(self):
index = self._zoom_factors.index(self._zoom_factor)
if index + 1 == len(self._zoom_factors):
return
self._zoom_factor = self._zoom_factors[index + 1]
if self._zoom_factors.index(self.zoom_factor) + 1 == len(self._zoom_factors):
... | Increase zoom factor and redraw TimeLine |
13,217 | def load_image(self, idx):
im = Image.open(.format(self.siftflow_dir, idx))
in_ = np.array(im, dtype=np.float32)
in_ = in_[:,:,::-1]
in_ -= self.mean
in_ = in_.transpose((2,0,1))
return in_ | Load input image and preprocess for Caffe:
- cast to float
- switch channels RGB -> BGR
- subtract mean
- transpose to channel x height x width order |
13,218 | def get_activity_lookup_session(self, proxy, *args, **kwargs):
if not self.supports_activity_lookup():
raise Unimplemented()
try:
from . import sessions
except ImportError:
raise OperationFailed()
proxy = self._convert_proxy(proxy)
try... | Gets the ``OsidSession`` associated with the activity lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ActivityLookupSession``
:rtype: ``osid.learning.ActivityLookupSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: `... |
13,219 | def create_call(self, raw_request, **kwargs):
req = self.create_request(raw_request, **kwargs)
res = self.create_response(**kwargs)
rou = self.create_router(**kwargs)
c = self.call_class(req, res, rou)
return c | create a call object that has endpoints understandable request and response
instances |
13,220 | def _define(self):
definition = []
q = QuantumRegister(2, "q")
rule = [
(U1Gate((self.params[2] - self.params[1]) / 2), [q[1]], []),
(CnotGate(), [q[0], q[1]], []),
(U3Gate(-self.params[0] / 2, 0, -(self.params[1] + self.params[2]) / 2), [q[1]], []),
... | gate cu3(theta,phi,lambda) c, t
{ u1((lambda-phi)/2) t; cx c,t;
u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t;
u3(theta/2,phi,0) t;
} |
13,221 | def _set_axis_ticks(self, axis, ticks, log=False, rotation=0):
if isinstance(ticks, (list, tuple)) and all(isinstance(l, list) for l in ticks):
axis.set_ticks(ticks[0])
axis.set_ticklabels(ticks[1])
elif isinstance(ticks, ticker.Locator):
axis.set_major_locat... | Allows setting the ticks for a particular axis either with
a tuple of ticks, a tick locator object, an integer number
of ticks, a list of tuples containing positions and labels
or a list of positions. Also supports enabling log ticking
if an integer number of ticks is supplied and settin... |
13,222 | def _add_var(var, value):
makeconf = _get_makeconf()
layman =
fullvar = .format(var, value)
if __salt__[](makeconf, layman):
cmd = [, , r.format(
layman.replace(, ),
fullvar),
makeconf]
__salt__[](cmd)
else:
... | Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line. |
13,223 | def full_text(self, level: int = 1) -> str:
res = ""
if self.wiki.extract_format == ExtractFormat.WIKI:
res += self.title
elif self.wiki.extract_format == ExtractFormat.HTML:
res += "<h{}>{}</h{}>".format(level, self.title, level)
else:
raise ... | Returns text of the current section as well as all its subsections.
:param level: indentation level
:return: text of the current section as well as all its subsections |
13,224 | def QA_fetch_index_list_adv(collections=DATABASE.index_list):
获取股票列表
index_list_items = QA_fetch_index_list(collections)
if len(index_list_items) == 0:
print("QA Error QA_fetch_index_list_adv call item for item in collections.find() return 0 item, maybe the DATABASE.index_list is empty!")
re... | '获取股票列表'
:param collections: mongodb 数据库
:return: DataFrame |
13,225 | def is_active(self, timeout=2):
try:
result = Result(*self.perform_request(, , params={: timeout}))
except ConnectionError:
return False
except TransportError:
return False
if result.response.status_code == 200:
return True
... | :param timeout: int
:return: boolean |
13,226 | def step(self, observations):
log_histogram = self(observations)
actions = self.q_head.sample(log_histogram)
return {
: actions,
: log_histogram
} | Sample action from an action space for given state |
13,227 | def print_square(row_queue, t):
occupied_rows = {y: row for _, y, row in row_queue}
empty_row = .join( for _ in range(t))
for y in range(t):
print(, end=)
if y not in occupied_rows:
print(empty_row, end=)
else:
row = dict(occupied_rows[y])
al... | Prints a row queue as its conceptual square array. |
13,228 | def match_regexp(self, value, q, strict=False):
value = stringify(value)
mr = re.compile(q)
if value is not None:
if mr.match(value):
return
self.shout(, strict, value, q) | if value matches a regexp q |
13,229 | def populate(self, priority, address, rtr, data):
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.set_attributes(priority, address, rtr)
self.module_type = data[0]
self.sub_address_1 = data[3]
self.sub... | :return: None |
13,230 | def rec_edit(self, zone, record_type, record_id, name, content, ttl=1, service_mode=None, priority=None,
service=None, service_name=None, protocol=None, weight=None, port=None, target=None):
params = {
: ,
: zone,
: record_type,
: record_... | Edit a DNS record for the given zone.
:param zone: domain name
:type zone: str
:param record_type: Type of DNS record. Valid values are [A/CNAME/MX/TXT/SPF/AAAA/NS/SRV/LOC]
:type record_type: str
:param record_id: DNS Record ID. Available by using the rec_load_all call.
:... |
13,231 | def V_horiz_spherical(D, L, a, h, headonly=False):
r
R = D/2.
r = (a**2 + R**2)/2./abs(a)
w = R - h
y = (2*R*h - h**2)**0.5
z = (r**2 - R**2)**0.5
Af = R**2*acos((R-h)/R) - (R-h)*(2*R*h - h**2)**0.5
if h == R and abs(a) <= R:
Vf = pi*a/6*(3*R**2 + a**2)
elif h == D and abs(a... | r'''Calculates volume of a tank with spherical heads, according to [1]_.
.. math::
V_f = A_fL + \frac{\pi a}{6}(3R^2 + a^2),\;\; h = R, |a|\le R
.. math::
V_f = A_fL + \frac{\pi a}{3}(3R^2 + a^2),\;\; h = D, |a|\le R
.. math::
V_f = A_fL + \pi a h^2\left(1 - \frac{h}{3R}\right),\;... |
13,232 | def simple_ins_from_obs(obsnames, insfilename=):
with open(insfilename, ) as ofp:
ofp.write()
[ofp.write(.format(cob)) for cob in obsnames] | writes an instruction file that assumes wanting to read the values names in obsnames in order
one per line from a model output file
Args:
obsnames: list of obsnames to read in
insfilename: filename for INS file (default: model.output.ins)
Returns:
writes a file <insfilename> with ea... |
13,233 | def build_rank_score_dict(rank_scores):
logger = getLogger(__name__)
logger.debug("Checking rank scores: {0}".format(rank_scores))
scores = {}
for family in rank_scores:
entry = family.split()
try:
family_id = entry[0]
logger.debug("Extracting rank score for ... | Take a list with annotated rank scores for each family and returns a
dictionary with family_id as key and a list of genetic models as value.
Args:
rank_scores : A list on the form ['1:12','2:20']
Returns:
scores : A dictionary with family id:s as key and scores as value
... |
13,234 | def _remove(self, removeList, selfValue):
s value, not recursive.
There is no need for a recursive one anyway.
Match by == operation.
Args:
removeList (list): The list of matching elements.
selfValue (list): The list you remove value from. Usually ``self.value``
... | Remove elements from a list by matching the elements in the other list.
This method only looks inside current instance's value, not recursive.
There is no need for a recursive one anyway.
Match by == operation.
Args:
removeList (list): The list of matching elements.
... |
13,235 | def write_compounds(self, stream, compounds, properties=None):
self._write_entries(
stream, compounds, self.convert_compound_entry, properties) | Write iterable of compounds as YAML object to stream.
Args:
stream: File-like object.
compounds: Iterable of compound entries.
properties: Set of compound properties to output (or None to output
all). |
13,236 | def parse_bind(bind):
if isinstance(bind, Connection):
engine = bind.engine
else:
engine = bind
m = re.match(r"Engine\((.*?)\)", str(engine))
if m is not None:
u = urlparse(m.group(1))
uses_netloc.append(u.scheme)
safe_url = ""
if u.password ... | Parses a connection string and creates SQL trace metadata |
13,237 | def draw(self):
if self.__conditional_flag is True:
return np.concatenate((self.__create_samples(), self.__create_samples()), axis=1)
else:
return self.__create_samples() | Draws samples from the `true` distribution.
Returns:
`np.ndarray` of samples. |
13,238 | def replace_parameter(self, name, value=None):
spec = self.__specs[name] if name in self.__specs else None
if self.extra_parameters() is False and spec is None:
raise ValueError()
if spec is not None and spec.nullable() is False and value is None:
raise ValueError( % name)
if spec is not None and val... | Replace a query parameter values with a new value. If a new value does not match current
specifications, then exception is raised
:param name: parameter name to replace
:param value: new parameter value. None is for empty (null) value
:return: None |
13,239 | def run_analysis(self, argv):
args = self._parser.parse_args(argv)
ccube_dirty = HpxMap.create_from_fits(args.ccube_dirty, hdu=)
bexpcube_dirty = HpxMap.create_from_fits(args.bexpcube_dirty, hdu=)
ccube_clean = HpxMap.create_from_fits(args.ccube_clean, hdu=)
be... | Run this analysis |
13,240 | def import_certificate(
ctx, slot, management_key, pin, cert, password, verify):
controller = ctx.obj[]
_ensure_authenticated(ctx, controller, pin, management_key)
data = cert.read()
while True:
if password is not None:
password = password.encode()
try:
... | Import a X.509 certificate.
Write a certificate to one of the slots on the YubiKey.
\b
SLOT PIV slot to import the certificate to.
CERTIFICATE File containing the certificate. Use '-' to use stdin. |
13,241 | def get_num_confirmations(tx_hash, coin_symbol=, api_key=None):
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
limit=1, api_key=api_key).get() | Given a tx_hash, return the number of confirmations that transactions has.
Answer is going to be from 0 - current_block_height. |
13,242 | def _processMsg(self, type, msg):
now = datetime.datetime.now()
if self.LOG_FILE_PATH == :
self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) +
log_file = self.LOG_FILE_PATH + now.strftime(self.LOG_FILE_FORMAT) +
m... | Process Debug Messages |
13,243 | def create_cursor(self, name=None):
cursor = self.connection.cursor()
cursor.tzinfo_factory = self.tzinfo_factory
return cursor | Creates a cursor. Assumes that a connection is established. |
13,244 | def on_drag_data_received(self, widget, context, x, y, data, info, time):
state_id_insert = data.get_text()
parent_m = self.model.selection.get_selected_state()
if not isinstance(parent_m, ContainerStateModel):
return
state_v = self.canvas.get_view_for_model(parent_m... | Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param data: SelectionData: contains state_id
:param info:
:param time... |
13,245 | def close(self):
if not (yield from super().close()):
return False
self.acpi_shutdown = False
yield from self.stop()
for adapter in self._ethernet_adapters:
if adapter is not None:
for nio in adapter.ports.values():
... | Closes this QEMU VM. |
13,246 | def select_newest_project(dx_project_ids):
if len(dx_project_ids) == 1:
return dx_project_ids[0]
projects = [dxpy.DXProject(x) for x in dx_project_ids]
created_times = [x.describe()["created"] for x in projects]
paired = zip(created_times,projects)
paired.sort(reverse=True)
ret... | Given a list of DNAnexus project IDs, returns the one that is newest as determined by creation date.
Args:
dx_project_ids: `list` of DNAnexus project IDs.
Returns:
`str`. |
13,247 | def activateRandomLocation(self):
self.activePhases = np.array([np.random.random(2)])
if self.anchoringMethod == "discrete":
self.activePhases = np.floor(
self.activePhases * self.cellDimensions)/self.cellDimensions
self._computeActiveCells() | Set the location to a random point. |
13,248 | def save(self, output_file, overwrite=False):
if os.path.exists(output_file) and overwrite is False:
raise ModelFileExists("The file %s exists already. If you want to overwrite it, use the "
"options as . " % (output_file, output_file))
else:
... | Save the model to disk |
13,249 | def urlunparse(data):
scheme, netloc, url, params, query, fragment = data
if params:
url = "%s;%s" % (url, params)
return urlunsplit((scheme, netloc, url, query, fragment)) | Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent). |
13,250 | def get_exchange_rates(self, **params):
response = self._get(, , params=params)
return self._make_api_object(response, APIObject) | https://developers.coinbase.com/api/v2#exchange-rates |
13,251 | def edit_custom_examples(program, config):
if (not config.custom_dir) or (not os.path.exists(config.custom_dir)):
_inform_cannot_edit_no_custom_dir()
return
resolved_program = get_resolved_program(program, config)
custom_file_paths = get_file_paths_for_program(
resolved_pr... | Edit custom examples for the given program, creating the file if it does
not exist. |
13,252 | def _match_net(self, net):
if self.network:
return match_list(self.network, net)
else:
return True | Match a query for a specific network/list of networks |
13,253 | def _make_scaled_srcmap(self):
self.logger.info()
bexp0 = fits.open(self.files[])
bexp1 = fits.open(self.config[][])
srcmap = fits.open(self.config[][])
if bexp0[0].data.shape != bexp1[0].data.shape:
raise Exception()
bexp_ratio = bexp0[0].data / ... | Make an exposure cube with the same binning as the counts map. |
13,254 | def removeCallback(cls, eventType, func, record=None):
callbacks = cls.callbacks()
callbacks.setdefault(eventType, [])
for i in xrange(len(callbacks[eventType])):
my_func, my_record, _ = callbacks[eventType][i]
if func == my_func and record == my_record:
... | Removes a callback from the model's event callbacks.
:param eventType: <str>
:param func: <callable> |
13,255 | def fetch(dbconn, tablename, n=1, uuid=None, end=True):
cur = dbconn.cursor()
order = if end else
try:
if uuid:
cur.execute("SELECT * FROM WHERE UUID= ORDER BY ROWID {} LIMIT {};".format(tablename, uuid, order, n))
else:
cur.execute("SELECT * FROM ORDER BY RO... | Returns `n` rows from the table's start or end
:param dbconn: database connection
:param tablename: name of the table
:param n: number of rows to return from the end of the table
:param uuid: Optional UUID to select from
:return: If n > 1, a list of rows. If n=1, a single row |
13,256 | def _get_fields(self, event, pull, message=None):
result = pull.fields_general(event)
if message is not None:
result["__message__"] = message
return result | Constructs a dictionary of fields and replacement values based on the
specified event and the status of the pull request.
:arg event: one of ["start", "error", "finish"].
:arg pull: an instance of PullRequest that has details about the current
status of the pull request testin... |
13,257 | def find_ent_endurance_tier_price(package, tier_level):
for item in package[]:
for attribute in item.get(, []):
if int(attribute[]) == ENDURANCE_TIERS.get(tier_level):
break
else:
continue
price_id = _find_price_id(item[], )
if price_id:
... | Find the price in the given package with the specified tier level
:param package: The Enterprise (Endurance) product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an error if not found |
13,258 | def repr2(x):
s = repr(x)
if len(s) >= 2 and s[0] == "u" and (s[1] == ""'):
s = s[1:]
return s | Analogous to repr(), but will suppress 'u' prefix when repr-ing a unicode string. |
13,259 | def send_to_redshift(
instance,
data,
replace=True,
batch_size=1000,
types=None,
primary_key=(),
create_boolean=False):
connection_kwargs = redshift_credentials.credential(instance)
print("Initiate send_to_redshift...")
print("Test to know if th... | data = {
"table_name" : 'name_of_the_redshift_schema' + '.' + 'name_of_the_redshift_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...]
} |
13,260 | def embed_snippet(views,
drop_defaults=True,
state=None,
indent=2,
embed_url=None,
requirejs=True,
cors=True
):
data = embed_data(views, drop_defaults=drop_defaults, state=state)
w... | Return a snippet that can be embedded in an HTML file.
Parameters
----------
{views_attribute}
{embed_kwargs}
Returns
-------
A unicode string with an HTML snippet containing several `<script>` tags. |
13,261 | def private_vlan_mode(self, **kwargs):
int_type = kwargs.pop().lower()
name = kwargs.pop()
mode = kwargs.pop().lower()
callback = kwargs.pop(, self._callback)
int_types = [, ,
, ,
]
valid_modes = [, , ,
... | Set PVLAN mode (promiscuous, host, trunk).
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
mode (str): The switchport PVLAN mode.
callback (function): A functi... |
13,262 | def load(self):
projects = {}
path = os.path.expanduser(self.path)
if not os.path.isdir(path):
return projects
logger.debug("Load project configs from %s", path)
for filename in os.listdir(path):
filename_parts = os.path.splitext(filename)
... | Load the projects config data from local path
Returns:
Dict: project_name -> project_data |
13,263 | def allow_network_access_grading(self):
vals = self._hook_manager.call_hook(, course=self.get_course(), task=self, default=self._network_grading)
return vals[0] if len(vals) else self._network_grading | Return True if the grading container should have access to the network |
13,264 | def create_package(self, output=None):
current_file = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
handler_file = os.sep.join(current_file.split(os.sep)[0:]) + os.sep +
if self.stage_config.get(, False):
... | Ensure that the package can be properly configured,
and then create it. |
13,265 | def export(self, nidm_version, export_dir):
atts = (
(PROV[], self.type),
(PROV[], self.label),
(NIDM_HAS_ALTERNATIVE_HYPOTHESIS, self.tail))
if self.partial_degree is not None:
atts += (
(SPM_PARTIAL_C... | Create prov entities and activities. |
13,266 | def visit_ClassDef(self, node):
for base in node.bases:
if isinstance(base, ast.Name) and isinstance(base.ctx, ast.Load):
base = getattr(runtime, base.id, None)
elif isinstance(base, ast.Attribute) and isinstance(base.ctx, ast... | Visit top-level classes. |
13,267 | def get_users_in_project(self, projectname):
ds_project = self.get_project(projectname)
if ds_project is None:
logger.error(
"Project does not exist in MAM" % projectname)
raise RuntimeError(
"Project does not exist in MAM" % projectname... | Get list of users in project from MAM. |
13,268 | def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None,
region=None, key=None, keyid=None, profile=None):
myfunnydhcpoptionsname
if not any((dhcp_options_name, dhcp_options_id)):
raise SaltInvocationError(
)
if not dhcp_options_id an... | Return a dict with the current values of the requested DHCP options set
CLI Example:
.. code-block:: bash
salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname'
.. versionadded:: 2016.3.0 |
13,269 | def present_active_subjunctive(self):
if self.sng == "vera":
forms = ["sé", "sér", "sé", "sém", "séð", "sé"]
return forms
elif self.sng == "sjá":
forms = ["sjá", "sér", "sé", "sém", "séð", "sé"]
return forms
else:
subjunctive_... | Strong verbs
I
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"])
>>> verb.present_active_subjunctive()
['líta', 'lítir', 'líti', 'lítim', 'lítið', 'líti']
II
>>> verb = StrongOldNorseVerb()
>>> verb.se... |
13,270 | def get_spaces(self, space_key=None, expand=None, start=None, limit=None, callback=None):
params = {}
if space_key:
params["spaceKey"] = space_key
if expand:
params["expand"] = expand
if start is not None:
params["start"] = int(start)
... | Returns information about the spaces present in the Confluence instance.
:param space_key (string): OPTIONAL: A list of space keys to filter on. Default: None.
:param expand (string): OPTIONAL: A comma separated list of properties to expand on the spaces.
Default: Empty
... |
13,271 | def ext_pillar(hyper_id, pillar, name, key):
vk = salt.utils.virt.VirtKey(hyper_id, name, __opts__)
ok = vk.accept(key)
pillar[] = {name: ok}
return {} | Accept the key for the VM on the hyper, if authorized. |
13,272 | def default_logging(grab_log=None,
network_log=None,
level=logging.DEBUG, mode=,
propagate_network_logger=False):
logging.basicConfig(level=level)
network_logger = logging.getLogger()
network_logger.propagate = propagate_network_logger
... | Customize logging output to display all log messages
except grab network logs.
Redirect grab network logs into file. |
13,273 | def output_xml(self, text):
document = Element()
comment = Comment()
document.append(comment)
aggregates = SubElement(document, )
aggregate = SubElement(aggregates, )
measurements = SubElement(aggregate, )
payload = json.loads(text)
... | Output results in JSON format |
13,274 | def make_generic_c_patterns(keywords, builtins,
instance=None, define=None, comment=None):
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kw = r"\b" + any("keyword", keywords.split()) + r"\b"
builtin = r"\b" + any("builtin", builtins.split()+C_TYPES.split()) + r"\b"... | Strongly inspired from idlelib.ColorDelegator.make_pat |
13,275 | def memberness(context):
if context:
texts = context.xpath().extract()
text = str(texts).lower()
if len(texts) > 1:
return 2
elif in text:
return 2
elif not in text:
return 0
elif in text:
return 2
... | The likelihood that the context is a "member". |
13,276 | def _load_model(self):
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
self.model = MujocoWorldBase()
self.arena = EmptyArena()
if self.use_indicator_object:
self.arena.add_pos_indicator()
self.model.merge(self.arena)
... | Loads the peg and the hole models. |
13,277 | def set_(device, **kwargs):
**
empty = {: 0, : 0,
: 0, : 0}
current = None
cmd =
if in kwargs:
cmd += .format(kwargs[])
parsed = _parse_quota(device, )
if kwargs[] in parsed:
current = parsed[][kwargs[]]
else:
current = empty
... | Calls out to setquota, for a specific user or group
CLI Example:
.. code-block:: bash
salt '*' quota.set /media/data user=larry block-soft-limit=1048576
salt '*' quota.set /media/data group=painters file-hard-limit=1000 |
13,278 | def _decode_argv(self, argv, enc=None):
uargv = []
if enc is None:
enc = DEFAULT_ENCODING
for arg in argv:
if not isinstance(arg, unicode):
arg = arg.decode(enc)
uargv.append(arg)
return uargv | decode argv if bytes, using stin.encoding, falling back on default enc |
13,279 | def run(self):
self.OnStartup()
try:
while True:
message = self._in_queue.get()
if message is None:
break
try:
self.HandleMessage(message)
except Exception as e:
logging.warning("%s", e)
self.SendReply(
... | Main thread for processing messages. |
13,280 | def ExecuteCmd(cmd, quiet=False):
result = None
if quiet:
with open(os.devnull, "w") as fnull:
result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull)
else:
result = subprocess.call(cmd, shell=True)
return result | Run a command in a shell. |
13,281 | def tar_add_bytes(tf, filename, bytestring):
if not isinstance(bytestring, bytes):
buff = io.BytesIO(bytestring)
tarinfo = tarfile.TarInfo(filename)
tarinfo.size = len(bytestring)
tf.addfile(tarinfo, buff) | Add a file to a tar archive
Args:
tf (tarfile.TarFile): tarfile to add the file to
filename (str): path within the tar file
bytestring (bytes or str): file contents. Must be :class:`bytes` or
ascii-encodable :class:`str` |
13,282 | def perm_by_group_and_perm_name(
cls, resource_id, group_id, perm_name, db_session=None
):
db_session = get_db_session(db_session)
query = db_session.query(cls.models_proxy.GroupResourcePermission)
query = query.filter(
cls.models_proxy.GroupResourcePermission.gr... | fetch permissions by group and permission name
:param resource_id:
:param group_id:
:param perm_name:
:param db_session:
:return: |
13,283 | def add_user_to_user_groups(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.add_user_to_user_groups_with_http_info(id, **kwargs)
else:
(data) = self.add_user_to_user_groups_with_http_info(id, **kwargs)
return data | Adds specific user groups to the user # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_user_to_user_groups(id, async_req=True)
>>> result = thread.get()
... |
13,284 | def getfile2(url, auth=None, outdir=None):
import requests
print("Retrieving: %s" % url)
fn = os.path.split(url)[-1]
if outdir is not None:
fn = os.path.join(outdir, fn)
if auth is not None:
r = requests.get(url, stream=True, auth=auth)
else:
r = requests.get(url, st... | Function to fetch files using requests
Works with https authentication |
13,285 | def get_resource_url(cls, resource, base_url):
if resource.Meta.resource_name:
url = .format(base_url, resource.Meta.resource_name)
else:
p = inflect.engine()
plural_name = p.plural(resource.Meta.name.lower())
url = .format(base_url, plural_name)
... | Construct the URL for talking to this resource.
i.e.:
http://myapi.com/api/resource
Note that this is NOT the method for calling individual instances i.e.
http://myapi.com/api/resource/1
Args:
resource: The resource class instance
base_url: The Base U... |
13,286 | def save_loop(filename, framerate=30, time=3.0, axis=np.array([0.,0.,1.]), clf=True, **kwargs):
n_frames = framerate * time
az = 2.0 * np.pi / n_frames
Visualizer3D.save(filename, n_frames=n_frames, axis=axis, clf=clf,
animate_rate=framerate, animate_az=az)
... | Off-screen save a GIF of one rotation about the scene.
Parameters
----------
filename : str
The filename in which to save the output image (should have extension .gif)
framerate : int
The frame rate at which to animate motion.
time : float
The... |
13,287 | def _fire_event(self, event_name, *event_args, **event_kwargs):
if event_name in self._allowed_events:
self._logger.debug("firing handlers for event %s ", event_name)
for func, args, kwargs in self._event_handlers[event_name]:
kwargs.update(event_kwargs)
... | Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. Optional positional and keyword arguments can be used to
pass arguments to **all** handlers added with this event. These
aguments updates arguments passed usin... |
13,288 | def read(self):
data = bytearray()
while True:
incoming_bytes = self.comport.inWaiting()
if incoming_bytes == 0:
break
else:
content = self.comport.read(size=incoming_bytes)
data.extend(bytearray(content))
... | Read data from serial port and returns a ``bytearray``. |
13,289 | def wrap(self, starter_cls):
if isinstance(starter_cls, type) and issubclass(starter_cls, ProcessStarter):
return starter_cls
depr_msg =
warnings.warn(depr_msg, DeprecationWarning, stacklevel=3)
return functools.partial(CompatStarter, starter_cls) | If starter_cls is not a ProcessStarter, assume it's the legacy
preparefunc and return it bound to a CompatStarter. |
13,290 | def data_to_binary(self):
return bytes([
COMMAND_CODE,
self.channels_to_byte(self.led_on),
self.channels_to_byte(self.led_slow_blinking),
self.channels_to_byte(self.led_fast_blinking)
]) | :return: bytes |
13,291 | def list(self):
return [x["_id"] for x in self._db.system.js.find(projection=["_id"])] | Get a list of the names of the functions stored in this database. |
13,292 | def get_translations_sorted(codes):
codes = codes or self.codes
return self._get_priority_translations(priority, codes) | Returns a sorted list of (code, translation) tuples for codes |
13,293 | def labels(self):
all_labels = set(self.token_patterns.keys())
all_labels.update(self.phrase_patterns.keys())
return tuple(all_labels) | All labels present in the match patterns.
RETURNS (set): The string labels.
DOCS: https://spacy.io/api/entityruler#labels |
13,294 | def send(self, node_id, request, wakeup=True):
conn = self._conns.get(node_id)
if not conn or not self._can_send_request(node_id):
self.maybe_connect(node_id, wakeup=wakeup)
return Future().failure(Errors.NodeNotReadyError(node_id))
fu... | Send a request to a specific node. Bytes are placed on an
internal per-connection send-queue. Actual network I/O will be
triggered in a subsequent call to .poll()
Arguments:
node_id (int): destination node
request (Struct): request object (not-encoded)
wakeup... |
13,295 | def restoreSettings(self, settings):
value = unwrapVariant(settings.value())
if value:
self.setFilenames(value.split(os.path.pathsep)) | Restores the files for this menu from the settings.
:param settings | <QSettings> |
13,296 | def run(self):
executor = concurrent.futures.ThreadPoolExecutor(
max_workers=self._config[])
now = int(datetime.datetime.utcnow().timestamp())
start_time = ((now + 29) // 30) * 30
self._log.info(.format(
datetime.datetime.fro... | Starts the sender. |
13,297 | def plot(self, channel_names, kind=,
gates=None, gate_colors=None, gate_lw=1, **kwargs):
ax = kwargs.get()
channel_names = to_list(channel_names)
gates = to_list(gates)
plot_output = graph.plotFCM(self.data, channel_names, kind=kind, **kwargs)
if gates is... | Plot the flow cytometry data associated with the sample on the current axis.
To produce the plot, follow up with a call to matplotlib's show() function.
Parameters
----------
{graph_plotFCM_pars}
{FCMeasurement_plot_pars}
{common_plot_ax}
gates : [None, Gate, li... |
13,298 | def get_cursor(cls, cursor_type=_CursorType.PLAIN) -> Cursor:
_cur = None
if cls._use_pool:
_connection_source = yield from cls.get_pool()
else:
_connection_source = yield from aiopg.connect(echo=False, **cls._connection_params)
if cursor_type == _Cursor... | Yields:
new client-side cursor from existing db connection pool |
13,299 | def apply_T5(word):
T5 =
WORD = word.split()
for i, v in enumerate(WORD):
if contains_VVV(v) and any(i for i in i_DIPHTHONGS if i in v):
I = v.rfind() - 1 or 2
I = I + 2 if is_consonant(v[I - 1]) else I
WORD[i] = v[:I] + + v[I:]
T5 =
wo... | If a (V)VVV-sequence contains a VV-sequence that could be an /i/-final
diphthong, there is a syllable boundary between it and the third vowel,
e.g., [raa.ois.sa], [huo.uim.me], [la.eis.sa], [sel.vi.äi.si], [tai.an],
[säi.e], [oi.om.me]. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.