Question:
Query data.

@param Many $type

@return array

public function query(Many $type): array
    {
        $this->name = $type->name;
        $this->description = $type->description;
        $this->entity = $type;

        $this->checkPermission(Post::POST_PERMISSION_PREFIX.$type->slug);

        $this->grid = $type->grid();
        $this->filters = $type->filters();

        return [
            'data' => $type->get(),
        ];
    }

public function toArray()
    {
        $arrRet = [];
        foreach ($this as $propName => $propValue) {
            if ($this->hasColumn($propName)) {
                $arrRet[$propName] = $propValue;
            }
        }

        return $arrRet;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
options:
whitelist
blacklist
allowEmpty (default: false)
recursive (default: true)
lowerKeys (default: false)
variableIndicatorPrefix (default: ~)
ignoreIndicatorPrefix (default: _)

function constructIncludedDirectory(data) {
  var defaults, opt, files, splitDirPath, tmp, included,
    src, ext, filename, relfilename, key, work, basepath, fullpath;

  basepath = yamlinc.getBasePath();

  work = {};
  opt = {};
  defaults = {
    whitelist: [],
    blacklist: [],
    allowEmpty: false,
    recursive: true,
    extensions: ['.yaml', '.yml'],
    lowerKeys: false,
    variableIndicator: '~',
    variablePrefix: '{',
    variableSuffix: '}',
    ignoreIndicator: '_',
    ignoreTopLevelDir: true,
    excludeTopLevelDirSeparator: false,
    pathSeparator: '/'
  };

  if (Array.isArray(data[0])) {
    files = data[0];
  } else {
    fullpath = p.join(basepath, data[0]);
    debug('reading %s', fullpath);
    files = recursiveReadSync(fullpath);
    files = files.map(function(filepath) {
      return filepath.replace(basepath + p.sep, '');
    });
    debug('files ', files);
  }

  // sort the by length of filepath
  files.sort(function(a, b) {
    return a.length - b.length;
  });

  if (!data[1]) {
    data[1] = {};
  }

  merge(opt, defaults, data[1]);

  debug('resolved options %j', opt);

  var keepFile = function(filepath) {
    ext = p.extname(filepath);
    if (opt.extensions.indexOf(ext) === -1) {
      debug('skipping disallowed file extension %s: %s', ext, filepath);
      return false;
    }

    filename = p.basename(filepath, ext);

    // check whitelist for filepath and file name
    if (opt.whitelist.indexOf(filepath) !== -1 ||
      opt.whitelist.indexOf(filename) !== -1 ||
      opt.whitelist.indexOf(filename + ext) !== -1) {
      debug('whitelisting %s', filepath);
      return true;
    }

    // if ANY part of the path has an ignorePrefix,
    // skip it
    if (filepath.indexOf('/' + opt.ignoreIndicator) !== -1) {
      debug('ignoring %s', filepath);
      return false;
    }

    // check blacklist for filepath and file name
    if (opt.blacklist.indexOf(filepath) !== -1 ||
      opt.blacklist.indexOf(filename) !== -1 ||
      opt.blacklist.indexOf(filename + ext) !== -1) {
      debug('blacklisting %s', filepath);
      return false;
    }

    // guess we're keeping it!
    debug('keepFile: keeping ' + filepath);
    return true;
  };

  files.forEach(function(filepath) {
    debug('looking at %s', filepath);
    if (!keepFile(filepath)) {
      return;
    }

    splitDirPath = filepath.split('/');
    splitDirPath.pop();

    // we generally don't want the top dir.
    if (opt.ignoreTopLevelDir) {
      splitDirPath.shift();
    }

    if (opt.lowerKeys) {
      filename = filename.toLowerCase();
    }

    // parameterize key
    if (opt.variableIndicator) {
      splitDirPath.forEach(function(element, i, a) {
        if (element.charAt(0) === opt.variableIndicator) {
          a[i] = opt.variablePrefix + element.substr(1) + opt.variableSuffix;
        }
      });
    }

    // get the source at last
    included = {};
    src = fs.readFileSync(p.join(basepath, filepath), 'utf8');
    if (src.length > 0) {
      yamlinc.YAML_VISITED_FILES.push(filepath);
      included = yaml.load(src, {
        schema: yamlinc.YAML_INCLUDE_SCHEMA,
        filename: filepath
      });
    }

    tmp = {};
    if (opt.recursive) {

      key = opt.excludeTopLevelDirSeparator ? '' : opt.pathSeparator;
      key += splitDirPath.join(opt.pathSeparator);
      if (opt.allowEmpty) {
        tmp[key] = {};
        tmp[key][filename] = included;
      } else {
        if (Object.getOwnPropertyNames(included).length > 0) {
          if (key.length > 0) {
            tmp[key] = {};
            tmp[key][filename] = included;
          } else {
            // this implements the opt.excludeTopLevelDirSeparator option when at the top level
            tmp[filename] = included;
          }
        }
      }
    } else {
      if (opt.allowEmpty) {
        tmp[filename] = included;
      } else {
        if (Object.getOwnPropertyNames(included).length > 0) {
          tmp[filename] = included;
        }
      }
    }

    work = merge(work, tmp);
  });
  return new IncludedDirectory(work);
}

public function __isset($k)
	{
		if (preg_match('#^[A-Z][A-Za-z_0-9]+$#D', $k))
		{
			return isset($this->plugins[$k]);
		}

		return isset($this->registeredVars[$k]);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // ExpireAfter implements ExpirableStorage.ExpireAfter.

func (s *storage) ExpireAfter(expireAfter time.Duration) ExpirableStorage {
	newStorage := *s
	newStorage.expireAfter = expireAfter
	return &newStorage
}

public function prune($tags)
    {
        $tags = is_array($tags) ? $tags : func_get_args();
        $this->callBeforeListeners('prune', [$this->storageName, $tags]);
        $this->storage->prune($tags);
        $this->callAfterListeners('prune', [$this->storageName, $tags]);

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Generate command.
index.php generate action_name [action_name [action_name [...]]]

@param array $arguments

public static function generate($args, $opts, $console)
    {
        $checklist = new ConsoleKit\Widgets\Checklist($console);
        foreach ($args as $action) {
            $console->writeln("Generating '$action'");
            $filename = ltrim($action, '/') . '.php';

            $actionsDir = (array) Atomik::get('atomik.dirs.actions');
            $actionsDir = array_shift($actionsDir);
            $checklist->step("Creating action file in $actionsDir", function() use ($actionsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($actionsDir, $filename),
                    "<?php\n\n// Logic goes here\n");
            });

            $viewsDir = (array) Atomik::get('atomik.dirs.views');
            $viewsDir = array_shift($viewsDir);
            $checklist->step("Creating view file in $viewsDir", function() use ($viewsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($viewsDir, $filename));
            });

            Atomik::fireEvent('Console::Generate', array($action));
        }
    }

protected function registerCommands()
    {
        $this->application->addCommands([
            new BuildCommand($this->viewFactory, $this->filesystem),
            new PostCommand($this->viewFactory, $this->filesystem)
        ]);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Allows third party extensions to replace or modify the page document
created by this indexer.

@param Document $pageDocument The page document created by this indexer.
@return Document An Apache Solr document representing the currently indexed page

protected function substitutePageDocument(Document $pageDocument)
    {
        if (!is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['Indexer']['indexPageSubstitutePageDocument'])) {
            return $pageDocument;
        }

        $indexConfigurationName = $this->getIndexConfigurationNameForCurrentPage();
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['Indexer']['indexPageSubstitutePageDocument'] as $classReference) {
            $substituteIndexer = GeneralUtility::makeInstance($classReference);

            if (!$substituteIndexer instanceof SubstitutePageIndexer) {
                $message = get_class($substituteIndexer) . ' must implement interface ' . SubstitutePageIndexer::class;
                throw new \UnexpectedValueException($message, 1310491001);
            }

            if ($substituteIndexer instanceof PageFieldMappingIndexer) {
                $substituteIndexer->setPageIndexingConfigurationName($indexConfigurationName);
            }

            $substituteDocument = $substituteIndexer->getPageDocument($pageDocument);
            if (!$substituteDocument instanceof Document) {
                $message = 'The document returned by ' . get_class($substituteIndexer) . ' is not a valid Document object.';
                throw new \UnexpectedValueException($message, 1310490952);
            }
            $pageDocument = $substituteDocument;
        }

        return $pageDocument;
    }

def get_docs(self, arg=None):
        '''

        '''
        if arg:
            if '*' in arg:
                target_mod = arg
                _use_fnmatch = True
            else:
                target_mod = arg + '.' if not arg.endswith('.') else arg
                _use_fnmatch = False
            if _use_fnmatch:
                docs = [(fun, self.functions[fun].__doc__)
                        for fun in fnmatch.filter(self.functions, target_mod)]
            else:
                docs = [(fun, self.functions[fun].__doc__)
                        for fun in sorted(self.functions)
                        if fun == arg or fun.startswith(target_mod)]
        else:
            docs = [(fun, self.functions[fun].__doc__)
                    for fun in sorted(self.functions)]
        docs = dict(docs)
        return salt.utils.doc.strip_rst(docs)

Instruction: Given a code description, retrieve the corresponding code.


Question: // Run re-provides keys with 'tick' interval or when triggered

func (rp *Reprovider) Run(tick time.Duration) {
	// dont reprovide immediately.
	// may have just started the daemon and shutting it down immediately.
	// probability( up another minute | uptime ) increases with uptime.
	after := time.After(time.Minute)
	var done doneFunc
	for {
		if tick == 0 {
			after = make(chan time.Time)
		}

		select {
		case <-rp.ctx.Done():
			return
		case done = <-rp.trigger:
		case <-after:
		}

		//'mute' the trigger channel so when `ipfs bitswap reprovide` is called
		//a 'reprovider is already running' error is returned
		unmute := rp.muteTrigger()

		err := rp.Reprovide()
		if err != nil {
			log.Debug(err)
		}

		if done != nil {
			done(err)
		}

		unmute()

		after = time.After(tick)
	}
}

