anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
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). |
def load_data_fashion_mnist(batch_size, resize=None): #@save
(x_train, y_train), (x_test,y_test) = tf.keras.datasets.fashion_mnist.load_data()
x_train,x_test = x_train/255, x_test/255
print(y_train.shape)
# Divide all numbers by 255 so that all pixel values are between
# 0 and 1, add a batch dimen... | Download the FashionMNIST dataset and then load it into memory. |
def report_cv_results(self, results, scores=['score'], filename=None, n_top=5):
res = ""
for score in scores:
res += "{}\n".format(score)
res += "-------------------------------\n"
for i in range(1, n_top + 1):
candidates = np.flatnonzero(results['ran... | Report CV results and save them to file |
def test_sample_one_date(self):
self.assertEqual(self.test_sample.date, datetime.datetime(2016, 2, 12, 7, 34, 26)) | test expected data is being loaded into db |
def set_dens_threshold(self, dens_threshold):
if dens_threshold < 0:
raise ValueError("The density threshold cannot be smaller than 0.")
core.xc_func_set_dens_threshold(self.xc_func, ctypes.c_double(dens_threshold)) | Sets the density threshold below which the functional will not be evaluated. |
def saveImages(saveImagePath,dataForSaving,enumeratedList):
for i in range(len(dataForSaving[0])):
singleChar = dataForSaving[0][i]
singleImage = dataForSaving[1][i]
if singleChar not in enumeratedList:
enumeratedList.append(singleChar)
... | Need a global enumerated list, not a local one, or there will be errors if one .gnt file skips a character |
def test_process_log_with_min_size_in_configuration(self):
with tempfile.TemporaryDirectory() as sandbox:
with mock.patch('sys.stdout', new=io.StringIO()) as fake_stdout:
srcfile = Path(sandbox, 'pokus.log')
srcfile.touch()
destfile = Path(sandbox, 'ba... | Tests of try rotation with min_size in configuration |
def perform_set(self, nodes=[]):
# Input validation
try:
# Works for XGNodeDict input
set_nodes = nodes.get_updates()
except (AttributeError, TypeError):
# Assume list instead
set_nodes = nodes
if not isinstance(set_nodes, list):
... | Performs a 'set' using the nodes specified and returns the result. |
def allocate_node_private_network_address(
self,
request: dds_20151201_models.AllocateNodePrivateNetworkAddressRequest,
) -> dds_20151201_models.AllocateNodePrivateNetworkAddressResponse:
runtime = util_models.RuntimeOptions()
return self.allocate_node_private_network_address_with_op... | This operation applies only to sharded cluster instances. For more information, see [Apply for an endpoint for a shard or Configserver node](~~134037~~). > The requested endpoint can only be accessed over the internal network. If you want to access the endpoint over the Internet, call the [AllocatePublicNetworkAddress]... |
def GetCmdStatusAndOutput(args,
cwd=None,
shell=False,
env=None,
merge_stderr=False):
status, stdout, stderr = GetCmdStatusOutputAndError(
args, cwd=cwd, shell=shell, env=env, merge_stderr=merge_stderr)
if... | Executes a subprocess and returns its exit code and output. |
def mean_more_n_reviews(x, n, review_books_df):
asin_1 = x['asin_1']
asin_2 = x['asin_2']
dic_1 = {}
dic_2 = {}
if (len(review_books_df.query('asin == @asin_1')) > n and len(review_books_df.query('asin == @asin_2')) > 20):
overall_reviews_1 = review_books_df.query('asin == @asin_1'... | return for the current row of the matching dataFrame a list of dictionary containing the mean of all the review from the nth |
def do_auth(self, access_token, *args, **kwargs):
data = self.user_data(access_token, *args, **kwargs)
response = kwargs.get('response') or {}
response.update(data or {})
if 'access_token' not in response:
response['access_token'] = access_token
kwargs.update({'respon... | Finish the auth process once the access_token was retrieved |
def flattenTest():
x = rampfloat(0,0,1,n1,n2)
t = rampfloat(0,1,0,n1,n2)
smax = 5.0
a = smax/(n1-1)
b = 2*PI/(n2-1)
bx = mul(b,x)
bt = mul(b,t)
cosbx = cos(bx)
sinbx = sin(bx)
acosbx = mul(a,cosbx)
asinbx = mul(a,sinbx)
p2 = div(mul(bt,acosbx),add(1,asinbx))
el = fillfloat(1,n1,n2)
fl = Flat... | Test for t(tau,x) = tau(1+asin(bx)) |
def ComputeExteriorOrientation_RzRyRz(self, imagePoints, groundPoints, epsilon):
# cameraPoints = self.ImageToCamera(imagePoints)
cameraPoints = imagePoints
self.exteriorOrientationParameters[0:3] = np.dot(self.rotationMatrix_RzRyRz, self.exteriorOrientationParameters[0:3])
self.exterior... | Compute exterior orientation parameters. This function can be used in conjecture with ``self.__ComputeDesignMatrix(groundPoints)`` and ``self__ComputeObservationVector(imagePoints)`` |
def lint(session):
session.install("pre-commit")
session.run("pre-commit", "run", "--all-files") | Check all files against the defined precommit hooks. |
def wait_for_execution_step_status_is_in_progress(self, execution_id, document_name, step_name, time_to_wait):
start_time = time.time()
step_status = self._get_execution_step_status(execution_id, step_name)
elapsed_time = time.time() - start_time
# Wait for execution step to resolve in ... | Returns when execution step is IN PROGRESS |
def factor_unit(P):
assert all(isinstance(c, ModInt) for c in P)
assert len(set(c.n for c in P)) == 1
if P.deg == 1:
return defaultdict(int, {P: 1})
p = P[0].n
S = Polynomial.gcd(P, P.prime())
if S.deg == P.deg:
# P' = 0 so P = R^p
R ... | Berlekamp's algorithm only in Z/pZ |
def stubborn_asker(low, high):
import random
a=random.randint(1,100)
for i in range(1,10):
n=input('enter the number: ')
if n.isdigit():
n=int(n)
if n==a:
return('Correct')
break
elif n>a:
return('The number ... | Ask for a number between low and high until actually given one. Ask for a number, and if the response is outside the bounds keep asking until you get a number that you think is OK |
def applyMask3first(imagem, value, bandNames):
mask = imagem.select(bandNames[0]).neq(value) \
.bitwiseAnd(imagem.select(bandNames[1]).eq(value)) \
.bitwiseAnd(imagem.select(bandNames[2]).eq(value))
change_img = imagem.select(bandNames[0]).mask(mask.eq(1)).where(mask.eq(1), value)
img_out = ... | Function to perform a 3 year window filter for a single land cover value (such as Forest as 1) for the first year in an image. The image bands do not need to be in order, but the bandNames argument must be in chronological order. For the first year of land cover classifications, a three consecutive years window is used... |
def get_reference(self):
return self.PotTax_reference | Getter for the reference (initial board state) biosafe output. |
def zero_pad_sparse(mat, margin_h, margin_v, fmt="coo"):
sm, sn = mat.shape
padded_mat = mat.copy()
# Up and down margins initialized with zeros and filled as needed
margin_h_0 = sp.csr_matrix((sm, margin_h), dtype=mat.dtype)
margin_v_0 = sp.csr_matrix((margin_v, sn + 2 * margin_h), dtype=mat.dtype... | Adds margin of zeros around an input sparse matrix. |
def get_icon(self):
return QIcon() | Return the icon for this node type. |
def create_appointment():
msg = render_template('date')
return question(msg) | Initialize appointment's creation workflow; Pass to date definition |
def divisor(self) -> Optional['outputs.CSIPowerStoreSpecDriverSideCarsEnvsValueFromResourceFieldRefDivisor']:
return pulumi.get(self, "divisor") | Specifies the output format of the exposed resources, defaults to "1" |
def random_states(self, num_of_states):
return numpy.random.choice([-1, 1], size=(num_of_states, ) + self.hilbert_state_shape) | Member function return random state of the Operator. |
def remove_dupl_2d(arr):
arr_len = len(arr)
idx = 0
unique = set()
while idx < arr_len:
if tuple(arr[idx]) in unique:
del arr[idx]
arr_len -= 1
continue
unique.add(tuple(arr[idx]))
idx += 1
return arr | Remove duplicates in a 2D list. |
def target_acceleration(self, time):
pass | Returns the arm's desired x,y,z acceleration in workspace coordinates at time t |
def test_networking_project_network_create(self):
pass | Test case for networking_project_network_create |
def _expand_args(arglst):
if not isinstance(arglst, Iterable):
arglst = [arglst]
elif isinstance(arglst, dict):
arglst = [arglst]
elif ('theano' in sys.modules
and isinstance(arglst, _gettheano().graph.basic.Variable)):
arglst = [arglst]
elif isinstance(arglst, cf.Termi... | Recursively expand slices, iterables, dictionaries into a list of scalar data type. Scalars are returned as a 1 element list. |
def nodalSum2(val,elems,tol):
nodes = unique1d(elems)
for i in nodes:
wi = where(elems==i)
vi = val[wi]
ai,ni = average_close(vi,tol=tol)
ai /= ni.reshape(ai.shape[0],-1)
val[wi] = ai | Compute the nodal sum of values defined on elements. |
def _invalidate_branch_cache(self):
self._cached_overlapping_branch_list = None | We have changed our branch_dict (or more likely finish_branch_definition()ed a branch within that dict) in a way that invalidates any cached calculations that consumed the branch dict. |
def _download_http(source_uri, dest_path, version):
try:
logger.info("Downloading the dataset.")
download_file(source_uri=source_uri, dest_path=dest_path)
except DownloadError as e:
logger.info(
f"The request download from {source_uri} -> {dest_path} ... | Download dataset from Public HTTP URL. |
def encode_splits(data):
lookup = {'train': 0, 'val': 1, 'test': 2}
return [lookup[datum['split']] for datum in data] | Encode splits as intetgers and return the array. |
def build_person(first_name,last_name, age =''):
person = { 'first': first_name.title(), 'last' : last_name.title()}
if age:
person['age'] = age
return person | Return a dictionary of information about a person |
def select_features(vec):
return sorted(vec, key=vec.get, reverse=True)[
: min(len(vec), FEATURE_LENGTH)
] | Selects most frequent features. Selects the x most frequent ngrams/features (x=FEATURE_LENGTH) to avoid a (possibly) too big featurelist. |
def describe_running_log_records_with_options(
self,
request: dds_20151201_models.DescribeRunningLogRecordsRequest,
runtime: util_models.RuntimeOptions,
) -> dds_20151201_models.DescribeRunningLogRecordsResponse:
UtilClient.validate_model(request)
query = {}
if not Ut... | This operation is applicable only to generalpurpose localdisk and dedicated localdisk instances. You can call this operation up to 30 times per minute. To call this operation at a higher frequency, use a Logstore. For more information, see [Manage a Logstore](~~48990~~). |
def _check_for_login_failure(self):
location = self.selenium.get_location()
if "//test.salesforce.com" in location or "//login.salesforce.com" in location:
login_url = self.cumulusci.org.config["instance_url"]
self.builtin.log(f"setting login_url temporarily to {login_url}", "DE... | Handle the case where we land on a login screen Sometimes we get redirected to a login URL rather than being logged in, and we've yet to figure out precisely why that happens. Experimentation shows that authentication has already happened, so in this case we'll try going back to the instance url rather than the front d... |
def _GetUpdatedSchema(
original_schema,
new_columns=None,
relaxed_columns=None):
orig_field_map = (
{f.name: f for f in original_schema.fields} if original_schema else {})
if relaxed_columns:
orig_field_map = _GetRelaxedCols(relaxed_columns, orig_field_map)
if new_columns:
orig_field_m... | Update original_schema by adding and/or relaxing mode on columns. |
def put(self, id):
data = request.json
update_scenario(id, data)
return None, 204 | Updates a testing scenario. |
def add_weight(self):
# Get the csrf token
csrf = self.extract_csrf('https://wger.de/en/weight/add/')
# Adding referer to the headers
self.headers['Referer'] = API.url_weight
# Take the weight entires from TOML file
entries = self.cfg.get('payload', {}).get('we... | Adds a new weight; params needed for post request's payload |
def _getParameterValueString(self, name):
warnings.warn("This function is deprecated; parameters have been replaced with uniform inputs in 1.38.", DeprecationWarning, stacklevel = 2)
return "" | (Deprecated) Return the value string of a parameter by its name. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.