anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
Returns the http request response code. | public function getCode()
{
$matches = array();
if (isset($this->headers) && isset($this->headers[0]))
preg_match('|HTTP/\d\.\d\s+(\d+)\s+.*|', $this->headers[0], $matches);
return isset($matches[1]) ? (int)$matches[1] : 0;
} |
Register any events for your application. | public function boot()
{
parent::boot();
Brand::observe(BrandObserver::class);
Email::observe(EmailObserver::class);
Media::observe(MediaObserver::class);
Category::observe(ScrappedCategoryMappingObserver::class);
ScrapedProducts::observe(ScrappedProductCategoryMap... |
A random way to say we found something. | public function foundSome() {
return $this->goodNews()
. ' '
. $this->randomItem(
'I found',
'I located',
'I have, just for you,',
'I got you'
);
} |
passo la palla alla classe astratta | public function __construct($Lang, $IDs, $from_ntt = "Fotovideo"){
parent::__construct("Fotovideo", $this->related_beans, $Lang, $IDs, $from_ntt);
// entitˆ Tfv che non viene prodotta nell'abstract
$this->Tfv = $this->beaner->build( $this->Lang,
"Tfv",
$this->IDs,
$this->bean_ntt)... |
Show the form for creating a new resource. | public function create()
{
return view('admin.teacherdetail.create');
} |
Rmdir executes an rmdir (remove directory) command on the remote FTP server. | public function rmdir($dir) {
if ($this->getActive()) {
// Remove the directory
if (ftp_rmdir($this->_connection, $dir)) {
return true;
} else {
return false;
}
} else {
throw new CHttpException(403, 'EFtpCompone... |
Store a newly created resource in storage. | public function store(Request $request)
{
//dd($request->all());
$request->validate([
'name'=>'required',
'category_id' => 'required',
'description'=>'required',
'quantity'=>'required',
'prize'=>'required',
'file' => 'im... |
Run the database seeds. | public function run()
{
DB::table('applicationScheduleTable')->insert(
[
'sessionId' => 1,
'scholarshipTypeValueId' => 18,
'startDate'=> Carbon::parse('2021-04-01'),
'lastDate'=> Carbon::parse('2021-05-31'),
'applic... |
update Status rawat jalan pasien dan waktu | public function selesai($id_rawat){
$no_pasien = $this->input->post('no_pasien');
$tanggal = date("d-m-Y");
$waktu = date("H:i:s");
$data = array(
'status' => 'finished',
'jam_keluar' => $waktu,
);
$id_transaksi = '';
$biaya_daftar = '';
$id_periksa = '';
$this->RawatModel->updateStatus($id_raw... |
/ | | Alternate route for Laravel Route::controller | | $prefix = path of route | $controller = controller name | $namespace = namespace of controller (optional) | | public static function denyAccess()
{
static::redirect(static::adminPath(), cbTrans('denied_access'));
} |
If present, specifies the start color for the gradient. | public function color1($color1)
{
if (is_string($color1)) {
$this->color1 = $color1;
} else {
throw new InvalidConfigValue(
__FUNCTION__,
'string'
);
}
return $this;
} |
Sets the survey status | function setStatus($status = self::STATUS_OFFLINE)
{
$result = "";
if (($status == self::STATUS_ONLINE) && (count($this->questions) == 0))
{
$this->status = self::STATUS_OFFLINE;
$result = $this->lng->txt("cannot_switch_to_online_no_questions");
}
else
{
$this->status = $status;
}
return $res... |
Declaramos que la habilidad tiene muchos niveles | public function niveles()
{
return $this->belongsTo('App\Models\Niveles', 'id_nivel');
} |
Returns the charge attempt's labels by their groups. | public static function getGroupedChargeAttemptLabels(PostFinanceCheckoutModelTransactioninfo $info)
{
try {
$labelDescriptionProvider = PostFinanceCheckoutProviderLabeldescription::instance();
$labelDescriptionGroupProvider = PostFinanceCheckoutProviderLabeldescription::instance();
... |
Inserts a record into the table | function insert_found_record($dbc, $finder, $item_name, $description, $location_id, $create_date) {
$query = 'INSERT INTO stuff(finder, item_name, description, location_id, create_date, status) VALUES ("'.$finder.'" ,"'.$item_name.'", "'.$description.'", "'.$location_id.'", "'.$create_date.'", "found")' ;
show_query... |
determine if the menu is a drop down | public function isDropdown()
{
return $this->dropdown;
} |
The creator/author of this CreativeWork. This is the same as the Author property for CreativeWork. | public function setCreator($creator) {
$this->properties['creator'] = $creator;
return $this;
} |
Returns the value of this object as a string. | public function __toString()
{
return $this->_;
} |
Register the plugin:seed command. | protected function registerPluginSeedCommand()
{
$this->app->singleton('command.plugin.seed', function ($app) {
return new PluginSeedCommand($app['plugins']);
});
$this->commands('command.plugin.seed');
} |
Method to retrieve a specific programme | public function getProgrammeByID($progID) {
try {
$programme = $this->em->getRepository(Entity\Programme::class)->findOneBy(array('progID' => $progID));
$this->em->flush();
} catch (\Doctrine\ORM\OptimisticLockException $e) {
$this->em->rollback();
}
r... |
Do we need to include various setup files? Utilising the 'setup_required' feature in XML files, loop through and determine if setup is required based on various modules being "available" | public function isSetupRequired()
{
$methodCodes = Mage::getConfig()->getNode('global/payment/setup_required')->asArray();
if (is_array($methodCodes) && count($methodCodes) > 0) {
foreach (array_keys($methodCodes) as $methodCode) {
$methodModel = Mage::getConfig()->getNod... |
Change matrix active flag If update is successful, the browser will be redirected to the 'create' page. | public function actionBlockmatrix($id){
$matrix = $this->findModelMatrix($id);
if ($matrix->getAttribute('active_flag')) {
$matrix->setAttribute('active_flag', 0);
$matrix->save();
Yii::$app->getSession()->setFlash('success','Matrix has been inactivated');
}... |
Set database connection configuration. | public static function setConfig($config, $type = 'base')
{
self::$config[$type] = $config;
} |
Create the element of body container if it does not exist | protected function _createRowContainer()
{
if ($this->_tbody == null) {
$this->_tbody = new HtmlElement('tbody');
$this->addElement($this->_tbody);
}
} |
LVP's central database contains a shed load of information. Using this method, we'll fetch whatever we may need from there and store it in some variable until it's needed. At the moment this method only fetches the crew status of a user. | public function fetchInformation($database, $profileId) {
$this->m_nProfileId = $profileId;
$pResult = $database->query(
'SELECT
u.level, u.is_developer
FROM
lvp_mainserver.users u
WHERE
u.user_id = ' . (int) $profileId);
if ($pResult !== false && $pResult->num_rows != 0) {
$aInformation... |
Show the form for editing the specified resource. | public function edit($id)
{
//
$data = Crud::find($id);
return view($this->folder.'/edit',compact('data'));;
} |
Show the form for creating a new pitch | public function create()
{
return View::make('pitches.create');
} |
Initializes internal state of \Tekstove\ApiBundle\Model\Acl\Base\PermissionGroupPermissionQuery object. | public function __construct($dbName = 'default', $modelName = '\\Tekstove\\ApiBundle\\Model\\Acl\\PermissionGroupPermission', $modelAlias = null)
{
parent::__construct($dbName, $modelName, $modelAlias);
} |
Get ONIX by ISBN ,returns XML as string | public function getByISBN(string $isbn): string
{
$subscription = $this->subscription;
$this->subscription = null;
$response = $this->apiClient->get(self::PATH . '/' . $isbn);
$this->subscription = $subscription;
return (string) $response->getBody();
} |
Update the specified resource in storage. | public function update(Request $request, Film $film)
{
$film->update($request->all());
} |
Returns whether or not the viewer is currently logged in and an admin user | public function isAdminLoggedIn() {
$user = $this->getLoggedInUser();
return $user && $user->isAdmin();
} |
/ array_multi_diff this function is used to compute the difference between to multidimensional arrays. it was taken from the php.net article on array_diff. | function array_multi_diff($a1,$a2) {
$diff = array();
foreach($a1 as $k=>$v){
$dv = null;
if(is_int($k)){
// Compare values
if(array_search($v,$a2)===false) $dv=$v;
else if(is_array($v)) $dv = array_multi_diff($v,$a2[$k]);
if($dv) $diff[]=$dv;
} else {
// Compare noninteger keys
if(!$a2[$k])... |
Toggle newsletter optin flag | public function processChangeOptinVal()
{
} |
A small helper function that pipes the output of `l()` though `ha()`. This makes sure the output can be safely inserted as an HTML attribute value. | function lha(){
return ha( call_user_func_array('l', func_get_args()) );
} |
Adds a listener to this execution. | public function addListener(ExecutionListenerInterface $listener)
{
if (!isset($this->plugins['Opensoft\\Workflow\\Execution\\Plugin\\Listener'])) {
$this->addPlugin(new Listener());
}
return $this->plugins['Opensoft\\Workflow\\Execution\\Plugin\\Listener']->addListener($listene... |
Load task data from a file. readtask(self,filename_) | def readtask(self,filename_):
if isinstance(filename_,unicode):
filename_ = filename_.encode("utf-8",errors="replace")
res = __library__.MSK_XX_readtask(self.__nativep,filename_)
if res != 0:
_,msg = self.__getlasterror(res)
raise Error(rescode(res),msg) |
Creates a new node from this read and adds it into the tree | def insert(self, dataset: List[Read]) -> bool:
node_to_insert = Node(self.k, self.num_buckets, self.fp_size, self.bucket_size, self.max_iter)
node_to_insert.populate_dataset_info(dataset)
self.aggregate_size += node_to_insert.get_size()
if self.root is None:
self.root = node... |
Test parsing of DPTValue1Ucount with wrong value (array containing string). | def test_from_knx_wrong_parameter2(self):
with self.assertRaises(ConversionError):
DPTValue1Ucount().from_knx("0x23") |
Shares are ready to decrypt. | def _ready_to_decrypt(self, shares: Dict[GuardianId, DecryptionShare]) -> bool:
# If all guardian shares are represented including if necessary
# the missing guardians reconstructed shares, the decryption can be made
return len(shares) == self._context.number_of_guardians |
Print out the end status of the game when the server closes the connection. | def server_closed_connection(self):
print("Game Over!")
if self._winner:
print("Player {} wins!".format(self._winner))
else:
print("Draw!") |
Actions to control hue lights | def lights(id, all, connect, info, action, bri):
try:
bridge = phue.Bridge(BRIDGE_IP)
except Exception:
click.secho(
"Press the bridge buttom and call the connect again", fg='red')
if connect:
# If the app is not registered and the button is not pressed,
# press ... |
Translate to logical and/or operators in C | def _BoolOp(self, t):
self.write("(")
s = " %s " % self.boolops[t.op.__class__]
interleave(lambda: self.write(s), self.dispatch, t.values)
self.write(")") |
Deleting an outcome group deletes descendant outcome groups and outcome links. The linked outcomes themselves are only deleted if all links to the outcome were deleted. Aligned outcomes cannot be deleted; as such, if all remaining links to an aligned outcome are included in this group's descendants, the group deletion ... | def delete_outcome_group_courses(request_ctx, course_id, id, **request_kwargs):
path = '/v1/courses/{course_id}/outcome_groups/{id}'
url = request_ctx.base_api_url + path.format(course_id=course_id, id=id)
response = client.delete(request_ctx, url, **request_kwargs)
return response |
Run the training procedure | def train(args):
log_header('Training network')
train_retriever(args) |
The server hostname to connect to. Accepts DNS entries or IP addresses | def server_hostname(self):
result = c_char_p(self.lib.iperf_get_test_server_hostname(self._test)).value
if result:
self._server_hostname = result.decode('utf-8')
else:
self._server_hostname = None
return self._server_hostname |
Store the value with the given key. Hash collisions should be handled with Linked List Chaining. Implement this. | def put(self, key, value):
hi = self.hash_index(key)
if self.storage[hi]:
current = self.storage[hi]
while current.next and current.key != key:
current = current.next
if current.key == key:
current.value = value
else:
... |
If something is not a list already make it one, otherwise simply return something | def aslist(something):
return something if isinstance(something, list) else [something] |
Instead of rendering each wall block, we create a single shape which can be drawn in a single call, rather than a call for each wall block | def create_wall_shape(self):
self.shape_walls = arcade.ShapeElementList()
self.shape_walls.center_x = 0
self.shape_walls.center_y = 0
self.shape_walls.angle = 0
point_list = []
color_list = []
# create the walls into a single shape
walls = self.g... |
Select CONFIG_DB PORT table changes, once there is a port configuration add/remove, notify observers | def handle_port_config_change(sel, asic_context, stop_event, port_mapping, logger, port_change_event_handler):
if not stop_event.is_set():
(state, _) = sel.select(SELECT_TIMEOUT_MSECS)
if state == swsscommon.Select.TIMEOUT:
return
if state != swsscommon.Select.OBJECT:
... |
Takes dictionaries of predicted and ground truth and returns confusion matrix | def confusion_matrix(predicted, gt):
tp = [k for k in predicted if predicted[k] and gt[k]]
tn = [k for k in predicted if not predicted[k] and not gt[k]]
fp = [k for k in predicted if predicted[k] and not gt[k]]
fn = [k for k in predicted if not predicted [k] and gt[k]]
return tp, tn, fp, fn |
Calculate the 15min delayed BTC market price in GBP. | def _get_btc_gbp_15min(self) -> None:
self._get_eur_gbp_last_daily()
self.btc_gbp_15min = self.btc_eur_15min * self.eur_gbp_last_day |
Test the popxl advanced getting / writing tensor data example that shows exactly when devicehost transfers occur | def test_documentation_popxl_adv_get_write(self):
filename = "tensor_get_write_adv.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) |
convert string to unicode | def str_to_unicode(text, encoding='utf-8'):
if isinstance(text, str):
return text.decode(encoding)
elif isinstance(text, unicode):
return text
else:
raise TypeError('str_to_unicode must receive a str or unicode object, got %s' % type(text).__name__) |
Fetches the metadata remote file REMOTE_METADATA_FILE and returns the metadata dict equivalent. | def _fetch_current_remote_metadata(conn):
content = _get(conn, REMOTE_METADATA_FILE)
metadata = json.loads(content) if content else {}
return metadata |
closing the second Tk object | def close_window(self, button_msgs):
if self.messages_window is not None:
self.messages_window.destroy()
self.messages_window = None
button_msgs.config(command=lambda: self.new_window_messages(button_msgs)) |
Occasionally, gvars get rendered to strings as, e.g., 4e06 + 1 instead of 0.000006(1.0). This makes a complete mess of trying to parse the a list of gvar which has been turned into a string, e.g., '[1(2) 1 + 2 0.003(2)]', since the usual str.split() separates '1 + 2' > ['1','+','2']. This function is a kludge which wor... | def kludge_gvars(mangled):
# Loop in reverse looking for '+-', but don't run off the end
for idx in range(len(mangled) - 1)[::-1]:
if mangled[idx + 1] == '+-':
reunited = ' '.join(mangled[idx:idx + 3])
# Throw away the used elements...
for _ in... |
Opens a text file | def txt_file_reader(path):
return open(path, encoding=cfg.ENCODING) |
get_board returns copy of the game's _board object | def get_board(self):
return self._board |
generate plumbum command given an incoming string | def parse_command(self, command):
split_list = command.split()
command = local[split_list[0]]
if 'python' in split_list[0]:
self.logger.debug(self.venv_pip)
command = self.venv_python
if split_list[0] == 'pip' or split_list[0] == 'pip3':
self.logger.d... |
Select font according to the input character | def selectfont(self, char):
charcode = ord(char)
for font in fontchecksequence:
for fontrange in fontmapping[font]:
if charcode in xrange(fontrange[0], fontrange[1]):
return font
return "Helvetica" # fallback, if no thirdparty font is installed |
Test user's dict is empty at first | def test_users_dictionary(self):
new_user = self.app
self.assertEqual(len(new_user.users), 0)
new_user.create_user()
self.assertIsInstance(new_user, User)
self.assertEqual(len(new_user.users), 1) |
The data type of the master array. | def dtype(self):
return self.config["dtype"] |
Convert a pygame surface into a cv image | def pygame_to_cvimage( surface ):
cv_image = cv.CreateImageHeader( surface.get_size(), cv.IPL_DEPTH_8U, 3 )
image_string = surface_to_string( surface )
cv.SetData( cv_image, image_string )
return cv_image |
Load QA data from night objects on disk | def load_data(self, inroot=None):
self.data = {}
# Load
for night in self.mexp_dict.keys():
qaNight = QA_Night(night, specprod_dir=self.specprod_dir, qaprod_dir=self.qaprod_dir)
qaNight.load_data()
#
self.data[night] = qaNight.data[night] |
saves classroomEntities in the ClassRoomData file | def saveClassroomData():
with open("ClassRoomData.txt","wb") as classroomData:
pickle.dump(classroomEntities,classroomData) |
Wrapper for reference pixel calculation | def _ref_pixel_calc(ifg_paths: List[str], params: dict) -> Tuple[int, int]:
lon = params[cf.REFX]
lat = params[cf.REFY]
ifg = Ifg(ifg_paths[0])
ifg.open(readonly=True)
# assume all interferograms have same projection and will share the same transform
transform = ifg.dataset.GetGeoTransform()
... |
Compute the offset polylines of centerline. Merge coordinates data (x & y information) with bed topography data (z information) to form a point cloud dataset in 3column xyz format. | def offset_all(x, y, beck_bed, t):
length = x.size
xyz1 = np.zeros((length, 3))
xyz2 = np.zeros((length, 3))
xyz1[:, 0] = np.copy(x)
xyz1[:, 1] = np.copy(y)
xyz1[:, 2] = np.copy(beck_bed[:, NUM])
allxyz = np.copy(xyz1)
offsetx = np.zeros((length, 2))
offsety = np.zeros((length, 2))
... |
Reset the obstacles' positions within the map (should be called when map is refreshed to clean the array) | def reset_obstacles(self):
self.obstacles = np.array([]) |
Should render to the console using a write_source function call on the internal step report's stdout_interceptor. | def test_render_to_console(self, _step: PropertyMock):
message = ' {{ a }} is not {{ b }}.'
_step_mock = MagicMock()
write_source = MagicMock()
_step_mock.report.stdout_interceptor.write_source = write_source
_step.return_value = _step_mock
step = exposed.ExposedStep()... |
generates and returns overlap graph from .paf files | def generate_graph(params):
alignedreads = read_paf(params, should_filter_paf=True)
aligned = [(t, h) for t, h, _ in alignedreads]
graph = nx.Graph()
graph.add_edges_from(aligned)
return graph |
Generate seed for the MFA TOTP device. | def generate_totp_seed(self, user_id, mfa_totp_device_id, **kwargs):
resource_path = "/users/{userId}/mfaTotpDevices/{mfaTotpDeviceId}/actions/generateSeed"
method = "POST"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"if_match"
]
... |
Add a session to the user's wishlist, returning a boolean. | def _addSessionToWishlist(self, request):
# Preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# Verify that the session actually exists
session = _getEntityByWebsafeKey(request... |
Return the Hamming distance between equallength sequences | def __hamming_distance(s1, s2):
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(el1 != el2 for el1, el2 in zip(s1, s2)) |
Called before anything else, i.e. just after installer controller creation. Return value is ignored. | def pre_installation(self):
pass |
Get the center of the projection. | def get_center(self,lonlat=False):
lon, lat = np.asarray(self.rotator.rots[0][0:2])*180/pi
if lonlat: return lon,lat
else: return pi/2.-lat*dtor, lon*dtor |
returns output of new layer | def l2_reg_create_layer(prev, n, activation, lambtha):
reg = tf.contrib.layers.l2_regularizer(lambtha)
init = tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG")
t = tf.layers.Dense(units=n, activation=activation,
kernel_initializer=init,
kernel_reg... |
Check {sysproid}.{appname}.{cell} is running. | def _test_app_running(self, running_set, sysproid, cell, appname):
full_app_name = '%s.%s.%s' % (sysproid, appname, cell)
self.assertIn(full_app_name, running_set) |
Test for template correctness | def test_for_template(self):
self.assertTemplateUsed(self.response, 'my_info_template.html') |
Setup authorization for whole API. Can be redefined for an endpoint. OpenAPI Authorization Specs | async def authorization(request):
# Decode tokens, load/check users and etc
# ...
# in the example we just ensure that the authorization header exists
return request.headers.get("authorization", "") |
Restore a database from a backup file. 'database' A database specification. 'backupfile' A backup file name. 'arguments' A list of the arguments to the GBAK without backup file name and database location. 'result' A 'Result' object. The outcome will be 'Result.PASS' when this method is called. The 'result' may be modif... | def RestoreDatabase(self, database, backupfile, arguments, result):
self.RunProgram("\""+self.__context["gbak_path"]+"\"",
[ self.__context["gbak_path"] ] + [ "-C ", backupfile ]
+ arguments + [ database ],
"", self.__context, result) |
Converts Strava datetime to epoch timestamp | def get_epoch(timestamp):
timestamp_dt = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ")
epoch = calendar.timegm(timestamp_dt.timetuple())
return epoch |
Rounding up to next 10th | def roundUP(x):
return int(ceil(x / 10.0)) * 10 |
A lightweight wrapper around `get_context()`. While this used to be the canonical method of instantiating a DataContext before 0.15.40, it is now recommended to use `get_context()`. | def BaseDataContext( # noqa: PLR0913
project_config: Union[DataContextConfig, Mapping],
context_root_dir: Optional[PathStr] = None,
runtime_environment: Optional[dict] = None,
cloud_mode: bool = False,
cloud_config: Optional[GXCloudConfig] = None,
# Deprecated as of 0.15.37
ge_cloud_mode: b... |
Performs a standard classification test with the given classifier. | def classify(dataset,classifier,feat_mask=None):
train = dataset.get_data('train',True)
X_train = train['x']
if feat_mask is not None:
X_train = X_train[:,feat_mask]
y_train = train['y']
classifier.fit(X_train,y_train)
test = dataset.get_data('test',True)
X_... |
Return the nth element of the pingpong sequence. >>> pingpong(7) 7 >>> pingpong(8) 6 >>> pingpong(15) 1 >>> pingpong(21) 1 >>> pingpong(22) 0 >>> pingpong(30) 6 >>> pingpong(68) 2 >>> pingpong(69) 1 >>> pingpong(70) 0 >>> pingpong(71) 1 >>> pingpong(72) 0 >>> pingpong(100) 2 >>> from construct_check import check >>> ch... | def pingpong(n):
# define two helper function, the recursion start from the bottom
# from 1 to n
"*** YOUR CODE HERE ***"
def positive(n, k, turn):
if turn == n:
return k
else:
if (k % 7 == 0) or has_seven(k):
return negative(n, k-1, turn + 1)
else:
return positive(n, k+1, turn + 1)
def negat... |
Set the RGB colour of an individual light in your Plasma chain. This will set all four LEDs on the Plasma light to the same colour. | def set_light(r, g, b):
for x in range(4):
set_pixel(x, r, g, b)
"""Output the buffer """
_sof()
for pixel in pixels:
r, g, b, brightness = pixel
_write_byte(0b11100000 | brightness)
_write_byte(b)
_write_byte(g)
_write_byte(r)
_eof() |
Return True if the campaign authorizes the user to provide data to the campaign. This is the case if the user owns or works for the campaign. Otherwise, return False. | def authorizes(self, user):
return self.owner == user or self.workers.filter(pk=user.id).exists() |
A humanreadable description of the new Role. | def description(self) -> pulumi.Output[str]:
return pulumi.get(self, "description") |
Calculates the solar elevation angle for a specific time. | def solar_elevation(self, dateandtime=None):
if self.astral is None:
self.astral = Astral()
if dateandtime is None:
dateandtime = datetime.datetime.now(tz=self.tz)
return self.astral.solar_elevation(dateandtime, self.latitude, self.longitude) |
Tests that stock and price fields must be numbers | def test_stock_and_price_must_be_numbers(self):
resp = self.admin_register()
reply = self.admin_login()
token = reply['token']
product = dict(
prod_name='NY_denims',
category='denims',
stock='stock',
price='money'
)
resp = s... |
after _send_celery_mail finishes, the tenant should be cleared again | def test_tenant_setup_celery_reset(self):
msg = mock.Mock()
tenant = mock.Mock()
tenant.client_name = 'mock-tenant'
_send_celery_mail(msg, tenant, send=False)
self.assertFalse(hasattr(properties, 'tenant'))
self.assertEqual(properties.tenant_properties, {}) |
The arguments into which the python args and kwargs are collected | def args(self):
return self._parse_args |
itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(itkLightObject obj) > itkTernaryAddImageFilterIUL2IUL2IUL2IUL2 | def itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args):
return _itkTernaryAddImageFilterPython.itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args) |
Poll tests for completion. When one finishes, start another one if there are more to run. Stop when all are finished. | def poll_tests(self):
for i, test in enumerate(self.tests):
if test.process.poll() is not None:
self.check_test(test)
self.tests.pop(i)
if self.test_numbers:
self.start_next_test() |
Wrapper for requests GET method | def _get(self, *args, **kwargs):
return self._request('get', *args, **kwargs) |
DEPERECIATED FUNCTION PLEASE USE active field of subscription | def is_active(self):
return self.active |
Used to allow a user to edit their own profile. | def edit_profile(request):
user = request.user
profile = Profile.objects.for_user(user)
if request.method != 'POST':
profile_form = ProfileForm(instance=profile)
user_form = UserForm(instance=user)
else:
profile_form = ProfileForm(request.POST, instance=profile)
... |
Sets the dual solution for a semidefinite variable. putbarsj(self,whichsol_,j_,barsj_) | def putbarsj(self,whichsol_,j_,barsj_):
_barsj_minlength = self.getlenbarvarj((j_))
if self.getlenbarvarj((j_)) > 0 and barsj_ is not None and len(barsj_) != self.getlenbarvarj((j_)):
raise ValueError("Array argument barsj is not long enough: Is %d, expected %d" % (len(barsj_),self.getlenbarvarj((j_))))
... |
Computes the (exact or approximate) Wasserstein distance of order 1 or 2 between empirical distributions | def wass_distance(X, Y, order=2, type='exact'):
if order == 2:
M = ot.dist(X, Y)
elif order == 1:
M = ot.dist(X, Y, metric='euclidean')
else:
raise Exception("Order should be 1 or 2.")
a = np.ones((X.shape[0],))/X.shape[0]
b = np.ones((Y.shape[0],))/Y.shape[0]
if type == ... |
Return a list of (name, arguments, return type) for all function definition2 found in code. Arguments are returned as [(type, name), ...]. | def find_functions(code):
regex = "^\s*" + re_func_decl + "\s*{"
funcs = []
while True:
m = re.search(regex, code, re.M)
if m is None:
return funcs
rtype, name, args = m.groups()[:3]
if args == 'void' or args.strip() == '':
args = []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.