func (r *Redis) Monitor() (*MonitorCommand, error) {
	c, err := r.pool.Get()
	if err != nil {
		return nil, err
	}
	if err := c.SendCommand("MONITOR"); err != nil {
		return nil, err
	}
	rp, err := c.RecvReply()
	if err != nil {
		return nil, err
	}
	if err := rp.OKValue(); err != nil {
		return nil, err
	}
	return &MonitorCommand{r, c}, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Delete a target in a cloud database
 https://developer.vuforia.com/library/articles/Solution/How-To-Delete-a-Target-Using-the-VWS-API

def delete_target(target_id)
      # In order to delete the target, we have to set it to non-active.
      # Therefore,first retrieve target info and act accordingly to target info
      # returned
      target_data = JSON.parse(retrieve_target(target_id)) # have to JSON.parse
      # retrieve_target's results since they're in string format
      target_result_code = target_data["result_code"]
      if target_result_code != "AuthenticationFailure"
        if target_result_code != "UnknownTarget"
          target_active_flag = target_data["target_record"]["active_flag"]
          target_status = target_data["status"]
          if target_result_code == "Success"
            if target_active_flag == true && target_status == "success"
              return {:result_code => "TargetActive"}.to_json
            elsif target_active_flag == false && target_status == "success"
              # if we reached this point, the target is fine, inactive and
              # ready to be deleted
              date_timestamp = Time.now.httpdate
              target_id_url = TARGETS_URL + '/' + target_id
              target_id_suburl = '/targets' + '/' + target_id
              signature = self.build_signature(target_id_suburl, nil, 'DELETE', date_timestamp)
              raise ArgumentError.new('Signature returned nil. Aborting...') if signature == nil
              authorization_header = "VWS " + @accesskey + ":" + signature
                begin
                  RestClient.delete(target_id_url,
                                             :'Date' => date_timestamp,
                                             :'Authorization' => authorization_header)
                rescue => e
                  e.response
                end
            else
              return {:result_code => "#{target_status}"}.to_json
            end
          end
        else
          return {:result_code => "UnknownTarget"}.to_json
        end
      else
        return {:result_code => "AuthenticationFailure"}.to_json
      end
    end

public function execute( Pg $pg, $simulate = false )
    {

        // only work on objects that have changed and aren't readonly
        $collection = array_filter(
            $this->object->collection,
            function($entity){
                return !$entity->isNew() and !$entity->isReadonly();
            }
        );

        if( count( $collection ) === 0 ) {
            return true;
        }

        $class = static::getClassFromCollection( $collection );

        $repo = $this->recordManager->entityManager->getRepository( $class );
        $table = $repo->table;
        $primaryKeys = $repo->dataTypesGet( DataType::PRIMARY_KEYS );

        // extract column info
        static::extractColumnInfoFromDataTypes( $primaryKeys, $pg, $modifiers );

        $data = array();
        foreach( $collection as $entity ) {

            // build data array
            $data[] = static::buildQueryDataFromEntity( $entity, array_keys( $modifiers ), null, null, Base::INITIAL, $this );

        }

        static::validateQueryDatas( $data, $modifiers );

        $query = self::buildQueryDelete(
            $pg,
            $table,
            $data,
            array()
        );

        $query = new Raw( $query, $data );
        $pg->query( $query );

        foreach( $collection as $entity ) {
            $entity->markDeleted();
        }

        return true;

    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Use this API to fetch sslciphersuite resource of given name .

public static sslciphersuite get(nitro_service service, String ciphername) throws Exception{
		sslciphersuite obj = new sslciphersuite();
		obj.set_ciphername(ciphername);
		sslciphersuite response = (sslciphersuite) obj.get_resource(service);
		return response;
	}

def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):

    return authenticate_with_certificate_chain(
        reactor, base_url, [client_cert], client_key, ca_cert,
    )

Instruction: Given a code description, retrieve the corresponding code.


Question: // newStreamingRows creates a new streamingRows from stream.

func newStreamingRows(stream sqltypes.ResultStream, conv *converter) driver.Rows {
	return &streamingRows{
		stream:  stream,
		convert: conv,
	}
}

def _transform_rows(self):

        self._find_all_step_methods()

        for row in self._source_reader.next():
            self._transform_row_wrapper(row)

Instruction: Given a code description, retrieve the corresponding code.


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@SuppressWarnings("unchecked")
	public EList<IfcAnnotationSurface> getAnnotatedSurface() {
		return (EList<IfcAnnotationSurface>) eGet(Ifc2x3tc1Package.Literals.IFC_TEXTURE_COORDINATE__ANNOTATED_SURFACE,
				true);
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

Instruction: Given a code description, retrieve the corresponding code.


Question: UnionTypeExtension

def parse_union_type_extension(lexer: Lexer) -> Node:
    """"""
    start = lexer.token
    expect_keyword(lexer, "extend")
    expect_keyword(lexer, "union")
    name = parse_name(lexer)
    directives = parse_directives(lexer, True)
    types = parse_union_member_types(lexer)
    if not (directives or types):
        raise unexpected(lexer)
    return Node(
        name=name, directives=directives, types=types, loc=loc(lexer, start)
    )

public static <D extends Comparable> DateExpression<D> date(Class<D> type, DateTimeExpression<?> dateTime) {
        return Expressions.dateOperation(type, Ops.DateTimeOps.DATE, dateTime);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Check if is possible subtract value from item qty

@param \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem
@return bool

protected function _canSubtractQty(
        \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem
    ) {
        $result = $stockItem->getManageStock() && $this->configStock->canSubtractQty();
        return $result;
    }

public function cancel(OrderInterface $order): void
    {
        $this->lockProductVariants($order);

        $this->decoratedOperator->cancel($order);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // AgentPresence returns whether the respective remote agent is alive.

func (a *Application) AgentPresence() (bool, error) {
	pwatcher := a.st.workers.presenceWatcher()
	return pwatcher.Alive(a.globalKey())
}

public function emitter(string $emitter, string $streamEmitter = null): void
    {
        $server = $this->server ?? $this->getServer();
        $server->setEmitter($emitter);

        $streamEmitter && $this->get('response')->setEmitter($streamEmitter);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Handle a mention notification.

Choose a random message and reply with it

@param {Notification} notification Notification event to handle
@returns {Promise} Resolves when event is processed

function handler(notification) {
        debug('summoner received a mention notification!');
        return notification.getUser()
            .then((user) => {
                debug(`summoner responding to summons by ${user.name}`);
                const index = Math.floor(Math.random() * messages.length);
                const message = messages[index].replace(/%(\w+)%/g, (_, key) => {
                    let value = user[key];
                    if (key === 'name' && !value) {
                        value = user.username;
                    }
                    value = value || `%${key}%`;
                    if (typeof value !== 'string') {
                        value = `%${key}%`;
                    }
                    return value;
                });
                debug(`summoner replying with: ${message}`);
                return forum.Post.reply(notification.topicId, notification.postId, message);
            }).catch((err) => {
                forum.emit('error', err);
                return Promise.reject(err);
            });
    }

public function reserveTask($tube = null)
    {
        if (is_null($tube)) {
            $tube = $this->defaultTube;
        }
        $inTask = $this->beanstalk
            ->watch($tube)
            ->ignore('default')
            ->reserve(2);
        if ($inTask === false) {
            return null;
        }
        $data = $inTask->getData();
        $parts = explode("::", $data, 2);
        if (count($parts) !== 2) {
            $this->beanstalk->delete($inTask);
            throw new TaskQueueServiceException("Invalid format in TaskQueue {$tube}");
        }
        try {
            $taskObject = $this->serializer->deserialize($parts[1], $parts[0], 'json');
        } catch (UnsupportedFormatException $exception) {
            $this->beanstalk->delete($inTask);
            throw new TaskQueueServiceException("Invalid format in TaskQueue {$tube} ");
        } catch (\ReflectionException $exception) {
            $this->beanstalk->delete($inTask);
            throw new TaskQueueServiceException(
                "Invalid format in TaskQueue {$tube} class " . $parts[0] . ' is unknown'
            );
        }
        if (!($taskObject instanceof TaskDescriptionInterface)) {
            $this->beanstalk->delete($inTask);
            throw new TaskQueueServiceException("Invalid data in TaskQueue {$tube}");
        }
        if (!$this->databaseDisabled) {
            $taskEntity = $this->taskRepo->find($taskObject->getTaskIdentifier());
        } else {
            //remake the task entity
            $taskEntity = new Task($taskObject, '', $tube);
        }
        if (!($taskEntity instanceof Task)) {
            $this->beanstalk->delete($inTask);
            throw new TaskQueueServiceException(
                "Unable to find taskEntity for task:" . $taskObject->getTaskIdentifier()
            );
        }
        /**
         * @var Task $taskEntity
         */
        $workPackage = new WorkPackage($taskEntity, $inTask, $taskObject);
        $this->updateTaskStatus($workPackage, Task::STATUS_WORKING);
        return $workPackage;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
{@inheritDoc}

@see jp.co.future.uroborosql.fluent.SqlQuery#findFirst(java.lang.Class)

@Override
	public <T> Optional<T> findFirst(final Class<T> type) {
		try (Stream<T> stream = stream(new EntityResultSetConverter<>(type, new PropertyMapperManager()))) {
			return stream.findFirst();
		}
	}

def ReadArtifact(self, name, cursor=None):
    """"""
    cursor.execute("SELECT definition FROM artifacts WHERE name = %s", [name])

    row = cursor.fetchone()
    if row is None:
      raise db.UnknownArtifactError(name)
    else:
      return _RowToArtifact(row)

Instruction: Given a code description, retrieve the corresponding code.


Question:
获取url的扩展名
@return null

protected function _ext() {
        $url = $this->uri;
        $urlinfo =  parse_url($url);
        $file = basename($urlinfo['path']);
        if(strpos($file,'.') !== false) {
            $ext = explode('.',$file);
            return $ext[count($ext)-1];
        }
        return null;
    }

protected void render(FacesContext context) throws IOException {

		String src = (String) getAttributes().get("src");
		boolean base64 = Boolean.parseBoolean((String) getAttributes().get("src"));
		String imagePath = getImageUrl(context, src, base64);
		ResponseWriter writer = context.getResponseWriter();
		writer.write(imagePath);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Identify objects from MRMS timesteps and link them together with object matching.

        Returns:
            List of STObjects containing MESH track information.

def find_mrms_tracks(self):

        obs_objects = []
        tracked_obs_objects = []
        if self.mrms_ew is not None:
            self.mrms_grid.load_data()

            if len(self.mrms_grid.data) != len(self.hours):
                print('Less than 24 hours of observation data found')

                return tracked_obs_objects

            for h, hour in enumerate(self.hours):
                mrms_data = np.zeros(self.mrms_grid.data[h].shape)
                mrms_data[:] = np.array(self.mrms_grid.data[h])
                mrms_data[mrms_data < 0] = 0
                hour_labels = self.mrms_ew.size_filter(self.mrms_ew.label(gaussian_filter(mrms_data,
                                                                                self.gaussian_window)),
                                                       self.size_filter)
                hour_labels[mrms_data < self.mrms_ew.min_thresh] = 0
                obj_slices = find_objects(hour_labels)
                num_slices = len(obj_slices)
                obs_objects.append([])
                if num_slices > 0:
                    for sl in obj_slices:
                        obs_objects[-1].append(STObject(mrms_data[sl],
                                                        np.where(hour_labels[sl] > 0, 1, 0),
                                                        self.model_grid.x[sl],
                                                        self.model_grid.y[sl],
                                                        self.model_grid.i[sl],
                                                        self.model_grid.j[sl],
                                                        hour,
                                                        hour,
                                                        dx=self.model_grid.dx))
                        if h > 0:
                            dims = obs_objects[-1][-1].timesteps[0].shape
                            obs_objects[-1][-1].estimate_motion(hour, self.mrms_grid.data[h-1], dims[1], dims[0])

            for h, hour in enumerate(self.hours):
                past_time_objs = []
                for obj in tracked_obs_objects:
                    if obj.end_time == hour - 1:
                        past_time_objs.append(obj)
                if len(past_time_objs) == 0:
                    tracked_obs_objects.extend(obs_objects[h])
                elif len(past_time_objs) > 0 and len(obs_objects[h]) > 0:
                    assignments = self.object_matcher.match_objects(past_time_objs, obs_objects[h], hour - 1, hour)
                    unpaired = list(range(len(obs_objects[h])))
                    for pair in assignments:
                        past_time_objs[pair[0]].extend(obs_objects[h][pair[1]])
                        unpaired.remove(pair[1])
                    if len(unpaired) > 0:
                        for up in unpaired:
                            tracked_obs_objects.append(obs_objects[h][up])
                print("Tracked Obs Objects: {0:03d} Hour: {1:02d}".format(len(tracked_obs_objects), hour))

        return tracked_obs_objects

def _get_fashion_mnist(directory):
  """"""
  # Fashion mnist files have the same names as MNIST.
  # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir.
  for filename in [
      _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME,
      _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME
  ]:
    generator_utils.maybe_download(directory,
                                   _FASHION_MNIST_LOCAL_FILE_PREFIX + filename,
                                   _FASHION_MNIST_URL + filename)

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetChannelCommander sets whether the client is a channel commander.

func (c *Client) SetChannelCommander(val bool) error {
	return c.ClientUpdate(NewArg(ClientIsChannelCommander, val))
}

def reset(cls, *args, **kwargs):
        """"""
        cls.local.tchannel = None
        cls.args = None
        cls.kwargs = None
        cls.prepared = False

Instruction: Given a code description, retrieve the corresponding code.


Question: // ListenAndServeKubeletReadOnlyServer initializes a server to respond to HTTP network requests on the Kubelet.

func ListenAndServeKubeletReadOnlyServer(host HostInterface, resourceAnalyzer stats.ResourceAnalyzer, address net.IP, port uint) {
	klog.V(1).Infof("Starting to listen read-only on %s:%d", address, port)
	s := NewServer(host, resourceAnalyzer, nil, false, false, false, nil)

	server := &http.Server{
		Addr:           net.JoinHostPort(address.String(), strconv.FormatUint(uint64(port), 10)),
		Handler:        &s,
		MaxHeaderBytes: 1 << 20,
	}
	klog.Fatal(server.ListenAndServe())
}

def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data.get("properties", {})

        load_balancing_rules = []
        for raw_content in properties.get("loadBalancingRules", []):
            resource = Resource.from_raw_data(raw_content)
            load_balancing_rules.append(resource)
        properties["loadBalancingRules"] = load_balancing_rules

        inbound_nat_rules = []
        for raw_content in properties.get("inboundNatRules", []):
            resource = Resource.from_raw_data(raw_content)
            inbound_nat_rules.append(resource)
        properties["inboundNatRules"] = inbound_nat_rules

        outbound_nat_rules = []
        for raw_content in properties.get("outboundNatRules", []):
            resource = Resource.from_raw_data(raw_content)
            outbound_nat_rules.append(resource)
        properties["outboundNatRules"] = outbound_nat_rules

        raw_content = properties.get("subnet", None)
        if raw_content is not None:
            resource = Resource.from_raw_data(raw_content)
            properties["subnet"] = resource

        return super(FrontendIPConfigurations, cls).process_raw_data(raw_data)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Return destination image quality

@param null|string $imgExtension
@return int

private static function getDestinationQuality(?string $imgExtension = null): int
    {
        switch ($imgExtension) {
            case 'png':
                $quality = static::$qualityPNG;
                break;
            default:
                $quality = static::$quality;
                break;
        }
        return $quality;
    }

function createPhotoUrl(id, farm, server, secret, size) {
		size = (size) ? '_' + size : '';
		return 'https://farm' + farm + '.staticflickr.com/' + server + '/' + id + '_' + secret + size + '.jpg';
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Gets the targetCpa value for this TargetCpaBiddingScheme.

@return targetCpa   * Average cost per acquisition (CPA) target. This target should
be greater than or equal to
minimum billable unit based on the currency for
the account.

public com.google.api.ads.adwords.axis.v201809.cm.Money getTargetCpa() {
        return targetCpa;
    }

def ctcBeamSearch(mat, classes, lm, k, beamWidth):

    blankIdx = len(classes)
    maxT, maxC = mat.shape

    # initialise beam state
    last = BeamState()
    labeling = ()
    last.entries[labeling] = BeamEntry()
    last.entries[labeling].prBlank = 1
    last.entries[labeling].prTotal = 1

    # go over all time-steps
    for t in range(maxT):
        curr = BeamState()

        # get beam-labelings of best beams
        bestLabelings = last.sort()[0:beamWidth]

	    # go over best beams
        for labeling in bestLabelings:

	        # probability of paths ending with a non-blank
            prNonBlank = 0
	        # in case of non-empty beam
            if labeling:
		       # probability of paths with repeated last char at the end
                try:
                    prNonBlank = last.entries[labeling].prNonBlank * mat[t, labeling[-1]]
                except FloatingPointError:
                    prNonBlank = 0

	    # probability of paths ending with a blank
            prBlank = (last.entries[labeling].prTotal) * mat[t, blankIdx]

	    # add beam at current time-step if needed
            addBeam(curr, labeling)

            # fill in data
            curr.entries[labeling].labeling = labeling
            curr.entries[labeling].prNonBlank += prNonBlank
            curr.entries[labeling].prBlank += prBlank
            curr.entries[labeling].prTotal += prBlank + prNonBlank
            curr.entries[labeling].prText = last.entries[labeling].prText # beam-labeling not changed, therefore also LM score unchanged from
            curr.entries[labeling].lmApplied = True # LM already applied at previous time-step for this beam-labeling

            # extend current beam-labeling
            for c in range(maxC - 1):
                # add new char to current beam-labeling
                newLabeling = labeling + (c,)

                # if new labeling contains duplicate char at the end, only consider paths ending with a blank
                if labeling and labeling[-1] == c:
                    prNonBlank = mat[t, c] * last.entries[labeling].prBlank
                else:
                    prNonBlank = mat[t, c] * last.entries[labeling].prTotal

		        # add beam at current time-step if needed
                addBeam(curr, newLabeling)

		        # fill in data
                curr.entries[newLabeling].labeling = newLabeling
                curr.entries[newLabeling].prNonBlank += prNonBlank
                curr.entries[newLabeling].prTotal += prNonBlank

		        # apply LM
                applyLM(curr.entries[labeling], curr.entries[newLabeling], classes, lm)

        # set new beam state
        last = curr

    # normalise LM scores according to beam-labeling-length
    last.norm()

    # sort by probability
    bestLabelings = last.sort()[:k] # get most probable labeling

    output = []
    for bestLabeling in bestLabelings:
        # map labels to chars
        res = ''
        for l in bestLabeling:
            res += classes[l]
        output.append(res)
    return output

Instruction: Given a code description, retrieve the corresponding code.


Question: Method called on autocompletion requests

def do_complete(self, code, cursor_pos):

        self._klog.info("{%s}", code[cursor_pos:cursor_pos+10])

        token, start = token_at_cursor(code, cursor_pos)
        tkn_low = token.lower()
        if is_magic(token, start, code):
            matches = [k for k in magics.keys() if k.startswith(tkn_low)]
        else:
            matches = [sparql_names[k] for k in sparql_names
                       if k.startswith(tkn_low)]
        self._klog.debug("token={%s} matches={%r}", token, matches)

        if matches:
            return {'status': 'ok',
                    'cursor_start': start,
                    'cursor_end': start+len(token),
                    'matches': matches}

def filename_complete(self, text, line, begidx, endidx):

        try:
            return self.real_filename_complete(text, line, begidx, endidx)
        except:
            traceback.print_exc()

Instruction: Given a code description, retrieve the corresponding code.


Question:
// ForbidLiveStream 禁止流
// StreamName	String	是	流名称
// LiveStreamType	String	是	用于指定主播推流还是客户端拉流, 目前支持"publisher" (主播推送)
// ResumeTime	String	否	恢复流的时间 UTC时间 格式：2015-12-01T17:37:00Z

func (l *Live) ForbidLiveStream(appName, streamName string, liveStreamType string, resumeTime *time.Time, resp interface{}) (err error) {
	if global.EmptyString == appName {
		return errors.New("appName should not to be empty")
	}
	req := l.cloneRequest(ForbidLiveStreamAction)
	req.AppName = appName
	req.SetArgs("StreamName", streamName)
	req.SetArgs("LiveStreamType", liveStreamType)
	if nil != resumeTime {
		req.SetArgs("ResumeTime", util.GetISO8601TimeStamp(*resumeTime))
	}
	err = l.rpc.Query(req, resp)
	return
}

def _wrap_callback_parse_time_info(subscription, on_data, message):

    if message.type == message.REPLY:
        time_response = web_pb2.TimeSubscriptionResponse()
        time_response.ParseFromString(message.reply.data)
        time = parse_isostring(time_response.timeInfo.currentTimeUTC)
        #pylint: disable=protected-access
        subscription._process(time)
        if on_data:
            on_data(time)
    elif message.type == message.DATA:
        if message.data.type == yamcs_pb2.TIME_INFO:
            time_message = getattr(message.data, 'timeInfo')
            time = parse_isostring(time_message.currentTimeUTC)
            #pylint: disable=protected-access
            subscription._process(time)
            if on_data:
                on_data(time)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Save Certificate Revocation List.

@param array $crl
@param int $format optional
@access public
@return string

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get row from a worksheet.

@param integer $rowIndex

@return string
@throws Exception

public function getRow($rowIndex)
    {
        //check whether worksheet name is set or not
        if ($this->worksheetName == '')
            throw new Exception('Worksheet name not specified');
        $strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() .
            '/worksheets/' . $this->worksheetName . '/cells/rows/' . $rowIndex;
        $signedURI = Utils::sign($strURI);
        $responseStream = Utils::processCommand($signedURI, 'GET', '', '');
        $json = json_decode($responseStream);
        return $json->Row;

    }

public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $filter) {
            $loopResultRow = new LoopResultRow($filter);

            $loopResultRow->set("ID", $filter->getId())
                ->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
                ->set("LOCALE", $filter->locale)
                ->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
                ->set("CODE", $filter->getCode())
                ->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("ACTIVATE", $filter->getActive())
                ->set("TYPE", $filter->getFiltertype());

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the URL for the given resource class

@param  str   $className
@param  str[] $params
@return str

public function uri($className, $params = array())
    {
        if (is_object($className)) {
            $className = get_class($className);
        }
        if (!isset($this->resources[$className])) {
            throw new \Exception('Resource class "'.$className.'" not found');
        }
        if ($params && !is_array($params)) {
            $params = array($params);
        }
        foreach ($this->resources[$className]->getUri() as $index => $uri) {
            if (count($params) == count($this->resources[$className]->getUriParams($index))) {
                $parts = explode('([^/]+)', $uri);
                $path = '';
                foreach ($parts as $key => $part) {
                    $path .= $part;
                    if (isset($params[$key])) {
                        $path .= $params[$key];
                    }
                }
                return $this->baseUri.$path;
            }
        }
    }

public static String getParameter(final Request request, final String parameterName)
	{
		String parameterValue = request.getRequestParameters().getParameterValue(parameterName)
			.toString();
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getPostParameters().getParameterValue(parameterName)
				.toString();
		}
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getQueryParameters().getParameterValue(parameterName)
				.toString();
		}
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getRequestParameters().getParameterValue(parameterName)
				.toString();
		}
		return parameterValue;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // Complete password reset.

func (s *Service) PasswordResetCompleteResetPassword(ctx context.Context, passwordResetResetPasswordToken string, o PasswordResetCompleteResetPasswordOpts) (*PasswordReset, error) {
	var passwordReset PasswordReset
	return &passwordReset, s.Post(ctx, &passwordReset, fmt.Sprintf("/password-resets/%v/actions/finalize", passwordResetResetPasswordToken), o)
}

public function handle()
    {
        $input = $this->collectInput();

        try {
            $this->validateInput($input);

            $this->registerUser($input);

            $this->sendResetPasswordLink($input);
        } catch (ValidationException $e) {
            $this->error(PHP_EOL . implode(PHP_EOL, $e->errors()->all()) . PHP_EOL);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Creation of a new node containing a CDATA block.

def newCDataBlock(self, content, len):

        ret = libxml2mod.xmlNewCDataBlock(self._o, content, len)
        if ret is None:raise treeError('xmlNewCDataBlock() failed')
        __tmp = xmlNode(_obj=ret)
        return __tmp

public CallTreeNode getOrAddChild(String name) {
		CallTreeNode child = getChild(name);
		if (child == null) {
			child = addChild(name);
		}
		return child;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@SuppressWarnings("unchecked")
	@Override
	public EList<IfcPropertyTemplate> getHasPropertyTemplates() {
		return (EList<IfcPropertyTemplate>) eGet(Ifc4Package.Literals.IFC_PROPERTY_SET_TEMPLATE__HAS_PROPERTY_TEMPLATES,
				true);
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Return a new Bootstrap Html Button
@param string $identifier
@param string $value
@param string $cssStyle
@param string $onClick
@return HtmlButton

public function htmlButton($identifier, $value="", $cssStyle=null, $onClick=null) {
		return $this->addHtmlComponent(new HtmlButton($identifier, $value, $cssStyle, $onClick));
	}

def read_cells(sheet = default_sheet)
      validate_sheet!(sheet)
      return if @cells_read[sheet]

      sheet_found = false
      doc.xpath("//*[local-name()='table']").each do |ws|
        next unless sheet == attribute(ws, 'name')

        sheet_found = true
        col         = 1
        row         = 1
        ws.children.each do |table_element|
          case table_element.name
          when 'table-column'
            @style_defaults[sheet] << table_element.attributes['default-cell-style-name']
          when 'table-row'
            if table_element.attributes['number-rows-repeated']
              skip_row = attribute(table_element, 'number-rows-repeated').to_s.to_i
              row      = row + skip_row - 1
            end
            table_element.children.each do |cell|
              skip_col   = attribute(cell, 'number-columns-repeated')
              formula    = attribute(cell, 'formula')
              value_type = attribute(cell, 'value-type')
              v          = attribute(cell, 'value')
              style_name = attribute(cell, 'style-name')
              case value_type
              when 'string'
                str_v      = ''
                # insert \n if there is more than one paragraph
                para_count = 0
                cell.children.each do |str|
                  # begin comments
                  #=begin
                  #- <table:table-cell office:value-type="string">
                  #  - <office:annotation office:display="true" draw:style-name="gr1" draw:text-style-name="P1" svg:width="1.1413in" svg:height="0.3902in" svg:x="2.0142in" svg:y="0in" draw:caption-point-x="-0.2402in" draw:caption-point-y="0.5661in">
                  #      <dc:date>2011-09-20T00:00:00</dc:date>
                  #      <text:p text:style-name="P1">Kommentar fuer B4</text:p>
                  #    </office:annotation>
                  #    <text:p>B4 (mit Kommentar)</text:p>
                  #  </table:table-cell>
                  #=end
                  if str.name == 'annotation'
                    str.children.each do |annotation|
                      next unless annotation.name == 'p'
                      # @comment ist ein Hash mit Sheet als Key (wie bei @cell)
                      # innerhalb eines Elements besteht ein Eintrag aus einem
                      # weiteren Hash mit Key [row,col] und dem eigentlichen
                      # Kommentartext als Inhalt
                      @comment[sheet]      = Hash.new unless @comment[sheet]
                      key                  = [row, col]
                      @comment[sheet][key] = annotation.text
                    end
                  end
                  # end comments
                  if str.name == 'p'
                    v          = str.content
                    str_v      += "\n" if para_count > 0
                    para_count += 1
                    if str.children.size > 1
                      str_v += children_to_string(str.children)
                    else
                      str.children.each do |child|
                        str_v += child.content #.text
                      end
                    end
                    str_v.gsub!(/'/, "'") # special case not supported by unescapeHTML
                    str_v = CGI.unescapeHTML(str_v)
                  end # == 'p'
                end
              when 'time'
                cell.children.each do |str|
                  v = str.content if str.name == 'p'
                end
              when '', nil, 'date', 'percentage', 'float'
                #
              when 'boolean'
                v = attribute(cell, 'boolean-value').to_s
              end
              if skip_col
                if !v.nil? || cell.attributes['date-value']
                  0.upto(skip_col.to_i - 1) do |i|
                    set_cell_values(sheet, col, row, i, v, value_type, formula, cell, str_v, style_name)
                  end
                end
                col += (skip_col.to_i - 1)
              end # if skip
              set_cell_values(sheet, col, row, 0, v, value_type, formula, cell, str_v, style_name)
              col += 1
            end
            row += 1
            col = 1
          end
        end
      end
      doc.xpath("//*[local-name()='automatic-styles']").each do |style|
        read_styles(style)
      end

      fail RangeError unless sheet_found

      @cells_read[sheet]    = true
      @comments_read[sheet] = true
    end

Instruction: Given a code description, retrieve the corresponding code.


Question: Catalog brain of the wrapped object

def brain(self):

        if self._brain is None:
            logger.debug("SuperModel::brain: *Fetch catalog brain*")
            self._brain = self.get_brain_by_uid(self.uid)
        return self._brain

func ExtractPayloadOrPanic(envelope *cb.Envelope) *cb.Payload {
	payload, err := ExtractPayload(envelope)
	if err != nil {
		panic(err)
	}
	return payload
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get index real name for Elastic Search

@param string $index

@return string

public function getIndexRealname($index)
    {
        if (isset($this->indexAliasMap[$index])) {
            return $this->indexAliasMap[$index];
        }

        return $index;
    }

function analyseExprDataHotspot(expr, accessorMeanDynamic) {
    var refs = [];
    var isDynamic;

    function analyseExprs(exprs, accessorMeanDynamic) {
        for (var i = 0, l = exprs.length; i < l; i++) {
            refs = refs.concat(analyseExprDataHotspot(exprs[i], accessorMeanDynamic));
            isDynamic = isDynamic || exprs[i].dynamic;
        }
    }

    switch (expr.type) {
        case ExprType.ACCESSOR:
            isDynamic = accessorMeanDynamic;

            var paths = expr.paths;
            refs.push(paths[0].value);

            if (paths.length > 1) {
                refs.push(paths[0].value + '.' + (paths[1].value || '*'));
            }

            analyseExprs(paths.slice(1), 1);
            break;

        case ExprType.UNARY:
            refs = analyseExprDataHotspot(expr.expr, accessorMeanDynamic);
            isDynamic = expr.expr.dynamic;
            break;

        case ExprType.TEXT:
        case ExprType.BINARY:
        case ExprType.TERTIARY:
            analyseExprs(expr.segs, accessorMeanDynamic);
            break;

        case ExprType.INTERP:
            refs = analyseExprDataHotspot(expr.expr);
            isDynamic = expr.expr.dynamic;

            each(expr.filters, function (filter) {
                analyseExprs(filter.name.paths);
                analyseExprs(filter.args);
            });

            break;

        case ExprType.ARRAY:
        case ExprType.OBJECT:
            for (var i = 0; i < expr.items.length; i++) {
                refs = refs.concat(analyseExprDataHotspot(expr.items[i].expr));
                isDynamic = isDynamic || expr.items[i].expr.dynamic;
            }
            break;
    }

    isDynamic && (expr.dynamic = true);
    return refs;
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// httpTransport constructs a HTTP Transport with settings appropriate for
// HTTP-01 validation. The provided dialerFunc is used as the Transport's
// DialContext handler.

func httpTransport(df dialerFunc) *http.Transport {
	return &http.Transport{
		DialContext: df,
		// We are talking to a client that does not yet have a certificate,
		// so we accept a temporary, invalid one.
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		// We don't expect to make multiple requests to a client, so close
		// connection immediately.
		DisableKeepAlives: true,
		// We don't want idle connections, but 0 means "unlimited," so we pick 1.
		MaxIdleConns:        1,
		IdleConnTimeout:     time.Second,
		TLSHandshakeTimeout: 10 * time.Second,
	}
}

def run(self):
        """"""
        self.api = self.context.get("cls")(self.context)
        self.context["inst"].append(self)  # Adapters used by strategies

        for call, calldata in self.context.get("calls", {}).items():
            def loop():
                """Loop on event scheduler, calling calls"""
                while not self.stopped.wait(calldata.get("delay", None)):
                    self.call(call, calldata.get("arguments", None))

            self.thread[call] = Process(target=loop)
            self.thread[call].start()

Instruction: Given a code description, retrieve the corresponding code.


Question:
Increments the value of the current byte at the pointer. If the result is over 255,
        then it will overflow to 0

def _increment_current_byte(self):

        # If the current byte is uninitialized, then incrementing it will make it 1
        if self.tape[self.pointer] is None:
            self.tape[self.pointer] = 1
        elif self.tape[self.pointer] == self.MAX_CELL_SIZE:  # If the current byte is already at the max, then overflow
            self.tape[self.pointer] = self.MIN_CELL_SIZE
        else:  # increment it
            self.tape[self.pointer] += 1

public void setChannelPosition(long dataOffset, boolean startWithPartialChunk)
      throws IOException {
    long channelSize = blockDataWriter.getChannelSize();
    if (channelSize < dataOffset) {
      String msg = "Trying to change block file offset of block "
          + block
          + "file "
          + ((blockDataFile.getFile() != null) ? blockDataFile.getFile()
              : "unknown") + " to " + dataOffset
          + " but actual size of file is " + blockDataWriter.getChannelSize();
      throw new IOException(msg);
    }
    if (dataOffset > channelSize) {
      throw new IOException("Set position over the end of the data file.");
    }

    if (startWithPartialChunk && channelSize != dataOffset + checksumSize) {
      DFSClient.LOG.warn("Inline Checksum Block " + block + " channel size "
          + channelSize + " but packet needs to start from " + dataOffset);
    }

    // This flush should be a no-op since we always flush at the end of
    // writePacket() and hence the buffer should be empty.
    // However we do this just to be extra careful so that the
    // channel.position() doesn't mess up things with respect to the
    // buffered dataOut stream.
    blockDataWriter.flush();
    blockDataWriter.position(dataOffset);
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: int: number of sections.

def number_of_sections(self):
    """"""
    if not self._is_parsed:
      self._Parse()
      self._is_parsed = True

    return len(self._sections)

def gru_state_tuples(num_nodes, name):
  """"""
  if not isinstance(num_nodes, tf.compat.integral_types):
    raise ValueError('num_nodes must be an integer: %s' % num_nodes)
  return [(STATE_NAME % name + '_0', tf.float32, num_nodes)]

Instruction: Given a code description, retrieve the corresponding code.


Question: // UpdateHTTPHealthCheck applies the given HTTPHealthCheck as an update.

func (gce *Cloud) UpdateHTTPHealthCheck(hc *compute.HttpHealthCheck) error {
	op, err := gce.service.HttpHealthChecks.Update(gce.projectID, hc.Name, hc).Do()
	if err != nil {
		return err
	}
	return gce.waitForGlobalOp(op)
}

func ValidateWebhook(w auditregistration.Webhook, fldPath *field.Path) field.ErrorList {
	var allErrs field.ErrorList
	if w.Throttle != nil {
		allErrs = append(allErrs, ValidateWebhookThrottleConfig(w.Throttle, fldPath.Child("throttle"))...)
	}

	cc := w.ClientConfig
	switch {
	case (cc.URL == nil) == (cc.Service == nil):
		allErrs = append(allErrs, field.Required(fldPath.Child("clientConfig"), "exactly one of url or service is required"))
	case cc.URL != nil:
		allErrs = append(allErrs, webhook.ValidateWebhookURL(fldPath.Child("clientConfig").Child("url"), *cc.URL, false)...)
	case cc.Service != nil:
		allErrs = append(allErrs, webhook.ValidateWebhookService(fldPath.Child("clientConfig").Child("service"), cc.Service.Name, cc.Service.Namespace, cc.Service.Path, cc.Service.Port)...)
	}
	return allErrs
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Register the given serializer if it has a name.

@param from
@param serializer

protected void registerIfNamed(Class<?> from, Serializer<?> serializer)
	{
		if(from.isAnnotationPresent(Named.class))
		{
			Named named = from.getAnnotation(Named.class);
			QualifiedName key = new QualifiedName(named.namespace(), named.name());
			nameToSerializer.put(key, serializer);
			serializerToName.put(serializer, key);
		}
	}

public function initialize(array $parameters = array())
    {
        $this->parameters = new ParameterContainer;

        // set default parameters
        foreach ($this->getDefaultParameters() as $key => $value) {
            if (is_array($value)) {
                $this->parameters->set($key, reset($value));
            } else {
                $this->parameters->set($key, $value);
            }
        }

        Helper::initialize($this, $parameters);

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Find the places a given method is overridden.

    Finds the places a method is implemented.  Returns a list of
    `Location`\s.

def find_implementations(project, resource, offset, resources=None,
                         task_handle=taskhandle.NullTaskHandle()):

    name = worder.get_name_at(resource, offset)
    this_pymodule = project.get_pymodule(resource)
    pyname = rope.base.evaluate.eval_location(this_pymodule, offset)
    if pyname is not None:
        pyobject = pyname.get_object()
        if not isinstance(pyobject, rope.base.pyobjects.PyFunction) or \
           pyobject.get_kind() != 'method':
            raise exceptions.BadIdentifierError('Not a method!')
    else:
        raise exceptions.BadIdentifierError('Cannot resolve the identifier!')

    def is_defined(occurrence):
        if not occurrence.is_defined():
            return False

    def not_self(occurrence):
        if occurrence.get_pyname().get_object() == pyname.get_object():
            return False
    filters = [is_defined, not_self,
               occurrences.InHierarchyFilter(pyname, True)]
    finder = occurrences.Finder(project, name, filters=filters)
    if resources is None:
        resources = project.get_python_files()
    job_set = task_handle.create_jobset('Finding Implementations',
                                        count=len(resources))
    return _find_locations(finder, resources, job_set)

private void exportInternalAPI(ClassLoader cl) {
        String[] packages = {
            "com.sun.tools.doclets",
            "com.sun.tools.doclets.standard",
            "com.sun.tools.doclets.internal.toolkit",
            "com.sun.tools.doclets.internal.toolkit.taglets",
            "com.sun.tools.doclets.internal.toolkit.builders",
            "com.sun.tools.doclets.internal.toolkit.util",
            "com.sun.tools.doclets.internal.toolkit.util.links",
            "com.sun.tools.doclets.formats.html",
            "com.sun.tools.doclets.formats.html.markup"
        };

        try {
            Method getModuleMethod = Class.class.getDeclaredMethod("getModule");
            Object thisModule = getModuleMethod.invoke(getClass());

            Class<?> moduleClass = Class.forName("java.lang.Module");
            Method addExportsMethod = moduleClass.getDeclaredMethod("addExports", String.class, moduleClass);

            Method getUnnamedModuleMethod = ClassLoader.class.getDeclaredMethod("getUnnamedModule");
            Object target = getUnnamedModuleMethod.invoke(cl);

            for (String pack : packages) {
                addExportsMethod.invoke(thisModule, pack, target);
            }
        } catch (Exception e) {
            // do nothing
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // rangePartitionString returns the partition string for a range typed partition.

func rangePartitionString(pi *model.PartitionInfo) string {
	// partition by range expr
	if len(pi.Columns) == 0 {
		return pi.Expr
	}

	// partition by range columns (c1)
	if len(pi.Columns) == 1 {
		return pi.Columns[0].L
	}

	// partition by range columns (c1, c2, ...)
	panic("create table assert len(columns) = 1")
}

def _ParseShellItemPathSegment(self, shell_item):

    path_segment = None

    if isinstance(shell_item, pyfwsi.root_folder):
      description = shell_folder_ids.DESCRIPTIONS.get(
          shell_item.shell_folder_identifier, None)

      if description:
        path_segment = description
      else:
        path_segment = '{{{0:s}}}'.format(shell_item.shell_folder_identifier)

      path_segment = '<{0:s}>'.format(path_segment)

    elif isinstance(shell_item, pyfwsi.volume):
      if shell_item.name:
        path_segment = shell_item.name
      elif shell_item.identifier:
        path_segment = '{{{0:s}}}'.format(shell_item.identifier)

    elif isinstance(shell_item, pyfwsi.file_entry):
      long_name = ''
      for extension_block in shell_item.extension_blocks:
        if isinstance(extension_block, pyfwsi.file_entry_extension):
          long_name = extension_block.long_name

      if long_name:
        path_segment = long_name
      elif shell_item.name:
        path_segment = shell_item.name

    elif isinstance(shell_item, pyfwsi.network_location):
      if shell_item.location:
        path_segment = shell_item.location

    if path_segment is None and shell_item.class_type == 0x00:
      # TODO: check for signature 0x23febbee
      pass

    if path_segment is None:
      path_segment = '<UNKNOWN: 0x{0:02x}>'.format(shell_item.class_type)

    return path_segment

Instruction: Given a code description, retrieve the corresponding code.


Question: documentation inherited from interface

public void log (int level, String moduleName, String message)
    {
        getLogger(moduleName).log(getLevel(level), message);
    }

public function setResolutionInfo(\AgentSIB\Diadoc\Api\Proto\Events\ResolutionInfo $value = null)
    {
        $this->ResolutionInfo = $value;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Adds an email address (to, cc, bcc inferred from $type) to the \Swift_message
instance passed.

@param \Swift_Message $email
@param string         $type
@param string         $address

protected function addAddress(\Swift_Message $email, string $type, string $address)
    {
        $method = 'add'.$type;

        $parsed = AddressParser::parse($address);
        $email->$method($parsed['address'], $parsed['personal']);
    }

def message_from_string(s, *args, **kws):

    from future.backports.email.parser import Parser
    return Parser(*args, **kws).parsestr(s)

Instruction: Given a code description, retrieve the corresponding code.


Question:
@inheritdoc

@return BaseObject[]|array The resulting elements.

public function populate($rows)
    {
        $indexBy = $this->indexBy;

        if ($indexBy === null) {
            return $this->createObjects($rows);
        }
        $result = [];
        foreach ($rows as $row) {
            if (is_string($indexBy)) {
                $key = $row[$indexBy];
            } else {
                $key = call_user_func($indexBy, $row);
            }
            $result[$key] = $this->createObject($row);
        }
        return $result;
    }

public function plugin($md, $ruleName, $tokenType, $iteartor)
    {
        $scan = function($state) use($md, $ruleName, $tokenType, $iteartor) {
            for ($blkIdx = count($state->tokens) - 1; $blkIdx >= 0; $blkIdx--) {
                if ($state->tokens[$blkIdx]->type !== 'inline') {
                    continue;
                }

                $inlineTokens = $state->tokens[$blkIdx]->children;

                for ($i = count($inlineTokens) - 1; $i >= 0; $i--) {
                    if ($inlineTokens[$i]->type !== $tokenType) {
                        continue;
                    }

                    $iteartor($inlineTokens, $i);
                }
            }
        };

        $md->core->ruler->push($ruleName, $scan);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns relevant URL.
@return \moodle_url

public function get_url() {
        $params = array();
        foreach ($this->validparams as $param) {
            if (!empty($this->other[$param])) {
                $params[$param] = $this->other[$param];
            }
        }
        return new \moodle_url('/blog/index.php', $params);
    }

def get_single_submission_courses(self, user_id, course_id, assignment_id, include=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - assignment_id
        """ID"""
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - user_id
        """ID"""
        path["user_id"] = user_id

        # OPTIONAL - include
        """Associations to include with the group."""
        if include is not None:
            self._validate_enum(include, ["submission_history", "submission_comments", "rubric_assessment", "visibility", "course", "user"])
            params["include"] = include

        self.logger.debug("GET /api/v1/courses/{course_id}/assignments/{assignment_id}/submissions/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/assignments/{assignment_id}/submissions/{user_id}".format(**path), data=data, params=params, no_data=True)

Instruction: Given a code description, retrieve the corresponding code.


Question:
// ParseReferenceParam parses a reference-based query string and returns a
// pointer to a ReferenceParam based on the query and the parameter definition.

func ParseReferenceParam(paramStr string, info SearchParamInfo) *ReferenceParam {
	if info.Postfix != "" {
		typ := findReferencedType("", info)
		q := Query{Resource: typ, Query: info.Postfix + "=" + paramStr}
		return &ReferenceParam{info, ChainedQueryReference{Type: typ, ChainedQuery: q}}
	} else {
		ref := unescape(paramStr)
		re := regexp.MustCompile("\\/?(([^\\/]+)\\/)?([^\\/]+)$")
		if m := re.FindStringSubmatch(ref); m != nil {
			typ := findReferencedType(m[2], info)
			if u, e := url.Parse(ref); e == nil && u.IsAbs() {
				return &ReferenceParam{info, ExternalReference{Type: typ, URL: ref}}
			} else {
				return &ReferenceParam{info, LocalReference{Type: typ, ID: m[3]}}
			}
		}
	}
	return &ReferenceParam{info, nil}
}

def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - quiz_id
        """ID"""
        path["quiz_id"] = quiz_id

        # OPTIONAL - includes_all_versions
        """Whether to retrieve reports that consider all the submissions or only
        the most recent. Defaults to false, ignored for item_analysis reports."""
        if includes_all_versions is not None:
            params["includes_all_versions"] = includes_all_versions

        self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/reports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/reports".format(**path), data=data, params=params, all_pages=True)

Instruction: Given a code description, retrieve the corresponding code.


Question: Create Lower triangular matrix from given matrix

function tril(A, k) {
    if (k === void 0) { k = 0; }
    if (A.shape.length !== 2) {
        throw new Error('Input is not matrix');
    }
    var copyA = A.clone();
    for (var i = 0; i < copyA.shape[0]; i++) {
        for (var j = 0; j < copyA.shape[1]; j++) {
            if (i < j - k) {
                copyA.set(i, j, 0);
            }
        }
    }
    return copyA;
}

public INDArray asMatrix(ImageWritable writable) throws IOException {
        Mat image = converter.convert(writable.getFrame());
        return asMatrix(image);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
设置保存数据 驼峰自动转小写下划线
@param \Illuminate\Pagination\LengthAwarePaginator $obj [分页对象]
@return \DdvPhp\DdvPage $page [分页对象]

public function LengthAwarePaginatorInit($obj)
  {
    $this->pageArray['now'] = intval($obj->currentPage());
    $this->pageArray['count'] = intval($obj->total());
    $this->pageArray['size'] = intval($obj->perPage());
    $this->pageArray['end'] = intval($obj->lastPage());
    $this->setup();
    $this->lists = $obj->getCollection();
    return $this;
  }

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Export exports as a JSON key, encrypted with newPassphrase.

func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
	_, key, err := ks.getDecryptedKey(a, passphrase)
	if err != nil {
		return nil, err
	}
	var N, P int
	if store, ok := ks.storage.(*keyStorePassphrase); ok {
		N, P = store.scryptN, store.scryptP
	} else {
		N, P = StandardScryptN, StandardScryptP
	}
	return EncryptKey(key, newPassphrase, N, P)
}

def to_dict(self):
        ''''''
        d = {'connectorId': self.connector_id,
                'name': self.name,
                'dataType': self.data_type,
                'interfaceType': self.interface_type,
                'dataflowType': self.data_flow_type,
                'sourceDataPort': self.source_data_port.to_dict(),
                'targetDataPort': self.target_data_port.to_dict()}
        if self.visible != True:
            d[RTS_EXT_NS_YAML + 'visible'] = self.visible
        if self.subscription_type:
            d['subscriptionType'] = self.subscription_type
        if self.push_interval:
            d['pushInterval'] = self.push_interval
        if self.comment:
            d[RTS_EXT_NS_YAML + 'comment'] = self.comment
        props = []
        for name in self.properties:
            p = {'name': name}
            if self.properties[name]:
                p['value'] = str(self.properties[name])
            props.append(p)
        if props:
            d[RTS_EXT_NS_YAML + 'properties'] = props
        return d

Instruction: Given a code description, retrieve the corresponding code.


Question:
Checks if a package is installed.

@param context Context to be used to verify the existence of the package.
@param packageName Package name to be searched.
@return true if the package is discovered; false otherwise

public static boolean isPackageInstalled(Context context, String packageName) {
		try {
			context.getPackageManager().getApplicationInfo(packageName, 0);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case BpsimPackage.ELEMENT_PARAMETERS__TIME_PARAMETERS:
				return timeParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__CONTROL_PARAMETERS:
				return controlParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__RESOURCE_PARAMETERS:
				return resourceParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__PRIORITY_PARAMETERS:
				return priorityParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__COST_PARAMETERS:
				return costParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__PROPERTY_PARAMETERS:
				return propertyParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__VENDOR_EXTENSION:
				return vendorExtension != null && !vendorExtension.isEmpty();
			case BpsimPackage.ELEMENT_PARAMETERS__ELEMENT_REF:
				return ELEMENT_REF_EDEFAULT == null ? elementRef != null : !ELEMENT_REF_EDEFAULT.equals(elementRef);
			case BpsimPackage.ELEMENT_PARAMETERS__ID:
				return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
		}
		return super.eIsSet(featureID);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
@see org.s1.objects.Objects#merge(java.util.List)

@param args
@return

@MapMethod
    public Map<String,Object> merge(List<Map<String,Object>> args){
        return Objects.merge(args);
    }

public void optimize() {
        Log.debug("Optimizing index");
        try {
            indexWriter.forceMerge(1, true);
            indexWriter.commit();
        } catch (IOException e) {
            Log.error(e, "Error while optimizing index");
            throw new RuntimeException(e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Print packages status bar

public function setPaper($paper, $orientation=null)
    {
        $this->snappy->setOption('page-size', $paper);
        if($orientation){
            $this->snappy->setOption('orientation', $orientation);
        }
        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Human indicates whether to return time and byte values in human-readable format.

func (s *NodesInfoService) Human(human bool) *NodesInfoService {
	s.human = &human
	return s
}

func Dump(socket *zmq.Socket) {

	fmt.Println("----------------------------------------")

	parts, err := socket.Recv()
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, msg := range parts {
		var binary bool
		for _, x := range msg {
			if x < 32 || x > 127 {
				binary = true
				break
			}
		}

		// Dump the message as text or binary
		fmt.Printf("[%03d] ", len(msg))

		if binary {
			fmt.Printf("% X\n", msg)
		} else {
			fmt.Println(string(msg))
		}
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
set pen shade

 @param Integer val shade

def pen_shade=(val)
      val %= 101
      h, s, = *Color.rgb_to_hsl(*pen_color)
      @pen_color = Color.hsl_to_rgb(h, s, val)
    end

def write_to_position (x, y, text, font = @font)
      print @builder.write_to_position(x, y, text, font)
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add where condition for sharing.

@param QueryBuilder                $qb       The query builder
@param SubjectIdentityInterface[]  $subjects The subjects
@param SecurityIdentityInterface[] $sids     The security identities

@return QueryBuilder

private function addWhereForSharing(QueryBuilder $qb, array $subjects, array $sids)
    {
        $where = '';
        $parameters = [];

        foreach ($subjects as $i => $subject) {
            $class = 'subject'.$i.'_class';
            $id = 'subject'.$i.'_id';
            $parameters[$class] = $subject->getType();
            $parameters[$id] = $subject->getIdentifier();
            $where .= '' === $where ? '' : ' OR ';
            $where .= sprintf('(s.subjectClass = :%s AND s.subjectId = :%s)', $class, $id);
        }

        $qb->where($where);

        foreach ($parameters as $key => $value) {
            $qb->setParameter($key, $value);
        }

        return $this->addWhereSecurityIdentitiesForSharing($qb, $sids);
    }

def get_specification_info(self, obj):

        info = self.get_base_info(obj)

        results_range = obj.getResultsRange()
        info.update({
            "results_range": results_range,
            "sample_type_uid": obj.getSampleTypeUID(),
            "sample_type_title": obj.getSampleTypeTitle(),
            "client_uid": obj.getClientUID(),
        })

        bsc = api.get_tool("bika_setup_catalog")

        def get_service_by_keyword(keyword):
            if keyword is None:
                return []
            return map(api.get_object, bsc({
                "portal_type": "AnalysisService",
                "getKeyword": keyword
            }))

        # append a mapping of service_uid -> specification
        specifications = {}
        for spec in results_range:
            service_uid = spec.get("uid")
            if service_uid is None:
                # service spec is not attached to a specific service, but to a
                # keyword
                for service in get_service_by_keyword(spec.get("keyword")):
                    service_uid = api.get_uid(service)
                    specifications[service_uid] = spec
                continue
            specifications[service_uid] = spec
        info["specifications"] = specifications
        # spec'd service UIDs
        info["service_uids"] = specifications.keys()
        return info

Instruction: Given a code description, retrieve the corresponding code.


Question: Retrieve all items from a story.

def get_items(self) -> Iterator[StoryItem]:
        """"""
        yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items']))

public function getAll($appId, $scanId, $issueId, array $queryParams = [])
    {
        $response = $this->api
            ->applications()
            ->scans()
            ->issues()
            ->contexts()
            ->getAll($appId, $scanId, $issueId, $queryParams);

        return new ContextsResponse($response);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Since TCP is a stream-orientated protocol, responses aren't guaranteed
        to be complete when they arrive. The buffer stores all the data and
        this function splits the data into replies based on the new line
        delimiter.

def parse_buf(self, encoding="unicode"):

        buf_len = len(self.buf)
        replies = []
        reply = b""
        chop = 0
        skip = 0
        i = 0
        buf_len = len(self.buf)
        for i in range(0, buf_len):
            ch = self.buf[i:i + 1]
            if skip:
                skip -= 1
                i += 1
                continue

            nxt = i + 1
            if nxt < buf_len:
                if ch == b"\r" and self.buf[nxt:nxt + 1] == b"\n":

                    # Append new reply.
                    if reply != b"":
                        if encoding == "unicode":
                            replies.append(encode_str(reply, encoding))
                        else:
                            replies.append(reply)
                        reply = b""

                    # Truncate the whole buf if chop is out of bounds.
                    chop = nxt + 1
                    skip = 1
                    i += 1
                    continue

            reply += ch
            i += 1

        # Truncate buf.
        if chop:
            self.buf = self.buf[chop:]

        return replies

func NewWriter(dest io.Writer, state ws.State, op ws.OpCode) *Writer {
	return NewWriterBufferSize(dest, state, op, 0)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Parse main body

@param array $body Body
@return array Parsed body

protected function parseBody(array $body)
    {
        $jobs = [];
        if (!empty($body)) {
            if (is_string($body[0])) {
                foreach ($body as $element) {
                    $jobs[] = ['id' => $element];
                }
            } else {
                $keyValueResponse = new KeyValueResponse();
                $keyValueResponse->setCommand($this->command);

                foreach ($body as $element) {
                    $keyValueResponse->setBody($element);
                    $jobs[] = $keyValueResponse->parse();
                }
            }
        }
        return ['jobs' => $jobs];
    }

func assemblePostBody(req Request) string {
	// Make a list of key/value pairs and sort them by key.
	kvPairs := keyValueList{}
	for key, val := range req {
		kvPairs = append(kvPairs, keyValuePair{key, val})
	}

	sort.Sort(kvPairs)

	// Assemble the appropriate parts.
	parts := make([]string, len(kvPairs))
	for i, kvPair := range kvPairs {
		parts[i] = url.QueryEscape(kvPair.Key) + "=" + url.QueryEscape(kvPair.Val)
	}

	result := strings.Join(parts, "&")

	// Amazon disagrees with Go about what to do with spaces; Go uses '+'
	// characters and Amazon wants "%20". Transform '+' characters appropriately.
	// This is safe because actual '+' characters have already been encoded as
	// "%2B".
	result = strings.Replace(result, "+", "%20", -1)

	return result
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
//AddResourceSeparateUdid adds a resource to a given rest node, in a way parallel
//to ResourceSeparateUdid.

func (self *RawDispatcher) AddResourceSeparateUdid(node *RestNode, name string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid) {
	t := self.validateType(wireExample)
	obj := &restObjUdid{
		restShared: restShared{
			typ:   t,
			name:  name,
			index: index,
			post:  post,
		},
		find: find,
		del:  del,
		put:  put,
	}
	node.ResUdid[strings.ToLower(name)] = obj
}

def get_multiple_devices(self, rids):

        headers = {
                'User-Agent': self.user_agent(),
                'Content-Type': self.content_type()
        }
        headers.update(self.headers())

        url = self.portals_url()+'/users/_this/devices/' + str(rids).replace("'", "").replace(' ','')
        # print("URL: {0}".format(url))
        r = requests.get(   url,
                            headers=headers,
                            auth=self.auth())

        if HTTP_STATUS.OK == r.status_code:
            # TODO: loop through all rids and fix 'meta' to be dict like add_device and get_device do
            return r.json()
        else:
            print("get_multiple_devices: Something went wrong: <{0}>: {1}".format(
                        r.status_code, r.reason))
            r.raise_for_status()

Instruction: Given a code description, retrieve the corresponding code.


Question:
Converts the relative position of @rect into an absolute position.To be
        used for event considerations, blitting is handled directly by the
        Container().

def convert_rect(self, rect):
        '''

        '''
        return self.container.convert_rect(rect.move(self.pos))

def _allocate_output(self, windows, shape):

        if self.dtype == int64_dtype:
            return super(CustomClassifier, self)._allocate_output(
                windows,
                shape,
            )

        # This is a little bit of a hack.  We might not know what the
        # categories for a LabelArray are until it's actually been loaded, so
        # we need to look at the underlying data.
        return windows[0].data.empty_like(shape)

Instruction: Given a code description, retrieve the corresponding code.


Question:
设置执行代码
@param callable $code callable(InputInterface $input, OutputInterface $output)
@return Command
@throws \InvalidArgumentException
@see execute()

public function setCode(callable $code) {
        if (!is_callable($code)) {
            throw new \InvalidArgumentException('Invalid callable provided to Command::setCode.');
        }

        if (PHP_VERSION_ID >= 50400 && $code instanceof \Closure) {
            $r = new \ReflectionFunction($code);
            if (null === $r->getClosureThis()) {
                $code = \Closure::bind($code, $this);
            }
        }

        $this->code = $code;

        return $this;
    }

func (cli *SeesawCLI) Execute(cmdline string) error {
	cmd, subcmds, _, args := FindCommand(cmdline)
	if cmd != nil {
		return cmd.function(cli, args)
	}
	if subcmds != nil {
		return errors.New("Incomplete command.")
	}
	return errors.New("Unknown command.")
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
build execution string like create_or_update_multiple_objects({"(a,b)","(c,d)" }).

@param   args

@return

private String getDebugLog(final Object[] args) {
        final StringBuilder sb = new StringBuilder(name);
        sb.append('(');

        int i = 0;
        for (final Object param : args) {
            if (i > 0) {
                sb.append(',');
            }

            if (param == null) {
                sb.append("NULL");
            } else if (params.get(i).isSensitive()) {
                sb.append("<SENSITIVE>");
            } else {
                sb.append(param);
            }

            i++;
            if (sb.length() > TRUNCATE_DEBUG_PARAMS_MAX_LENGTH) {
                break;
            }
        }

        if (sb.length() > TRUNCATE_DEBUG_PARAMS_MAX_LENGTH) {

            // Truncate params for debug output
            return sb.substring(0, TRUNCATE_DEBUG_PARAMS_MAX_LENGTH) + TRUNCATE_DEBUG_PARAMS_ELLIPSIS + ")";
        } else {
            sb.append(')');
            return sb.toString();
        }
    }

public function bulkCreate(CrudConfigurator $crudConfigurator)
    {
        /** @var BulkCreateActionHandler $viewHandler */
        $viewHandler = $this->actionHandlers[BulkCreateActionHandler::class];
        $viewHandler->setView($this->view);
        $viewHandler->setRequest($this->request);
        $viewHandler->setCrudConfigurator($crudConfigurator);

        $view = $viewHandler->getView($this->driver);

        return new JsonResponse(array(
            'status' => $view->getParam('status'),
            'message' => $view->getParam('message'),
        ));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
We need to find the blocks that didn't match.  Likely only one
is corrupt but we will report both to the namenode.  In the future,
we can consider figuring out exactly which block is corrupt.

public boolean reportChecksumFailure(Path f,
                                       FSDataInputStream in, long inPos,
                                       FSDataInputStream sums, long sumsPos) {
    return getDFS().reportChecksumFailure(f, in, inPos, sums, sumsPos);
  }

def handle_moban_file(moban_file, options):

    moban_file_configurations = load_data(None, moban_file)
    if moban_file_configurations is None:
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_INVALID_MOBAN_FILE % moban_file
        )
    if (
        constants.LABEL_TARGETS not in moban_file_configurations
        and constants.LABEL_COPY not in moban_file_configurations
    ):
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_NO_TARGETS % moban_file
        )
    check_none(moban_file_configurations, moban_file)
    version = moban_file_configurations.get(
        constants.MOBAN_VERSION, constants.DEFAULT_MOBAN_VERSION
    )
    if version == constants.DEFAULT_MOBAN_VERSION:
        mobanfile.handle_moban_file_v1(moban_file_configurations, options)
    else:
        raise exceptions.MobanfileGrammarException(
            constants.MESSAGE_FILE_VERSION_NOT_SUPPORTED % version
        )
    HASH_STORE.save_hashes()

Instruction: Given a code description, retrieve the corresponding code.


Question: // AddEventsWithToken emits a list of events using a supplied token

func (a *AsyncMultiTokenSink) AddEventsWithToken(token string, events []*event.Event) (err error) {
	var channelID int64
	if channelID, err = a.getChannel(token, len(a.evChannels)); err == nil {
		var worker = a.evChannels[channelID]
		_ = atomic.AddInt64(&a.evBuffered, int64(len(events)))
		var m = &evMsg{
			token: token,
			data:  events,
		}
		select {
		// check if the sink is closing and return if so
		// reading from a.closing will only return a value if the a.closing channel is closed
		case <-a.closing:
			err = fmt.Errorf("unable to add events: the worker has been stopped")
		default:
			select {
			case worker.input <- m:
				atomic.AddInt64(&a.stats.TotalEventsBuffered, int64(len(events)))
			default:
				err = fmt.Errorf("unable to add events: the input buffer is full")
			}
		}

	} else {
		err = fmt.Errorf("unable to add events: there was an error while hashing the token to a worker. %v", err)
	}

	return
}

public function generateFeed()
    {
        if ($this->version != Feed::ATOM && !array_key_exists('link', $this->channels))
            throw new InvalidOperationException('RSS1 & RSS2 feeds need a link element. Call the setLink method before this method.');

        return $this->makeHeader()
            . $this->makeChannels()
            . $this->makeItems()
            . $this->makeFooter();
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets the main dataframe to rows that has the exact string
        value in a column

def exact(self, column, *values):

        df = self._exact(column, *values)
        if df is None:
            self.err("Can not select exact data")
        self.df = df

def get_collections_like_name(collection_name,**kwargs):

    try:
        collections = db.DBSession.query(DatasetCollection).filter(DatasetCollection.name.like("%%%s%%"%collection_name.lower())).all()
    except NoResultFound:
        raise ResourceNotFoundError("No dataset collection found with name %s"%collection_name)

    return collections

Instruction: Given a code description, retrieve the corresponding code.


Question:
Definition of the avhrr instrument, gac version

    Source: NOAA KLM User's Guide, Appendix J
    http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm

def avhrr_gac(scan_times, scan_points,
              scan_angle=55.37, frequency=0.5):

    try:
        offset = np.array([(t - scan_times[0]).seconds +
                           (t - scan_times[0]).microseconds / 1000000.0 for t in scan_times])
    except TypeError:
        offset = np.arange(scan_times) * frequency
    scans_nb = len(offset)

    avhrr_inst = np.vstack(((scan_points / 1023.5 - 1)
                            * np.deg2rad(-scan_angle),
                            np.zeros((len(scan_points),))))

    avhrr_inst = np.tile(
        avhrr_inst[:, np.newaxis, :], [1, np.int(scans_nb), 1])
    # building the corresponding times array
    times = (np.tile(scan_points * 0.000025, [scans_nb, 1])
             + np.expand_dims(offset, 1))
    return ScanGeometry(avhrr_inst, times)

public java.util.List<Destination> getDestinations() {
        if (destinations == null) {
            destinations = new com.amazonaws.internal.SdkInternalList<Destination>();
        }
        return destinations;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Die "E.123" ist eine Empfehlung der Internationalen Fernmeldeunion.
Dabei werden die einzelnen Bestandteile (Laenderkennzeichen, Vorwahl
und Rufnummer) durch Leerzeichen gruppiert.

@return z.B. "+49 30 12345 67" oder "(030) 12345 67" (national)

public String toE123String() {
        if (getLaenderkennzahl().isPresent()) {
            return toDinString().replace('-', ' ');
        } else {
            return "(" + getVorwahl() + ") " + getRufnummer().toString().replace('-', ' ');
        }
    }

protected function autolink($matches)
	{
		$href = $matches[0];

		if (substr($href, 0, 1) == '!')
		{
			return substr($href, 1);
		}

		$href = str_replace('"', '', $href);
		$href = str_replace("'", '', $href);
		$href = str_replace('&#8221', '', $href);

		$h = array('h', 'm', 'f', 'g', 'n');
		if (!in_array(substr($href, 0, 1), $h))
		{
			$href = substr($href, 1);
		}
		$name = trim($href);
		if (substr($name, 0, 7) == 'mailto:')
		{
			$name = substr($name, 7, strlen($name));
			$name = Str::obfuscate($name);

			$href = 'mailto:' . $name;
		}
		$l = sprintf(
			' %s', $href, $name
		);
		return $l;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Check file attribute

@param  string  $path  file path
@param  string  $name  attribute name (read|write|locked|hidden)
@param  bool    $val   attribute value returned by file system
@return bool
@author Dmitry (dio) Levashov

protected function attr($path, $name, $val=false) {
		if (!isset($this->defaults[$name])) {
			return false;
		}

		$perm = null;

		if ($this->access) {
			if (is_array($this->access)) {
				$obj    = $this->access[0];
				$method = $this->access[1];
				$perm   = $obj->{$method}($name, $path, $this->options['accessControlData'], $this);
			} else {
				$func = $this->access;
				$perm = $func($name, $path, $this->options['accessControlData'], $this);
			}

			if ($perm !== null) {
				return !!$perm;
			}
		}

		for ($i = 0, $c = count($this->attributes); $i < $c; $i++) {
			$attrs = $this->attributes[$i];
			$p = $this->separator.$this->_relpath($path);
			if (isset($attrs[$name]) && isset($attrs['pattern']) && preg_match($attrs['pattern'], $p)) {
				$perm = $attrs[$name];
			}
		}

		return $perm === null ? $this->defaults[$name] : !!$perm;
	}

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Flush the current write buffer to disk.

@param buffer Buffer to write
@param output Output channel
@throws IOException on IO errors

private void flushBuffer(ByteBuffer buffer, WritableByteChannel output) throws IOException {
    buffer.flip();
    output.write(buffer);
    buffer.flip();
    buffer.limit(buffer.capacity());
  }

func (d *driver) PutContent(context context.Context, path string, contents []byte) error {
	return retry(func() error {
		wc := storage.NewWriter(d.context(context), d.bucket, d.pathToKey(path))
		wc.ContentType = "application/octet-stream"
		return putContentsClose(wc, contents)
	})
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Creates the doManifest-Request

@param string|string[] $shipmentNumbers - Shipment-Number(s) for Manifest (up to 30 Numbers)
@return bool|Response - false on error or DHL-Response Object

public function doManifest($shipmentNumbers) {
		switch($this->getMayor()) {
			case 1:
				$data = $this->createDoManifestClass_v1($shipmentNumbers);
				break;
			case 2:
			default:
				$data = $this->createDoManifestClass_v2($shipmentNumbers);
		}

		try {
			$response = $this->sendDoManifestRequest($data);
		} catch(Exception $e) {
			$this->addError($e->getMessage());

			return false;
		}

		if(is_soap_fault($response)) {
			$this->addError($response->faultstring);

			return false;
		} else
			return new Response($this->getVersion(), $response);
	}

@Override
	public long dynamicQueryCount(DynamicQuery dynamicQuery,
		Projection projection) {
		return commerceShipmentItemPersistence.countWithDynamicQuery(dynamicQuery,
			projection);
	}

Instruction: Given a code description, retrieve the corresponding code.