Question: Get the arthur params given a URL for the data source

def get_arthur_params_from_url(cls, url):

        params = {}

        args = cls.get_perceval_params_from_url(url)
        parser = GitLabCommand.setup_cmd_parser()

        parsed_args = parser.parse(*args)

        params['owner'] = parsed_args.owner
        params['repository'] = parsed_args.repository
        # include only blacklist ids information
        params['blacklist_ids'] = parsed_args.blacklist_ids

        return params

public function post($query, Array $parameters = [], $autoParser = true) {
        curl_setopt_array($this->resource, [
            CURLOPT_POSTFIELDS => array_merge($parameters, [
                self::PARAMETER_QUERY => $query,
                self::PARAMETER_APIKEY => $this->apiKey
            ])
        ]);

        $dom = new \DOMDocument;
        $ret = curl_exec($this->resource);
        if (!$autoParser) return $ret;
        $dom->loadXML($ret);
        static::assert($dom);
        return $dom;
    }

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


Question:
Ensure that project metadata is available.

        Under PEP 517, call the backend hook to prepare the metadata.
        Under legacy processing, call setup.py egg-info.

def prepare_metadata(self):
        # type: () -> None

        assert self.source_dir

        with indent_log():
            if self.use_pep517:
                self.prepare_pep517_metadata()
            else:
                self.run_egg_info()

        if not self.req:
            if isinstance(parse_version(self.metadata["Version"]), Version):
                op = "=="
            else:
                op = "==="
            self.req = Requirement(
                "".join([
                    self.metadata["Name"],
                    op,
                    self.metadata["Version"],
                ])
            )
            self._correct_build_location()
        else:
            metadata_name = canonicalize_name(self.metadata["Name"])
            if canonicalize_name(self.req.name) != metadata_name:
                logger.warning(
                    'Generating metadata for package %s '
                    'produced metadata for project name %s. Fix your '
                    '#egg=%s fragments.',
                    self.name, metadata_name, self.name
                )
                self.req = Requirement(metadata_name)

def make(parser):

    config_parser = parser.add_subparsers(dest='subcommand')
    config_parser.required = True

    config_push = config_parser.add_parser(
        'push',
        help='push Ceph config file to one or more remote hosts'
        )
    config_push.add_argument(
        'client',
        metavar='HOST',
        nargs='+',
        help='host(s) to push the config file to',
        )

    config_pull = config_parser.add_parser(
        'pull',
        help='pull Ceph config file from one or more remote hosts'
        )
    config_pull.add_argument(
        'client',
        metavar='HOST',
        nargs='+',
        help='host(s) to pull the config file from',
        )
    parser.set_defaults(
        func=config,
        )

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


Question:
Verifies that data matches a hash
@param string $data
@param string $hash
@return boolean

public static function validateHash($data, $hash) {

        if(false === is_string($data) && false === is_numeric($data)) {
            return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string or number, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
        }

        if(false === is_string($hash)) {
            return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($hash)), E_USER_ERROR);
        }

        return hash(self :: HASH_ALGORITHM, $data) === $hash;
    }

def check_data(yaml_data, errors_array)
      valid = check_not_empty?(yaml_data, errors_array)
      valid &&= check_syntax_valid?(yaml_data, errors_array)
      valid &&= check_overlapping_keys?(yaml_data, errors_array)

      valid
    end

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


Question:
Attempts to call #columns on the model's class
 If the (Active Record) #columns method does not exist, it attempts to
 perform the (Mongoid) #fields method instead

def columns
      begin
        excluded_column_names = %w[id created_at updated_at]
        Kernel.const_get(@model_name).columns.reject{|c| excluded_column_names.include?(c.name) }.collect{|c| Rails::Generators::GeneratedAttribute.new(c.name, c.type)}
      rescue NoMethodError
        Kernel.const_get(@model_name).fields.collect{|c| c[1]}.reject{|c| excluded_column_names.include?(c.name) }.collect{|c| Rails::Generators::GeneratedAttribute.new(c.name, c.type.to_s)}
      end
    end

def set_row(row, val)
      # Setter
      if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
        raise ArgumentError, 'Illegal argument type'
      elsif val.is_a?(Array) && val.size != col_keys.size
        raise ArgumentError, 'Column size not match'
      end

      case val
      when Array
        if @row_keys[row]
          row = @row_keys[row]
          @content[row] = val
        else
          @row_keys[row] = @row_keys.size
          @content << val
        end
      when Hash
        unless @row_keys[row]
          @row_keys[row] = @row_keys.size
          @content << ([''] * @col_keys.size)
        end

        row = @row_keys[row]
        val.each do |k, v|
          col = @col_keys[k]
          @content[row][col] = v if col
        end
      end

      self
    end

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


Question:
Sets the {@link LinkDiscoverers} to use. By default a single {@link HalLinkDiscoverer} is registered. If
{@literal null} is provided the default is reapplied.

@param discoverer can be {@literal null}.
@return

public Traverson setLinkDiscoverers(@Nullable List<? extends LinkDiscoverer> discoverer) {

		List<? extends LinkDiscoverer> defaultedDiscoverers = discoverer == null //
				? DEFAULTS.getLinkDiscoverers(mediaTypes) //
				: discoverer;

		this.discoverers = new LinkDiscoverers(PluginRegistry.of(defaultedDiscoverers));

		return this;
	}

func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
	if !value.IsValid() {
		if typ == nil || canBeNil(typ) {
			// An untyped nil interface{}. Accept as a proper nil value.
			return reflect.Zero(typ)
		}
		s.errorf("invalid value; expected %s", typ)
	}
	if typ != nil && !value.Type().AssignableTo(typ) {
		if value.Kind() == reflect.Interface && !value.IsNil() {
			value = value.Elem()
			if value.Type().AssignableTo(typ) {
				return value
			}
			// fallthrough
		}
		// Does one dereference or indirection work? We could do more, as we
		// do with method receivers, but that gets messy and method receivers
		// are much more constrained, so it makes more sense there than here.
		// Besides, one is almost always all you need.
		switch {
		case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
			value = value.Elem()
			if !value.IsValid() {
				s.errorf("dereference of nil pointer of type %s", typ)
			}
		case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
			value = value.Addr()
		default:
			s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
		}
	}
	return value
}

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


Question:
Updates an existing model.
If update is successful, the browser will be redirected to the 'view' page.
@param integer $id
@return mixed

public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if (!\Yii::$app->user->can('update'))
            return $this->alert(Module::t('core', 'Access denied.'));

        $this->_tag = $model->name;

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            // replace all tags in all posts
            \Yii::$app->db->createCommand("UPDATE {{%post}} SET tags = REPLACE(tags, '{$this->_tag}', '{$model->name}') WHERE tags LIKE '%{$this->_tag}%'")
                ->execute();
            return YII_DEBUG
                ? $this->redirect(['index'])
                : $this->redirect(\Yii::$app->request->referrer);
        } else {
            return $this->renderAjax('update', [
                'model' => $model,
            ]);
        }
    }

public function setWarehouseId( $warehouseid )
	{
		if ( $warehouseid === $this->getWarehouseId() ) { return; }

		if ( $warehouseid !== null ) {
			$warehouseid = (int) $warehouseid;
		}

		$this->_values['warehouseid'] = $warehouseid;
		$this->setModified();
	}

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


