anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc....
Mark a component as needing a rerender, adding an optional callback to a list of functions which will be executed once the rerender occurs.
function retrieveFooterIcon(iconNum) { iconNum = iconNum ? iconNum : 0 switch(iconNum) { // Devices Cards case '1': return <FontAwesomeIcon icon={faMapMarkerAlt} style={{width: '20px', height: '20px'}} />; // Warehouses Cards case '2': return <FontAwesomeIcon icon={faWare...
Retrieving an icon for the card's footer:
function squareTest(t){ //t=1 for player1, t=2 for player2 j=1; while (gotSquare==0 && j<n+1){ i=1; while (gotSquare==0 && i<n+1){ if (state[i][j]==t){ for (l=j;l<n+1;l++){ if (l==j){start=i+1}else{start=1;} for (k=start;k<n+1;k++){ if (state[k][l]==t){ if ((0<k+l-j && k+l-j<n+1 &&...
test for square code
function formatQueryParams(params) { const queryItems = Object.keys(params).map( (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}` ); return queryItems.join("&"); }
combines searchURL with user input
function changeEmojiWeek(){ var em = document.getElementById("weekList").childElementCount; if(em == 0){ document.getElementById("emojiWeek").innerHTML = "😀"; }else if(em < 3){ document.getElementById("emojiWeek").innerHTML = "🙄"; }else if(em < 5){ document.getElementById("emojiWeek").innerHTML...
This does the same as the function above, but for the weekList table.
function getIt(id) { var result; result = document.getElementById(id).value.trim(); return result; }
Get the value for the table cell
setCurrentRouteName(routeName){ currentRoute = routeName; currentPoiIndex = null; }
set xurrent route name
function toggleDetails() { const details = d3.select("#details"); details.style("display", details.style("display") === "none" ? "block" : "none" ); d3.select("#guide strong").text( details.style("display") === "none" ? "show" : "hide" ); }
Show or hide the ondemand details panel.
function mergeHook ( parentVal, childVal ) { var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res }
Hooks and props are merged as arrays.
function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; }
Convert Stringformatted options into Objectformatted ones
createMultiplayerIO() { this.socket.on("pong", (pingTimestamp) => { var pongTimestamp = Date.now(); var ping = pongTimestamp - pingTimestamp; this.events.emit('ping', ping); }); this.otherPlayers = this.physics.add.group(); this.socket.on('currentPlayers', function (data) { this.createAllPlayers(...
Partial class which not works on its own
function createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/ { var state = draggable.state; var isStart = !(0, _shims.isNum)(state.lastX); var node = findDOMNode(draggable); if (isStart) { // If this is our first move, use the x and y as last coords. return...
Create an data object exposed by 's events
setOption(internal_name, option) { if (IsString(internal_name, true) && IsObject(option)) { PopLog.info(this.name, `Option set for ${internal_name}`, option); this.asset.option.set(internal_name, option); } }
Attach a set of options to widget
function getExternalId(story) { $.ajax({ url: pivotalProjectUrl + "/stories/" + story.getAttribute('data-id'), async: false, dataType: 'json', success: function(data) { id = data.external_id; if(id !== null) { jiraUrl = jiraBase + id; ...
Grabs the external_id from the Pivotal API
isWorseThan(other) { return !this.isBetterThan(other); }
So we can use nice names
makeBody(){ // an object for mail let mail; mail = new mailComposer({ to: this.to, text: this.body, subject: this.sub, textEncoding: "base64" }); //Compiles and encodes the mail. mail.compile().build((err, msg) => { if (err){ return console.log('Error compiling email ' + error); } ...
Creates the mail body and encodes it to base64 format.
static findOneWhereOrder(from, select, where, orderBy, callback) { findOne(from, where, select, orderBy, callback); }
FROM, SELECT, WHERE, ORDERBY, CALLBACK
function fetchImage2base64 (path, dest, key) { return limitedFetch(`${domain}${path}`) .then(r=>r.buffer()) .then(buf=>{ const imgdom = new JSDOM(buf); const src = imgdom.window.document.querySelector('img').getAttribute('src'); const imageBuffer = decodeBase64Ima...
Fetch an image (html img snippet with inline base64 src attribute) snippet and save the image as file
displayPath() { // Show start and end waypoints. let startMarker = new google.maps.Marker({ position: this._navPath.waypoints[0], map: this._map, icon: { path: google.maps.SymbolPath.CIRCLE, scale: 5, fillCo...
Display path on map, along with markers for start and end waypoints, and for the next waypoint.
constructor() { super(); }
Instance of the element is created/upgraded. Use: initializing state, set up event listeners, create shadow dom.
function average(numbers) { let sum = 0; numbers.forEach(function(arrNum) { sum = arrNum += sum; }); let arrAvg = sum/numbers.length; return arrAvg; }
Compute the average with .forEach()
function toTitleCase(str) { return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); }
helper function to make title case
function RSAEncrypt(text) { var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); if(m == null) return null; var c = this.doPublic(m); if(c == null) return null; var h = c.toString(16); if((h.length & 1) == 0) return h; else return "0" + h; }
Return the PKCS1 RSA encryption of "text" as an evenlength hex string
function deleteCourse() { let courseId = $(this).attr('data-id'); coursesService.deleteCourse(courseId) .then(() => { showInfo('Course deleted.'); loadMyCourses(); // showView('Catalog'); }).catch(handleError); }
LOGIC TO DELETE COURSE
fillForm(fSalut) { this.salutationForm.setValue({ firstname: fSalut.firstname, gender: fSalut.gender, // language: fSalut.language, language: this.convertLanguage(fSalut.language), lastname: fSalut.lastname, letterSalutation: fSalut.letterS...
Fill the formatted Salutation in the Form
isEmpty() { return this.heap.length === 0; }
check if the heap is empty
function fizzBuzz(fizz, buzz) { // initialize an array to hold our results let resultsArray = []; // use a for loop to replace words divisable by 3, 5, or both with fizz, buzz, or fizzbuzz respectively // use the continue statement to exit the current iteration of the for loop and continue to the next ...
logic function calculate which numbers to replace with fizz/buzz
function astFromValue(value, type) { // Ensure flow knows that we treat function params as const. var _value = value; if (type instanceof _definition.GraphQLNonNull) { var astValue = astFromValue(_value, type.ofType); if (astValue && astValue.kind === Kind.NULL) { return null; } return astV...
Produces a GraphQL Value AST given a JavaScript value. A GraphQL type must be provided, which will be used to interpret different JavaScript values. | JSON Value | GraphQL Value | | | | | Object | Input Object | | Array | List | | Boolean | Boolean | | String | String / Enum Value | | Number | Int / Float | | Mixed | E...
function generatePathLinkout(pathArray) { // Build an html string of the paths // pathArray is a list of dicts for each edge in the path: // pathArray[i] gives a dict for the support of edge i // pathArray[i][stmt type j] is a list of all statements of type j supporting edge i // pathArray[i][stmt type j][k] ...
Function to put stmts from path in a HTML format with linkouts
gotoCheckLimit(current_line, n_item, line_limit) { if (n_item > 0 && current_line < line_limit) { return true; } else if (n_item < 0 && current_line > line_limit) { return true; } else { return false; } }
gotoCheckLimit is configured only for [n_item = +1 or 1] it may be extended later
initViews() { let viewsId = []; //array used for interface cameras dropdown for (var key in this.graph.views) { if (this.graph.views.hasOwnProperty(key)) { var view = this.graph.views[key]; if (view.type === "ortho") { let v = new CGFcame...
Initializes the scene views with the values read from the XML file.
function handleClickOutside(event) { if (ref.current && !ref.current.contains(event.target) && menuButtonRef.current && !menuButtonRef.current.contains(event.target) && props.isColumnNavBarDisplayed) { // If outside, then close the ul list props.requireColumnNavBarDisplayedToggle(); ...
Alert if clicked on outside of ul list and menu button
function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); }
format date using native date object
greet() { console.log('hello' + ' ' + this.firstname + ' ' + this.lastname); }
public function avialble for evryone just like function prototype
function fieldPathFromArgument(methodName, path) { if (path instanceof FieldPath$1) { return path._internalPath; } else if (typeof path === 'string') { return fieldPathFromDotSeparatedString(methodName, path); } else { var message = 'Field path arguments must be of ty...
Helper that calls fromDotSeparatedString() but wraps any error thrown.
function interpolate(from, to, direction, stream) { circleStream(stream, radius, delta, direction, from, to); }
TODO optimise for this common case
function getRegularCustomerAccountsAndValue(jsonFeed){ var regValues = new Array(4); regValues[0] = jsonFeed[3]; regValues[1] = jsonFeed[4]; regValues[2] = jsonFeed[1]; regValues[3] = jsonFeed[1]; return regValues; }
replace this once we get the database in place
Remove the specified resource from storage.
public function destroy(keterlambatan $keterlambatan) { // }
Generates a new configuration name based on the provided parameters
protected function generateConfigurationName(array $vclList = null, $prefix = 'load') { if (!$vclList) { $vclList = $this->getVclList(); } $index = 1; foreach ($vclList as $name => $status) { if (strpos($name, $prefix) !== 0) { continue; ...
Sets the Icontact Prospect Last Name attribute value.
public function setLastName(string $last_name = null) : CNabuDataObject { $this->setValue('nb_icontact_prospect_last_name', $last_name); return $this; }
Update the specified resource in storage.
public function update(Request $request, Category $category) { $path = $category->title_image; if($request->file('image')) { if(Storage::exists($category->title_image && $category->title_image !== "public/1.jpg")) { Storage::delete($category->title_image); } ...
The agency the account belongs to. Technically the owner should also be part of the agency.
public function agency(): BelongsTo { return $this->belongsTo(Agency::class); }
Set the max Chars that can be in each line
public function setMaxLineLength(?int $maxLineLength): void { $this->maxLineLength = $maxLineLength; }
Constructs the forum settings.
public function __construct($forumManager) { $this -> forumManager = $forumManager; $this -> db = $forumManager -> getDatabase(); }
Show the form for creating a new resource.
public function create() { if(Auth::check()){ $user_id = auth::user()->id; if($user_id==2){ return redirect('/delivery/payment'); } } $category = Category::all(); $subcategory = SubCategory::all(); return view('admin_ui....
This is the unique name corresponding to the Pay Connector installed in the Twilio Addons. Learn more about [ Connectors]( The default value is `Default`.
public function setPaymentConnector(string $paymentConnector): self { $this->options['paymentConnector'] = $paymentConnector; return $this; }
Indicates whether this content is family friendly.
public function setIsFamilyFriendly($isFamilyFriendly) { $this->properties['isFamilyFriendly'] = $isFamilyFriendly; return $this; }
quitar caracteres especiales para evitar sqlinjection
function decode($string){ $nopermitidos = array("'",'\\','<','>',"\"","%"); $string = str_replace(" ","",$string); $string = str_replace($nopermitidos, "", $string); return $string; }
Extension Functions ========================================================= Activate Extension
public function activate_extension() { // Check for Freeform install if ( ! $this->EE->db->table_exists('freeform_fields')) { return FALSE; } $hooks = array( 'freeform_module_insert_begin' => 'insert_new_entry' ); foreach ($hooks as $hook => $method) { $this->EE->db->insert( 'exp_exte...
Create tables in db
public static function up(){ DBW::create('Comment',function($t){ $t -> varchar('name') -> text('message') -> tinyint('public_flag') -> datetime('timestamp'); }); }
Store a newly created resource in storage.
public function store(KitchenRecipeCreateRequest $request) { $data = $request->input(); $data['user_id'] = Auth::user()->id; $recipe = (new KitchenRecipe())->create($data); if($recipe){ return redirect()->route('kitchen.admin.recipes.edit', [$recipe->id]) ...
Validate and update the given user's profile information.
public function update($user, array $input) { Validator::make($input, [ 'phone' => ['required', 'numeric', 'digits_between:1,15'], 'address' => ['required', 'string'], 'city' => ['required', 'string'], 'country' => ['required', 'string'], ])->validate(...
Removes singleuse query args derived from executed actions in the admin.
function affwp_remove_query_args( $query_args ) { // Prevent certain repeated AffWP actions on refresh. if ( isset( $_GET['_wpnonce'] ) && ( isset( $_GET['affiliate_id'] ) || isset( $_GET['creative_id'] ) || isset( $_GET['referral_id'] ) || isset( $_GET['visit_id'] ) ) ) { $query_args[] = '_wpn...
Show the form for editing the specified resource.
public function edit(Employee $employee) { // }
Gave up on the Eloquent relational model
public function getLeadVolunteers($ProjectID) { return $project_leads = Volunteer::join('project_volunteer_role', 'volunteers.VolunteerID', '=', 'project_volunteer_role.VolunteerID') ->join('project_roles', 'project_volunteer_role.ProjectRoleID', '=', 'project_roles.ProjectRoleID') ...
Returns information for photo by given id.
abstract public function getById($id);
Return current logged in user
public static function current(): ?User { if ($userId = get_current_user_id()) { return new static($userId); } return null; }
Display the specified resource.
public function show($id) { // }
Get the plan price status
public function hasPrice() { return $this->amount_month || $this->amount_year; }
Find object by primary key.
protected function findPkComplex($key, ConnectionInterface $con) { // As the query uses a PK condition, no limit(1) is necessary. $criteria = $this->isKeepQuery() ? clone $this : $this; $dataFetcher = $criteria ->filterByPrimaryKey($key) ->doSelect($con); ret...
Create tmp file und return its FileInfo.
protected function getDeletableFileInfo() { $file = tempnam('.', ''); $spl = new \SplFileInfo($file); return $spl; }
module should throw Exception in case of merge is not possible
protected function merge(User $target, User $source) { $event = new Am_Event(Am_Event::USER_BEFORE_MERGE, array( 'target' => $target, 'source' => $source )); $this->getDi()->hook->call(Am_Event::USER_BEFORE_MERGE, $event); $this->getDi()->db->query('UPDATE ?_...
Creates a cms page
protected function createPage($name, $hierarchy, Page $parent = null): Page { $page = new Page(); $page->setParent($parent); $page->setHierarchy($hierarchy); $page->setPublish(1); $page->setRedirectType(0); $page->setSection(''); $page->addShop($this->shop); ...
Form render function Construct and output the form we have gathered info about.
public function render($buffer=false) { //-------------------------------------------------------- // Inset Value Buffer //-------------------------------------------------------- ob_start(); //-------------------------------------------------------- // Data Output Buffer //-----------------------------...
Commits all pending changes.
protected function commit() { $this->get_search_client()->commit(); }
Traverse an \StdClass object recursively in search of the needed property
private function traverseGet(\StdClass $json, array $chain, $index = 0) { $property = $chain[$index]; if (!property_exists($json, $property)) { return false; } if (isset($chain[$index + 1])) { return $this->traverseGet($json->{$property}, $chain, $index + 1); ...
Returns the static model of the specified AR class.
public static function model($className = __CLASS__) { return parent::model($className); }
Checks whether the transaction info for the transaction linked to the order is already linked to another order.
protected function checkTransactionInfo(Mage_Sales_Model_Order $order) { /* @var PostFinanceCheckout_Payment_Model_Entity_TransactionInfo $info */ $info = Mage::getModel('postfinancecheckout_payment/entity_transactionInfo')->loadByTransaction( $order->getPostfinancecheckoutSpaceId(), $or...
Execute the console command.
public function fire() { $rows = Report::getReport(); $table = new Table($this->output); $table->setHeaders(array_shift($rows)); array_walk($rows, function($row) use ($table) { $table->addRow($row); }); $table->render(); }
Update the specified resource in storage.
public function update(Request $request, $id) { $film = Film::findOrFail($id); $film->update($request->all()); return $film; }
Set the nom marital.
public function setNomMarital($nomMarital) { $this->nomMarital = $nomMarital; return $this; }
END VERIFIKASI REKENING PEMBIAYAAN BEGIN ASURANSI SETUP
public function datatable_insurance_setup() { /* Array of database columns which should be read and sent back to DataTables. Use a space where * you want to insert a non-database field (for example a counter or static image) */ $aColumns = array( '','mfi_account_insurance.account_insurance_no', 'mfi_cif.nama...
Display the specified resource.
public function show(Request $request) { $user_id = $request->user_id; $validation = Validator::make( $request->all(), [ 'status_id' => 'required|integer|numeric', ] ); $errors = $validation->errors(); if($validation->fails...
Determine which templates support layouts.
function layout_get_templates_options_object( ) { $ret = new stdClass(); $template_option = $this->get_option('templates'); if ($template_option) { foreach($template_option as $file => $layout) { $layout_templates[] = $file; } } $templates = wp_get...
Show the form for creating a new resource.
public function create() { }
Initializes context with parameters from behat.yml.
public function __construct(array $parameters) { $this->parameters = $parameters; }
Return xpath of dropdown button.
private function getButtonXpath() { return sprintf(Dropdown::BUTTON_XPATH,$this::$keyWord); }
Returns the controller class name from provided route
public function inflect(Route $route): ControllerDispatch { $arguments = $this->extractAttributes($route); return $this->createDispatch($arguments); }
Get Address type Type of the address. This is a code. You can find the possible values at Guidelines
public function getAddressType(): ?string { return $this->AddressType ?? null; }
Returns the mood for the current post. The mood is set by the 'mood' custom field.
function unique_entry_mood_shortcode( $attr ) { $attr = shortcode_atts( array( 'before' => '', 'after' => '' ), $attr ); $mood = get_post_meta( get_the_ID(), 'mood', true ); if ( !empty( $mood ) ) $mood = $attr['before'] . convert_smilies( $mood ) . $attr['after']; return $mood; }
Testing the user search
public function testSearchUser() { echo "\nTesting user search..."; //$url = TestServiceAsReadOnly::$elasticsearchHost . "/CIL_RS/index.php/rest/users?search=Vicky"; $url = TestServiceAsReadOnly::$elasticsearchHost . $this->context."/users?search=Vicky"; $response = $this->c...
Gestion information de l'item
public function setData(Array $texts, Array $files){ $this->_data = array_merge($this->_structure,$this->_data); $this->setTexts($texts); $newFiles = $this->setImages($files); $this->saveData(); // Information de la collection $collectionData = $this->_collectionAdministr...
End Score Operator Comment for problem operator
function get_CommentsByProb($probId) { $query = "SELECT c.id,c.userID,u.name,u.nickname,u.photoPath,c.content,c.time FROM commentsforproblem AS c,user AS u where c.stat=0 and c.probID=$probId AND c.userID=u.id AND u.stat=0 order by c.time;"; return mydb_query_return_double_array($query); }
Create a new rule instance.
public function __construct(PriceList $price_list = null) { $this->price_list = $price_list; }
Save Categoriees to Reservation category database
function savecat(){ $data =[ 'reservation_category' => $_POST['reservation_category'], 'category_description' => $_POST['category_description'], 'reservation_duration' => $_POST['reservation_duration'] ]; insert( 'reservation_categories', $data ); redirect( route('dashboard/...
Show Willow fancy Banner
public static function fancyBanner(CLImate $cli): void { // Display Willow's fancy message $cli->forceAnsiOn(); $cli->green()->border('*', 55); $cli->addArt(__DIR__); $cli->bold()->lightGreen()->animation('willow')->speed(200)->enterFrom('left'); $cli->backgroundGreen()...
Get the validation rules that apply to the request.
public function rules(): array { return [ 'total' => 'nullable|numeric', 'price' => 'nullable|numeric', 'note' => 'nullable|string', //{{REQUEST_RULES_NOT_DELETE_THIS_LINE}} ]; }
Initialises the search engine configuration.
public function __construct() { parent::__construct(); $curlversion = curl_version(); if (isset($curlversion['version']) && stripos($curlversion['version'], '7.35.') === 0) { // There is a flaw with curl 7.35.0 that causes problems with client reuse. $this->cacheclient =...
Load controller. Returns true on success and false otherwise
public function loadCtrl($ctrlName, $use_dir = null) { if ($use_dir === null) { $use_dir = $this->app->conf['mvc']['use_subdirs']['controllers']; } $filename = $this->app->app_path.$this->app->conf['mvc']['dirs']['controllers'].($use_dir ? '/'.$ctrlName : '').'/'.$ctrlName.'.ctrl.php'; if ($this->app->mode...
Show the form for editing the specified resource.
public function chooseRevision(Request $request, $doc) { $doc = Document::findBySlug($doc); if (!$doc) { return response(view('docs.404'), 404); } $this->authorize('manage', $doc); $doc->load('updatedBy', 'createdBy'); $results = $doc->revisionHistory->sortByDesc('created_at'); $paginator = new L...
Get the route key for the model.
public function getRouteKeyName() { return 'uuid'; }
Set a given configuration value.
public function set($key, $value) { }
Read data from database.
public function read(){ $this->_getDAO(false); if($array = $this->dao->read($this->user->getID(), $this->ident)){ $this->_setFromArray($array); return true; } else { return false; } }
Gets the page layout
public function getLayout();
/ Function: data returns content of files stored as gzipped base64 encoded strings. This function is replaced by the build command. See Also:
function data($name) { switch ($name) { //START_OF_DATA case 'index': return ''; case 'system/languages/languages.json': return file_get_contents('system/languages/languages.json'); //END_OF_DATA } if ($zip) return gzdecode(base64_decode($zip)); }
Returns table with associative array of row values. Example: [ [id => 1, name => Bonifac], [id => 2, name => Michael] ]
public function fetchAll(): array { if($this->database === null) { throw new \Exception('Database connection has not been set.'); } $this->queryProperty->setFetchType($this->queryProperty::FETCH_ALL); $cachedResult = $this->checkQueriesCache($this->queryProperty); ...
Get paging view for a collection of events.
private function getView(Collection $collection) { $view = []; foreach (['first', 'previous', 'next', 'last'] as $key) { $url = $collection->get($key); if ($url) { $info = parse_url($url); if (!empty($info['query'])) { parse_str($info['query'], $query); $view[$ke...
Checks if a given email is already in the database
public function usernameExists($email) { $stmt = $this->db->prepare("SELECT count(email) FROM users where email=?"); $stmt->execute(array($username)); if ($stmt->fetchColumn() > 0) { return true; } }
Set pricing attributes for a service
public function actionAddPricing($id) { $model = $this->findModel($id); $motherMatrix = new ServiceAttributeMatrix($model); return $this->render('add-pricing', [ 'model' => $model, 'motherMatrix' => $motherMatrix, ]); }
/start of login request
public function login(Request $request){ $rules = [ 'email' => 'required|email', 'password'=> 'required' ]; $validator = Validator::make(request()->all(),$rules); if($validator->fails()){ result( 401, $validator->messages(), null); } e...