anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Sets the filters relative flag
public function relative($relative) { if (is_bool($relative)) { $this->relative = $relative; } return $this->relative; }
/ For a given Special Offer and an expiration date generate for each Recipient a Voucher Code
public function codeGeneration(Request $request) { $offer = new Offer([ 'name' => $request->input('offer_name'), 'discount' => $request->input('discount'), 'expiry' => Carbon::createFromFormat('d/m/Y', $request->input('expiry')), ]); $offer->save(); ...
Sets a callback to handle after the route callback.
public function after(callable $callback): Route { $current = $this->getOption('after_middlewares'); $current[] = $callback; $this->setOption('_after_middlewares', $current); return $this; }
/ This method is used when a user has added a restaurant Dont forget to add a query for type!
public function saveNewRestaurant(Restaurant $res){ $city = strtolower($res->getCity()); if ($city == 'göteborg' || $city == 'goteborg' || $city == 'gÖteborg'){ $city = 'gothenburg'; } $res->setCity($city); /* * This is if we're going to add a search before the insert to check if the rest exists $que...
/ Delete all resources.
public function deleteAllResources() { $this->resources = array(); }
Base class for controllers
protected function isPostRequest() { return $_SERVER['REQUEST_METHOD'] == 'POST'; }
Check if the specified configuration key is defined
public function hasConfig($key);
Loads the user info, how many favorites and how many replies, etc. the audio has. And adds it to the array.
public static function complete(array $audio) { $has = function ($key) use ($audio) { return array_key_exists($key, $audio); }; if ($has('user_id')) { $audio['user'] = Users::get($audio['user_id']); unset($audio['user_id']); } if ($has('id'))...
Return the group that owns this permission
public function group() { return $this->belongsTo('Bocapa\Permissions\Models\Group'); }
Supprime le panier de la session
public function remove() { return $this->session->remove('cart'); }
Get requiredbooleans set higher up in the form structure.
protected function isRequiredFromAncestor($key) { if ($ancestor = $this->getControlBlockContainer()) { return $ancestor->isRequired($key); } return null; }
The latest version for in place update. The current appliance can be updated to this version using the API or m4c CLI. Generated from protobuf field .google.cloud.vmmigration.v1.ApplianceVersion in_place_update = 2;
public function setInPlaceUpdate($var) { GPBUtil::checkMessage($var, \Google\Cloud\VMMigration\V1\ApplianceVersion::class); $this->in_place_update = $var; return $this; }
Funciones Get y Set de la Clase clQuery
public function getStrPaginaSiguiente() { return $this->strPaginaSiguiente; }
Run the database seeds.
public function run() { $titles = ['Нижние модули', 'Верхние модули']; foreach ($titles as $title) { $title = [ 'title' => $title, ]; \App\Models\TypeModules::create($title); } }
STI 84189 Retorna as mensalidades vencidas
public function getMensalidadesVencidas($strContratos, $maiorDataRescisao) { $sql = " SELECT distinct CASE WHEN titnfloid IS NOT NULL THEN ( SELECT nflno_numero || '/' || nflserie AS nota ...
Filter the query on the id_user_created column Example usage: $query>filterByIdUserCreated(1234); // WHERE id_user_created = 1234 $query>filterByIdUserCreated(array(12, 34)); // WHERE id_user_created IN (12, 34) $query>filterByIdUserCreated(array('min' => 12)); // WHERE id_user_created > 12
public function filterByIdUserCreated($idUserCreated = null, $comparison = null) { if (is_array($idUserCreated)) { $useMinMax = false; if (isset($idUserCreated['min'])) { $this->addUsingAlias(CiSettingsTableMap::COL_ID_USER_CREATED, $idUserCreated['min'], Criteria::GR...
Generate a test message.
protected function getMessage() { //return new \Swift_Message('Test subject', 'Test body.'); }
/ Check the license key
public function getChecks() { $result = (version_compare(phpversion(), '5.2.8', '>=')) ? self::CHECK_OK : self::CHECK_ERROR; $this->addResult('system', 'PHP version', $result, "PHP version 5.2.8 or higher is needed. A latest PHP version is always recommended."); $current = ini_get('memory_l...
Remove the specified resource from storage.
public function destroy($id) { $document = Document::find($id); $document->file->delete(); $document->delete(); return response()->json([ 'Документ №' . $document->id . ' удален' ]); }
lay du lieu form
public function toFormData() { $data = $this->toArray(); return $data; }
Store a newly created resource in storage.
public function store(Request $request) { // /*$this->validate($request,[ 'name' => 'required|max:255' ]); $category = new Category; $category->name = $request->name; $category->save(); Session::flash('success', ' New Category has been created')...
checks if can use cache
protected function useCache() { if (isset($_COOKIE['nc']) && $_COOKIE['nc'] == 1) { return FALSE; } if (isset($_GET['nc']) && $_GET['nc'] == 1) { return FALSE; } return TRUE; }
Display a listing of the resource.
public function customerDataRequest() { return view($this->_config['view']); }
Register an updating model event with the dispatcher.
public static function updating($callback, $priority = 0) { static::registerModelEvent('updating', $callback, $priority); }
Gets the screenshot id's associated with the addon
public function getScreenshots() { return ScreenshotManager::getScreenshotsFromAddon($this->id); }
Formats a Mysql DateTime string in the specified format.
public static function Date($Timestamp = '', $Format = '') { // Was a mysqldatetime passed? if (!is_numeric($Timestamp)) $Timestamp = self::ToTimestamp($Timestamp); if (!$Timestamp) $Timestamp = time(); // return ' '; Apr 22, 2009 - found a bug where "Draft Saved At X" returned...
Test case for addVendorComplianceSurvey Create a vendorComplianceSurvey.
public function testAddVendorComplianceSurvey() { }
Test Request GET (orchestra)/users/view/1 without auth
public function testGetSingleUserPageWithoutAuth() { $response = $this->call('orchestra::users@view', array(1)); $this->assertInstanceOf('Laravel\Redirect', $response); $this->assertEquals(302, $response->foundation->getStatusCode()); $this->assertEquals(handles('orchestra::login'), $response->foundati...
Get source image url
public function getSrcMediaImage() { return $this->_designerHelper->getSrcMediaImage(); }
Update record activity status.
function update_record_status($id, $status, $table, $key) { $sql = "UPDATE ".TB_PREF.$table." SET inactive = " . ((int)$status)." WHERE $key=".db_escape($id); db_query($sql, "Can't update record status"); }
/ DELETING TRANSACTION SAVING(TABUNGAN) DELETE SETORAN TUNAI
public function delete_setoran_tunai() { $trx_detail_id=$this->input->post('trx_detail_id'); $data_trx_account_saving=$this->model_transaction->get_trx_account_saving_by_trx_detail_id($trx_detail_id); if(count($data_trx_account_saving)==1){ $data_trx_account_saving=$data_trx_account_saving[0]; $account_sav...
Sets the field by wrapping a primitive type in a Google\Protobuf\DoubleValue object. Allows throttling dispatch of tasks from this queue Generated from protobuf field .google.protobuf.DoubleValue max_tasks_per_second = 1;
public function setMaxTasksPerSecondUnwrapped($var) { $this->writeWrapperValue("max_tasks_per_second", $var); return $this;}
get the id of selected user to edit
public function deleteAction(){ $id = $this->filterInt($this->_params[0]); $supplier = SupplierModel::getByPK($id); if($supplier === FALSE){ $this->redirect('/suppliers'); } $this->language->load('suppliers.messages'); if($supplier ->delete()){ ...
Begin querying the model on a given datasource.
public static function on($datasource = null) { // First we will just create a fresh instance of this model, and then we can // set the datasource on the model so that it is be used for the queries. $instance = new static; $instance->setDatasource($datasource); return $inst...
Set icon paths Sets the URLs and file system paths for the social media icons, which can also be customized via filters.
private function setIconPaths() { // Directory URL and path $plugin = CGIT_SOCIALIZE_PLUGIN; $dir = 'icons'; $url = plugin_dir_url($plugin) . $dir; $path = plugin_dir_path($plugin) . $dir; // Apply filters for customization $ext = apply_filters('cgit_socializ...
Test to ensure a user receives their own profile data
public function testGetOwnProfile() { $url = "http://127.0.0.1/app_test.php/profile/view/bucky-barnes"; $username = 'profileBucky@gmail.com'; $password = 'password'; $response = \Httpful\Request::get($url)->basicAuth($username, $password)->send(); $this->assertEqu...
Show the form for editing the specified resource.
public function edit(Category $category,$id) { $category=Category::get($id); return view('admin.category.update',compact('category')); }
return parent::tableName(); // TODO: Change the autogenerated stub
public static function tableName() { return 'category'; }
Set the value of DOCUMENT_PRODUCT_NCM
public function setDocumentProductNcm(int $document_product_ncm) { $this->collection->put('document_product_ncm', (string) $document_product_ncm); }
This is the delete.
public function handleGrievanceDelete($id) { $Grievance = new Grievance; $re=$Grievance->deleteGrievance($id); SentryHelper::setMessage('Grievance Deleted....'); return Redirect::to('grievance/list'); }
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