Question:
/* (non-Javadoc)
@see com.ibm.ws.sib.processor.runtime.SIMPRemoteConsumerReceiverControllable#getNumberOfRequestsIssuecd()

public long getNumberOfRequestsIssued()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "getNumberOfRequestsIssued");
    long returnValue = anycastIH.getTotalSentRequests();
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "getNumberOfRequestsIssued", Long.valueOf(returnValue));
    return returnValue;
  }

def help
      puts
      puts  "chimpd -- a RightScale Platform command-line tool"
      puts
      puts  "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
      puts
      puts  "Options:"
      puts
      puts  " --logfile=<name>            Specifiy the desired log location"
      puts  " --concurrency=<n>           Specify the level of concurrent actions"
      puts  " --delay=<n>                 Specify the number of seconds to wait before executing the action"
      puts  " --retry=<r>                 Specify the number of times chimpd should retry executing the action"
      puts
      puts  " --verbose                   Run chimpd in verbose mode."
      puts  " --quiet                     Supress non-essential output"
      puts
      puts  " --port=<port>               Specify the port number for chimpd to listen on (default: 9055)"
      puts  " --bind-address=<addr>       Specify an interface address for chimpd to bind to.  0.0.0.0 allows all, default is 'localhost'"
      puts
      puts  " --help                      Displays this menu"
      puts
      exit 0
    end

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


Question:
Turn an object into an array. Alternative to array_map magic.

@param object|array $object
@return array

public static function buildArray($object) {
        $array = array();

        foreach ($object as $key => $value) {
            if (is_object($value) || is_array($value)) {
                $array[$key] = static::buildArray($value);
            } else {
                $array[$key] = static::autobox($value);
            }
        }

        return $array;
    }

private function parseOptionsArray($options, \stdClass $result)
    {
        foreach ($options as $option => $value) {
            if (! property_exists($this, $option)) {
                $result->invalidOptions[] = $option;
                continue;
            }

            //Define Option
            $this->$option = $value;
            unset($result->missingOptions[$option]);
        }
    }

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


Question:
Find a return statment in the current node

@param {ASTNode} ASTnode The AST node being checked

function(node) {
      if (!node.value || !node.value.body || !node.value.body.body) {
        return false;
      }
      var i = node.value.body.body.length - 1;
      for (; i >= 0; i--) {
        if (node.value.body.body[i].type === 'ReturnStatement') {
          return node.value.body.body[i];
        }
      }
      return false;
    }

def _rt_parse_execs(self, statement, element, mode, lineparser):
        """"""
        #This is the same deal as with _rt_parse_types() below.
        if mode == "insert":
            enew, start, end = self.xparser.parse_signature(statement, element, element)
            if enew is not None:
                enew.start, enew.end = lineparser.absolute_charindex(statement, start, end)
                enew.incomplete = True
                element.executables[enew.name.lower()] = enew
                lineparser.additions.append((enew, element))

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


Question:
// Rewatch implements Watcher interface.
//
// TODO(rjeczalik): This is a naive hack. Rewrite might help.

func (t *trg) Rewatch(p string, _, e Event) error {
	fi, err := os.Stat(p)
	if err != nil {
		return err
	}
	t.Lock()
	if err = t.unwatch(p, fi); err == nil {
		// TODO(rjeczalik): If watch fails then we leave trigger in inconsistent
		// state. Handle? Panic? Native version of rewatch?
		err = t.watch(p, e, fi)
	}
	t.Unlock()
	return nil
}

def write_source(self, source, comment=None, reject=False):

        if not self._header_written:
            observations = [reading.get_observation() for reading in source.get_readings()]
            self.write_headers(observations, self.sys_header)

        self._write_source(source, comment=comment, reject=reject)

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


Question: // FieldValueByName returns the value of a field given row number and name provided

func (dt *DbfTable) FieldValueByName(row int, fieldName string) (value string, err error) {
	if fieldIndex, entryFound := dt.fieldMap[fieldName]; entryFound {
		return dt.FieldValue(row, fieldIndex), err
	}
	err = errors.New("Field name \"" + fieldName + "\" does not exist")
	return
}

public void dataToField(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
    {
        if (componentCache.m_rgcompoments[iColumnIndex] != null)
        {
            String string = null;
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
                string = ((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).getText();
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
                if (((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).isSelected())
                    string = "1";
            //xif (string != null) if (string.length() > 0)
            this.getModel().setValueAt(string, iRowIndex, iColumnIndex);
        }
    }

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


Question:
Creates tags info beans from given
tags map with tag names as keys and tag values as map values

@param tagsMap map of tag names and values
@return list of tag entries

public static List<TagEntryAO> tagsMapToTagEntries(Map<String, String> tagsMap) {

    	if (tagsMap==null)
    		return Collections.EMPTY_LIST;

        List<TagEntryAO> tagEntries = new ArrayList<>(tagsMap.size());

        for (Map.Entry<String,String> entry : tagsMap.entrySet())
            tagEntries.add(
                    new TagEntryAO(entry.getKey(), entry.getValue())
            );

        return tagEntries;

    }

public ResourceDescription getChildDescription(String type, String name) {
        if (hasChildrenDefined()) {
            List<Property> children = get("children").asPropertyList();
            for (Property child : children) {
                if (type.equals(child.getName()) && child.getValue().hasDefined(MODEL_DESCRIPTION)) {
                    List<Property> modelDescriptions = child.getValue().get(MODEL_DESCRIPTION).asPropertyList();
                    for (Property modelDescription : modelDescriptions) {
                        if (name.equals(modelDescription.getName())) {
                            return new ResourceDescription(modelDescription.getValue());
                        }
                    }
                }
            }
        }
        return EMPTY;
    }

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


Question: parse reveive msgs to global variable

def parse_rev_args(receive_msg):

    global trainloader
    global testloader
    global net
    global criterion
    global optimizer

    # Loading Data
    logger.debug("Preparing data..")

    transform_train, transform_test = utils.data_transforms_cifar10(args)

    trainset = torchvision.datasets.CIFAR10(
        root="./data", train=True, download=True, transform=transform_train
    )
    trainloader = torch.utils.data.DataLoader(
        trainset, batch_size=args.batch_size, shuffle=True, num_workers=2
    )

    testset = torchvision.datasets.CIFAR10(
        root="./data", train=False, download=True, transform=transform_test
    )
    testloader = torch.utils.data.DataLoader(
        testset, batch_size=args.batch_size, shuffle=False, num_workers=2
    )

    # Model
    logger.debug("Building model..")
    net = build_graph_from_json(receive_msg)

    net = net.to(device)
    criterion = nn.CrossEntropyLoss()
    if device == "cuda" and torch.cuda.device_count() > 1:
        net = torch.nn.DataParallel(net)

    if args.optimizer == "SGD":
        optimizer = optim.SGD(
            net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=5e-4
        )
    if args.optimizer == "Adadelta":
        optimizer = optim.Adadelta(net.parameters(), lr=args.learning_rate)
    if args.optimizer == "Adagrad":
        optimizer = optim.Adagrad(net.parameters(), lr=args.learning_rate)
    if args.optimizer == "Adam":
        optimizer = optim.Adam(net.parameters(), lr=args.learning_rate)
    if args.optimizer == "Adamax":
        optimizer = optim.Adamax(net.parameters(), lr=args.learning_rate)
    if args.optimizer == "RMSprop":
        optimizer = optim.RMSprop(net.parameters(), lr=args.learning_rate)

    return 0

def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2
        """"""
        ret = cls(message.items())
        # ret now contains only the last header line for each duplicate.
        # Importing with all duplicates would be nice, but this would
        # mean to repeat most of the raw parsing already done, when the
        # message object was created. Extracting only the headers of interest
        # separately, the cookies, should be faster and requires less
        # extra code.
        for key in duplicates:
            ret.discard(key)
            for val in message.getheaders(key):
                ret.add(key, val)
            return ret

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


Question:
// NotEqual succeeds if string is not equal to given Go string.
//
// Example:
//  str := NewString(t, "Hello")
//  str.NotEqual("Goodbye")

func (s *String) NotEqual(value string) *String {
	if !(s.value != value) {
		s.chain.fail("\nexpected string not equal to:\n %q", value)
	}
	return s
}

func Login(login, password string) (*User, error) {
	var email *mail.Address
	var username string
	var id uint64
	var e error

	if email, e = mail.ParseAddress(login); e == nil { // is a mail
		if e = Db().Model(User{}).Select("username").Where(&User{Email: email.Address}).Scan(&username); e != nil {
			return nil, e
		}
	} else if id, e = strconv.ParseUint(login, 10, 64); e == nil { // if login the user ID
		if e = Db().Model(User{}).Select("username").Where(&User{Counter: id}).Scan(&username); e != nil {
			return nil, e
		}
	} else { // otherwise is the username
		username = login
	}

	var logged bool
	var counter uint64

	if e = Db().Model(User{}).Select("login(?, ?) AS logged, counter", username, password).Where("LOWER(username) = ?", username).Scan(&logged, &counter); e != nil {
		return nil, e
	}

	if !logged {
		return nil, errors.New("wrong username or password")
	}

	return NewUser(counter)
}

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


Question: Create a scroll bar div with the given direction *

function(direction) {
    var bar = document.createElement('div'),
      indicator = document.createElement('div');

    indicator.className = 'scroll-bar-indicator scroll-bar-fade-out';

    if (direction == 'h') {
      bar.className = 'scroll-bar scroll-bar-h';
    } else {
      bar.className = 'scroll-bar scroll-bar-v';
    }

    bar.appendChild(indicator);
    return bar;
  }

private void addFirstChildElements() {
        for (Node node : nodes) {
            if (DOMHelper.getPreviousSiblingElement(node) == null) {
                result.add(node);
            }
        }
    }

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


Question:
Reset webcam driver.

This method is not thread-safe!

public static void resetDriver() {

		synchronized (DRIVERS_LIST) {
			DRIVERS_LIST.clear();
		}

		if (discovery != null) {
			discovery.shutdown();
			discovery = null;
		}

		driver = null;
	}

def set_night_light_brightness(self, brightness=200):
        """"""
        self.publish(
            action='set',
            resource='cameras/{}'.format(self.device_id),
            publish_response=False,
            properties={'nightLight': {'brightness': brightness}}
        )

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


Question:
Save file into the database

@param FileCreateOrUpdateEvent $event      the event
@param FileModelInterface      $imageModel the file model object (image or document) to save.

@return int number of modified rows in database

public function saveImage(FileCreateOrUpdateEvent $event, FileModelInterface $imageModel)
    {
        return $this->saveFile($event->getParentId(), $imageModel);
    }

public function permissionSave(Permission $permission)
    {
        if ($permission->permission_id) {
            $query = "
                UPDATE
                    auth_permission
                SET
                    `name` = :name, description = :description, updated_on = " . $this->sql_time_func . "
                WHERE
                    permission_id = :permission_id
            ";
        } else {
            $query = "
                INSERT INTO
                    auth_permission (`name`, description, updated_on, added_on)
                VALUES
                    (:name, :description, " . $this->sql_time_func . ", " . $this->sql_time_func . ")
            ";
        }
        $cur = $this->db->prepare($query);
        $cur->bindParam(":name", $permission->name, PDO::PARAM_STR, 32);
        $cur->bindParam(":description", $permission->description, PDO::PARAM_STR);
        if ($permission->permission_id) {
            $cur->bindParam(":permission_id", $permission->permission_id, PDO::PARAM_INT);
        }
        $this->db->beginTransaction();
        try {
            $cur->execute();
            if (!$permission->permission_id) {
                $permission->permission_id = $this->db->lastInsertId();
            }
            $this->db->commit();
        } catch (PDOException $db_err) {
            $this->db->rollBack();
            if ($this->logger) {
                $this->logger->error("Failed to create/update permission", ['exception' => $db_err]);
            }
            return false;
        }
        return true;
    }

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


Question:
Remove variety.

@param \Librinfo\VarietiesBundle\Entity\Variety $variety

@return bool tRUE if this collection contained the specified element, FALSE otherwise

public function removeVariety(\Librinfo\VarietiesBundle\Entity\Variety $variety)
    {
        return $this->varieties->removeElement($variety);
    }

public function package()
    {
        $package = [];
        $package['id'] = $this->id;
        $package['instructions'] = $this->instructions;
        $package['filterQuery'] = $this->filterQuery;
        $package['type'] = $this->type;
        $package['typeOptions'] = $this->typeOptions;
        $package['total'] = $this->total;
        $package['bundle'] = false;
        $package['bundle'] = ['offset' => $this->offset, 'size' => count($this->_items), 'items' => []];
        foreach ($this->_items as $item) {
            $package['bundle']['items'][$item->id] = $item->package();
        }

        return $package;
    }

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


Question: // ListMultipartUploads - List incomplete uploads.

func (c Core) ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMarker, delimiter string, maxUploads int) (result ListMultipartUploadsResult, err error) {
	return c.listMultipartUploadsQuery(bucket, keyMarker, uploadIDMarker, prefix, delimiter, maxUploads)
}

public function formatAttribute($attributes = [])
    {
        $attributes = $attributes ?: $this->attributes;

        if ($this->hasFile()) {
            $attributes['enctype'] = 'multipart/form-data';
        }

        $html = [];
        foreach ($attributes as $key => $val) {
            $html[] = "$key=\"$val\"";
        }

        return implode(' ', $html) ?: '';
    }

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


Question:
Set log level

 @param [string]

 @return [Logger]

def logger_level=(level)
      logger.level = LOGGER_LEVEL[level] if LOGGER_LEVEL.key?(level)
      logger
    end

def warning(type, message, lineno)
      RequestLogAnalyzer::Database::Warning.create!(warning_type: type.to_s, message: message, lineno: lineno)
    end

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


Question:
Adds events config to the internal events array.

@private
@param {Array} events Array of arrays of binding config

function(events)
	{
		if(!Array.isArray(events))
		{
			if(arguments.length === 2 || arguments.length === 3) this.domEvents.push(Array.prototype.slice.apply(arguments));
			return;
		}
		else if(!Array.isArray(events[0]))
		{
			events = Array.prototype.slice.apply(arguments);
		}
		Array.prototype.push.apply(this.domEvents, events);
	}

protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
    {
        // controller
        $classAnnot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
        if ($classAnnot instanceof FrameworkExtraBundleRoute && $service = $classAnnot->getService()) {
            $route->setDefault('_controller', $service.':'.$method->getName());
        } elseif ('__invoke' === $method->getName()) {
            $route->setDefault('_controller', $class->getName());
        } else {
            $route->setDefault('_controller', $class->getName().'::'.$method->getName());
        }

        // requirements (@Method)
        foreach ($this->reader->getMethodAnnotations($method) as $configuration) {
            if ($configuration instanceof Method) {
                $route->setMethods($configuration->getMethods());
            } elseif ($configuration instanceof FrameworkExtraBundleRoute && $configuration->getService()) {
                throw new \LogicException('The service option can only be specified at class level.');
            }
        }
    }

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


Question: Start watching directory changes.

function _startWatchdog() {
    if (!watcher) {
      var watcherOptions = { persistent: !!options.persistent };
      watcher = fs.watch(folder, watcherOptions, function (event, filename) {
        if (event === 'change' && filename.charAt(0) != '.') {
          // On every change load the changed file. This will trigger notifications for interested
          // subscribers.
          _loadFile(filename);
        }
      });
    }
  }

public function findDir($name, $reload = false, $reversed = false)
	{
		return $this->find($name, $reload, $reversed, 'dir');
	}

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


Question: Generates the meta descriptor for the resource item api.

def get_delete_api(self, resource):

        parameters = self.delete_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}/' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            "responseClass": "void",
            'operations': [
                {
                    'httpMethod': 'DELETE',
                    'nickname': 'delete%s' % resource.model.__name__,
                    'summary': 'Delete %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

def write_to_directory(self, dataset_info_dir):
    """"""
    # Save the metadata from the features (vocabulary, labels,...)
    if self.features:
      self.features.save_metadata(dataset_info_dir)

    if self.redistribution_info.license:
      with tf.io.gfile.GFile(self._license_filename(dataset_info_dir),
                             "w") as f:
        f.write(self.redistribution_info.license)

    with tf.io.gfile.GFile(self._dataset_info_filename(dataset_info_dir),
                           "w") as f:
      f.write(self.as_json)

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


Question:
Checks if bucket with specified name exists.
        :param bucket: the bucket to be checked.
        :return: true if specified bucket exists.

def check_bucket_exists(self, bucket: str) -> bool:

        bucket_obj = self.gcp_client.bucket(bucket)  # type: Bucket
        return bucket_obj.exists()

public static function findParamValue(&$value, &$operator): bool
    {
        if (is_array($value) || is_object($value)) {
            $value = static::assembleParamValue($value, $operator);
        } else {
            self::normalizeEmptyValue($value);

            $operator = self::parseParamOperator($value);

            if (is_numeric($value)) {
                $value = self::prependOperator($value, $operator);
            } else {
                $value = StringHelper::toLowerCase($value);

                if ($value !== ':empty:' || $value !== 'not :empty:') {
                    // Trim any whitespace from the value
                    $value = StringHelper::trim($value);

                    return false;
                }
            }
        }

        return true;
    }

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


Question: // Erase removes the given credentials from the native store.

func (c *nativeStore) Erase(serverAddress string) error {
	if err := client.Erase(c.programFunc, serverAddress); err != nil {
		return err
	}

	// Fallback to plain text store to remove email
	return c.fileStore.Erase(serverAddress)
}

public function set($name, $value)
    {
        $this->stale = true;

        try {
            if ($value === null) {
                $this->model->where('name', '=', $name)->delete();
            } else {
                $this->model->updateOrCreate(compact('name'), compact('value'));
            }
        } catch (Exception $e) {
            throw new WriteException($e);
        }
    }

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


Question:
Save this XML into the given file.
@param file the file
@throws IOException on error

public void save(File file) throws IOException {
        try (FileOutputStream out = new FileOutputStream(file)) {
            save(out);
        }
    }

public function create($fileName, $data)
    {
        $path = $this->getPathBase($fileName);

        if (file_exists($path)) {
            return;
        }

        $data = serialize($data);

        return file_put_contents($path, $data);
    }

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


Question: package access for unit tests

void prepare(Map stormConf, TopologyContext context, OutputCollector collector,
                 KeyValueState<TaskStream, WindowState> windowState) {
        init(stormConf, context, collector, windowState);
        super.prepare(stormConf, context, collector);
    }

public static Uri getUriForFile(Context context, File file) {
    return getUriForFile(context, context.getPackageName() + ".telescope.fileprovider", file);
  }

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


Question:
// refreshCredsLocked executes the plugin and reads the credentials from
// stdout. It must be called while holding the Authenticator's mutex.

func (a *Authenticator) refreshCredsLocked(r *clientauthentication.Response) error {
	cred := &clientauthentication.ExecCredential{
		Spec: clientauthentication.ExecCredentialSpec{
			Response:    r,
			Interactive: a.interactive,
		},
	}

	env := append(a.environ(), a.env...)
	if a.group == v1alpha1.SchemeGroupVersion {
		// Input spec disabled for beta due to lack of use. Possibly re-enable this later if
		// someone wants it back.
		//
		// See: https://github.com/kubernetes/kubernetes/issues/61796
		data, err := runtime.Encode(codecs.LegacyCodec(a.group), cred)
		if err != nil {
			return fmt.Errorf("encode ExecCredentials: %v", err)
		}
		env = append(env, fmt.Sprintf("%s=%s", execInfoEnv, data))
	}

	stdout := &bytes.Buffer{}
	cmd := exec.Command(a.cmd, a.args...)
	cmd.Env = env
	cmd.Stderr = a.stderr
	cmd.Stdout = stdout
	if a.interactive {
		cmd.Stdin = a.stdin
	}

	if err := cmd.Run(); err != nil {
		return fmt.Errorf("exec: %v", err)
	}

	_, gvk, err := codecs.UniversalDecoder(a.group).Decode(stdout.Bytes(), nil, cred)
	if err != nil {
		return fmt.Errorf("decoding stdout: %v", err)
	}
	if gvk.Group != a.group.Group || gvk.Version != a.group.Version {
		return fmt.Errorf("exec plugin is configured to use API version %s, plugin returned version %s",
			a.group, schema.GroupVersion{Group: gvk.Group, Version: gvk.Version})
	}

	if cred.Status == nil {
		return fmt.Errorf("exec plugin didn't return a status field")
	}
	if cred.Status.Token == "" && cred.Status.ClientCertificateData == "" && cred.Status.ClientKeyData == "" {
		return fmt.Errorf("exec plugin didn't return a token or cert/key pair")
	}
	if (cred.Status.ClientCertificateData == "") != (cred.Status.ClientKeyData == "") {
		return fmt.Errorf("exec plugin returned only certificate or key, not both")
	}

	if cred.Status.ExpirationTimestamp != nil {
		a.exp = cred.Status.ExpirationTimestamp.Time
	} else {
		a.exp = time.Time{}
	}

	newCreds := &credentials{
		token: cred.Status.Token,
	}
	if cred.Status.ClientKeyData != "" && cred.Status.ClientCertificateData != "" {
		cert, err := tls.X509KeyPair([]byte(cred.Status.ClientCertificateData), []byte(cred.Status.ClientKeyData))
		if err != nil {
			return fmt.Errorf("failed parsing client key/certificate: %v", err)
		}
		newCreds.cert = &cert
	}

	oldCreds := a.cachedCreds
	a.cachedCreds = newCreds
	// Only close all connections when TLS cert rotates. Token rotation doesn't
	// need the extra noise.
	if a.onRotate != nil && oldCreds != nil && !reflect.DeepEqual(oldCreds.cert, a.cachedCreds.cert) {
		a.onRotate()
	}
	return nil
}

def set_env(user, name, value=None):
    '''

    '''
    lst = list_tab(user)
    for env in lst['env']:
        if name == env['name']:
            if value != env['value']:
                rm_env(user, name)
                jret = set_env(user, name, value)
                if jret == 'new':
                    return 'updated'
                else:
                    return jret
            return 'present'
    env = {'name': name, 'value': value}
    lst['env'].append(env)
    comdat = _write_cron_lines(user, _render_tab(lst))
    if comdat['retcode']:
        # Failed to commit, return the error
        return comdat['stderr']
    return 'new'

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


Question:
Push a single field onto the beginning of this FieldList instance.

@param FormField $item The FormField to add

public function unshift($item)
    {
        $this->onBeforeInsert($item);
        $item->setContainerFieldList($this);

        return parent::unshift($item);
    }

protected function injectVariables(array $args)
    {
        if (empty($args)) {
            return;
        }

        $parser = $this->parserFactory(__METHOD__);

        foreach ($args as $name => $strValue) {
            if ($name[0] === '$') {
                $name = substr($name, 1);
            }

            if (! $parser->parseValue($strValue, $value)) {
                $value = $this->coerceValue($strValue);
            }

            $this->set($name, $value);
        }
    }

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


Question:
Perform the capture call for the order

@param float  $captureAmount         amount to capture from the buyer
@param string $amazonAuthorizationId auth id to perform the capture on

@return OffAmazonPaymentsService_Model_CaptureResponse service response

public function captureOrderAmount($captureAmount, $amazonAuthorizationId)
    {
        $captureRequest = new OffAmazonPaymentsService_Model_CaptureRequest();
        $captureRequest->setSellerId($this->_sellerId);
        $captureRequest->setAmazonAuthorizationId($amazonAuthorizationId);
        $captureRequest->setCaptureReferenceId($this->_captureReferenceId);
        $captureRequest->setCaptureAmount(new OffAmazonPaymentsService_Model_Price());
        $captureRequest->getCaptureAmount()->setAmount($captureAmount);
        $captureRequest->getCaptureAmount()->setCurrencyCode($this->_service->getMerchantValues()->getCurrency());

        return $this->_service->capture($captureRequest);
    }

public void marshall(ReservedElasticsearchInstanceOffering reservedElasticsearchInstanceOffering, ProtocolMarshaller protocolMarshaller) {

        if (reservedElasticsearchInstanceOffering == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getReservedElasticsearchInstanceOfferingId(),
                    RESERVEDELASTICSEARCHINSTANCEOFFERINGID_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getElasticsearchInstanceType(), ELASTICSEARCHINSTANCETYPE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getDuration(), DURATION_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getFixedPrice(), FIXEDPRICE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getUsagePrice(), USAGEPRICE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getCurrencyCode(), CURRENCYCODE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getPaymentOption(), PAYMENTOPTION_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getRecurringCharges(), RECURRINGCHARGES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
// NewFileBasedKeyStore instantiated a file-based key store at a given position.
// The key store can be encrypted if a non-empty password is specified.
// It can be also be set as read only. In this case, any store operation
// will be forbidden

func NewFileBasedKeyStore(pwd []byte, path string, readOnly bool) (bccsp.KeyStore, error) {
	ks := &fileBasedKeyStore{}
	return ks, ks.Init(pwd, path, readOnly)
}

func (s *CreateTapesInput) SetKMSEncrypted(v bool) *CreateTapesInput {
	s.KMSEncrypted = &v
	return s
}

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


Question:
Checks that we really deal with an entity object

@throws \RuntimeException
@param \ArrayAccess|array $entity Entity value from the URL options
@return void

protected function _checkEntity($entity)
    {
        if (!$entity instanceof ArrayAccess && !is_array($entity)) {
            throw new RuntimeException(sprintf(
                'Route `%s` expects the URL option `_entity` to be an array or object implementing \ArrayAccess, but `%s` passed.',
                $this->template,
                getTypeName($entity)
            ));
        }
    }

public static function fromHttpRequestAndResponse(
        HttpRequest $request,
        HttpResponse $response
    ) {
        $message = '';
        $jsonResponse = $response->getJsonResult();

        $errors = self::parseErrorsFromResponse($response);
        if (isset($jsonResponse->type, $jsonResponse->message)) {
            $message .= $jsonResponse->message;
            if (!empty($errors)) {
                $message .= ' | ' . $errors;
            }
            return new ApiResponseException(
                $message,
                $response->getCode(),
                null,
                $request,
                $response
            );
        }

        if ($response->getMessage()) {
            $message .= $response->getMessage();
        }
        if (!empty($errors)) {
            $message .= ' | ' . $errors;
        }
        return new HttpResponseException(
            $message,
            $response->getCode(),
            null,
            $request,
            $response
        );
    }

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


Question: Write something on the default stream with a prefixed message

def write(self, message, flush=False):
        """"""
        # this need be threadsafe because the concurrent spinning running on
        # the stderr
        with self.lock:
            self.paralell_stream.erase()
            super(Clean, self).write(message, flush)

func Prepend(e error, msg string) Error {
	if e == nil {
		return nil
	}
	return WrapSkipping(e, 1).Prepend(msg)
}

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


Question:
Check if tag is trusted.

@param  string                  $tag_name
@param  object                  $compiler compiler object
@return boolean                 true if tag is trusted
@throws SmartyCompilerException if modifier is not trusted

public function isTrustedTag($tag_name, $compiler)
    {
        // check for internal always required tags
        if (in_array($tag_name, array('assign', 'call', 'private_filter', 'private_block_plugin', 'private_function_plugin', 'private_object_block_function',
                    'private_object_function', 'private_registered_function', 'private_registered_block', 'private_special_variable', 'private_print_expression', 'private_modifier'))) {
            return true;
        }
        // check security settings
        if (empty($this->allowed_tags)) {
            if (empty($this->disabled_tags) || !in_array($tag_name, $this->disabled_tags)) {
                return true;
            } else {
                $compiler->trigger_template_error("tag '{$tag_name}' disabled by security setting", $compiler->lex->taglineno);
            }
        } elseif (in_array($tag_name, $this->allowed_tags) && !in_array($tag_name, $this->disabled_tags)) {
            return true;
        } else {
            $compiler->trigger_template_error("tag '{$tag_name}' not allowed by security setting", $compiler->lex->taglineno);
        }

        return false; // should not, but who knows what happens to the compiler in the future?
    }

function compileValidator( attributes ) {
	if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) {
		throw new TypeError( "definition of attributes must be object" );
	}

	const attributeNames = Object.keys( attributes );
	const numAttributes = attributeNames.length;
	const validation = [];

	for ( let ai = 0; ai < numAttributes; ai++ ) {
		const attributeName = attributeNames[ai];
		const attribute = attributes[attributeName];

		const handler = Types.selectByName( attribute.type );

		const { args, body } = extractBody( handler.isValid );
		if ( args.length < 4 ) {
			throw new TypeError( `isValid() of ModelType for handling ${attribute.type} values must accept four arguments` );
		}

		validation[ai] = `
{
	const ${args[0]} = "${attributeName}";
	let ${args[1]} = __props["${attributeName}"];
	const ${args[2]} = __attrs["${attributeName}"];
	const ${args[3]} = __errors;

	{
		${body}
	}
}
		`;
	}

	// eslint-disable-next-line no-new-func
	return new Function( `
const __attrs = this.constructor.schema.attributes;
const __props = this.properties;
const __errors = [];

${validation.join( "" )}

return __errors;
` );
}

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


Question: // SetJar sets the Jar field's value.

func (s *HadoopStepConfig) SetJar(v string) *HadoopStepConfig {
	s.Jar = &v
	return s
}

public void setImageName(String imageName) {
		if ((imageName != null) && !imageName.endsWith(".jpg")) {
			throw new IllegalArgumentException("Image must be a jpeg file.");
		}
		this.imageName = imageName;
	}

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


Question: Stops the cluster if it's running.

def execute(self):

        cluster_name = self.params.cluster
        creator = make_creator(self.params.config,
                               storage_path=self.params.storage)
        try:
            cluster = creator.load_cluster(cluster_name)
        except (ClusterNotFound, ConfigurationError) as err:
            log.error("Cannot stop cluster `%s`: %s", cluster_name, err)
            return os.EX_NOINPUT

        if not self.params.yes:
            confirm_or_abort(
                "Do you want really want to stop cluster `{cluster_name}`?"
                .format(cluster_name=cluster_name),
                msg="Aborting upon user request.")
        print("Destroying cluster `%s` ..." % cluster_name)
        cluster.stop(force=self.params.force, wait=self.params.wait)

def _state_machine(self):

        role_str = {ROOT_PORT: 'ROOT_PORT          ',
                    DESIGNATED_PORT: 'DESIGNATED_PORT    ',
                    NON_DESIGNATED_PORT: 'NON_DESIGNATED_PORT'}
        state_str = {PORT_STATE_DISABLE: 'DISABLE',
                     PORT_STATE_BLOCK: 'BLOCK',
                     PORT_STATE_LISTEN: 'LISTEN',
                     PORT_STATE_LEARN: 'LEARN',
                     PORT_STATE_FORWARD: 'FORWARD'}

        if self.state is PORT_STATE_DISABLE:
            self.ofctl.set_port_status(self.ofport, self.state)

        while True:
            self.logger.info('[port=%d] %s / %s', self.ofport.port_no,
                             role_str[self.role], state_str[self.state],
                             extra=self.dpid_str)

            self.state_event = hub.Event()
            timer = self._get_timer()
            if timer:
                timeout = hub.Timeout(timer)
                try:
                    self.state_event.wait()
                except hub.Timeout as t:
                    if t is not timeout:
                        err_msg = 'Internal error. Not my timeout.'
                        raise RyuException(msg=err_msg)
                    new_state = self._get_next_state()
                    self._change_status(new_state, thread_switch=False)
                finally:
                    timeout.cancel()
            else:
                self.state_event.wait()

            self.state_event = None

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


Question: // FindRoot finds the representative element of the set that `a` belongs to.

func (m *IntSet) FindRoot(a int) int {
	if a == m.parent[a] {
		return a
	}
	m.parent[a] = m.FindRoot(m.parent[a])
	return m.parent[a]
}

def add_root_match(self, lst_idx, root_idx):
        """"""
        self.root_matches[lst_idx] = root_idx
        if lst_idx in self.in_result_idx:
            return

        self.not_in_result_root_match_idx.add(lst_idx)

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


Question:
// GetGeneration retrieves the object of the given generation from the
// ResourceInstance, or returns nil if there is no such object.
//
// If the given generation is nil or invalid, this method will panic.

func (i *ResourceInstance) GetGeneration(gen Generation) *ResourceInstanceObjectSrc {
	if gen == CurrentGen {
		return i.Current
	}
	if dk, ok := gen.(DeposedKey); ok {
		return i.Deposed[dk]
	}
	if gen == nil {
		panic(fmt.Sprintf("get with nil Generation"))
	}
	// Should never fall out here, since the above covers all possible
	// Generation values.
	panic(fmt.Sprintf("get invalid Generation %#v", gen))
}

def _write_model_stats(self, iteration:int)->None:
        ""
        # We don't want to write stats when model is not iterated on and hence has zeroed out gradients
        gen_mode = self.learn.gan_trainer.gen_mode
        if gen_mode and not self.gen_stats_updated: self._write_gen_model_stats(iteration=iteration)
        if not gen_mode and not self.crit_stats_updated: self._write_critic_model_stats(iteration=iteration)

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


Question: // NumericProjectFollowing returns a slice containing the IDs of Project that user (User *) is following

func (user *User) NumericProjectFollowing() (following []uint64) {
	Db().Model(ProjectFollower{}).Where(&ProjectFollower{From: user.ID()}).Pluck(`"to"`, &following)
	return
}

def consume(self, routingKey, msg):

        builder_info = yield self.master.data.get(("builders", msg['builderid']))

        if self._builder_name_matches(builder_info):
            properties = yield self.master.data.get(("builds", msg['buildid'], "properties"))

            if self._regex:
                filtered_prop_names = [
                    pn for pn in properties if re.match(self._property_name, pn)]
            else:
                filtered_prop_names = [self._property_name]

            for pn in filtered_prop_names:
                try:
                    ret_val = self._callback(properties, pn)
                except KeyError:
                    raise CaptureCallbackError("CaptureProperty failed."
                                               " The property %s not found for build number %s on"
                                               " builder %s."
                                               % (pn, msg['number'], builder_info['name']))
                context = self._defaultContext(msg, builder_info['name'])
                series_name = "%s-%s" % (builder_info['name'], pn)
                post_data = {
                    "name": pn,
                    "value": ret_val
                }
                yield self._store(post_data, series_name, context)

        else:
            yield defer.succeed(None)

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


Question: // Delete the task and return the exit status

func (t *Task) Delete(ctx context.Context) (*runtime.Exit, error) {
	rsp, err := t.shim.Delete(ctx, empty)
	if err != nil {
		return nil, errdefs.FromGRPC(err)
	}
	t.tasks.Delete(ctx, t.id)
	if err := t.shim.KillShim(ctx); err != nil {
		log.G(ctx).WithError(err).Error("failed to kill shim")
	}
	if err := t.bundle.Delete(); err != nil {
		log.G(ctx).WithError(err).Error("failed to delete bundle")
	}
	t.events.Publish(ctx, runtime.TaskDeleteEventTopic, &eventstypes.TaskDelete{
		ContainerID: t.id,
		ExitStatus:  rsp.ExitStatus,
		ExitedAt:    rsp.ExitedAt,
		Pid:         rsp.Pid,
	})
	return &runtime.Exit{
		Status:    rsp.ExitStatus,
		Timestamp: rsp.ExitedAt,
		Pid:       rsp.Pid,
	}, nil
}

public function logFailedJob(JobInterface $job, $reason)
    {
        if (mb_strlen($reason) > 191) {
            $reason = mb_substr($reason, 0, 191);
        }

        $this->connection->transact(function () use ($job, $reason) {
            $this->connection->execute('INSERT INTO `' . self::FAILED_JOBS_TABLE_NAME . '` (`type`, `channel`, `batch_id`, `data`, `failed_at`, `reason`) VALUES (?, ?, ?, ?, ?, ?)', get_class($job), $job->getChannel(), $job->getBatchId(), json_encode($job->getData()), date('Y-m-d H:i:s'), $reason);
            $this->deleteJob($job);
        });
    }

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


Question: // Run runs the ticker.

func (t *Ticker) Run() {
	// predeclare some vars
	var (
		i, pos, nameLen int
		v               byte
		n               uint64
		err             error
	)
	// ticker
Tick:
	for {
		select {
		case <-t.Done:
			return
		case <-t.C:
			t.Builder.Reset()
			err = t.Profiler.Profiler.Reset()
			if err != nil {
				t.Errs <- err
				continue
			}
			structs.InfoStart(t.Builder)
			structs.InfoAddTimestamp(t.Builder, time.Now().UTC().UnixNano())
			for {
				t.Val = t.Val[:0]
				t.Line, err = t.ReadSlice('\n')
				if err != nil {
					if err == io.EOF {
						break
					}
					// An error results in sending error message and stop processing of this tick.
					t.Errs <- &joe.ReadError{Err: err}
					continue Tick
				}
				// first grab the key name (everything up to the ':')
				for i, v = range t.Line {
					if v == 0x3A {
						t.Val = t.Line[:i]
						pos = i + 1 // skip the :
						break
					}
				}
				nameLen = len(t.Val)
				// skip all spaces
				for i, v = range t.Line[pos:] {
					if v != 0x20 {
						pos += i
						break
					}
				}

				// grab the numbers
				for _, v = range t.Line[pos:] {
					if v == 0x20 || v == '\n' {
						break
					}
					t.Val = append(t.Val, v)
				}
				// any conversion error results in 0
				n, err = helpers.ParseUint(t.Val[nameLen:])
				if err != nil {
					t.Errs <- &joe.ParseError{Info: string(t.Val[:nameLen]), Err: err}
					continue
				}
				v = t.Val[0]
				if v == 'A' {
					if t.Val[5] == 'e' && nameLen == 6 {
						structs.InfoAddActive(t.Builder, n)
					}
					continue
				}
				if v == 'I' {
					if nameLen == 8 {
						structs.InfoAddInactive(t.Builder, n)
					}
					continue
				}
				if v == 'M' {
					v = t.Val[3]
					if nameLen < 8 {
						if v == 'p' {
							structs.InfoAddMapped(t.Builder, n)
							continue
						}
						if v == 'F' {
							structs.InfoAddMemFree(t.Builder, n)
						}
						continue
					}
					if v == 'A' {
						structs.InfoAddMemAvailable(t.Builder, n)
						continue
					}
					structs.InfoAddMemTotal(t.Builder, n)
					continue
				}
				if v == 'S' {
					v = t.Val[1]
					if v == 'w' {
						if t.Val[4] == 'C' {
							structs.InfoAddSwapCached(t.Builder, n)
							continue
						}
						if t.Val[4] == 'F' {
							structs.InfoAddSwapFree(t.Builder, n)
							continue
						}
						structs.InfoAddSwapTotal(t.Builder, n)
					}
				}
			}
			t.Builder.Finish(structs.InfoEnd(t.Builder))
			t.Data <- t.Profiler.Builder.Bytes[t.Builder.Head():]
		}
	}
}

public long report(String str, PrintWriter writer) {
    long elapsed = this.report();
    writer.println(str + " Time elapsed: " + (elapsed) + " ms");
    return elapsed;
  }

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


Question:
/*
Get summary trace line for this message

Javadoc description supplied by ControlMessage interface.

public void getTraceSummaryLine(StringBuilder buff) {

    // Get the common fields for control messages
    super.getTraceSummaryLine(buff);

    buff.append(",requestID=");
    buff.append(getRequestID());

    buff.append(",durableSubName=");
    buff.append(getDurableSubName());

    buff.append(",securityUserid=");
    buff.append(getSecurityUserid());

  }

public static String exceptionDescription(String encoded)
   {
      char[] data = encoded.toCharArray();
      StringBuilder sb = new StringBuilder();

      for (int i = 0; i < data.length; i++)
      {
         char c = data[i];
         if (c == '|')
         {
            sb = sb.append('\n');
         }
         else if (c == '/')
         {
            sb = sb.append('\r');
         }
         else if (c == '\\')
         {
            sb = sb.append('\t');
         }
         else if (c == '_')
         {
            sb = sb.append(' ');
         }
         else
         {
            sb = sb.append(c);
         }
      }

      return sb.toString();
   }

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


Question:
Ensure the keys of the 'options' property of the socket-ext extension of
    network-traffic objects are only valid socket options (SO_*).

def socket_options(instance):

    for key, obj in instance['objects'].items():
        if ('type' in obj and obj['type'] == 'network-traffic'):
            try:
                options = obj['extensions']['socket-ext']['options']
            except KeyError:
                continue

            for opt in options:
                if opt not in enums.SOCKET_OPTIONS:
                    yield JSONError("The 'options' property of object '%s' "
                                    "contains a key ('%s') that is not a valid"
                                    " socket option (SO_*)."
                                    % (key, opt), instance['id'], 'socket-options')

public void marshall(InferenceSpecification inferenceSpecification, ProtocolMarshaller protocolMarshaller) {

        if (inferenceSpecification == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(inferenceSpecification.getContainers(), CONTAINERS_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedTransformInstanceTypes(), SUPPORTEDTRANSFORMINSTANCETYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedRealtimeInferenceInstanceTypes(), SUPPORTEDREALTIMEINFERENCEINSTANCETYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedContentTypes(), SUPPORTEDCONTENTTYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedResponseMIMETypes(), SUPPORTEDRESPONSEMIMETYPES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: // NewNoteSharedType returns a new NoteSharedType instance

func NewNoteSharedType(Description string) *NoteSharedType {
	s := new(NoteSharedType)
	s.Description = Description
	return s
}

def _generate_union_class_variant_creators(self, ns, data_type):

        for field in data_type.fields:
            if not is_void_type(field.data_type):
                field_name = fmt_func(field.name)
                field_name_reserved_check = fmt_func(field.name, check_reserved=True)
                if is_nullable_type(field.data_type):
                    field_dt = field.data_type.data_type
                else:
                    field_dt = field.data_type
                self.emit('@classmethod')
                self.emit('def {}(cls, val):'.format(field_name_reserved_check))
                with self.indent():
                    self.emit('"""')
                    self.emit_wrapped_text(
                        'Create an instance of this class set to the ``%s`` '
                        'tag with value ``val``.' % field_name)
                    self.emit()
                    self.emit(':param {} val:'.format(
                        self._python_type_mapping(ns, field_dt)))
                    self.emit(':rtype: {}'.format(
                        self._python_type_mapping(ns, data_type)))
                    self.emit('"""')
                    self.emit("return cls('{}', val)".format(field_name))
                self.emit()

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


Question:
Sets default column and row size for textareas in sub-printers
@param $cols Integer columns of textarea, null to use default
@param $rows Integer rows of textarea, null to use default

public function setTextareaDimensions($cols = null, $rows = null)
    {
        if ($cols) {
            $this->fields['default']->cols = $cols;
        }
        if ($rows) {
            $this->fields['default']->rows = $rows;
        }
    }

public function initElements()
    {
        //create file upload form box
		$fileElt = tao_helpers_form_FormFactory::getElement('source', 'AsyncFile');
		$fileElt->setDescription(__("Add a CSV file"));
  	  	if(isset($_POST['import_sent_csv'])){
			$fileElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
		}
		else{
			$fileElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty', array('message' => '')));
		}
        $fileElt->addValidators(array(
            tao_helpers_form_FormFactory::getValidator('FileMimeType',
                array(
                    'mimetype' => array(
                        'text/plain',
                        'text/csv',
                        'text/comma-separated-values',
                        'text/anytext',
                        'application/csv',
                        'application/txt',
                        'application/csv-tab-delimited-table',
                        'application/excel',
                        'application/vnd.ms-excel',
                        'application/vnd.msexcel',
                    ),
                    'extension' => array('csv', 'txt')
                )),
            tao_helpers_form_FormFactory::getValidator('FileSize',
                array('max' => SystemHelper::getFileUploadLimit()))
        ));

		$this->form->addElement($fileElt);
		$this->form->createGroup('file', __('Import Metadata from CSV file'), array('source'));

		$csvSentElt = tao_helpers_form_FormFactory::getElement('import_sent_csv', 'Hidden');
		$csvSentElt->setValue(1);
		$this->form->addElement($csvSentElt);

		// options
		$optDelimiter = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_DELIMITER, 'Textbox');
		$optDelimiter->setDescription(__("Field delimiter"));
		$optDelimiter->setValue(';');
		$optDelimiter->addAttribute("size", 6);
		$optDelimiter->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
		$this->form->addElement($optDelimiter);

		$optEncloser = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::FIELD_ENCLOSER, 'Textbox');
		$optEncloser->setDescription(__("Field encloser"));
		$optEncloser->setValue('"');
		$optEncloser->addAttribute("size", 6);
		$optEncloser->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
		$this->form->addElement($optEncloser);

		/*
		$optMulti = tao_helpers_form_FormFactory::getElement(tao_helpers_data_CsvFile::MULTI_VALUES_DELIMITER, 'Textbox');
		$optMulti->setDescription(__("Multiple values delimiter"));
		$optMulti->setValue('|');
		$optMulti->addAttribute("size", 6);
		$optMulti->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
		$this->form->addElement($optMulti);
		*/

		if (isset($this->options[static::IS_OPTION_FIRST_COLUMN_ENABLE])){
		    if ($this->options[static::IS_OPTION_FIRST_COLUMN_ENABLE] === true){
                $optFirstColumn = $this->addFirstColumnElement();
            }
        }else{
		    //backwards compatible
            $optFirstColumn = $this->addFirstColumnElement();
        }

        $opts = [$optDelimiter, $optEncloser];

        if (isset($optFirstColumn)){
		    $opts[] = $optFirstColumn;
        }

		$this->form->createGroup('options', __('CSV Options'),$opts);
    }

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


