Dataset Viewer
Auto-converted to Parquet Duplicate
input_code
stringlengths
19
22.3k
target_completion
stringlengths
10
22.2k
task
stringclasses
2 values
lang
stringclasses
6 values
complete go: func (x *DiagnosticReport) UnmarshalJSON(data []byte) (err error) { x2 := diagnosticReport{} if err = json.Unmarshal(data, &x2); err == nil { if x2.Contained != nil { for i := range x2.Contained { x2.Contained[i] = MapToResource(x2.Contained[i], true)
} } *x = DiagnosticReport(x2) return x.checkResourceType() } return }
completion
go
complete java: public void setupCellPositoin(final CellPosition address) { ArgUtils.notNull(address, "address");
setupCellPositoin(address.getRow(), address.getColumn()); }
completion
java
complete java: public Observable<InboundNatRuleInner> beginCreateOrUpdateAsync(String resourceGroupName, String loadBalancerName, String inboundNatRuleName, InboundNatRuleInner inboundNatRuleParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, loadBalancerName, inboundNatRuleName,...
return response.body(); } }); }
completion
java
complete php: public function transform($blockCollection, array $params = array())
{ $facade = $this->newFacade(); foreach ($blockCollection as $block) { $facade->addBlock($this->getContext()->transform('block', $block)); } return $facade; }
completion
php
complete go: func (c *SSM) DeleteInventoryWithContext(ctx aws.Context, input *DeleteInventoryInput, opts ...request.Option) (*DeleteInventoryOutput, error) { req, out := c.DeleteInventoryRequest(input) req.SetContext(ctx)
req.ApplyOptions(opts...) return out, req.Send() }
completion
go
complete php: public static function modify($content, $type) { if (!array_key_exists($type, self::$types)) { throw new \LogicException(sprintf("Unsuported type `%s` of minifier.", $type)); } $modifier = self::$types[$type]; if (!$modifier['enabled']) { retur...
); self::$cache && self::$cache->save(self::$cache->getItem($cacheId)->set($content)); return $content; }
completion
php
generate docstring javascript: function wrapExpressionFromAst(ast: Object): string { // Transform let and var declarations into assignments, and get back an array // of variable declarations. let { newAst, declarations } = translateDeclarationsIntoAssignment(ast); const body = addReturnNode(newAst); // Creat...
Given an AST, wrap its body in an async iife, transform variable declarations in assignments and move the variable declarations outside of the async iife. Example: With the AST for the following expression: `let a = await 123`, the function will return: let a; (async => { return a = await 123; })();
docstring
javascript
complete javascript: function initRepeater () {
// simulate network latency var loadDelays = ['300', '600', '900', '1200']; var sort = function (data, sortProperty, sortDirection) { var sortedData = _.sortBy(data, function (item) { return item[sortProperty]; }); // sort direction if (sortDirection === 'desc') { sortedData = sortedData.reve...
completion
javascript
generate docstring ruby: def snippet_path(path = nil) if snippet_json["main"].nil? real_path path else real_path ::File.join(snippet_json["main"], path) end end
path from snippet_json["main"]
docstring
ruby
complete go: func (service *BaseService) InitBaseService() { service.initMethodManager() service.initHandlerManager() service.Timeout = 120 * time.Second service.Heartbeat = 3 * time.Second service.ErrorDelay = 10 * time.Second service.topics = make(map[string]*topic) service.AddFunction("#", util.UUIDv4, Option...
return invoke(name, args, context.(ServiceContext)) } service.override.beforeFilterHandler = func( request []byte, context Context) (response []byte, err error) { return service.beforeFilter(request, context.(ServiceContext)) } service.override.afterFilterHandler = func( request []byte, context Context) (re...
completion
go
complete python: def _parse_reactome_association_file( self, file, limit=None, subject_prefix=None, object_prefix=None): """ Parse ensembl gene to reactome pathway file
:param file: file path (not handle) :param limit: limit (int, optional) limit the number of rows processed :return: None """ eco_map = Reactome.get_eco_map(Reactome.map_files['eco_map']) count = 0 with open(file, 'r') as tsvfile: reader = csv.reader(ts...
completion
python
complete ruby: def copy(options = {}) options = options.merge(source_db_snapshot_identifier: @snapshot_id) resp = @client.copy_db_snapshot(options) DBSnapshot.new( instance_id: resp.data.db_snapshot.db_instance_identifier,
snapshot_id: resp.data.db_snapshot.db_snapshot_identifier, data: resp.data.db_snapshot, client: @client ) end
completion
ruby
complete php: private function generateV4GUID(): string
{ if (true === \function_exists('com_create_guid')) { return trim(com_create_guid(), '{}'); } $data = openssl_random_pseudo_bytes(16); $data[6] = \chr(\ord($data[6]) & 0x0f | 0x40); $data[8] = \chr(\ord($data[8]) & 0x3f | 0x80); return vsprintf('%s%s-...
completion
php
complete java: protected Content getTypeParameterLink(LinkInfo linkInfo,
Type typeParam) { LinkInfoImpl typeLinkInfo = new LinkInfoImpl(m_writer.configuration, ((LinkInfoImpl) linkInfo).getContext(), typeParam); typeLinkInfo.excludeTypeBounds = linkInfo.excludeTypeBounds; typeLinkInfo.excludeTypeParameterLinks = linkInfo.excludeTypeParameterLi...
completion
java
complete javascript: function sortByFileFormat(srcDir, format) { const initialFiles = `${srcDir}/*.${format}` const files = glob.sync(initialFiles); const dest = `${srcDir}/${format}`; let count = 0; createDirs([dest]); // Loop through and move each file const promises = files.map(f => { return new ...
thisDest = `${thisDest}/${size}`; createDirs([thisDest]); } fs.rename(f, `${thisDest}/${filename}`, err => { if (err) { reject(err); } count++; resolve(`${dest}/${filename}`); }); }); }); return Promise.all(promises).then(() => { ...
completion
javascript
complete javascript: function (ary, item) { /*Line 150 - 'AtomBindingHelper.js' */ var i = ary.indexOf(item); /*Line 151 - 'AtomBindingHelper.js' */ if (i == -1)
/*Line 152 - 'AtomBindingHelper.js' */ return; /*Line 153 - 'AtomBindingHelper.js' */ ary.splice(i, 1); /*Line 154 - 'AtomBindingHelper.js' */ AtomBinder.invokeItemsEvent(ary, "remove", i, item); /*Line 155 - 'AtomBindingHelper.js' */ }
completion
javascript
generate docstring ruby: def parameters=(new_val) return nil if new_val == @parameters new_val = {} if new_val.nil? || (new_val == '') ### check the values raise JSS::InvalidDataError, ':parameters must be a Hash with keys :parameter4 thru :parameter11' unless \ new_val.is_a?(Hash) && (...
notes= Replace all the script parameters at once. This will replace the entire set with the hash provided. @param new_val[Hash] the Hash keys must exist in {PARAMETER_KEYS} @return [void]
docstring
ruby
generate docstring php: public function set_text(string $id, string $text): bool { if ( \bbn\str::is_uid($id) && $this->pref->set_text($id, $text) ){ $this->delete_cache($id); return true; } return false; }
Sets the menu's text and deletes its chache @param string $id The menu's ID @param array $text The new text tp set @return bool
docstring
php
complete ruby: def modal(*args, &block) modal = Bh::Modal.new self, *args, &block modal.extract! :button, :size, :body, :title, :id modal.extract_from :button, [:context, :size, :layout, :caption] modal.append_class_to! :button, :btn modal.append_class_to! :button, modal.button_context_cl...
modal.merge! button: {caption: modal.caption} modal.append_class_to! :div, :'modal-dialog' modal.append_class_to! :div, modal.dialog_size_class modal.merge! div: {title: modal.title, id: modal.id} modal.render_partial 'modal' end
completion
ruby
complete java: public static void incrementSessionStep(final UIContext uic) { int step = uic.getEnvironment().getStep();
uic.getEnvironment().setStep(step + 1); }
completion
java
complete python: def write_packed(self, outfile, rows): """ Write PNG file to `outfile`. The pixel data comes from `rows` which should be in boxed row packed format. Each row should be a sequence of packed bytes. Technically, this method does work for interlaced images but it ...
This method should not be used when the source image bit depth is not one naturally supported by PNG; the bit depth should be 1, 2, 4, 8, or 16. """ if self.rescale: raise Error("write_packed method not suitable for bit depth %d" % self.rescale[0]) ...
completion
python
complete javascript: function t (template, data) { for (var key in data) { template = template.replace(new RegExp('{' + key + '}', 'g'), data[key] || '')
} return template }
completion
javascript
complete java: void initResolution(Resolution source)
{ Check.notNull(source); setSystemCursorVisible(cursorVisibility.booleanValue()); this.source = source; screen.onSourceChanged(source); final int width = source.getWidth(); final int height = source.getHeight(); // Standard rendering final Resolution...
completion
java
complete go: func (c *IoTDataPlane) GetThingShadowRequest(input *GetThingShadowInput) (req *request.Request, output *GetThingShadowOutput) { op := &request.Operation{ Name: opGetThingShadow, HTTPMethod: "GET", HTTPPath: "/things/{thingName}/shadow", }
if input == nil { input = &GetThingShadowInput{} } output = &GetThingShadowOutput{} req = c.newRequest(op, input, output) return }
completion
go
generate docstring go: func (s *storeImpl) UpdateCurrentState(ctx datastore.Context, serviceID string, currentState string) error { plog.WithFields(log.Fields{ "serviceID": serviceID, "currentState": currentState, }).Debug("Storing currentState") s.updateCurrentState(serviceID, currentState, time.Now()) retu...
// UpdateCurrentState updates the CurrentState for the service by saving the information in volatile storage.
docstring
go
generate docstring php: public function setDefault(): void { $repo = $this->getRepository(); $locales = $repo->findAll(); foreach ($locales as $locale) { /* @var $locale self */ $locale->default = false; $repo->persist($locale); } $this->default = true; $repo->persist($this); $repo->flush(); }
Nastavi na vychozi
docstring
php
complete java: @Override public Collection<Class<? extends Saga>> scanForSagas() { Set<Class<? extends Saga>> sagaTypes = reflections.getSubTypesOf(Saga.class); // separate searches in case saga-lib is in embedded jar when performing directory scanning
Set<Class<? extends AbstractSaga>> abstractSagaTypes = reflections.getSubTypesOf(AbstractSaga.class); Set<Class<? extends AbstractSingleEventSaga>> singleEventSagaTypes = reflections.getSubTypesOf(AbstractSingleEventSaga.class); Set<Class<? extends Saga>> foundTypes = Sets.union(sagaTypes, abst...
completion
java
generate docstring ruby: def parse_headers(header_data_for_multiple_responses) @headers = {} responses = Patron::HeaderParser.parse(header_data_for_multiple_responses) last_response = responses[-1] # Only use the last response (for proxies and redirects) @status_line = last_response.status_lin...
Called by the C code to parse and set the headers
docstring
ruby
complete go: func (s *GetSmsChannelOutput) SetSMSChannelResponse(v *SMSChannelResponse) *GetSmsChannelOutput {
s.SMSChannelResponse = v return s }
completion
go
complete python: def edit_securitygroup_rule(self, group_id, rule_id, remote_ip=None, remote_group=None, direction=None, ethertype=None, port_max=None, port_min=None, protocol=None): """Edit a security group rule. ...
:param str protocol: The protocol to enforce (icmp, udp, tcp) """ successful = False obj = {} if remote_ip is not None: obj['remoteIp'] = remote_ip if remote_group is not None: obj['remoteGroupId'] = remote_group if direction is not None: ...
completion
python
generate docstring javascript: function compatible (middleware) { return function ($) { var req = $.request var res = $.response var $req = new Proxy(req, { defineProperty (target, prop, descriptor) { return Object.defineProperty(target, prop, descriptor) && Object.defineProperty($, prop, descrip...
/* @param {function} middleware - connect style, (req, res, next) @return {function} middleware - dietjs style ($) Proxies the signal object
docstring
javascript
complete java: public void createReference(Reference reference) throws GreenPepperServerException {
try { sessionService.startSession(); sessionService.beginTransaction(); Repository repository = loadRepository(reference.getSpecification().getRepository().getUid()); documentDao.createReference(reference); sessionService.commitTransaction(); ...
completion
java
complete javascript: function inCircle ( p, p1, p2, p3 ) { var EPSILON = Number.MIN_VALUE; if ( Math.abs( p1.y - p2.y ) < EPSILON && Math.abs( p2.y - p3.y) < EPSILON) { //INCIRCUM - F - Points are coincident !! return false; } var m1, m2 ,mx1, mx2 ,my1, my2 ,xc, yc; if ( Math.abs(p2.y - p...
my1 = (p1.y + p2.y) * 0.5; //Calculate CircumCircle center (xc,yc) xc = (p3.x + p2.x) * 0.5; yc = m1 * (xc - mx1) + my1; } else { m1 = -(p2.x - p1.x) / (p2.y - p1.y); m2 = -(p3.x - p2.x) / (p3.y - p2.y); mx1 = (p1.x + p2.x) * 0.5; mx2 = (p2.x + p3.x) * 0.5; my1 = (p1.y + p2.y) * 0.5; my2 = (p2.y ...
completion
javascript
complete python: def get_receiver(self, receiver=None): """
Returns a single receiver or a dictionary of receivers for this plugin. """ return self.__app.signals.get_receiver(receiver, self._plugin)
completion
python
complete java: public void setDynamicParameters(Set<String> dynamicParams) { if (dynamicParams == null) {
dynamicParams = Sets.newHashSet(); } m_dynamicParameters = dynamicParams; }
completion
java
generate docstring go: func (s *BatchUnsuspendUserOutput) SetUserErrors(v []*UserError) *BatchUnsuspendUserOutput { s.UserErrors = v return s }
// SetUserErrors sets the UserErrors field's value.
docstring
go
generate docstring go: func (g *Group) Uint32() *Statement { // notest s := Uint32() g.items = append(g.items, s) return s }
// Uint32 renders the uint32 identifier.
docstring
go
complete ruby: def select_variant(experiment) # starts off at 0 accum = 0.0 sample = Kernel.rand # go through our experiments and return the variation that matches # our random value experiment.variations.each_with_index do |variation, i| # we want to record the index in th...
# add the variation's weight to accum accum += variation.weight # return the variation if accum is more than our random value if sample <= accum return variation end end # default to nil return nil end
completion
ruby
generate docstring java: public static void bufferedToInterleaved(DataBufferByte buffer, WritableRaster src, InterleavedF32 dst) { byte[] srcData = buffer.getData(); int srcStride = stride(src); int srcOffset = getOffset(src); int length = dst.width*dst.numBands; //CONCURRENT_BELOW BoofConcurrency.loopFor(...
A faster convert that works directly with a specific raster
docstring
java
generate docstring javascript: function (position) { /** @type {?} */ var positionChangeData = new PositionChangeData(position, this.limitRoles); /** @type {?} */ var limitException = this.limitsService.exceedsLimit(positionChangeData); if ...
registers a position change on the limits service, and adjusts position if necessary @param {?} position - the current position of the point @return {?}
docstring
javascript
generate docstring python: def print_table(table, name=None, fmt=None): """ Pretty print a pandas DataFrame. Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output. Parameters ---------- table : pd.Series or pd.DataFrame Table to pretty-print. name...
Pretty print a pandas DataFrame. Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output. Parameters ---------- table : pd.Series or pd.DataFrame Table to pretty-print. name : str, optional Table name to display in upper left corner. fmt : str, ...
docstring
python
complete php: public function process(ContainerBuilder $container) { if ('all' !== $container->getParameter('okvpn_datadog.logging') || false === $container->getParameter('okvpn_datadog.profiling')) { return; } $loggerByChanel = array_map( function ($channel) { ...
if ($container->hasDefinition($loggerId)) { $definition = $container->getDefinition($loggerId); $definition->addMethodCall('pushHandler', [new Reference('okvpn_datadog.monolog.log_handler')]); } } }
completion
php
complete python: def add_badge(self, kind): '''Perform an atomic prepend for a new badge''' badge = self.get_badge(kind) if badge: return badge if kind not in getattr(self, '__badges__', {}): msg = 'Unknown badge type for {model}: {kind}' raise db.Vali...
} } }) self.reload() post_save.send(self.__class__, document=self) on_badge_added.send(self, kind=kind) return self.get_badge(kind)
completion
python
generate docstring python: def get_rupture_surface(mag, nodal_plane, hypocenter, msr, rupture_aspect_ratio, upper_seismogenic_depth, lower_seismogenic_depth, mesh_spacing=1.0): """ Create and return rupture surface object with given properties. :param mag: ...
Create and return rupture surface object with given properties. :param mag: Magnitude value, used to calculate rupture dimensions, see :meth:`_get_rupture_dimensions`. :param nodal_plane: Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane` describing the rupture o...
docstring
python
complete javascript: function isTypeOf(path, typePath) {
var node = _getNode(path); if (node) { return state.core.isTypeOf(node, typePath); } return false; }
completion
javascript
complete go: func (locker *MemoryLocker) LockUpload(id string) error { locker.mutex.Lock() defer locker.mutex.Unlock() // Ensure file is not locked if _, ok := locker.locks[id]; ok {
return tusd.ErrFileLocked } locker.locks[id] = struct{}{} return nil }
completion
go
complete php: function installOverrides( $overrideListNode, &$parameters ) { if ( !$overrideListNode ) { return true; } $overrideINIArray = array(); foreach( $overrideListNode->getElementsByTagName( 'block' ) as $blockNode ) { if ( isset( $par...
// eZDebug::writeNotice( 'Found object id: "' . $blockArray[$blockName]['Match']['object'] . '" for matchblock "[' . $blockName . '][Match][object]"', __METHOD__ ); } if ( isset( $blockArray[$blockName][$this->OverrideNodeRemoteID] ) ) { $contentNode =...
completion
php
generate docstring go: func (lc *LightningChannel) validateCommitmentSanity(theirLogCounter, ourLogCounter uint64, remoteChain bool, predictAdded *PaymentDescriptor) error { // Fetch all updates not committed. view := lc.fetchHTLCView(theirLogCounter, ourLogCounter) // If we are checking if we can add a new HTLC...
// validateCommitmentSanity is used to validate the current state of the // commitment transaction in terms of the ChannelConstraints that we and our // remote peer agreed upon during the funding workflow. The predictAdded // parameter should be set to a valid PaymentDescriptor if we are validating // in the state when...
docstring
go
complete go: func ReplaceStringSecret(val string, secretValues map[string]string) string {
if val == "" || !strings.HasPrefix(val, "$") { return val } secretKey := val[1:] secretVal, ok := secretValues[secretKey] if !ok { log.Warnf("config referenced '%s', but key does not exist in secret", val) return val } return secretVal }
completion
go
complete javascript: function checkTimeCriteria() { // don't bother if another box is currently open if( isAnyBoxVisible() ) { return; } boxes.forEach(function(box) { if( ! box.mayAutoShow() ) { return; }
// check "time on site" trigger if (box.config.trigger.method === 'time_on_site' && siteTimer.time >= box.config.trigger.value) { box.trigger(); } // check "time on page" trigger if (box.config.trigger.method === 'time_on_page' && pageTimer.time >= box.config.trigger...
completion
javascript
generate docstring go: func (s *DeleteClusterParameterGroupInput) SetParameterGroupName(v string) *DeleteClusterParameterGroupInput { s.ParameterGroupName = &v return s }
// SetParameterGroupName sets the ParameterGroupName field's value.
docstring
go
complete ruby: def query_term(term) # rubocop:disable Style/GuardClause
if term.is_a?(Symbol) return term.to_s elsif term.is_a?(Integer) return term elsif term.is_a?(TrueClass) return term elsif !term.is_a?(Term) return "'#{term}'" end # rubocop:enable Style/GuardClause terms = term.args.map { |t| query_term(t) } ...
completion
ruby
complete go: func loadPlugins(path string) error { abs, err := filepath.Abs(path)
if err != nil { return err } pattern := filepath.Join(abs, fmt.Sprintf( "*-%s-%s.%s", runtime.GOOS, runtime.GOARCH, getLibExt(), )) libs, err := filepath.Glob(pattern) if err != nil { return err } for _, lib := range libs { if _, err := plugin.Open(lib); err != nil { return err } } return n...
completion
go
generate docstring java: public static double round(double val, int places) { long factor = (long) Math.pow(10, places); // Shift the decimal the correct number of places // to the right. val = val * factor; // Round to the nearest integer. long tmp = Math.round(val); ...
Round a double value to a specified number of decimal places. @param val the value to be rounded. @param places the number of decimal places to round to. @return val rounded to places decimal places.
docstring
java
complete go: func closeResources(handler http.Handler, closers ...io.Closer) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for _, closer := range closers { defer closer.Close() } handler.ServeHTTP(w, r) }) }
completion
go
generate docstring ruby: def get_parent_of(record, path) parent_object = path[0..-2].reduce(record) { |a, e| a.is_a?(Hash) ? a[e] : nil } [parent_object, path[-1]] end
returns [parent, child_key] of child described by path array in record's tree returns [nil, child_key] if path doesnt exist in record
docstring
ruby
complete java: public static synchronized void clearDaoCache() { if (classMap != null) { classMap.clear(); classMap = null; } if (tableConfigMap != null) {
tableConfigMap.clear(); tableConfigMap = null; } }
completion
java
generate docstring python: def _close(self): """ Release the USB interface again. """ self._usb_handle.releaseInterface() try: # If we're using PyUSB >= 1.0 we can re-attach the kernel driver here. self._usb_handle.dev.attach_kernel_driver(0) excep...
Release the USB interface again.
docstring
python
complete php: public function convert($records): string
{ $doc = $this->xml_converter->convert($records); $doc->documentElement->setAttribute('class', $this->class_name); $doc->documentElement->setAttribute('id', $this->id_value); return $doc->saveHTML($doc->documentElement); }
completion
php
complete python: def get_encoder(self):
"Return an encoder based on encoding settings" kwargs = self.connection_kwargs return Encoder( encoding=kwargs.get('encoding', 'utf-8'), encoding_errors=kwargs.get('encoding_errors', 'strict'), decode_responses=kwargs.get('decode_responses', False) )
completion
python
generate docstring ruby: def get_search_results_async(resource_group_name, workspace_name, parameters, custom_headers:nil) # Send request promise = begin_get_search_results_async(resource_group_name, workspace_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| ...
@param resource_group_name [String] The name of the resource group to get. The name is case insensitive. @param workspace_name [String] Log Analytics workspace name @param parameters [SearchParameters] The parameters required to execute a search query. @param custom_headers [Hash{String => String}] A hash of custo...
docstring
ruby
complete go: func PodValidateLimitFunc(limitRange *corev1.LimitRange, pod *api.Pod) error {
var errs []error for i := range limitRange.Spec.Limits { limit := limitRange.Spec.Limits[i] limitType := limit.Type // enforce container limits if limitType == corev1.LimitTypeContainer { for j := range pod.Spec.Containers { container := &pod.Spec.Containers[j] for k, v := range limit.Min { i...
completion
go
generate docstring php: static public function validBirthday($iY, $iM, $iD) { $iDate = $iY . '-' . $iM . '-' . $iD; $rPattern = '/^(([0-9]{2})|(19[0-9]{2})|(20[0-9]{2}))-((0[1-9]{1})|(1[012]{1}))-((0[1-9]{1})|(1[0-9]{1})|(2[0-9]{1})|3[01]{1})$/'; if (preg_match($rPattern, $iDate, $arr)) { ...
验证身份证出生日期是否正确 @param string $iY @param string $iM @param string $iD @return bool
docstring
php
generate docstring go: func (c *clusterConnection) Protocols() driver.ProtocolSet { c.mutex.RLock() defer c.mutex.RUnlock() var result driver.ProtocolSet for _, s := range c.servers { for _, p := range s.Protocols() { if !result.Contains(p) { result = append(result, p) } } } return result }
// Protocols returns all protocols used by this connection.
docstring
go
complete ruby: def pre_populate_buyer_email=(pre_populate_buyer_email) if !pre_populate_buyer_email.nil? && pre_populate_buyer_email.to_s.length > 254 fail ArgumentError, "invalid value for 'pre_populate_buyer_email', the character length must be smaller than or equal to 254."
end @pre_populate_buyer_email = pre_populate_buyer_email end
completion
ruby
generate docstring python: def get_JWT(url, address=None): """ Given a URL, fetch and decode the JWT it points to. If address is given, then authenticate the JWT with the address. Return None if we could not fetch it, or unable to authenticate it. NOTE: the URL must be usable by the requests libra...
Given a URL, fetch and decode the JWT it points to. If address is given, then authenticate the JWT with the address. Return None if we could not fetch it, or unable to authenticate it. NOTE: the URL must be usable by the requests library
docstring
python
complete ruby: def do_classes
# look for class renames like # %rename(Solvable) _Solvable; # typedef struct _Solvable {} XSolvable; /* expose XSolvable as 'Solvable' */ extends = Hash.new @body.scan(/^%rename\s*\(([^\"\)]+)\)\s+([_\w]+);/) do |class_name, struct_name| # puts "rename #{class_name} -> #{struct_name...
completion
ruby
complete php: private function preUse(Middleware $call) { $class = get_class($call); if (in_array($class, $this->preMiddlewareArr)) { throw new Exception($class . ' Pre-Middleware has loaded'); } $this->preMiddlewareArr[] = $class; if ($this->preMiddleware) { ...
} $call->setVitex($this); $this->preMiddleware = $call; return $this; }
completion
php
complete python: def serial_with_temp_timeout(serial_connection, timeout): '''Implements a temporary timeout for a serial connection''' saved_timeout = serial_connection.timeout
if timeout is not None: serial_connection.timeout = timeout yield serial_connection serial_connection.timeout = saved_timeout
completion
python
generate docstring javascript: function verifyModules(filePaths) { return Promise.all( _.map(filePaths, function(filePath) { return firstline(filePath).then(function(line) { var matches = line.match(/^(?:(?:port|effect)\s+)?module\s+(\S+)\s*/); if (matches) { var moduleName = matc...
Check for modules where the name doesn't match the filename. elm-make won't get a chance to detect this; they'll be filtered out first.
docstring
javascript
complete php: public function countryFilter($country, $default = '', $locale = null)
{ $locale = $locale == null ? \Locale::getDefault() : $locale; $countries = Intl::getRegionBundle()->getCountryNames($locale); return array_key_exists($country, $countries) ? $countries[$country] : $default; }
completion
php
complete java: @Override public void validate() { try { currentIfd = 0; for (TiffObject o : model.getImageIfds()) { currentIfd++; IFD ifd = (IFD) o; IfdTags metadata = ifd.getMetadata(); int sft = -1; int photo = -1; int bps = -1; int planar = -1...
if (bps > 1) { validateIfdCT(ifd, p); } else if (bps == 1) { validateIfdSD(ifd, p); } } } else if (photo == 2) { if (planar == 1) { validateIfdCT(ifd, p); } else if (...
completion
java
generate docstring java: @Override public Date firstBetween(Date start, Date end) { return rule.firstBetween(start, end); }
Return the first occurrence of this holiday that is on or after the given start date and before the given end date. @param start Only occurrences on or after this date are returned. @param end Only occurrences before this date are returned. @return The date on which this event occurs, or null if it does not oc...
docstring
java
complete go: func (s *ListPrincipalThingsInput) SetMaxResults(v int64) *ListPrincipalThingsInput {
s.MaxResults = &v return s }
completion
go
complete javascript: function(i, value, delaySort) { AP.splice.call( this, i, 0, value );
this.trigger( Collection.Events.Add, [this, value, i] ); if ( !delaySort ) { this.sort( undefined, undefined, true ); } return this; }
completion
javascript
complete php: public function getAutoIncrementString() { if ($this->isAutoIncrement() && IdMethod::NATIVE === $this->parentTable->getIdMethod()) { return $this->getPlatform()->getAutoIncrement(); } if ($this->isAutoIncrement()) { throw new EngineException(sprintf(
'You have specified autoIncrement for column "%s", but you have not specified idMethod="native" for table "%s".', $this->name, $this->parentTable->getName() )); } return ''; }
completion
php
complete java: public void marshall(GenerateDataKeyRequest generateDataKeyRequest, ProtocolMarshaller protocolMarshaller) { if (generateDataKeyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); }
try { protocolMarshaller.marshall(generateDataKeyRequest.getKeyId(), KEYID_BINDING); protocolMarshaller.marshall(generateDataKeyRequest.getEncryptionContext(), ENCRYPTIONCONTEXT_BINDING); protocolMarshaller.marshall(generateDataKeyRequest.getNumberOfBytes(), NUMBEROFBYTES_BI...
completion
java
generate docstring php: public function assignUploadedAssetToSiteAssetCollection(Asset $asset, NodeInterface $node, string $propertyName) { $contentContext = $node->getContext(); if (!$contentContext instanceof ContentContext) { return; } $site = $contentContext->getCurre...
Adds an asset to the asset collection of the site it has been uploaded to Note: This is usually triggered by the ContentController::assetUploaded signal @param Asset $asset @param NodeInterface $node @param string $propertyName @return void
docstring
php
complete go: func handleExtensionsParseDidStart(p *Params) ([]gqlerrors.FormattedError, parseFinishFuncHandler) { fs := map[string]ParseFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ParseFinishFunc ) // catch panic from ...
fs[ext.Name()] = finishFn }() } return errs, func(err error) []gqlerrors.FormattedError { errs := gqlerrors.FormattedErrors{} for name, fn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Err...
completion
go
complete python: def set_entry_points(self, names): """
sets the internal collection of entry points to be equal to `names` `names` can be a single object or an iterable but must be a string or iterable of strings. """ names = util.return_set(names) self.entry_point_names = names
completion
python
complete javascript: function getConverter(content) {
var rbr = /\r\n|\r|\n/mg; var steps = [0], m; while((m = rbr.exec(content))) { steps.push(m.index + m[0].length); } return function(line, column) { if (steps.length < line) { return -1; } return steps[line-1] + column; }; }
completion
javascript
generate docstring php: public function merge(\Protobuf\Message $message) { if ( ! $message instanceof \AgentSIB\Diadoc\Api\Proto\Invoicing\Organizations\ExtendedOrganizationInfo) { throw new \InvalidArgumentException(sprintf('Argument 1 passed to %s must be a %s, %s given', __METHOD__, __CLASS_...
{@inheritdoc}
docstring
php
complete java: @Override
public PortletEventQueue getPortletEventQueue(HttpServletRequest request) { request = this.portalRequestUtils.getOriginalPortalRequest(request); synchronized (PortalWebUtils.getRequestAttributeMutex(request)) { PortletEventQueue portletEventQueue = (PortletEventQueue...
completion
java
generate docstring ruby: def from_signal(intf, signal) signal = signal.name unless signal.is_a?(String) self.type = "signal" self.interface = intf.name self.member = signal self.path = intf.object.path self end
Sets the match rule to filter for the given _signal_ and the given interface _intf_.
docstring
ruby
complete python: def set_fd_value(tag, value): """ Setters for data that also work with implicit transfersyntax :param value: the value to set on the tag
:param tag: the tag to read """ if tag.VR == 'OB' or tag.VR == 'UN': value = struct.pack('d', value) tag.value = value
completion
python
complete php: public static function parseConstantName($constName, $separator='_') { if (!empty($separator)){ $pos = strpos($constName, $separator); if (false !== $pos && $pos != strlen($constName))
$constName = substr($constName, $pos+1); } $constName = str_replace($separator, ' ', $constName); return ucwords($constName); }
completion
php
complete ruby: def patch_closed_list_with_http_info(app_id, version_id, cl_entity_id, closed_list_model_patch_object, custom_headers:nil)
patch_closed_list_async(app_id, version_id, cl_entity_id, closed_list_model_patch_object, custom_headers:custom_headers).value! end
completion
ruby
complete javascript: function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomContent)){ return new AtomContent(json);
} // If the given object is already an instance then just return it. DON'T copy it. if(AtomContent.isInstance(json)){ return json; } this.init(json); }
completion
javascript
generate docstring javascript: function run() { const updatedFiles = []; const passFiles = []; const pendingFiles = []; eachFile(function (absolutePath, fileExt) { const fileStr = fs.readFileSync(absolutePath, 'utf-8'); const existLicense = preamble.extractLicense(fileStr, fileExt); ...
const lists = [ '../src/**/*.js', '../build/*.js', '../benchmark/src/*.js', '../benchmark/src/gulpfile.js', '../extension-src/**/*.js', '../extension/**/*.js', '../map/js/**/*.js', '../test/build/**/*.js', '../test/node/**/*.js', '../test/ut/core/*.js', '../test/ut/spe/*.js', '../test/ut/ut.js', '../test/*.js', '../the...
docstring
javascript
complete java: public synchronized static void write(int fd, ByteBuffer ... data) throws IOException{ // write each byte buffer to the serial port for(ByteBuffer single : data) { // read the byte buffer from the current position up to the limit
byte[] payload = new byte[single.remaining()]; single.get(payload); // write the data contents to the serial port via JNI native method write(fd, payload, payload.length); } }
completion
java
complete ruby: def input_field(attribute_name, options = {})
components = (wrapper.components.map(&:namespace) & ATTRIBUTE_COMPONENTS) options = options.dup options[:input_html] = options.except(:as, :boolean_style, :collection, :disabled, :label_method, :value_method, :prompt, *components) options = @defaults.deep_dup.deep_merge(options) if @defaults ...
completion
ruby
complete javascript: function compareKey(one: string, two: string): number {
const delta = one.length - two.length; if (delta > 0) { return 1; } if (delta < 0) { return -1; } return one > two ? 1 : -1; }
completion
javascript
complete python: def _pad(self, a, axis, extrap, out): """Add padding to an array. Parameters ---------- a : (..., Nin, ...) ndarray array to be padded to size `N` axis : int axis along which to pad extrap : {bool, 'const'} or 2-tuple ...
else: _Npad, Npad_ = Npad//2, Npad - Npad//2 try: _extrap, extrap_ = extrap except (TypeError, ValueError): _extrap = extrap_ = extrap if isinstance(_extrap, bool): if _extrap: end = np.take(a, [0], axis=axis) ...
completion
python
generate docstring php: protected function _getHeaderCommentHtml($e) {return !($m = df_fe_m($e, false)) ? parent::_getHeaderCommentHtml($e) : df_tag('div', 'comment', df_tag_ab(__('Have a question?'), df_package($m, 'homepage'))) ;}
2016-07-01 @override @see \Magento\Config\Block\System\Config\Form\Fieldset::_getHeaderCommentHtml() https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Config/Block/System/Config/Form/Fieldset.php#L166-L175 @used-by \Magento\Config\Block\System\Config\Form\Fieldset::_getHeaderHtml() https://github.com/mage...
docstring
php
complete ruby: def report_failure(title, msg=nil) @context.audit.append_error(title, :category => RightScale::EventCategories::CATEGORY_ERROR)
@context.audit.append_error(msg) unless msg.nil? @context.succeeded = false fail true end
completion
ruby
generate docstring go: func (s *Deque) Empty() bool { s.RLock() defer s.RUnlock() return s.container.Len() == 0 }
// Empty checks if the deque is empty
docstring
go
complete python: def _stringtie_expression(bam, data, out_dir="."):
""" only estimate expression the Stringtie, do not assemble new transcripts """ gtf_file = dd.get_gtf_file(data) num_cores = dd.get_num_cores(data) error_message = "The %s file for %s is missing. StringTie has an error." stringtie = config_utils.get_program("stringtie", data, default="string...
completion
python
complete java: private static List<Object> asList(final int n, final Object[] o) {
return Arrays.asList(o).subList(0, n); }
completion
java
generate docstring java: @Override public WorkItemHandlerModel setClazz(Class<?> clazz) { String c = clazz != null ? clazz.getName() : null; setModelAttribute("class", c); return this; }
{@inheritDoc}
docstring
java
complete go: func (c *Connection) watchRequests(ch *Channel) { for { select { case req, ok := <-ch.reqChan: // new request on the request channel if !ok { // after closing the request channel, release API channel and return c.releaseAPIChannel(ch) return }
if err := c.processRequest(ch, req); err != nil { sendReplyError(ch, req, err) } } } }
completion
go
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5