anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
def init_db(conn: Connection) -> None:
logger.info(f"{Fore.YELLOW}Initializing database ...{Style.RESET_ALL}")
# Create specified schema if not exists
if not conn.dialect.has_schema(conn, schema_name):
logger.info(f"{Fore.YELLOW}Schema {schema_name} does not exist, creating it ...{Style.RESET_ALL}... | Configures the target schema in which the tweets data will be stored, creates the schema and the table if not existing yet |
def getInfo(self):
doc = minidom.parse(urllib.urlopen(serverString + "/rest/asset/" + self.id))
self._getInfoFromNode(doc.getElementsByTagName("asset")[0]) | Get name, description, tags, 10 latest comments, type, parent, rating, creation date and author name/id |
def _build_infinite_size_dataloader(dataloader):
iterator = dataloader.__iter__()
while True:
try:
yield iterator.__next__()
except StopIteration:
iterator = dataloader.__iter__() | Build a looped dataloader with infinite size. |
def lab_to_xyz(image: tf.Tensor) -> tf.Tensor:
l, a, b = tf.unstack(image, axis=-1)
var_y = (l + 16) / 116
var_x = a / 500 + var_y
var_z = var_y - b / 200
var_x = tf.where(tf.pow(var_x, 3) > 0.008856, tf.pow(var_x, 3),
(var_x - 16 / 116) / 7.787)
var_y = tf.where(tf.pow(var... | Convert an image from LAB color space to XYZ color space |
def calc_bus_value(self, bus):
b = bus.comps.loc[self]
comp_val = self.bus_func(b)
expr = self.calc_bus_expr(bus)
if b['base'] == 'component':
return comp_val * b['char'].evaluate(expr)
else:
return comp_val / b['char'].evaluate(expr) | r""" Return the busses' value of the component's energy transfer. |
def fusion_api_edit_server_profile_template(self, body, uri, api=None, headers=None):
return self.profile_template.update(body, uri, api, headers) | Updates a Server Profile Template. [Arguments] |
def monome(c,d):
P = [0]*(d+1)
P[d] = c
return P | Construit un monome d'un degre donne et de coefficient donne |
def _syncDataWithParent(self):
parent = self.parent()
if parent is None:
data, range_ = None, None
else:
data = parent.getData(copy=False)
range_ = parent.getDataRange()
self._updateData(data, range_) | Synchronize this instance data with that of its parent |
def get_losses(self):
if self.loss is not None:
return [self.loss]
else:
return [] | Get losses of last computation if existing |
def plug_vifs(self, instance, network_info):
raise NotImplementedError() | Plug VIFs into networks. |
def convert_sparse_to_igraph(indices, matrix):
# sources, targets = matrix.nonzero()
# weights = matrix[sources, targets]
# weights = np.array(weights)[0]
# print(dir(louvain))
# ig = igraph.Graph(zip(sources, targets), directed=True,
# edge_attrs={'weight': weights})
# return... | Convert an adjacency graph in scipy sparse matrix format into an iGraph format. |
def get(self, namespace_name, repository_name, username):
roles = model.get_repo_roles(username, namespace_name, repository_name)
if not roles:
raise NotFound
return {"permissions": [r.to_dict() for r in roles]} | Get the fetch the permission for the specified user. |
def _getShaderRefs(self):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return getShaderNodes(self) | (Deprecated) Return a vector of all shader references in this material element. |
def test_init(self):
# the self.assertEqual() checks fofr an expected result
# We are checking if the name and description of our new object is what we actually put
self.assertEqual(self.new_contact.first_name, "James")
self.assertEqual(self.new_contact.last_name, "Muriuki")
self... | has to be called test_init. This is to test if the object is initialized properly. |
def get_nodes(self):
try:
for node in Linode.search(status=Linode.STATUS_RUNNING):
self.add_node(node)
except chube_api.linode_api.ApiError, e:
print "Looks like Linode's API is down:"
print
print e
sys.exit(1) | Makes an Linode API call to get the list of nodes. |
def test_normals(self, faces, point):
space = self.Space(faces=faces)
cube_normals = gs.array(
[
[0.0, 0.0, 2.0],
[0.0, 0.0, 2.0],
[0.0, 2.0, 0.0],
[0.0, 2.0, 0.0],
[2.0, 0.0, 0.0],
[2.0, 0.0, 0.0... | Test normals. We test this on a space whose initializing point is a cube, and we test the function on a cube with sides of length 2 centered at the origin. The cube is meshed with 12 triangles (2 triangles per face.) Recall that the magnitude of each normal vector is equal to the area of the face it is normal to. |
def execute(self, i: dict) -> None:
# execute instruction for instruction processor
if i["recipient"] == "proc":
if self.suffixes_condition[i["suf"]]():
if i["type"] == "proc_alu":
# TODO: cmpi_ fix
i["func"](self.regs[i["dest"]], self.... | Executes given parsed instruction |
def dump(self, camel_case: bool = False) -> Dict[str, Any]:
dumped = {
"id": self.id,
"external_id": self.external_id,
"is_string": self.is_string,
"is_step": self.is_step,
"unit": self.unit,
"datapoints": [dp.dump(camel_case=camel_case) fo... | Dump the datapoints into a json serializable Python data type. |
def subsample_training_set(self, k, seed=None):
if seed is not None:
rng_state = th.random.get_rng_state()
with th.random.fork_rng():
th.manual_seed(seed)
self._subsample_training_set(k)
if any(th.random.get_rng_state() != rng_state):
... | Subsample the training data (for low resource experiments) |
def get_portfolio_value(prices, allocs, start_val):
normed = prices/prices.iloc[0]
alloced = np.multiply(allocs, normed)
pos_vals = alloced * start_val
port_val = pos_vals.sum(axis=1)
return port_val | Given a starting value and prices of stocks in portfolio with allocations return the portfolio value over time. |
def getlenbarvarj(self,j_):
lenbarvarj_ = ctypes.c_int64()
res = __library__.MSK_XX_getlenbarvarj(self.__nativep,j_,ctypes.byref(lenbarvarj_))
if res != 0:
_,msg = self.__getlasterror(res)
raise Error(rescode(res),msg)
lenbarvarj_ = lenbarvarj_.value
_lenbarvarj_return_value = lenbarvarj... | Obtains the length of one semidefinite variable. getlenbarvarj(self,j_) |
def trigger_delete(cls, instance):
es_client.delete(instance.blog.index_name(), 'blog_page_index', instance.id) | Delete the index from Elastic Search |
def compute(self):
self.find_n()
# call hotspot field plots
for scenario in self.scenarios:
fields_dict = {}
ancestor_files = []
for filename in io.get_all_ancestor_files(self.cfg,
pattern='hotspot_*.nc'):... | Collect datasets and call the plotting functions. |
def loglikeobs(self, params, *args, **kwargs):
raise NotImplementedError # pragma: no cover | Loglikelihood of model evaluated pointwise |
def configuration_options_object_processor(configuration_options):
option_names = [option.name for option in configuration_options.configuration_options]
for option_name in option_names:
if option_names.count(option_name) > 1:
raise WashError(f'Configuration option with the name {option_name... | Validates if all ConfigurationOption names are unique in the ConfigurationOptions instance. |
def extract_phrase(self, src_text, tgt_text, alignment, max_phrase_len=0):
def extract_from_range(tgt_start, tgt_end, src_start, src_end, max_phrase_len):
"""Extract a set of possible phrase given the source, language ranges.
"""
# print("rages", tgt_start, tgt_end, src_star... | Extract all phrases from word alignment. |
def __init__(self, policy: TypePolicy, byte_offset: int, byte_size: int, bin: TypeBinName):
self._children= (
byte_offset,
byte_size,
_GenericExpr(_ExprOp._AS_EXP_BIT_FLAGS, 0, {_Keys.VALUE_KEY: policy['bit_write_flags']} if policy is not None and 'bit_write_flags' in... | Create an expression that performs a bit_remove operation. |
def update_freshclam(module, freshclam_binary):
rc_code, out, err = module.run_command("%s" % (freshclam_binary))
return rc_code, out, err | Run freshclam to update ClamAV signatures |
def compute_fog_faded_color(self, color: Color, dz: float) -> Color:
fade_amount = math.exp(-(dz * self._fog_factor)**2)
return mix_colors(UPPER_SKY_COLOR, color, fade_amount) | Fade a color depending on how far from the camera it is. |
def sum_over_all_but_batch_and_last_n(
tensor: torch.Tensor, n_dims: int
) -> torch.Tensor:
if tensor.dim() == n_dims + 1:
return tensor
else:
dims = list(range(1, tensor.dim() - n_dims))
return tensor.sum(dim=dims) | r""" Calculates the sum over all dimensions, except the first (batch dimension), and excluding the last n_dims. This function will ignore the first dimension and it will not aggregate over the last n_dims dimensions. |
def test_sqs_log_handler_extra_json_data(self):
try:
extra = {
"test": "test logging",
"num": 1,
5: "9",
"float": 1.75,
"nested": {"more": "data"}
}
self.logger.info("test info message with proper... | Fails if log handler does not output expected log message with extras |
def get_connection(self, params):
return Redis(connection_pool=self.get_or_create_connection_pool(params)) | Given a now preformated params, return a new connection. The default implementation uses a cached pools for create new connection. |
def get_clever_key(self):
key = self.bot_data_file["apiKeys"]["cleverbot"]
if self.check_empty_key(key):
return key
else:
print("ERROR GETTING THE CLEVERBOT KEY (get yours from https://www.cleverbot.com/api/)- ABORTING")
quit(1) | Function that return the api key for the cleverbot api. |
def detect_objects(self, image, threshold):
self.set_input_tensor(image)
self.interpreter.invoke()
# Get all output details
boxes = self.get_output_tensor(0)
classes = self.get_output_tensor(1)
scores = self.get_output_tensor(2)
count = int(self.get_output_tensor... | Returns a list of detection results, each a dictionary of object info. |
def close(self) -> None:
self.simulator.close() | Clean up the environment after the user has finished using it. It terminates the Python Jiminy engine. |
def click_vendor_price_lists_search_button(self):
search_button_element = self.wait().until(EC.element_to_be_clickable(self.search_button_locator), 'search button not found before specified time')
self.script_executor_click(search_button_element)
self.wait_for_ajax_spinner_load(300) | Implementing click vendor price lists search button functionality |
def attach_display(self, display):
self.extra_displays.append(display)
self.addDockWidget(Qt.RightDockWidgetArea, display)
#self.display_attached.emit(display) | Attach an extra display to the control. Those displays are updated whenever a step occurs. |
def ang2xy(self, theta, phi=None, lonlat=False, direct=False):
pass | From angular direction to position in the projection plane (%s). |
def add_blogpost(manuscript, subject, url):
line_number = 0
with open(manuscript, "r") as file:
lines = file.readlines()
for line in lines:
if ("## ブロマガ全集" in line):
lines.insert(line_number + 2, f"- [{subject}]({url})\n")
with open(manuscript, "w") as file:
... | Add blogpost to manuscript |
def list_aspects(request, pk):
category = get_object_or_404(GradeCategory, pk=pk)
aspects = GradeCategoryAspect.objects.filter(Category=category)
ts = get_timeslot()
return render(request, "results/list_aspects.html", {
"aspects": aspects,
'ts': ts,
'cat': category,
}) | List all aspects of a given grade category in the current timeslot |
def ndarray_print(nd):
try:
x = nd.tolist()
except (TypeError, NotImplementedError):
x = nd.tobytes()
if isinstance(nd, ndarray):
offset = nd.offset
flags = nd.flags
else:
offset = 'unknown'
flags = 'unknown'
print("ndarray(%s, shape=%s, strides=%s, su... | Print ndarray for debugging. |
def get_classes(self, include_ref=True):
defs = self._get_class_defs()
ans = {}
ans.update(defs)
if include_ref:
refs = self._get_class_refs()
ans.update(refs)
return list(ans.values()) | get all classes and label them if they are referenced if include_ref is False, only "defined" classes are included. |
def configure(username, password, domain):
art = r'''
Welcome! __ ___. .__
_____ ____ ____ ____ __ __ _____/ |______ \_ |__ | | ____
\__ \ _/ ___\/ ___\/ _ \| | \/ \ __\__ \ | __ \| | _/ __ \
/ __ \\ \__\ \__( <_> ) | / | \ | / __ \| \_\ \ |_... | Initial configuration. Used to specify your username, password and domain. Configuration is stored in ~/.accountable/config.yaml. |
def test_about_page(self):
response = self.testapp.get('/about')
self.assertEqual(response.status_int, 200)
self.assertEqual(response.content_type, 'text/html')
response.mustcontain('Community Guidelines', 'Lifecycle', 'License') | Test the About page. |
def f2c_cml_exc_function():
import sys
try:
F = float(sys.argv[1])
C = 5/9.0*F - 32
print("The temperatire in Celcius is {:g}".format(C))
except:
print("Format should be {} with a temperature in Farenheit" \
.format(sys.argv[0])) | Take an argument as input from the command line |
def __init__(self,fname):
try:
self.handler = open(fname,'r')
self.filename = fname
except Exception:
log.exception('Fallo al abrir ' + fname)
return None
self.content = self.handler.readlines()
self.handler.close() | Constructor de la clase, que lee el archivo de texto "fname" a modificar. |
def set_password(self, password):
self.password = md5crypt(password, gen_salt()) | Salt and hashes the password. |
def regularResponse(p, dom: string, ip_dom: string, ip_srv: string, dt: float):
id_IP = int(RandShort()) #id for IP layer
ar_ans = DNSRR(rrname = dom, rdata = ip_dom) #Domain answer
ar_ext = DNSRROPT(rclass=4096) #Extension
an_ans = DNSRR(rrname = dom, rdata = ip_srv) #Domain server answer
ns_ans =... | Gives a regular response to packet "p" |
def makes10(a,b):
return a==10 or b==10 or a+b==10 | Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. |
def execute(self, symbol_table, test_mode=False): | Execute on REM does nothing. |
def predict(self, datafile):
sentences_emb,labels=self.read_data(datafile)
predictions=self.clf.predict(sentences_emb)
polarity=[]
for p in predictions:
if p==1:
polarity.append("positive")
elif p==0:
polarity.append("neutra... | Predicts class labels for the input instances in file 'datafile' Returns the list of predicted labels |
def get_pid(ssh):
pid_file_path = data_dir.MM_PID_DIR+"master_monitord.pid" #獲得master_monitord.pid之檔案路徑
cmd = "sudo cat %s" % pid_file_path #組合cat指令
s_stdin, s_stdout, s_stderr = ssh.exec_command(cmd) #透過ssh執行指令
return s_stdout.read()
#pid, error = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE).communicate... | get master monitor pid |
def doc2bow(self, document, allow_update=False, return_missing=False):
doc=[t.text for t in document.tokens]
if isinstance(doc, string_types):
raise TypeError("doc2bow expects an array of unicode tokens on input, not a single string")
# Construct (word, frequency) mapping.
... | Convert `document` into the bagofwords (BoW) format = list of `(token_id, token_count)` tuples. |
def resolve_k(k: float or Callable[[int], float] or None, n: int, k_max: int = None):
if k_max is None:
k_max = n
if callable(k):
k = k(n)
elif k is None:
k = k_max
elif not 1 <= k <= k_max:
raise ValueError(f'{k} is too many nearest neighbours, number has to be between 1... | Helper method to obtain a valid number of neighbours from a parameter `k` given `n` target records, where `k` may be defined in terms of `n`. |
def _experiment_options(self, index: int = -1) -> Dict[str, Any]:
try:
return self.__experiment_metadata["job_metadata"][index]["experiment_options"]
except (TypeError, KeyError, IndexError):
# Ignore experiment metadata or job metadata is not set or key is not found
... | Return the experiment options of given job index. |
def get_all_headlines(self):
list_vals = list(self.keyword_headlines().values())
uniq_headlines = set()
for list_val in list_vals:
for headlineobj in list_val:
uniq_headlines.add(headlineobj.headlineid.content)
return list(uniq_headlines) | Returns a list of all headlines |
def distance_between(point1, point2):
x1, y1 = point1
x2, y2 = point2
return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) | Computes distance between point1 and point2. Points are (x, y) pairs. |
def __init__(self, db):
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
self.cursor.execute("CREATE TABLE IF NOT EXISTS Book (Id INTEGER PRIMARY KEY, \
Title TEXT, Author TEXT, Year INTEGER, ISBN INTEGER)")
self.connection.commit() | Creates the book table in the Book database |
def draw_stacking_context(stream, stacking_context):
# See https://www.w3.org/TR/CSS2/zindex.html
with stacked(stream):
box = stacking_context.box
stream.begin_marked_content(box, mcid=True)
# apply the viewport_overflow to the html box, see #35
if box.is_for_root_element and (... | Draw a ``stacking_context`` on ``stream``. |
async def process_issue_hook(issue_data):
project = issue_data.project
issue = issue_data.issue
user = issue_data.user
description = ""
action = "Issue updated"
colour = discord.Colour.light_grey()
if issue.action == "open":
action = "Issue opened"
description = issue.descrip... | Builds and sends an embed message with issues information. |
def cv(self, x: pd.Series, y: pd.Series, n_splits: int, refit: bool = True, **fit_kwargs) -> List[list]:
x = self.text_formatter.fit_transform(x)
y_one_hot = self.label_encoder.fit_transform(y)
if y_one_hot.shape[1] == 1:
y_one_hot = np.hstack((y_one_hot, 1 - y_one_hot))
skf ... | Performs cross validation and returns the scores. |
def utilization(user, ressource):
if ressource == 'accounts':
return Account.objects.filter(vhost__in=list(get_vhosts(user))).count()
return None | Returns the correct ressource. |
def _program_key(self, slot, base32_key, require_button):
try:
config = self.parent.yk.init_config()
except (AttributeError, yubico.yubikey_usb_hid.usb.USBError):
return tkMessageBox.showerror(
"Error",
"No YubiKey detected"
)
c... | Once we get here, things get destructive |
def create(self):
if self.isInitialized():
self.Loaded = self.loader.create() | Creates a new net |
def history_log(self, user, action=CHANGE, message=''):
LogEntry.objects.log_action(
user_id=user.pk,
content_type_id=ContentType.objects.get_for_model(self).pk,
object_id=self.pk,
object_repr=force_text(self),
action_flag=action,
change_me... | Log that an object has been successfully changed. The default implementation creates an admin LogEntry object. |
def create_array(n, bound):
array = [np.random.randint(0, bound) for x in range(n)]
return array | Creates a random array |
def _get_cli_area(self):
for rec in self:
rec.cli_area = rec.cli_url | We use cli_url to set CLI URL and reflect this in cli_area to take it from JS. |
def test_ds_2d(i, num_bins):
np.random.seed(2191+i)
#simulated_dataset = simulate_twolayer(num_bins, ntaxa=47, nsamples=int(180/num_bins), Sigma_trace=10, scaling_factor=1)
simulated_dataset = sim_twolayer_delta(num_bins, ntaxa=47, nsamples=int(180/num_bins), Sigma_trace=1, angle_threshold=np.pi/4, Q_tr=5, ... | i defines the seed, num_bins defines the number of bins. We only test 2d datasets here |
def build_images(prefix, images, tag=None, commit_range=None, push=False, chart_version=None, skip_build=False):
value_modifications = {}
for name, options in images.items():
image_path = options.get('contextPath', os.path.join('images', name))
image_tag = tag
# include chartpress.yaml i... | Build a collection of docker images |
def test_put_item_wrong_id(self):
data = {"name": "bucketlist item name", "completed": "true"}
email = "test@test.com"
_pword = "test"
user = User.query.filter_by(email=email).first()
bucketlist = BucketList.query.filter_by(user_id=user.id, name="test bucketlist").first()
... | Method tests the error raised when end point for updating a bucket list item using put contains the wrong id |
def check_user(session_user, apache_user, sid):
if session_user != apache_user:
cherrypy.log.error("session_user::%s is not equal to apache_user::%s in standard auth"
"deleting session and throwing 403 error to the browser" % (session_user, apache_user))
# force a lock so ... | check to see if the session user is equal to the apache user raise 403 and delete the session if they are not equal |
def do_jira_case_commit_message(self, arg):
cases = [(issue.key, issue.fields.summary, self.jira_url() + "/browse/" + issue.key) for issue in self.get_open_issues()]
msg = """
--------------------------------------------------------------------
[{}] {}
<msg>
{}
------------------------... | Creates a git commit message template for cases currently assigned to you. |
def get_last_price_list_from_vendors_grid(self):
return self.get_specific_column_value_from_grid(self.vendors_div_id, self.vendors_grid_row_count, self.last_price_list_column_name, self.vendors_data_grid_name) | Implementing get last price list from vendor grid functionality |
def check_obstructed(r1,r2):
if r1==r2:
return False
#Densely sample line connecting r1 and r2.
#If any of those sampled points is inside the rectangle, then the
#line of sight intersects the rectangle and the tower's... | return True if r1 r2 line of sight is obstrucetd; oherwise False |
def _get_echo_resp_sent_count(self):
return self.__echo_resp_sent_count | Getter method for echo_resp_sent_count, mapped from YANG variable /mpls_state/statistics_oam/echo_resp_sent_count (uint32) |
def _all_na_or_values(series, values):
series_excl_na = series[series.notna()]
if not len(series_excl_na):
out = True
elif series_excl_na.isin(values).all():
out = True
else:
out = False
return out | Test whether every element in the series is either missing or in values This is fiddly because isin() changes behavior if the series is totally NaN (because of type issues) |
def tcp_ping_nodes(self, timeout=20.0):
for node in self.all_instances:
if node.instance_type in [
InstanceType.RESILIENT_SINGLE,
InstanceType.SINGLE,
InstanceType.DBSERVER,
]:
node.check_version_request(timeout) | tries to wait for the server to restart after the 'restore' command |
def getvarbound(self,i_):
bk_ = ctypes.c_int32()
bl_ = ctypes.c_double()
bu_ = ctypes.c_double()
res = __library__.MSK_XX_getvarbound(self.__nativep,i_,ctypes.byref(bk_),ctypes.byref(bl_),ctypes.byref(bu_))
if res != 0:
_,msg = self.__getlasterror(res)
raise Error(rescode(res),msg)
_... | Obtains bound information for one variable. getvarbound(self,i_) |
def editCategory(category_id):
# authentication
if 'username' not in login_session:
flash('Please login to edit category')
return redirect(url_for('showCategories'))
# validation
editedCategory = session.query(Category).filter_by(id=category_id).first()
if not editedCategory... | Process requests to edit existing category |
def update_syllable_count(word, syll_count):
syllables = word.split('-')
for i in range(1, 4):
for j in range(len(syllables) - i + 1):
gram = '-'.join(syllables[j: j + i])
count = syll_count.setdefault(gram, 0)
syll_count[gram] = count + 1 | Update the total occurrence counts of each unigram, bigram, and trigram |
def parse_command_line(args):
# Initial validity check of input command: each argument may be
# defined only once
for a in args:
if a.startswith('--'):
if args.count(a) > 1:
raise STAPLERerror.STAPLERerror('Each command line parameter can be '
... | Parses and validates command line arguments into a named tuple |
def questions(self, limit=-1, get_features=True, restrict_to_dupes=True):
if not self._answers_loaded:
self.load_answers()
if (limit, get_features, restrict_to_dupes) in self._questions_cache:
# Found in cache, no need to hit database.
cached = self._questions_cache[(limit, get_features, rest... | If get_features is true, loads all features in addition to just returning questions. |
def __init__(self):
self.vert_list = {}
self.num_vertices = 0 | initializes a graph object with an empty dictionary. |
async def DeleteRoutine(self, name: str):
#okay. problem was being cased by this line.
#the problem is, that we delete items as part of updating
#from gitlab. And in that case, we don't want to wipe out the local config.
#so while it may seem like we should conveniently do this, probab... | Override and call super. Then do the deletion. |
def write_to_vtk(mesh, displacement=None, file_name="gridfile"):
cents = get_cell_centroids(mesh)
dim = len(cents[0])
if displacement is not None:
cents+= displacement
file_name = "./"+file_name
write_function=None
if dim==3:
write_function = write_to_vtk3D
if... | writes the peridynamic mesh coordinates to a vetk supported file format |
def job_sorter(self, job):
key = natsort.natsort_keygen(key=self.job_title, alg=natsort.REAL)
return key(job) | Override this method for custom job sorting. This method returns a key that can be compared to sort jobs. By |
def render_path(path_to_item):
result = ""
for pth in path_to_item:
if isinstance(pth, six.integer_types):
result += "[{0}]".format(pth)
else:
result += "['{0}']".format(pth)
return result | Returns a string representation of a path |
def collide_hit_rect(first, second):
return first.hit_rect.colliderect(second.hit_rect) or first.hit_rect.colliderect(second.hit_rect) | Call back function which checks if two rectangles have collided with each other |
def visit_graph_end(self, network: Network):
pass | This method gets called after all nodes from a graph have been called |
async def release_node_private_network_address_async(
self,
request: dds_20151201_models.ReleaseNodePrivateNetworkAddressRequest,
) -> dds_20151201_models.ReleaseNodePrivateNetworkAddressResponse:
runtime = util_models.RuntimeOptions()
return await self.release_node_private_network_a... | This operation can be used to release the internal endpoint of a shard or Configserver node in a sharded cluster instance. For more information, see [Release the endpoint of a shard or Configserver node](~~134067~~). To release the public endpoint of a shard or Configserver node in a sharded cluster instance, you can c... |
def search_for_word(self, word, depth="shallow"):
# self._get_search_response(word)
self._extract_html(uri_for_search(word))
results = self.html.select(".concept_light.clearfix")
# print(results)
fmtd_results = []
if depth == "shallow":
for r in results:
... | Take a japanese word and spit out wellformatted dictionaries for each entry. |
def config(self, cluster_name, name, username, version, int_netmask, int_ip_low,
int_ip_high, ext_netmask, ext_ip_low, ext_ip_high, gateway, dns_servers,
encoding, sc_zonename, smartconnect_ip, join_cluster, compliance, txn_id):
logger = get_task_logger(txn_id=txn_id, task_id=self.request.id, ... | Turn a blank OneFS node into a usable device |
def initializeC(self, image):
super(CPupilFit, self).initializeC(image)
self.mfit = self.clib.pfitInitialize(self.pupil_fn.getCPointer(),
self.rqe,
self.scmos_cal,
self... | This initializes the C fitting library. |
def __cycle_consistency_loss(self, reconstructedA, reconstructedB):
loss = self.opt.lamA * tf.reduce_mean(tf.abs(reconstructedA - self.realA)) + \
self.opt.lamB * tf.reduce_mean(tf.abs(reconstructedB - self.realB))
return loss | Compute the cycle consistenty loss. L_cyc = lamA [Expectation of L1_norm(F(G(A)) A)] + lamb [Expectation of L1_norm(G(F(B)) B)] |
def on_event(self, c, e):
# any updates available?
if EVENT_MCX_UPDATES_AVAILABLE.isSet():
# gather all updates
availableUpdates = mcxUpdateThread.getUpdates()
# for each update group
for updateGroupId, updateMessageList in availableUpdates.iteritems():
... | method that's executed on every event |
def model(self, **config_kwargs):
measurement = self.get_measurement(**config_kwargs)
log.debug(
'model being created for measurement {0:s}'.format(measurement['name'])
)
patches = config_kwargs.get('patches', [])
modelspec = {
'channels': self.spec['cha... | Create a model object with/without patches applied. |
def get_nic_setting(self, nic_id, attribute_name):
return self._nic_cfg.get_nic_setting(nic_id, attribute_name) | Obtain a setting of a NIC. |
def __sort_predictors_by_corr(self, station, selections, var, From, To, by, how, constant=True,
selectionsnames=None, sort_cor=True, cor_lim=None):
scores_corel = pd.DataFrame(index=np.arange(0, len(selections)), columns=['corel', 'selections', 'params',
... | Return a sorted selections by the correlation rsquared scores |
def __init__(self, version="latest", no_internet=False):
# Set some needed variables, and pass them to the parent Dataset class __init__ function
valid_versions = ["0.0", "0.0.1"] # This keeps a record of all versions that the code is equipped to handle. That way, if there's a new data release but the... | Load all of the ovarian dataframes as values in the self._data dict variable, with names as keys, and format them properly. |
async def promote(self, ctx, *, member = None):
# Only allow admins to change server stats
if not await self._can_run(ctx): return
em = discord.Embed(color = 0XFF8C00, description = "Menaikan jabatan role xp member ke role xp selanjutnya\n\n"
... | Menaikan jabatan role xp member ke role xp selanjutnya(admin only). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.