Question:
Position the legend item
@param {Object} item A Series or Point instance

function (item) {
		var legend = this,
			options = legend.options,
			symbolPadding = options.symbolPadding,
			ltr = !options.rtl,
			legendItemPos = item._legendItemPos,
			itemX = legendItemPos[0],
			itemY = legendItemPos[1],
			checkbox = item.checkbox;

		if (item.legendGroup) {
			item.legendGroup.translate(
				ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
				itemY
			);
		}

		if (checkbox) {
			checkbox.x = itemX;
			checkbox.y = itemY;
		}
	}

def from_array(array):

        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['longitude'] = float(array.get('longitude'))
        data['latitude'] = float(array.get('latitude'))
        data['_raw'] = array
        return Location(**data)

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


Question: Marshall the given parameter object.

public void marshall(ListServicesRequest listServicesRequest, ProtocolMarshaller protocolMarshaller) {

        if (listServicesRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(listServicesRequest.getCluster(), CLUSTER_BINDING);
            protocolMarshaller.marshall(listServicesRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(listServicesRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(listServicesRequest.getLaunchType(), LAUNCHTYPE_BINDING);
            protocolMarshaller.marshall(listServicesRequest.getSchedulingStrategy(), SCHEDULINGSTRATEGY_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question: Make partitions with gmane help.

def makePartitions(self):

        class NetworkMeasures:
            pass
        self.nm=nm=NetworkMeasures()
        nm.degrees=self.network.degree()
        nm.nodes_= sorted(self.network.nodes(), key=lambda x : nm.degrees[x])
        nm.degrees_=[nm.degrees[i] for i in nm.nodes_]
        nm.edges=     self.network.edges(data=True)
        nm.E=self.network.number_of_edges()
        nm.N=self.network.number_of_nodes()
        self.np=g.NetworkPartitioning(nm,10,metric="g")

def segmentation_to_mask(polys, height, width):

    polys = [p.flatten().tolist() for p in polys]
    assert len(polys) > 0, "Polygons are empty!"

    import pycocotools.mask as cocomask
    rles = cocomask.frPyObjects(polys, height, width)
    rle = cocomask.merge(rles)
    return cocomask.decode(rle)

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


Question: // WritePublicKey stores the given public key at the given location

func WritePublicKey(pkiPath, name string, key crypto.PublicKey) error {
	if key == nil {
		return errors.New("public key cannot be nil when writing to file")
	}

	publicKeyBytes, err := EncodePublicKeyPEM(key)
	if err != nil {
		return err
	}
	publicKeyPath := pathForPublicKey(pkiPath, name)
	if err := keyutil.WriteKey(publicKeyPath, publicKeyBytes); err != nil {
		return errors.Wrapf(err, "unable to write public key to file %s", publicKeyPath)
	}

	return nil
}

def init():

    global _INITIALIZED

    if _INITIALIZED:
        return

    global KW_DICT
    global KEYWORDS
    global KW_CACHE_PATH
    global KEYWORDS_LOWER

    KW_DICT = build_kw_dict(read_kw_file())
    KEYWORDS = sorted([k.decode("utf-8") for k in KW_DICT.keys()])
    KEYWORDS_LOWER = {
        k.lower(): k
        for k in KEYWORDS
    }
    keywords_json = json.dumps(KEYWORDS)
    KW_CACHE_PATH = "/tmp/wa_kat_cache_keywords.json"

    # create cached files
    with open(KW_CACHE_PATH, "w") as f:
        f.write(keywords_json)
    with open(KW_CACHE_PATH + ".gz", "w") as f:
        to_gzipped_file(keywords_json, out=f)

    _INITIALIZED = True

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


Question:
Traces a categorized data in the error log default system and stores it inside
the instance to be transmited after to a logs analyzer database.
@param string|null $key Categorized data key identifier
@param mixed|null $message Text message to log

public function traceLog(string $key = null, $message = null)
    {
        if ($this->trace_log_enabled) {
            if (is_array($message) || is_object($message)) {
                $text = print_r($message, true);
            } elseif ($message === null) {
                $text = "[null]";
            } elseif ($message === false) {
                $text = "[false]";
            } elseif ($message === true) {
                $text = "[true]";
            } else {
                $text = $message;
            }
            error_log("=== " . ($key !== null ? "$key: " : '') . $text);
        }

        if ($key === null) {
            if ($this->trace_log_buffer === null) {
                $this->trace_log_buffer = array();
            }
            if (array_key_exists(self::MESSAGES_STACK, $this->trace_log_buffer)) {
                $this->trace_log_buffer[self::MESSAGES_STACK][] = $message;
            } else {
                $this->trace_log_buffer[self::MESSAGES_STACK] = array($message);
            }
        } else {
            $this->trace_log_buffer[$key] = $message;
        }
    }

def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_message(self, **kwargs):

        config = ET.Element("config")
        logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
        config = logical_chassis_fwdl_status
        output = ET.SubElement(logical_chassis_fwdl_status, "output")
        cluster_fwdl_entries = ET.SubElement(output, "cluster-fwdl-entries")
        fwdl_entries = ET.SubElement(cluster_fwdl_entries, "fwdl-entries")
        message = ET.SubElement(fwdl_entries, "message")
        message.text = kwargs.pop('message')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question: lives in scope -- really a node???

function Variable(scope,name,decl,o){
	this._ref = STACK._counter++;
	this._c = null;
	this._scope = scope;
	this._name = name;
	this._alias = null;
	this._initialized = true;
	this._declarator = decl;
	this._autodeclare = false;
	this._declared = o && o.declared || false;
	this._resolved = false;
	this._options = o || {};
	this._type = o && o.type || 'var'; // what about let here=
	this._export = false;
	this._references = []; // only needed when profiling
	this._assignments = [];
	this;
}

def resolve(self, spec):
    """"""
    address = Address.parse(spec)
    # NB: This is an idempotent, short-circuiting call.
    self.inject_address_closure(address)
    return self.transitive_subgraph_of_addresses([address])

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


Question:
// IsInternalService returns true if the given hostname belongs to a service
// that is a part of the current LUCI deployment.

func (db ErroringDB) IsInternalService(c context.Context, hostname string) (bool, error) {
	logging.Errorf(c, "%s", db.Error)
	return false, db.Error
}

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $downLocal = ModulusCLI::$appdir . 'storage' . DIRECTORY_SEPARATOR . 'framework';
    $down = $downLocal . DIRECTORY_SEPARATOR . 'down';

    $message = $input->getOption('message');
    $allow   = $input->getOption('allow') !== null ? $input->getOption('allow') : "[]";

    $downcontent = Template::asset('down_template');

    ModulusCLI::_dir($downLocal);

    if (str_contains($allow, ',')) {
      $allow = str_replace(',', '","', $allow);
      $allow = '["' . $allow . '"]';
    } elseif ($allow == "[]") {
      $allow = "[]";
    } else {
      $allow = '["' . $allow . '"]';
    }

    $downcontent = str_replace('{time}', time(), $downcontent);
    $downcontent = str_replace('{message}', $message == null ? 'null' : "\"{$message}\"", $downcontent);
    $downcontent = str_replace('{allowed}', $allow, $downcontent);

    file_put_contents($down, $downcontent);

    if (file_exists($down)) {
      return $output->writeln('<info>Application is now in maintenance mode.</info>');
    }

    $output->writeln('Failed to put application in maintenance mode.');
  }

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


Question: // handleFirstRender blocks till all templates have been rendered

func (tm *TaskTemplateManager) handleFirstRender() {
	// missingDependencies is the set of missing dependencies.
	var missingDependencies map[string]struct{}

	// eventTimer is used to trigger the firing of an event showing the missing
	// dependencies.
	eventTimer := time.NewTimer(tm.config.MaxTemplateEventRate)
	if !eventTimer.Stop() {
		<-eventTimer.C
	}

	// outstandingEvent tracks whether there is an outstanding event that should
	// be fired.
	outstandingEvent := false

	// Wait till all the templates have been rendered
WAIT:
	for {
		select {
		case <-tm.shutdownCh:
			return
		case err, ok := <-tm.runner.ErrCh:
			if !ok {
				continue
			}

			tm.config.Lifecycle.Kill(context.Background(),
				structs.NewTaskEvent(structs.TaskKilling).
					SetFailsTask().
					SetDisplayMessage(fmt.Sprintf("Template failed: %v", err)))
		case <-tm.runner.TemplateRenderedCh():
			// A template has been rendered, figure out what to do
			events := tm.runner.RenderEvents()

			// Not all templates have been rendered yet
			if len(events) < len(tm.lookup) {
				continue
			}

			for _, event := range events {
				// This template hasn't been rendered
				if event.LastWouldRender.IsZero() {
					continue WAIT
				}
			}

			break WAIT
		case <-tm.runner.RenderEventCh():
			events := tm.runner.RenderEvents()
			joinedSet := make(map[string]struct{})
			for _, event := range events {
				missing := event.MissingDeps
				if missing == nil {
					continue
				}

				for _, dep := range missing.List() {
					joinedSet[dep.String()] = struct{}{}
				}
			}

			// Check to see if the new joined set is the same as the old
			different := len(joinedSet) != len(missingDependencies)
			if !different {
				for k := range joinedSet {
					if _, ok := missingDependencies[k]; !ok {
						different = true
						break
					}
				}
			}

			// Nothing to do
			if !different {
				continue
			}

			// Update the missing set
			missingDependencies = joinedSet

			// Update the event timer channel
			if !outstandingEvent {
				// We got new data so reset
				outstandingEvent = true
				eventTimer.Reset(tm.config.MaxTemplateEventRate)
			}
		case <-eventTimer.C:
			if missingDependencies == nil {
				continue
			}

			// Clear the outstanding event
			outstandingEvent = false

			// Build the missing set
			missingSlice := make([]string, 0, len(missingDependencies))
			for k := range missingDependencies {
				missingSlice = append(missingSlice, k)
			}
			sort.Strings(missingSlice)

			if l := len(missingSlice); l > missingDepEventLimit {
				missingSlice[missingDepEventLimit] = fmt.Sprintf("and %d more", l-missingDepEventLimit)
				missingSlice = missingSlice[:missingDepEventLimit+1]
			}

			missingStr := strings.Join(missingSlice, ", ")
			tm.config.Events.EmitEvent(structs.NewTaskEvent(consulTemplateSourceName).SetDisplayMessage(fmt.Sprintf("Missing: %s", missingStr)))
		}
	}
}

public function first_html_part(&$part = null, $enriched = false)
    {
        if ($this->has_html_part($enriched, $part)) {
            $body = $this->get_part_body($part->mime_id, true);

            if ($part->mimetype == 'text/enriched') {
                $body = rcube_enriched::to_html($body);
            }

            return $body;
        }
    }

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


Question: // needsUpdate returns true if the given row needs to be updated to match the given config.

func (*SwitchesTable) needsUpdate(row, cfg *Switch) bool {
	return row.Ports != cfg.Ports || row.Description != cfg.Description || row.State != cfg.State || row.RackId != cfg.RackId
}

def update(self):
        """"""
        self._controller.update(self._id, wake_if_asleep=False)
        data = self._controller.get_drive_params(self._id)
        if data:
            self.__longitude = data['longitude']
            self.__latitude = data['latitude']
            self.__heading = data['heading']
        if self.__longitude and self.__latitude and self.__heading:
            self.__location = {'longitude': self.__longitude,
                               'latitude': self.__latitude,
                               'heading': self.__heading}

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


Question: // SetRoleArn sets the RoleArn field's value.

func (s *DescribeRuleOutput) SetRoleArn(v string) *DescribeRuleOutput {
	s.RoleArn = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question: // Options returns the indexing options for this field.

func (fm *FieldMapping) Options() document.IndexingOptions {
	var rv document.IndexingOptions
	if fm.Store {
		rv |= document.StoreField
	}
	if fm.Index {
		rv |= document.IndexField
	}
	if fm.IncludeTermVectors {
		rv |= document.IncludeTermVectors
	}
	if fm.DocValues {
		rv |= document.DocValues
	}
	return rv
}

def write(self, fp):
        """"""
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")
        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key == "__name__":
                    continue
                if (value is not None) or (self._optcre == self.OPTCRE):
                    key = " = ".join((key, str(value).replace('\n', '\n\t')))
                fp.write("%s\n" % (key))
            fp.write("\n")

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


Question:
Because GitPython sucks (cmd.commit() hangs)

    # pip install GitPython
    # import git
    # repo = git.Repo('.')
    # g = git.cmd.Git('.')
    # g.pull()
    # g.push()
    # g.commit()

def update_git_repo():

    today
    commands = """
        git add docs/*.html
        git add docs/images/
        git add docs*.ipynb
        git commit -am "autocommit new docs build {}"
        git push hobson
        git push origin

        git checkout master
        git merge gh-pages -m "automerge gh-pages into master"
        git push hobson
        git push origin

        git checkout gh-pages
        git merge master -m "automerge master into gh-pages"
        git push hobson
        git push origin
        """.format(datetime.datetime.today().isoformat())

    for cmd in commands.split('\n'):
        cmd = cmd.strip()
        if cmd:
            try:
                output = subprocess.check_output(cmd.split())
                print(output)
            except CalledProcessError:
                print_exc()

def __create_translation_migration(self):

        migrations_dir = os.path.join(self.BASE_DIR, self.app_name + "/migrations/")
        dependency_migration = os.path.basename(max(glob.iglob(migrations_dir + '*.py'), key=os.path.getctime)).replace(
            ".py", "")
        """
        If there's no migration before this, which is unlikely to happen, then create a migration without dependencies
        """
        if "__init__" in dependency_migration:
            dependency_migration = ""
        """ Make an empty migration """
        call_command('makemigrations', self.app_name, "--empty")
        """ Get last migration name and edit it, adding the new code """
        last_migration_file = max(glob.iglob(migrations_dir + '*.py'), key=os.path.getctime)
        new_lines = self.__create_translation_lines()
        translation_type_lines = self.__create_translation_type_lines()
        if len(dependency_migration) > 0:
            dependency_string = "('%(app_name)s', '%(dependency)s')," % {'app_name': self.app_name,
                                                                         'dependency': dependency_migration}
        else:
            dependency_string = ""
        try:
            if len(new_lines) > 0:
                with open(last_migration_file, 'w+') as file:
                    file.write(self.migration_string % {
                        'django_version': django.get_version(),
                        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        'translation_strings': "\n".join(new_lines),
                        'tags_to_remove': ", ".join('"{0}"'.format(tag) for tag in self.updated_translations),
                        'dependency_string': dependency_string,
                        'app_name': 'translation_server',
                        'translation_type_strings': "\n".join(translation_type_lines),
                        'translation_types_to_remove': ", ".join(
                            '"{0}"'.format(tag) for tag in self.updated_translation_types),
                    })
            else:
                os.remove(last_migration_file)
                self.stdout.write(self.style.NOTICE("There was no new translations to make migrations"))
                return
        except Exception as error:
            os.remove(last_migration_file)
            raise error
        else:
            self.__update_translation()
            self.stdout.write(self.style.SUCCESS("Translation migration file create successfully"))
            return

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


Question:
// parseLinuxDevice parses a device mapping string to a container.DeviceMapping struct
// knowing that the target is a Linux daemon

func parseLinuxDevice(device string) (container.DeviceMapping, error) {
	src := ""
	dst := ""
	permissions := "rwm"
	arr := strings.Split(device, ":")
	switch len(arr) {
	case 3:
		permissions = arr[2]
		fallthrough
	case 2:
		if validDeviceMode(arr[1]) {
			permissions = arr[1]
		} else {
			dst = arr[1]
		}
		fallthrough
	case 1:
		src = arr[0]
	default:
		return container.DeviceMapping{}, errors.Errorf("invalid device specification: %s", device)
	}

	if dst == "" {
		dst = src
	}

	deviceMapping := container.DeviceMapping{
		PathOnHost:        src,
		PathInContainer:   dst,
		CgroupPermissions: permissions,
	}
	return deviceMapping, nil
}

def _init_harness(self):

        self._hc = HarnessController(self.result_dir)
        self._hc.stop()
        time.sleep(1)
        self._hc.start()
        time.sleep(2)

        harness_config = ConfigParser.ConfigParser()
        harness_config.read('%s\\Config\\Configuration.ini' % settings.HARNESS_HOME)
        if harness_config.has_option('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate') and \
                harness_config.getboolean('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate'):
            logger.error('BrowserAutoNavigate in Configuration.ini should be False')
            raise FailError('BrowserAutoNavigate in Configuration.ini should be False')
        if settings.MIXED_DEVICE_TYPE:
            if harness_config.has_option('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection') and \
                    not harness_config.getboolean('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection'):
                logger.error('EnableDeviceSelection in Configuration.ini should be True')
                raise FailError('EnableDeviceSelection in Configuration.ini should be True')

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


Question: Generate an inventory of datasets in a base URI.

def inventory(uri, format):
    """"""
    base_uri = dtoolcore.utils.sanitise_uri(uri)
    info = _base_uri_info(base_uri)

    if format is None:
        _cmd_line_report(info)
    elif format == "csv":
        _csv_tsv_report(info, ",")
    elif format == "tsv":
        _csv_tsv_report(info, "\t")
    elif format == "html":
        _html_report(info)

def get_banks_by_item(self, *args, **kwargs):
        """"""
        # Implemented from kitosid template for -
        # osid.resource.ResourceBinSession.get_bins_by_resource
        catalogs = self._get_provider_session('item_bank_session').get_banks_by_item(*args, **kwargs)
        cat_list = []
        for cat in catalogs:
            cat_list.append(Bank(self._provider_manager, cat, self._runtime, self._proxy))
        return BankList(cat_list)

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


Question:
See date is a Thursday.

@param string $date

public function seeDateIsThursday($date) {
        \PHPUnit_Framework_Assert::assertTrue($this->_ParseDate($date)->dayOfWeek == Carbon::THURSDAY);
    }

String getLiteralPrefix() {

        switch (type) {

            case Types.SQL_BINARY :
            case Types.SQL_BLOB :
            case Types.SQL_CHAR :
            case Types.SQL_NCHAR :
            case Types.SQL_CLOB :
            case Types.SQL_VARBINARY :
            case Types.SQL_VARCHAR :
            case Types.SQL_NVARCHAR :
                return "'";

            case Types.SQL_DATALINK :
                return "'";    // hypothetically: "{url '";

            case Types.SQL_DATE :
                return "'";    // or JDBC escape: "{d '";

            case Types.OTHER :
                return "'";    // hypothetically: "{o '"; or new "pkg.cls"(...)

            case Types.SQL_TIME_WITH_TIME_ZONE :
            case Types.SQL_TIME :
                return "'";    // or JDBC escape: "{t '";

            case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
            case Types.SQL_TIMESTAMP :
                return "'";    // or JDBC escape: "{ts '";

            case Types.SQL_XML :
                return "'";    // hypothetically: "{xml '";

            default :
                return null;
        }
    }

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


Question: // ResolveStaticAddress implements stack.LinkAddressResolver.

func (*protocol) ResolveStaticAddress(addr tcpip.Address) (tcpip.LinkAddress, bool) {
	if addr == header.IPv4Broadcast {
		return broadcastMAC, true
	}
	if header.IsV4MulticastAddress(addr) {
		// RFC 1112 Host Extensions for IP Multicasting
		//
		// 6.4. Extensions to an Ethernet Local Network Module:
		//
		// An IP host group address is mapped to an Ethernet multicast
		// address by placing the low-order 23-bits of the IP address
		// into the low-order 23 bits of the Ethernet multicast address
		// 01-00-5E-00-00-00 (hex).
		return tcpip.LinkAddress([]byte{
			0x01,
			0x00,
			0x5e,
			addr[header.IPv4AddressSize-3] & 0x7f,
			addr[header.IPv4AddressSize-2],
			addr[header.IPv4AddressSize-1],
		}), true
	}
	return "", false
}

public function getById($id)
    {
        $ip = $this->adapter->get(sprintf('%s/floating_ips/%s', $this->endpoint, $id));

        $ip = json_decode($ip);

        return new FloatingIpEntity($ip->floating_ip);
    }

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


Question:
function to build query of table creation.

@param string   $name
@param callable $script

@return bool

public static function create($name, $script)
    {
        if (!self::existe($name)) {
            $name = self::table($name);
            //
            self::$query = 'create table '.$name.'(';
            //
            $object = new self();
            $script($object);
            //
            $query = '';
            //
            for ($i = 0; $i < Collection::count(self::$colmuns); $i++) {
                $query .= ($i == (Collection::count(self::$colmuns) - 1)) ? self::$colmuns[$i] : self::$colmuns[$i].',';
            }
            //
            self::$query .= $query.') DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;';
            //
            return Database::exec(self::$query);
        } else {
            throw new SchemaTableExistsException($name);
        }
    }

func (s *CreateNamedQueryInput) SetDatabase(v string) *CreateNamedQueryInput {
	s.Database = &v
	return s
}

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


Question:
Return progress of this job.

@return the value in interval <0,1> representing job progress.

public float progress() {
    Freezable f = UKV.get(destination_key);
    if( f instanceof Progress )
      return ((Progress) f).progress();
    return 0;
  }

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question:
reimp (Does nothing, lets php handle sessions)
Does set gc_maxlifetime to SessionTimeout to make sure timeout works like DB handler

public function setSaveHandler()
    {
        $ini = eZINI::instance();
        if ( $ini->hasVariable('Session', 'SessionTimeout') && $ini->variable('Session', 'SessionTimeout') )
        {
            ini_set("session.gc_maxlifetime", $ini->variable('Session', 'SessionTimeout') );
        }
        // make sure eZUser does not update lastVisit on every request and only on login
        $GLOBALS['eZSessionIdleTime'] = 0;
        return true;
    }

public function loginByRememberMe(): bool {

		// build the cookie name
		$cookieName = static::getRememberMeCookieName();

		// check if cookie exists
		if (!isset($_COOKIE[$cookieName])) {
			return FALSE;
		}

		// try to unserialize the cookie content
		$content = unserialize($_COOKIE[$cookieName]);

		// cookie content is not unserializable
		if (FALSE === $content) {
			return FALSE;
		}

		// check if content exists and RememberMe length
		if (isset($content[0]) and isset($content[1]) and 32==strlen($content[1])) {

			// try to load user
			$user = static::getByRememberMe($content[1]);

			// if user exists, return it
			if (is_a($user, 'Pair\User')) {
				$user->createSession($content[0]);
				$user->renewRememberMe();
				return TRUE;
			}

		}

		return FALSE;

	}

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


Question:
Overloaded to track all templates used in the current request

{@inheritDoc}

public function process($item, $arguments = null, $inheritedScope = null)
    {
        self::trackTemplateUsed($this->chosen);
        return parent::process($item, $arguments, $inheritedScope);
    }

function(doc) {
    if (!doc) {
      doc = document;
    }
    if (doc === document && this.pool.length) {
      return this.pool.pop();
    }

    return View.makeInstanceOf(doc.importNode(this, true), this);
  }

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


Question:
Read the HTML file corresponding to identifier ``fileroot``
    in the raw HTML directory below the root ``data_dir``.

    Args:
        data_dir (str)
        fileroot (str)
        encoding (str)

    Returns:
        str

def read_html_file(data_dir, fileroot, encoding=None):

    fname = os.path.join(
        data_dir, RAW_HTML_DIRNAME, fileroot + RAW_HTML_EXT)
    encodings = (encoding,) if encoding else ('utf-8', 'iso-8859-1')  # 'utf-16'
    for encoding in encodings:
        try:
            with io.open(fname, mode='rt', encoding=encoding) as f:
                raw_html = f.read()
            break
        except (UnicodeDecodeError, UnicodeError):
            raw_html = None

    return ftfy.fix_encoding(raw_html).strip()

public function getCommonRootFolder( $actualUri, $uri )
	{
		$uriParts = array_reverse( explode( "/", $uri ) );
		$actualUriParts = array_reverse( explode( "/", $actualUri ) );

		$count = min( array( count( $uriParts ), count( $actualUriParts ) ) );

		for( $i = 0; $i < $count; $i++ )
		{
			if ( $uriParts[ $i ] != $actualUriParts[ $i ] ) break;
		}

		if ( $uriParts[ $i ] === '' && isset( $uriParts[ $i + 1 ] ) && preg_match_all( "/https?:/", $uriParts[ $i + 1 ] ) )
		{
			$i--;
		}

		return array(
			'actual' => implode( "/", array_reverse( array_slice( $actualUriParts, $i ) ) ),
			'uri'    => implode( "/", array_reverse( array_slice( $uriParts, $i ) ) )
		);
	}

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


Question:
Take a Storage snapshot and unwrap only the needed properties.

@param snapshot
@returns An object containing the unwrapped values.

function _unwrapStorageSnapshot(storageSnapshot) {
    return {
      bytesTransferred: storageSnapshot.bytesTransferred,
      downloadURL: storageSnapshot.downloadURL,
      metadata: storageSnapshot.metadata,
      ref: storageSnapshot.ref,
      state: storageSnapshot.state,
      task: storageSnapshot.task,
      totalBytes: storageSnapshot.totalBytes
    };
  }

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question: Validate wavelengths for sampling.

def _validate_wavelengths(self, wave):
        """"""
        if wave is None:
            if self.waveset is None:
                raise exceptions.SynphotError(
                    'self.waveset is undefined; '
                    'Provide wavelengths for sampling.')
            wavelengths = self.waveset
        else:
            w = self._process_wave_param(wave)
            utils.validate_wavelengths(w)
            wavelengths = w * self._internal_wave_unit

        return wavelengths

func IsScanValue(v interface{}) bool {
	if v == nil {
		return true
	}
	switch v.(type) {
	case int64, float64, []byte, bool, time.Time:
		return true
	}
	return false
}

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


Question: Prepare encoder for images.

def prepare_encoder(inputs, hparams, attention_type="local_1d"):
  """"""
  x = prepare_image(inputs, hparams, name="enc_channels")
  # Add position signals.
  x = add_pos_signals(x, hparams, "enc_pos")
  x_shape = common_layers.shape_list(x)
  if attention_type == "local_1d":
    x = tf.reshape(x, [x_shape[0], x_shape[1]*x_shape[2], hparams.hidden_size])
    x.set_shape([None, None, hparams.hidden_size])
  elif attention_type == "local_2d":
    x.set_shape([None, None, None, hparams.hidden_size])
  return x

def send_media(self, path, chatid, caption):

        imgBase64 = self.convert_to_base64(path)
        filename = os.path.split(path)[-1]
        return self.wapi_functions.sendImage(imgBase64, chatid, filename, caption)

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