Question:
创建根据传入的Array数组进行判断的sql语句

@param introspectedTable The metadata for database table
@return generated xml element for check input array params

protected XmlElement buildSqlClause(IntrospectedTable introspectedTable) {

    XmlElement sql = new XmlElement("sql");
    sql.addAttribute(new Attribute("id", IDENTIFIERS_ARRAY_CONDITIONS));

    XmlElement foreach = new XmlElement("foreach");
    foreach.addAttribute(new Attribute("collection", "array"));
    foreach.addAttribute(new Attribute("item", "item"));
    foreach.addAttribute(new Attribute("index", "index"));
    foreach.addAttribute(new Attribute("separator", " and "));

    StringBuilder sb = new StringBuilder();
    for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
      XmlElement isEqualElement = new XmlElement("if");
      sb.setLength(0);
      sb.append("item == \'");
      sb.append(introspectedColumn.getJavaProperty());
      sb.append("\'");
      isEqualElement.addAttribute(new Attribute("test", sb.toString()));
      foreach.addElement(isEqualElement);

      sb.setLength(0);
      sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
      sb.append(" = ");
      sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, PROPERTY_PREFIX));

      isEqualElement.addElement(new TextElement(sb.toString()));
    }

    sql.addElement(foreach);
    return sql;
  }

public function dynamicWhere($method, $parameters)
    {
        $finder = substr($method, 5);

        $segments = preg_split('/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);

        // The connector variable will determine which connector will be used for the
        // query condition. We will change it as we come across new boolean values
        // in the dynamic method strings, which could contain a number of these.
        $connector = 'and';

        $index = 0;

        foreach ($segments as $segment) {
            // If the segment is not a boolean connector, we can assume it is a column's name
            // and we will add it to the query as a new constraint as a where clause, then
            // we can keep iterating through the dynamic method string's segments again.
            if ($segment != 'And' && $segment != 'Or') {
                $this->addDynamic($segment, $connector, $parameters, $index);

                $index++;
            }

            // Otherwise, we will store the connector so we know how the next where clause we
            // find in the query should be connected to the previous ones, meaning we will
            // have the proper boolean connector to connect the next where clause found.
            else {
                $connector = $segment;
            }
        }

        return $this;
    }

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


Question:
Checks given arguments

@param args

args[0] the settings file like described in
{@link SettingsXML}

@return true if all necessary arguments are given and false otherwise

@see SettingsXML

private static boolean checkArgs(String[] args) {
		boolean result = (args.length > 0);
		if (!result) {
			System.out
					.println("Usage: java -jar JWPLTimeMachine.jar <config-file>");
		}
		return result;
	}

public static function createConfig(array $dados = [])
    {
        $path = defined("PATH_HOME") ? PATH_HOME : "../../../";
        if (empty($dados))
            $dados = json_decode(file_get_contents($path . "_config/config.json"), true);
        else
            self::writeFile("_config/config.json", json_encode($dados));

        $conf = "<?php\n";
        foreach ($dados as $dado => $value) {
            $value = (is_bool($value) ? ($value ? 'true' : 'false') : "'{$value}'");
            $conf .= "define('" . strtoupper(trim($dado)) . "', {$value});\n";
        }

        $conf .= "\nrequire_once PATH_HOME . 'vendor/autoload.php';\nnew LinkControl\Sessao();";

        self::writeFile("_config/config.php", $conf);
    }

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


Question:
Interpolate missing values in timeseries (linear interpolation)

        Parameters
        ----------
        year: int
             year to be interpolated

def interpolate(self, year):

        df = self.pivot_table(index=IAMC_IDX, columns=['year'],
                              values='value', aggfunc=np.sum)
        # drop year-rows where values are already defined
        if year in df.columns:
            df = df[np.isnan(df[year])]
        fill_values = df.apply(fill_series,
                               raw=False, axis=1, year=year)
        fill_values = fill_values.dropna().reset_index()
        fill_values = fill_values.rename(columns={0: "value"})
        fill_values['year'] = year
        self.data = self.data.append(fill_values, ignore_index=True)

func ParseParams(params *Params, req *Request) {
	params.Query = req.GetQuery()

	// Parse the body depending on the content type.
	switch req.ContentType {
	case "application/x-www-form-urlencoded":
		// Typical form.
		var err error
		if params.Form, err = req.GetForm(); err != nil {
			paramsLogger.Warn("ParseParams: Error parsing request body", "error", err)
		}

	case "multipart/form-data":
		// Multipart form.
		if mp, err := req.GetMultipartForm(); err != nil {
			paramsLogger.Warn("ParseParams: parsing request body:", "error", err)
		} else {
			params.Form = mp.GetValues()
			params.Files = mp.GetFiles()
		}
	case "application/json":
		fallthrough
	case "text/json":
		if body := req.GetBody(); body != nil {
			if content, err := ioutil.ReadAll(body); err == nil {
				// We wont bind it until we determine what we are binding too
				params.JSON = content
			} else {
				paramsLogger.Error("ParseParams: Failed to ready request body bytes", "error", err)
			}
		} else {
			paramsLogger.Info("ParseParams: Json post received with empty body")
		}
	}

	params.Values = params.calcValues()
}

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


Question:
Prints the details of the sessions.

    Args:
      storage_reader (BaseStore): storage.

def _PrintSessionsDetails(self, storage_reader):

    for session_number, session in enumerate(storage_reader.GetSessions()):
      session_identifier = uuid.UUID(hex=session.identifier)
      session_identifier = '{0!s}'.format(session_identifier)

      start_time = 'N/A'
      if session.start_time is not None:
        start_time = timelib.Timestamp.CopyToIsoFormat(session.start_time)

      completion_time = 'N/A'
      if session.completion_time is not None:
        completion_time = timelib.Timestamp.CopyToIsoFormat(
            session.completion_time)

      enabled_parser_names = 'N/A'
      if session.enabled_parser_names:
        enabled_parser_names = ', '.join(sorted(session.enabled_parser_names))

      command_line_arguments = session.command_line_arguments or 'N/A'
      parser_filter_expression = session.parser_filter_expression or 'N/A'
      preferred_encoding = session.preferred_encoding or 'N/A'
      # Workaround for some older Plaso releases writing preferred encoding as
      # bytes.
      if isinstance(preferred_encoding, py2to3.BYTES_TYPE):
        preferred_encoding = preferred_encoding.decode('utf-8')
      if session.artifact_filters:
        artifact_filters_string = ', '.join(session.artifact_filters)
      else:
        artifact_filters_string = 'N/A'
      filter_file = session.filter_file or 'N/A'

      title = 'Session: {0:s}'.format(session_identifier)
      table_view = views.ViewsFactory.GetTableView(
          self._views_format_type, title=title)

      table_view.AddRow(['Start time', start_time])
      table_view.AddRow(['Completion time', completion_time])
      table_view.AddRow(['Product name', session.product_name])
      table_view.AddRow(['Product version', session.product_version])
      table_view.AddRow(['Command line arguments', command_line_arguments])
      table_view.AddRow(['Parser filter expression', parser_filter_expression])
      table_view.AddRow(['Enabled parser and plugins', enabled_parser_names])
      table_view.AddRow(['Preferred encoding', preferred_encoding])
      table_view.AddRow(['Debug mode', session.debug_mode])
      table_view.AddRow(['Artifact filters', artifact_filters_string])
      table_view.AddRow(['Filter file', filter_file])

      table_view.Write(self._output_writer)

      if self._verbose:
        self._PrintPreprocessingInformation(storage_reader, session_number + 1)

        self._PrintParsersCounter(
            session.parsers_counter, session_identifier=session_identifier)

        self._PrintAnalysisReportCounter(
            session.analysis_reports_counter,
            session_identifier=session_identifier)

        self._PrintEventLabelsCounter(
            session.event_labels_counter,
            session_identifier=session_identifier)

public function addReadableModel($id) {

        common_Logger::i('ADDING MODEL '.$id);

        $readables = $this->getOption(self::OPTION_READABLE_MODELS);
        $this->setOption(self::OPTION_READABLE_MODELS, array_unique(array_merge($readables, array($id))));

        // update in persistence
        ModelManager::setModel($this);
    }

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


Question: // RenderAWS is responsible for performing creating / updating the launch template

func (t *LaunchTemplate) RenderAWS(c *awsup.AWSAPITarget, a, ep, changes *LaunchTemplate) error {
	name := t.LaunchTemplateName()

	// @step: resolve the image id to an AMI for us
	image, err := c.Cloud.ResolveImage(fi.StringValue(t.ImageID))
	if err != nil {
		return err
	}

	// @step: lets build the launch template input
	input := &ec2.CreateLaunchTemplateInput{
		LaunchTemplateData: &ec2.RequestLaunchTemplateData{
			DisableApiTermination: fi.Bool(false),
			EbsOptimized:          t.RootVolumeOptimization,
			ImageId:               image.ImageId,
			InstanceType:          t.InstanceType,
		},
		LaunchTemplateName: aws.String(name),
	}
	lc := input.LaunchTemplateData

	// @step: add the the actual block device mappings
	rootDevices, err := t.buildRootDevice(c.Cloud)
	if err != nil {
		return err
	}
	ephemeralDevices, err := buildEphemeralDevices(c.Cloud, fi.StringValue(t.InstanceType))
	if err != nil {
		return err
	}
	additionalDevices, err := buildAdditionalDevices(t.BlockDeviceMappings)
	if err != nil {
		return err
	}
	for _, x := range []map[string]*BlockDeviceMapping{rootDevices, ephemeralDevices, additionalDevices} {
		for name, device := range x {
			input.LaunchTemplateData.BlockDeviceMappings = append(input.LaunchTemplateData.BlockDeviceMappings, device.ToLaunchTemplateBootDeviceRequest(name))
		}
	}

	// @step: add the ssh key
	if t.SSHKey != nil {
		lc.KeyName = t.SSHKey.Name
	}
	var securityGroups []*string
	// @step: add the security groups
	for _, sg := range t.SecurityGroups {
		securityGroups = append(securityGroups, sg.ID)
	}
	// @step: add any tenacy details
	if t.Tenancy != nil {
		lc.Placement = &ec2.LaunchTemplatePlacementRequest{Tenancy: t.Tenancy}
	}
	// @step: set the instance monitoring
	lc.Monitoring = &ec2.LaunchTemplatesMonitoringRequest{Enabled: fi.Bool(false)}
	if t.InstanceMonitoring != nil {
		lc.Monitoring = &ec2.LaunchTemplatesMonitoringRequest{Enabled: t.InstanceMonitoring}
	}
	// @step: add the iam instance profile
	if t.IAMInstanceProfile != nil {
		lc.IamInstanceProfile = &ec2.LaunchTemplateIamInstanceProfileSpecificationRequest{
			Name: t.IAMInstanceProfile.Name,
		}
	}
	// @step: are the node publically facing
	if fi.BoolValue(t.AssociatePublicIP) {
		lc.NetworkInterfaces = append(lc.NetworkInterfaces,
			&ec2.LaunchTemplateInstanceNetworkInterfaceSpecificationRequest{
				AssociatePublicIpAddress: t.AssociatePublicIP,
				DeleteOnTermination:      aws.Bool(true),
				DeviceIndex:              fi.Int64(0),
				Groups:                   securityGroups,
			})
	} else {
		lc.SecurityGroupIds = securityGroups
	}
	// @step: add the userdata
	if t.UserData != nil {
		d, err := t.UserData.AsBytes()
		if err != nil {
			return fmt.Errorf("error rendering LaunchTemplate UserData: %v", err)
		}
		lc.UserData = aws.String(base64.StdEncoding.EncodeToString(d))
	}

	// @step: attempt to create the launch template
	err = func() error {
		for attempt := 0; attempt < 10; attempt++ {
			if _, err = c.Cloud.EC2().CreateLaunchTemplate(input); err == nil {
				return nil
			}

			if awsup.AWSErrorCode(err) == "ValidationError" {
				message := awsup.AWSErrorMessage(err)
				if strings.Contains(message, "not authorized") || strings.Contains(message, "Invalid IamInstance") {
					if attempt > 10 {
						return fmt.Errorf("IAM instance profile not yet created/propagated (original error: %v)", message)
					}
					glog.V(4).Infof("got an error indicating that the IAM instance profile %q is not ready: %q", fi.StringValue(ep.IAMInstanceProfile.Name), message)

					time.Sleep(5 * time.Second)
					continue
				}
				glog.V(4).Infof("ErrorCode=%q, Message=%q", awsup.AWSErrorCode(err), awsup.AWSErrorMessage(err))
			}
		}

		return err
	}()
	if err != nil {
		return fmt.Errorf("failed to create aws launch template: %s", err)
	}

	ep.ID = fi.String(name)

	return nil
}

def primary_deployment(cluster)
      # Try to describe the existing service.
      description = begin
        Ecs.describe_services(cluster.name, [@name])
      rescue => e
        puts "Error: #{e}"
        nil
      end

      missing_service_warning = <<-STR
Can't find an existing service '#{name}'.  You'll probably need to
register one manually using the AWS console and set up any load balancers
you might need.
      STR

      if description.nil?
        puts missing_service_warning
        return nil
      end

      unless service = description.fetch("services")[0]
        puts missing_service_warning
        return nil
      end

      # Find the primary deployment.
      deployment = service.fetch("deployments").find do |d|
        d["status"] == "PRIMARY"
      end
      return nil if deployment.nil?

      # Extract a task definition `name:revision`.
      arn = deployment.fetch("taskDefinition")
      arn.split('/').last
    end

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


Question: Boot the application's service providers.

public function boot(): KernelInterface
    {
        if (! $this->isBooted) {
            foreach ($this->serviceProviders as $provider) {
                $this->bootProvider($provider);
            }
            $this->isBooted = true;
        }

        return $this;
    }

def run(self, start_command_srv):

        if start_command_srv:
            # note, this must be established *before* the task runner is forked
            # so the task runner can communicate with the command server.

            # fork the command server
            self._command_server.start()

            # drop root privileges; command server will remain as the only
            # daemon process with root privileges. while root plugins have root
            # shell access, they are known and the commands are logged by the
            # command server.
            self._drop_privs()

        # fork the task runner
        self._task_runner.start()

        # setup signal handlers
        self._reg_sighandlers()

        while self.running:
            time.sleep(self._sleep_period)

        self.shutdown()

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


Question:
Match to chain-hash

@param {String} newHash - The new hash to navigate
@param {Array} parents - The array of pushed parents
@param {Array} hashes - The array of pushed hashes
@private

function match_(newHash, parents, hashes) {
    parents.push(parents[hashes.length].parentElement.closest(selClass));
    hashes.push(parents[hashes.length].getAttribute('hash'));

    if (parents[hashes.length]) {
      return match_(newHash, parents, hashes);
    } else {
      return hashes.slice(0, hashes.length).reverse().join('/');
    }
  }

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

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

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

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

        return $parameters;
    }

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


Question: // SetExternalExecutionUrl sets the ExternalExecutionUrl field's value.

func (s *ActionExecutionResult) SetExternalExecutionUrl(v string) *ActionExecutionResult {
	s.ExternalExecutionUrl = &v
	return s
}

def violations(self, src_path):

        if not any(src_path.endswith(ext) for ext in self.driver.supported_extensions):
            return []
        if src_path not in self.violations_dict:
            if self.reports:
                self.violations_dict = self.driver.parse_reports(self.reports)
            else:
                if self.driver_tool_installed is None:
                    self.driver_tool_installed = self.driver.installed()
                if not self.driver_tool_installed:
                    raise EnvironmentError("{} is not installed".format(self.driver.name))
                command = copy.deepcopy(self.driver.command)
                if self.options:
                    command.append(self.options)
                if os.path.exists(src_path):
                    command.append(src_path.encode(sys.getfilesystemencoding()))
                    output, _ = execute(command, self.driver.exit_codes)
                    self.violations_dict.update(self.driver.parse_reports([output]))

        return self.violations_dict[src_path]

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


Question:
Set time_out field of all flagged
    timesheet entries to Null.

def migrate_050_to_051(session):

    entries_to_update = session.query(Entry).filter(
            Entry.forgot_sign_out.is_(True)).filter(
            Entry.time_out.isnot(None))

    for entry in entries_to_update:
        entry.time_out = None
        logging.info('Entry updated {}'.format(entry.uuid))
        logging.debug(entry.uuid)
        session.add(entry)

public function updateCMSFields(FieldList $fields)
    {
        // Update Field Objects (from parent):

        parent::updateCMSFields($fields);

        // Create Style Fields:

        $fields->addFieldsToTab(
            'Root.Style',
            [
                FieldSection::create(
                    'LinkColorStyle',
                    $this->owner->fieldLabel('LinkColorStyle'),
                    [
                        FieldGroup::create(
                            $this->owner->fieldLabel('Background'),
                            [
                                ColorField::create(
                                    'ColorBackgroundLink',
                                    $this->owner->fieldLabel('Link')
                                ),
                                ColorField::create(
                                    'ColorBackgroundHover',
                                    $this->owner->fieldLabel('Hover')
                                ),
                                ColorField::create(
                                    'ColorBackgroundActive',
                                    $this->owner->fieldLabel('Active')
                                )
                            ]
                        ),
                        FieldGroup::create(
                            $this->owner->fieldLabel('Foreground'),
                            [
                                ColorField::create(
                                    'ColorForegroundLink',
                                    $this->owner->fieldLabel('Link')
                                ),
                                ColorField::create(
                                    'ColorForegroundHover',
                                    $this->owner->fieldLabel('Hover')
                                ),
                                ColorField::create(
                                    'ColorForegroundActive',
                                    $this->owner->fieldLabel('Active')
                                )
                            ]
                        )
                    ]
                )
            ]
        );
    }

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


Question: ------------------ 内部方法 ------------------ *

protected function initService($config) {
        $rs = NULL;

        if ($config instanceOf Closure) {
            $rs = $config();
        } elseif (is_string($config) && class_exists($config)) {
            $rs = new $config();
            if(is_callable(array($rs, 'onInitialize'))) {
                call_user_func(array($rs, 'onInitialize'));
            }
        } else {
            $rs = $config;
        }

        return $rs;
    }

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

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

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

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

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


Question: Set a client name.

def set_name(self, name):
        """"""
        if not name:
            name = ''
        self._client['config']['name'] = name
        yield from self._server.client_name(self.identifier, name)

func (s *DescribeSecurityProfileInput) SetSecurityProfileName(v string) *DescribeSecurityProfileInput {
	s.SecurityProfileName = &v
	return s
}

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


Question:
Get the SAX string of this whole collection.

@param separatorToken The separator token to use for the string.

@return The whole data as a string.

public String getSAXString(String separatorToken) {
    StringBuffer sb = new StringBuffer();
    ArrayList<Integer> index = new ArrayList<Integer>();
    index.addAll(this.realTSindex.keySet());
    Collections.sort(index, new Comparator<Integer>() {
      public int compare(Integer int1, Integer int2) {
        return int1.compareTo(int2);
      }
    });
    for (int i : index) {
      sb.append(this.realTSindex.get(i).getPayload()).append(separatorToken);
    }
    return sb.toString();
  }

public static List<String> parserStringList(JsonPullParser parser) throws IOException,
			JsonFormatException {

		State eventType = parser.getEventType();
		if (eventType == State.VALUE_NULL) {
			return null;
		}
		if (eventType != State.START_ARRAY) {
			throw new IllegalStateException("not started brace!");
		}
		List<String> list = new ArrayList<String>();
		while (parser.lookAhead() != State.END_ARRAY) {
			eventType = parser.getEventType();
			if (eventType == State.VALUE_NULL) {
				list.add(null);
			} else if (eventType == State.VALUE_STRING) {
				list.add(parser.getValueString());
			} else {
				throw new IllegalStateException("unexpected state. expected=VALUE_STRING, but get="
						+ eventType.toString());
			}
		}
		parser.getEventType();
		return list;
	}

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


Question:
Compare two dicts returning only keys that exist in the first dict and are
    different in the second one

def compare_changes(obj, **kwargs):
    '''

    '''
    changes = {}
    for k, v in obj.items():
        if k in kwargs:
            if v != kwargs[k]:
                changes[k] = kwargs[k]
    return changes

def _check_samples_nodups(fnames):

    counts = defaultdict(int)
    for f in fnames:
        for s in get_samples(f):
            counts[s] += 1
    duplicates = [s for s, c in counts.items() if c > 1]
    if duplicates:
        raise ValueError("Duplicate samples found in inputs %s: %s" % (duplicates, fnames))

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


Question:
Returns keys from the global $_SERVER array

@param string|array $mKeys     The key(s) to return
@param bool         $bXssClean Whether to run the result through the XSS filter

@return array|mixed
@throws \Nails\Common\Exception\FactoryException

public static function server($mKeys = null, $bXssClean = false)
    {
        $aArray = isset($_SERVER) ? $_SERVER : [];
        return static::getItemsFromArray($mKeys, $bXssClean, $aArray);
    }

function queryChecker(checkQuery) {
  if (!checkQuery) {
    throw new Error('check query can not be null');
  }
  debug('query checker conditions:%s', checkQuery);
  const arr = checkQuery.split('&');
  const checkParams = {};
  const checkKeys = [];
  arr.forEach((str) => {
    const tmpArr = str.split('=');
    const key = tmpArr[0];
    checkKeys.push(key);
    checkParams[key] = tmpArr[1];
  });

  return (ctx, next) => {
    const query = ctx.query;
    debug('query:%j', query);
    let valid = true;
    checkKeys.forEach((key) => {
      if (valid && query[key] !== checkParams[key]) {
        valid = false;
      }
    });

    if (valid) {
      return next();
    }
    const originalUrl = ctx.originalUrl;
    const urlInfo = url.parse(originalUrl);
    checkKeys.forEach((key) => {
      query[key] = checkParams[key];
    });
    /* eslint no-param-reassign:0 */
    ctx.status = 302;
    ctx.set('Cache-Control', 'no-cache, no-store, max-age=0');
    ctx.redirect(`${urlInfo.pathname}?${qs.stringify(query)}`);
    return null;
  };
}

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


Question: A field data terms query for the provided field name.

public static FieldDataTermsQueryBuilder fieldDataTermsQuery(String name, byte[] value, int cacheKey) {
    return new FieldDataTermsQueryBuilder(name, value, cacheKey);
  }

private void init() {

		factories.put(NotEmptyQuery.class,     new NotEmptyQueryFactory(this));
		factories.put(FulltextQuery.class,     new KeywordQueryFactory(this));
		factories.put(SpatialQuery.class,      new SpatialQueryFactory(this));
		factories.put(GroupQuery.class,        new GroupQueryFactory(this));
		factories.put(RangeQuery.class,        new RangeQueryFactory(this));
		factories.put(ExactQuery.class,        new KeywordQueryFactory(this));
		factories.put(ArrayQuery.class,        new ArrayQueryFactory(this));
		factories.put(EmptyQuery.class,        new EmptyQueryFactory(this));
		factories.put(TypeQuery.class,         new TypeQueryFactory(this));
		factories.put(UuidQuery.class,         new UuidQueryFactory(this));
		factories.put(RelationshipQuery.class, new RelationshipQueryFactory(this));
		factories.put(ComparisonQuery.class,   new ComparisonQueryFactory(this));

		converters.put(Boolean.class, new BooleanTypeConverter());
		converters.put(String.class,  new StringTypeConverter());
		converters.put(Date.class,    new DateTypeConverter());
		converters.put(Long.class,    new LongTypeConverter());
		converters.put(Short.class,   new ShortTypeConverter());
		converters.put(Integer.class, new IntTypeConverter());
		converters.put(Float.class,   new FloatTypeConverter());
		converters.put(Double.class,  new DoubleTypeConverter());
		converters.put(byte.class,    new ByteTypeConverter());
	}

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


Question:
Helper for :meth:`build`.  Returns subdomain and path for the
        rule that accepts this endpoint, values and method.

        :internal:

def _partial_build(self, endpoint, values, method, append_unknown):

        # in case the method is none, try with the default method first
        if method is None:
            rv = self._partial_build(
                endpoint, values, self.default_method, append_unknown
            )
            if rv is not None:
                return rv

        # default method did not match or a specific method is passed,
        # check all and go with first result.
        for rule in self.map._rules_by_endpoint.get(endpoint, ()):
            if rule.suitable_for(values, method):
                rv = rule.build(values, append_unknown)
                if rv is not None:
                    return rv

func (c *Context) SetServiceBaseURL(domainOrURL string) {
	u, _ := getBaseURL(domainOrURL)

	if u != nil && u.Host != "" {
		c.ServiceBaseURL = *u
	} else if domainOrURL != "" {
		c.ServiceBaseURL = url.URL{Scheme: "https", Host: domainOrURL}
	} else {
		c.Log().Error("Can't use SetServiceHostFromURL with empty arg")
	}
}

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


Question: Run the given section.

def run_section(self, name, input_func=_stdin_):
        """"""
        print('\nStuff %s by the license:\n' % name)
        section = self.survey[name]
        for question in section:
            self.run_question(question, input_func)

func (s *Scte35SegmentationDescriptor) SetSegmentNum(v int64) *Scte35SegmentationDescriptor {
	s.SegmentNum = &v
	return s
}

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


Question:
Apply filter into all values
        Params
            <lambda> | <function> given_filter
            <bool> only_nonzero

def filter(self, given_filter, apply_zerovalue=False):

        get_ = self.get___method
        set_ = self.set___method
        max_value = self.max_value
        for table_id in range(self.depth):
            for cell_id in range(self.width):
                val = get_(self, table_id, cell_id)
                if val or apply_zerovalue:
                    val = given_filter(val)
                    val = max_value if val > max_value else val
                    set_(self, table_id, cell_id, val)

func (t BackendTransform) Validate() error {
	switch {
	case t.Adjust:
		if t.Zero {
			return fmt.Errorf("--adjust and --zero may not be specified together")
		}
		if t.Equal {
			return fmt.Errorf("--adjust and --equal may not be specified together")
		}
		if len(t.Inputs) != 1 {
			return fmt.Errorf("only one backend may be specified when adjusting")
		}

	case t.Zero, t.Equal:
		if t.Equal && t.Zero {
			return fmt.Errorf("--zero and --equal may not be specified together")
		}
		if len(t.Inputs) > 0 {
			return fmt.Errorf("arguments may not be provided when --zero or --equal is specified")
		}

	default:
		percent := false
		names := sets.NewString()
		for i, input := range t.Inputs {
			if names.Has(input.Name) {
				return fmt.Errorf("backend name %q may only be specified once", input.Name)
			}
			names.Insert(input.Name)
			if input.Percentage {
				if !percent && i != 0 {
					return fmt.Errorf("all backends must either be percentages or weights")
				}
				percent = true
			}
			if input.Value < 0 {
				return fmt.Errorf("negative percentages are not allowed")
			}
		}
	}
	return nil
}

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *GetSearchSuggestionsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetSearchSuggestionsInput"}
	if s.Resource == nil {
		invalidParams.Add(request.NewErrParamRequired("Resource"))
	}
	if s.SuggestionQuery != nil {
		if err := s.SuggestionQuery.Validate(); err != nil {
			invalidParams.AddNested("SuggestionQuery", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
Populate the pivot table.

@param  Model   $currentParent
@param  array[] $insertedPKs
@return void

public function execute(Model $currentParent, array $insertedPKs)
    {
        if (!isset($insertedPKs[$this->relatedClass])) {
            return;
        }

        $this->updateParentKey($currentParent);

        $this->relation->attach(
            collect($this->pickRelatedIds($insertedPKs))
                ->mapWithKeys(function ($relatedId) use ($insertedPKs, $currentParent) {
                    return [$relatedId => $this->getExtraAttributes($insertedPKs, $currentParent)];
                })
                ->all()
        );
    }

public function init()
    {

        // initialize the parend class
        parent::init();

        // initialize the prepared statements
        $this->categoryStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::CATEGORY));
        $this->categoryByPathStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::CATEGORY_BY_PATH));
        $this->categoryCountChildrenStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::CATEGORY_COUNT_CHILDREN));
    }

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


Question: Add local owner role from parent object

def _addLocalOwnerRole(self, username):

        parent = self.getParent()
        if parent.portal_type == "Client":
            parent.manage_setLocalRoles(username, ["Owner", ])
            # reindex object security
            self._recursive_reindex_object_security(parent)

public function execute(Model $currentParent, array $insertedPKs)
    {
        if (!isset($insertedPKs[$this->relatedClass])) {
            return;
        }

        $this->updateParentKey($currentParent);

        $this->relation->attach(
            collect($this->pickRelatedIds($insertedPKs))
                ->mapWithKeys(function ($relatedId) use ($insertedPKs, $currentParent) {
                    return [$relatedId => $this->getExtraAttributes($insertedPKs, $currentParent)];
                })
                ->all()
        );
    }

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


Question:
训练
@throws Exception

public void train() throws Exception {

		loadData();
		/**
		 *
		 * 更新参数的准则
		 */
		Update update;
		// viterbi解码
		Inferencer inference;

		HammingLoss loss = new HammingLoss();
		if (standard) {
			inference = new LinearViterbi(templets, labels.size());
			update = new LinearViterbiPAUpdate((LinearViterbi) inference, loss);
		} else {
			inference = new HigherOrderViterbi(templets, labels.size());
			update = new HigherOrderViterbiPAUpdate(templets, labels.size(), true);
		}

		OnlineTrainer trainer;

		if(cl!=null){
			trainer = new OnlineTrainer(cl, update, loss, factory,iterNum, c);
		}else{
			trainer = new OnlineTrainer(inference, update, loss,
					factory, iterNum, c);
		}

		cl = trainer.train(trainSet, testSet);

		if(cl!=null&&newmodel!=null)
			saveTo(newmodel);
		else
			saveTo(model);

	}

public static void sleep (int millis)
    {
        if (RunAnywhere.isLinux() && isLoaded()) {
            nativeSleep(millis);
        } else {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException ie) {
                log.info("Thread.sleep(" + millis + ") interrupted.");
            }
        }
    }

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


Question: // And will add an AND op to the filter. One or more FilterOps can be passed in.

func (f *FilterOp) And(filters ...*FilterOp) *FilterOp {
	if len(f.AndFilters) == 0 {
		f.AndFilters = filters[:]
	} else {
		f.AndFilters = append(f.AndFilters, filters...)
	}

	return f
}

function processLogicalOr(tokenizer, scope) {
  let node = processLogicalAnd(tokenizer, scope);

  while (tokenizer.token.match(types.LOGICAL_OR)) {
    node = createOperatorNode(tokenizer.token.value, [node, processLogicalAnd(tokenizer.skipToken(), scope)]);
  }

  return node;
}

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


Question: // Run executes the program with the given CLI arguments.

func (m *Launcher) Run(ctx context.Context, args ...string) error {
	cmd := &cobra.Command{
		Use:   "run",
		Short: "Start the influxd server (default)",
		RunE: func(cmd *cobra.Command, args []string) error {
			return m.run(ctx)
		},
	}

	buildLauncherCommand(m, cmd)

	cmd.SetArgs(args)
	return cmd.Execute()
}

def cmd(send, msg, args):

    if not msg:
        send("kill who?")
        return
    if msg.lower() == args['botnick'].lower():
        send('%s is not feeling suicidal right now.' % msg)
    else:
        send('Die, %s!' % msg)

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


Question:
Counts columns in the specified range of a standard column family

@param key
@param start
@param end
@param max
@return

public int countColumns(K key, N start, N end, int max) {
    CountQuery<K, N> query = HFactory.createCountQuery(keyspace, keySerializer,
        topSerializer);
    query.setKey(key);
    query.setColumnFamily(columnFamily);
    query.setRange(start, end, max);
    return query.execute().get();
  }

public function fetchAll($style=null, $argument=null, $ctor_args=null)
    {
        $style = is_null($style) ? $this->_fetch_sty : $style;
        $rst   = null;
        try {
            switch ($style)
            {
            case \PDO::FETCH_ASSOC:
                \oci_fetch_all($this->_stmt, $rst, 0, -1, \OCI_FETCHSTATEMENT_BY_ROW + \OCI_ASSOC);
                break;

            case \PDO::FETCH_NUM:
                \oci_fetch_all($this->_stmt, $rst, 0, -1, \OCI_FETCHSTATEMENT_BY_ROW + \OCI_NUM);
                break;

            case \PDO::FETCH_BOTH:
                \oci_fetch_all($this->_stmt, $rst, 0, -1, \OCI_FETCHSTATEMENT_BY_ROW + \OCI_NUM + \OCI_ASSOC);
                break;

            case \PDO::FETCH_COLUMN:
                \oci_fetch_all($this->_stmt, $rst, 0, -1, \OCI_FETCHSTATEMENT_BY_ROW + \OCI_NUM);
                $rst = array_map(
                    function ($vals) use ($argument) {
                        return $vals[intval($argument)];
                    }, $rst
                );
                break;

            case \PDO::FETCH_COLUMN|\PDO::FETCH_GROUP:
                \oci_fetch_all($this->_stmt, $rst, 0, -1, \OCI_FETCHSTATEMENT_BY_ROW + \OCI_NUM);
                $temp = array();
                foreach ($rst as $key => $value) {
                    if (!array_key_exists($value[0], $temp)) {
                        $temp[$value[0]] = array();
                    }
                    array_push($temp[$value[0]], $value[1]);
                }
                $rst = $temp;
                break;

            case \PDO::FETCH_CLASS:
                \oci_fetch_all($this->_stmt, $rst, 0, -1, \OCI_FETCHSTATEMENT_BY_ROW + \OCI_ASSOC);
                $temp = array();
                foreach ($rst as $idx => $data) {
                    array_push($temp, $this->_createObjectFromData($argument, $data));
                }
                $rst  = $temp;
                break;

            case \PDO::FETCH_FUNC:
                if (!function_exists($argument)) {
                    throw new \PDOException("Function $argument does not exists");
                }
                $ref  = new \ReflectionFunction($argument);
                $args = $ref->getNumberOfParameters();
                if ($args<1) {
                    throw new \PDOException("Function $argument can't receive parameters");
                }
                \oci_fetch_all($this->_stmt, $rst, 0, -1, \OCI_FETCHSTATEMENT_BY_ROW + \OCI_NUM);
                foreach ($rst as $idx => $value) {
                    $temp = array();
                    foreach ($value as $key => $data) {
                        array_push($temp, $data);
                    }
                    call_user_func_array($argument, $temp);
                }
                break;
            }
        } catch (\Exception $e) {
            throw new \PDOException($e->getMessage());
        }
        $rst = $this->_fixResultKeys($rst);
        return $rst;
    }

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


Question:
Remove a user from the minion

    CLI Example:

    .. code-block:: bash

        salt '*' user.delete name remove=True force=True

def delete(name, remove=False, force=False):
    '''

    '''
    if salt.utils.data.is_true(force):
        log.warning(
            'userdel does not support force-deleting user while user is '
            'logged in'
        )
    cmd = ['userdel']
    if remove:
        cmd.append('-r')
    cmd.append(name)
    return __salt__['cmd.retcode'](cmd, python_shell=False) == 0

public function purge() {
        if ($this->isready) {
            $this->collection->drop();
            $this->collection = $this->database->selectCollection($this->definitionhash);
        }

        return true;
    }

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


Question: Disbatch local client_async commands

def _disbatch_local_async(self, chunk):
        '''

        '''
        f_call = self._format_call_run_job_async(chunk)
        # fire a job off
        pub_data = yield self.saltclients['local_async'](*f_call.get('args', ()), **f_call.get('kwargs', {}))

        raise tornado.gen.Return(pub_data)

func writeBindExecuteMsg(buf *pool.WriteBuffer, name string, params ...interface{}) error {
	buf.StartMessage(bindMsg)
	buf.WriteString("")
	buf.WriteString(name)
	buf.WriteInt16(0)
	buf.WriteInt16(int16(len(params)))
	for _, param := range params {
		buf.StartParam()
		bytes := types.Append(buf.Bytes, param, 0)
		if bytes != nil {
			buf.Bytes = bytes
			buf.FinishParam()
		} else {
			buf.FinishNullParam()
		}
	}
	buf.WriteInt16(0)
	buf.FinishMessage()

	buf.StartMessage(executeMsg)
	buf.WriteString("")
	buf.WriteInt32(0)
	buf.FinishMessage()

	writeSyncMsg(buf)

	return nil
}

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


Question:
@param       $viewPath
@param array $data
@param bool  $bypass

@return string

public function render($viewPath, array $data = null, $bypass = false)
	{
	    $this->setView($viewPath);

        if (!is_null($data)) {
            $this->setData($data);
        }

        if (!$this->isAjax() && $this->getLayout() !== null && !$bypass) {
            return $this->renderLayout($this->getSharedData());
        }

        return $this->renderView($this->getView(), $this->getData());
	}

protected function parseQueryParams() : void
    {
        $queryParams = [];
        $queryString = $this->request->getUri()->getQuery();
        parse_str($queryString, $queryParams);
        $this->queryParams = $queryParams;
    }

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


Question:
指定したパスとクラスタイプに対する{@link FieldFormatter}を取得する。

引数「fieldPath」に完全に一致するフォーマッタを取得します。

@param fieldPath フィールドパス。
@param requiredType 取得したいクラスタイプ
@return 見つからない場合は、nullを返す。

public <T> FieldFormatter<T> getFormatter(final String fieldPath, final Class<T> requiredType) {
        FormatterHolder holder = pathMap.get(fieldPath);
        return holder != null ? holder.getFormatter(requiredType) : null;
    }

public static boolean isValid(final DocumentSymbol symbol) {
    return ((symbol != null) && (!IterableExtensions.<Object>exists(IterableExtensions.<Field, Object>map(IterableExtensions.<Field, Field>map(IterableExtensions.<Field>filter(((Iterable<Field>)Conversions.doWrapArray(DocumentSymbol.class.getDeclaredFields())), ((Function1<Field, Boolean>) (Field it) -> {
      final Function1<Annotation, Boolean> _function = (Annotation it_1) -> {
        Class<? extends Annotation> _annotationType = it_1.annotationType();
        return Boolean.valueOf((_annotationType == NonNull.class));
      };
      return Boolean.valueOf(IterableExtensions.<Annotation>exists(((Iterable<Annotation>)Conversions.doWrapArray(it.getAnnotations())), _function));
    })), ((Function1<Field, Field>) (Field it) -> {
      Field _xblockexpression = null;
      {
        it.setAccessible(true);
        _xblockexpression = it;
      }
      return _xblockexpression;
    })), ((Function1<Field, Object>) (Field it) -> {
      try {
        return it.get(symbol);
      } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
      }
    })), ((Function1<Object, Boolean>) (Object it) -> {
      return Boolean.valueOf((it == null));
    }))));
  }

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


Question:
return a list of all experiments

 @return [Array<Gxapi::Ostruct>]

def get_experiments
      @experiments ||= begin
        # fetch our data from the cache
        data = Gxapi.with_error_handling do
          # handle caching
          self.list_experiments_from_cache
        end
        # turn into Gxapi::Ostructs
        (data || []).collect{|data| Ostruct.new(data)}
      end
    end

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question:
Store an item in the cache indefinitely.

@param  string  $key
@param  mixed   $value
@return bool

public function forever($key, $value)
    {
        $this->pushForeverKeys($this->tags->getNamespace(), $key);

        return parent::forever($key, $value);
    }

protected void allocateBuffers(int arraySize) {
    assert Integer.bitCount(arraySize) == 1;

    // Compute new hash mixer candidate before expanding.
    final int newKeyMixer = this.orderMixer.newKeyMixer(arraySize);

    // Ensure no change is done if we hit an OOM.
    KType[] prevKeys = Intrinsics.<KType[]> cast(this.keys);
    VType[] prevValues = Intrinsics.<VType[]> cast(this.values);
    try {
      int emptyElementSlot = 1;
      this.keys = Intrinsics.<KType> newArray(arraySize + emptyElementSlot);
      this.values = Intrinsics.<VType> newArray(arraySize + emptyElementSlot);
    } catch (OutOfMemoryError e) {
      this.keys = prevKeys;
      this.values = prevValues;
      throw new BufferAllocationException(
          "Not enough memory to allocate buffers for rehashing: %,d -> %,d",
          e,
          this.mask + 1,
          arraySize);
    }

    this.resizeAt = expandAtCount(arraySize, loadFactor);
    this.keyMixer = newKeyMixer;
    this.mask = arraySize - 1;
  }

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


Question:
Asynchronous iterator for the view. Downloads a view in pages
    and calls the callback for each row.
    This helps avoid transfering data in huge datachunks.

def view_aterator(connection, callback, view, view_keys=dict(),
                  args=tuple(), kwargs=dict(), per_page=15,
                  consume_errors=True):
    '''

    '''
    skip = 0
    while True:
        keys = dict(view_keys)
        keys.update(dict(skip=skip, limit=per_page))
        records = yield connection.query_view(view, **keys)
        log.debug('view_aterator', "Fetched %d records of the view: %s",
                  len(records), view.name)
        skip += len(records)
        for record in records:
            try:
                yield callback(connection, record, *args, **kwargs)
            except Exception as e:
                error.handle_exception(
                    'view_aterator', e,
                    "Callback %s failed its iteration on a row %r",
                    callback.__name__, record)
                if not consume_errors:
                    raise e

        if not records:
            break

func (li *MemberListIterator) Next(ctx context.Context, items *[]Member) bool {
	if li.err != nil {
		return false
	}
	li.err = li.fetch(ctx, li.Paging.Next)
	if li.err != nil {
		return false
	}
	*items = li.Lists
	if len(li.Lists) == 0 {
		return false
	}
	return true
}

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


Question:
Gets next day of week

        :param weekday: day of week
        :param including_today: If today is sunday and requesting next sunday
        :return: Date of next monday, tuesday ..

def get_next(weekday, including_today=False):

        now = datetime.datetime.now()
        if now.weekday() == weekday.value and including_today:
            delta = datetime.timedelta(days=0)
        elif now.weekday() == weekday.value and not including_today:
            delta = datetime.timedelta(days=7)
        else:
            delta = datetime.timedelta(
                (7 + weekday.value - now.weekday()) % 7
            )  # times delta to next instance
        return Day(now + delta).get_just_date()

def schedule_cycles(minutes,location_id,conditions = {})

			products = Auth.configuration.product_class.constantize.all if conditions.blank?

			products = Auth.configuration.product_class.constantize.where(conditions) if !conditions.blank?

			minutes.keys.each do |epoch|

				products.each do |product|

					all_cycles_valid = true
					product.cycles.each do |cycle|

						all_cycles_valid = cycle.requirements_satisfied(epoch + cycle.time_since_prev_cycle.minutes*60,location_id)

					end

					## just because the cycles are valid, it means we have workers, but how many?
					## that also has to be returned by the cycle validity statements

					if all_cycles_valid == true
						cycle_chain = []
						product.cycles.each do |cycle|
							epoch_at_which_to_add = epoch + cycle.time_since_prev_cycle.minutes*60
							cycle_to_add = cycle.dup
							cycle_to_add.start_time = epoch_at_which_to_add
							cycle_to_add.end_time = cycle_to_add.start_time + cycle_to_add.duration
							cycle_to_add.cycle_chain = cycle_chain
							if minutes[epoch_at_which_to_add]

								add_to_previous_rolling_n_minutes(minutes,epoch_at_which_to_add,cycle_to_add)

								minutes[epoch_at_which_to_add].cycles << cycle_to_add

								cycle_chain << cycle_to_add.id.to_s
							else
								#raise "necessary minute not in range."
							end
						end
					end
				end
			end
			minutes
		end

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


Question:
Get the raw GeoIP info using ipstack.

@param string $ip

@return array

public function getRaw($ip)
    {
        try {
            return json_decode($this->guzzle->get($this->getUrl($ip))->getBody(), true);
        } catch (RequestException $e) {
            // ignore
        }

        return [];
    }

def export(name: str, value: Any):

    stack = get_root_resource()
    if stack is not None:
        stack.output(name, value)

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


Question: Returns true if array1 starts with array2

public static boolean startsWith(Object array1[], Object array2[]){
        return equals(array1, 0, array2, 0, array2.length);
    }

function setOpening(tokenOrLexer) {
    metaObj.line = tokenOrLexer.line;
    metaObj.col = tokenOrLexer.col;

    // whitespace or comments that preceded the opening token
    // (e.g. on a () list whitespace or comments that preceded "(")
    metaObj.prelude = tokenOrLexer.prelude;
  }

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


Question:
/*
(non-Javadoc)

@see com.ibm.ws.sib.processor.impl.interfaces.DestinationHandler#getSourceProtocolItemStream()

@Override
    public SourceProtocolItemStream getSourceProtocolItemStream()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "getSourceProtocolItemStream");

        SourceProtocolItemStream sourceProtocolItemStream =
                        _protoRealization.
                                        getRemoteSupport().
                                        getSourceProtocolItemStream();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "getSourceProtocolItemStream", sourceProtocolItemStream);

        return sourceProtocolItemStream;
    }

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

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


Question:
Check if tile is blocking.

@param mover The mover reference.
@param tx The horizontal tile to check.
@param ty The vertical tile to check.
@return true if blocked, false else.

private boolean isTileBlocked(Pathfindable mover, int tx, int ty)
    {
        final Tile tile = map.getTile(tx, ty);
        if (tile != null)
        {
            final TilePath tilePath = tile.getFeature(TilePath.class);
            return mover.isBlocking(tilePath.getCategory());
        }
        return false;
    }

private static void updateWindowed(final CpcSketch sketch, final int rowCol) {
    assert ((sketch.windowOffset >= 0) && (sketch.windowOffset <= 56));
    final int k = 1 << sketch.lgK;
    final long c32pre = sketch.numCoupons << 5;
    assert c32pre >= (3L * k); // C < 3K/32, in other words flavor >= HYBRID
    final long c8pre = sketch.numCoupons << 3;
    final int w8pre = sketch.windowOffset << 3;
    assert c8pre < ((27L + w8pre) * k); // C < (K * 27/8) + (K * windowOffset)

    boolean isNovel = false; //novel if new coupon
    final int col = rowCol & 63;

    if (col < sketch.windowOffset) { // track the surprising 0's "before" the window
      isNovel = PairTable.maybeDelete(sketch.pairTable, rowCol); // inverted logic
    }
    else if (col < (sketch.windowOffset + 8)) { // track the 8 bits inside the window
      assert (col >= sketch.windowOffset);
      final int row = rowCol >>> 6;
      final byte oldBits = sketch.slidingWindow[row];
      final byte newBits = (byte) (oldBits | (1 << (col - sketch.windowOffset)));
      if (newBits != oldBits) {
        sketch.slidingWindow[row] = newBits;
        isNovel = true;
      }
    }
    else { // track the surprising 1's "after" the window
      assert col >= (sketch.windowOffset + 8);
      isNovel = PairTable.maybeInsert(sketch.pairTable, rowCol); // normal logic
    }

    if (isNovel) {
      sketch.numCoupons += 1;
      updateHIP(sketch, rowCol);
      final long c8post = sketch.numCoupons << 3;
      if (c8post >= ((27L + w8pre) * k)) {
        modifyOffset(sketch, sketch.windowOffset + 1);
        assert (sketch.windowOffset >= 1) && (sketch.windowOffset <= 56);
        final int w8post = sketch.windowOffset << 3;
        assert c8post < ((27L + w8post) * k); // C < (K * 27/8) + (K * windowOffset)
      }
    }
  }

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


Question:
Contract internal nodes labeled by a number (e.g. branch support) below ``threshold``

        Args:
            ``threshold`` (``float``): The support threshold to use when contracting nodes

def contract_low_support(self, threshold):
        ''''''
        if not isinstance(threshold, float) and not isinstance(threshold, int):
            raise TypeError("threshold must be float or int")
        to_contract = list()
        for node in self.traverse_preorder():
            try:
                if float(str(node)) < threshold:
                    to_contract.append(node)
            except:
                pass
        for node in to_contract:
            node.contract()

def _find_control_structure(self, start_address, search_length):

        words = self._read_memory(start_address, search_length, chunk_size=4, join=False)
        found_offset = None

        for i, word in enumerate(words):
            if word == ControlStructure.CONTROL_MAGIC_1:
                if (len(words) - i) < 4:
                    continue

                if words[i + 1] == ControlStructure.CONTROL_MAGIC_2 and words[i + 2] == ControlStructure.CONTROL_MAGIC_3 and words[i + 3] == ControlStructure.CONTROL_MAGIC_4:
                    found_offset = i
                    break

        if found_offset is None:
            raise HardwareError("Could not find control structure magic value in search area")

        struct_info = words[found_offset + 4]
        _version, _flags, length = struct.unpack("<BBH", struct.pack("<L", struct_info))

        if length % 4 != 0:
            raise HardwareError("Invalid control structure length that was not a multiple of 4", length=length)

        word_length = length // 4
        control_data = struct.pack("<%dL" % word_length, *words[found_offset:found_offset + word_length])

        logger.info("Found control stucture at address 0x%08X, word_length=%d", start_address + 4*found_offset, word_length)

        return ControlStructure(start_address + 4*found_offset, control_data)

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


Question: // SetAttackVectors sets the AttackVectors field's value.

func (s *SubResourceSummary) SetAttackVectors(v []*SummarizedAttackVector) *SubResourceSummary {
	s.AttackVectors = v
	return s
}

public function offsetGet($name)
    {
        if (!isset($this->variables[$name])) {
            $this->variables[$name] = new RuleBuilder\Variable($this, $name);
        }

        return $this->variables[$name];
    }

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


Question:
// GetThriftFilePath returns the value of ThriftFilePath if it is set or its
// zero value if it is unset.

func (v *Module) GetThriftFilePath() (o string) {
	if v != nil {
		o = v.ThriftFilePath
	}
	return
}

def handle_import(self, name, compilation, rule):

        original_path = PurePath(name)

        search_exts = list(compilation.compiler.dynamic_extensions)
        if original_path.suffix and original_path.suffix in search_exts:
            basename = original_path.stem
        else:
            basename = original_path.name

        if original_path.is_absolute():
            # Remove the beginning slash
            search_path = original_path.relative_to('/').parent
        elif rule.source_file.origin:
            search_path = rule.source_file.origin
            if original_path.parent:
                search_path = os.path.normpath(str(search_path / original_path.parent))
        else:
            search_path = original_path.parent

        for prefix, suffix in product(('_', ''), search_exts):
            filename = PurePath(prefix + basename + suffix)

            full_filename, storage = get_file_and_storage(str(search_path / filename))

            if full_filename:
                with storage.open(full_filename) as f:
                    return SourceFile.from_file(f, origin=search_path, relpath=filename)

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


Question: // SetProductId sets the ProductId field's value.

func (s *ModelPackageContainerDefinition) SetProductId(v string) *ModelPackageContainerDefinition {
	s.ProductId = &v
	return s
}

@Override
	public com.liferay.commerce.model.CommerceShipmentItem createCommerceShipmentItem(
		long commerceShipmentItemId) {
		return _commerceShipmentItemLocalService.createCommerceShipmentItem(commerceShipmentItemId);
	}

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


Question:
/*
(non-Javadoc)

@see com.ibm.websphere.concurrent.persistent.mbean.PersistentExecutorMBean#transfer(java.lang.Long, long)

@Override
    public int transfer(Long maxTaskId, long oldPartitionId) throws Exception {

        try {
            return _pe.transfer(maxTaskId, oldPartitionId);
        } catch (Exception e) {
            throw buildAndLogException(e);
        }
    }

private void insertNewLocal(final long _propertyid,
                                final String _value,
                                final String _language)
    {
        try {
            final Insert insert = new Insert(DBPropertiesUpdate.TYPE_PROPERTIES_LOCAL);
            insert.add("Value", _value);
            insert.add("PropertyID", _propertyid);
            insert.add("LanguageID", getLanguageId(_language));
            insert.executeWithoutAccessCheck();
            insert.close();
        } catch (final EFapsException e) {
            DBPropertiesUpdate.LOG.error("insertNewLocal(String)", e);
        }
    }

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


Question: Facade construction function for the SphericalHistogram.

def spherical_histogram(data=None, radial_bins="numpy", theta_bins=16, phi_bins=16, transformed=False, *args, **kwargs):

    dropna = kwargs.pop("dropna", True)
    data = _prepare_data(data, transformed=transformed, klass=SphericalHistogram, dropna=dropna)

    if isinstance(theta_bins, int):
        theta_range = (0, np.pi)
        if "theta_range" in "kwargs":
            theta_range = kwargs["theta_range"]
        elif "range" in "kwargs":
            theta_range = kwargs["range"][1]
        theta_range = list(theta_range) + [theta_bins + 1]
        theta_bins = np.linspace(*theta_range)

    if isinstance(phi_bins, int):
        phi_range = (0, 2 * np.pi)
        if "phi_range" in "kwargs":
            phi_range = kwargs["phi_range"]
        elif "range" in "kwargs":
            phi_range = kwargs["range"][2]
        phi_range = list(phi_range) + [phi_bins + 1]
        phi_bins = np.linspace(*phi_range)

    bin_schemas = binnings.calculate_bins_nd(data, [radial_bins, theta_bins, phi_bins], *args,
                                             check_nan=not dropna, **kwargs)
    weights = kwargs.pop("weights", None)
    frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=3,
                                                                  binnings=bin_schemas,
                                                                  weights=weights)
    return SphericalHistogram(binnings=bin_schemas, frequencies=frequencies, errors2=errors2, missed=missed)

func NewFakeClusterLister(resp *containerservice.ListResult, err error) *FakeClusterLister {
	return &FakeClusterLister{
		Resp: resp,
		Err:  err,
	}
}

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


Question:
Appends WHERE column IN (..) expression

@param string $column
@param array|\Krystal\Db\Sql\RawBindingInterface|\Krystal\Db\Sql\RawSqlFragmentInterface $values
@param boolean $filter Whether to rely on filter
@return \Krystal\Db\Sql\Db

public function whereIn($column, $values, $filter = false)
    {
        return $this->whereInValues(__FUNCTION__, $column, $values, $filter);
    }

function DiscoveryDecorator(AkeraConnector) {

  function getDatabasesMeta(conn, cb) {
    conn.getMetaData(function(err, meta) {
      if (err !== null)
        cb(err);
      else {
        meta.allDatabases().then(function(dbs) {
          cb(null, dbs);
        }, cb);
      }
    });
  }

  function getTableMeta(conn, schema, table, cb) {
    getDatabasesMeta(conn,
        function(err, dbs) {
          if (err !== null)
            cb(err);
          else {
            var callback = function(err) {
              if (err !== null)
                cb(err);

              for ( var t in tables) {
                if (table === tables[t].getName()) {
                  cb(null, tables[t]);
                  return;
                }
              }

              cb(new Error('Table not found in database: ' + schema + '.'
                  + table));
            };

            // select first database as default if not specified
            if (!schema)
              schema = dbs[0].getLname();

            for ( var d in dbs) {
              if (schema === dbs[d].getLname()) {
                var tables = [];
                var info = {
                  idx : d,
                  schema : schema
                };

                fetchSchemaTables(dbs, info, tables, callback);

                return;
              }
            }
            cb(new Error('Database not connected: ' + schema));
          }
        });
  }

  var dataTypeConversion = {
    DATE : 'Date',
    DATETIME : 'Date',
    'DATETIME-TZ' : 'Date',
    LOGICAL : 'Boolean',
    DECIMAL : 'Number',
    INTEGER : 'Number',
    INT64 : 'Number',
    CHARACTER : 'String',
    CLOB : 'String',
    BLOB : 'Buffer'
  };

  function getTableModel(tblMeta, cb) {
    tblMeta.getAllFields().then(function(fields) {
      var result = [];

      for ( var f in fields) {
        var field = fields[f];

        result.push({
          owner : tblMeta.getDatabase(),
          tableName : tblMeta.getName(),
          columnName : field.name,
          dataType : field.type,
          nullable : field.mandatory ? 'N' : 'Y',
          type : dataTypeConversion[field.type.toUpperCase()]
        });
      }

      cb(null, result);
    }, cb);
  }

  function getTablePrimaryKeys(tblMeta, cb) {
    tblMeta.getPk().then(function(pk) {
      var result = [];

      for ( var f in pk.fields) {
        var field = pk.fields[f];

        result.push({
          owner : tblMeta.getDatabase(),
          tableName : tblMeta.getName(),
          columnName : field.name,
          keySeq : field.fld_pos,
          pkName : field.idx_name
        });
      }

      cb(null, result);
    }, cb);
  }

  function getDatabaseSchemas(dbs, options) {
    var offset = 0;
    var limit = dbs.length;
    var result = [];

    if (options !== null && typeof options === 'object') {
      if (typeof options.offset === 'number')
        offset = options.offset;
      if (typeof options.skip === 'number')
        offset += options.skip;
      if (typeof options.limit === 'number')
        limit = options.limit;
    }

    for (var i = offset; i < limit; i++) {
      result.push({
        catalog : dbs[i].getLname(),
        schema : dbs[i].getLname()
      });
    }

    return result;
  }

  function getModelDefinitions(tblsMeta) {
    var result = [];

    for ( var t in tblsMeta) {
      result.push({
        type : 'table',
        name : tblsMeta[t].getName(),
        owner : tblsMeta[t].getDatabase()
      });
    }

    return result;
  }

  function getDatabaseTables(dbMeta, cb) {
    dbMeta.allTables().then(function(tables) {
      cb(null, tables);
    }, cb);
  }

  function fetchSchemaTables(dbs, info, tables, cb) {
    getDatabaseTables(dbs[info.idx], function(err, tbls) {
      if (err !== null)
        cb(err);
      else {
        for ( var t in tbls) {
          tables.push(tbls[t]);
        }
        // reach the end of databases or found the one we're looking for
        if ((info.schema && info.schema === dbs[info.idx].getLname())
            || ++info.idx === dbs.length)
          cb(null, tables);
        else
          fetchSchemaTables(dbs, info, tables, cb);
      }
    });
  }

  AkeraConnector.prototype.discoverDatabaseSchemas = function(options, cb) {
    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    getDatabasesMeta(this, function(err, dbs) {
      if (err !== null)
        cb(err);
      else {
        cb(null, getDatabaseSchemas(dbs, options));
      }
    });
  };

  /**
   * Discover model definitions
   *
   * @param {Object}
   *         options Options for discovery
   * @param {Function}
   *         [cb] The callback function
   */
  AkeraConnector.prototype.discoverModelDefinitions = function(options, cb) {
    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    var schema = null;
    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    getDatabasesMeta(this, function(err, dbs) {
      if (err !== null)
        cb(err);
      else {
        var tables = [];
        var info = {
          idx : 0,
          schema : schema
        };

        fetchSchemaTables(dbs, info, tables, function(err) {
          if (err !== null)
            cb(err);

          cb(null, getModelDefinitions(tables));
        });
      }
    });

  };

  /**
   * Discover model properties from a table
   *
   * @param {String}
   *         table The table name
   * @param {Object}
   *         options The options for discovery (schema/owner)
   * @param {Function}
   *         [cb] The callback function
   *
   */
  AkeraConnector.prototype.discoverModelProperties = function(table, options,
      cb) {
    var schema = null;

    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    if (table === null && typeof table !== 'string') {
      cb(new Error('Table name is mandatory for model properties discovery.'));
      return;
    }

    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    if (!schema) {
      schema = this.getDefaultSchema();
    }

    getTableMeta(this, schema, table, function(err, tblMeta) {
      if (err) {
        cb(err);
      } else {
        getTableModel(tblMeta, cb);
      }
    });
  };

  /**
   * Discover model primary keys from a table
   *
   * @param {String}
   *         table The table name
   * @param {Object}
   *         options The options for discovery (schema/owner)
   * @param {Function}
   *         [cb] The callback function
   *
   */
  AkeraConnector.prototype.discoverPrimaryKeys = function(table, options, cb) {
    var schema = null;

    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    if (table === null && typeof table !== 'string') {
      cb(new Error('Table name is mandatory for model primary keys discovery.'));
      return;
    }

    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    if (!schema) {
      schema = this.getDefaultSchema();
    }

    getTableMeta(this, schema, table, function(err, tblMeta) {
      if (err) {
        cb(err);
      } else {
        getTablePrimaryKeys(tblMeta, cb);
      }
    });
  };

  AkeraConnector.prototype.getDefaultSchema = function() {
    if (this.dataSource && this.dataSource.settings
        && this.dataSource.settings.database) {
      return this.dataSource.settings.database;
    }
    return undefined;
  };
}

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


Question: Purge everything from a service.

def purge_service(self, service_id):
		""""""
		content = self._fetch("/service/%s/purge_all" % service_id, method="POST")
		return self._status(content)

public static void dispose() {
        synchronized (Command.class) {
            if (IS_BIND) {
                Context context = Cmd.getContext();
                if (context != null) {
                    try {
                        context.unbindService(I_CONN);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                I_COMMAND = null;
                IS_BIND = false;
            }
        }
    }

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


Question:
Performs a field p into modal amplitudes pn
                using the basis [pmodes]. The inverse
                transform calculates p from pn

def modal_projection(self,p,forward=True):

        if forward:
            pt = np.linalg.solve(self.pmodes[np.newaxis,np.newaxis],p.T).T
        else:
            pt = np.einsum("ik,k...->i...",self.pmodes,p)

        return pt

def image_question_encoder(encoder_inputs,
                           encoder_self_attention_bias,
                           hparams,
                           query=None,
                           name="image_question_encoder",
                           save_weights_to=None,
                           make_image_summary=True):
  """"""
  x = encoder_inputs
  with tf.variable_scope(name):
    for layer in range(hparams.num_encoder_layers or hparams.num_hidden_layers):
      with tf.variable_scope("layer_%d" % layer):
        with tf.variable_scope("self_attention"):
          y = vqa_layers.multihead_attention(
              common_layers.layer_preprocess(x, hparams),
              None,
              encoder_self_attention_bias,
              hparams.attention_key_channels or hparams.hidden_size,
              hparams.attention_value_channels or hparams.hidden_size,
              hparams.hidden_size,
              hparams.num_heads,
              hparams.attention_dropout,
              attention_type=hparams.self_attention_type,
              block_length=hparams.block_length,
              save_weights_to=save_weights_to,
              make_image_summary=make_image_summary,
              scale_dotproduct=hparams.scale_dotproduct,
          )
          utils.collect_named_outputs(
              "norms", "encoder_self_attention_%d"%(layer),
              tf.norm(y, axis=-1))
          x = common_layers.layer_postprocess(x, y, hparams)
          utils.collect_named_outputs(
              "norms", "encoder_self_attention_postprocess_%d"%(layer),
              tf.norm(x, axis=-1))
        if query is not None:
          with tf.variable_scope("encdec_attention"):
            y = common_attention.multihead_attention(
                common_layers.layer_preprocess(x, hparams),
                query,
                None,
                hparams.attention_key_channels or hparams.hidden_size,
                hparams.attention_value_channels or hparams.hidden_size,
                hparams.hidden_size,
                hparams.num_heads,
                hparams.attention_dropout,
                attention_type=hparams.self_attention_type,
                block_length=hparams.block_length,
                save_weights_to=save_weights_to,
                make_image_summary=make_image_summary,
                scale_dotproduct=hparams.scale_dotproduct,
            )
            utils.collect_named_outputs(
                "norms",
                "encoder_decoder_attention_%d"%(layer),
                tf.norm(y, axis=-1))
            x = common_layers.layer_postprocess(x, y, hparams)
            utils.collect_named_outputs(
                "norms",
                "encoder_decoder_attention_post_%d"%(layer),
                tf.norm(x, axis=-1))
        with tf.variable_scope("ffn"):
          y = common_layers.dense_relu_dense(
              common_layers.layer_preprocess(x, hparams),
              hparams.filter_size,
              hparams.hidden_size,
              dropout=hparams.relu_dropout,
              )
          utils.collect_named_outputs(
              "norms", "encoder_ffn_%d"%(layer), tf.norm(y, axis=-1))
          x = common_layers.layer_postprocess(x, y, hparams)
          utils.collect_named_outputs(
              "norms", "encoder_ffn_postprocess_%d"%(layer),
              tf.norm(x, axis=-1))
    # if normalization is done in layer_preprocess, then it should also be done
    # on the output, since the output can grow very large, being the sum of
    # a whole stack of unnormalized layer outputs.
    return common_layers.layer_preprocess(x, hparams)

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


Question: Version&Schema-specific filling into the impl

@Override public DeepWaterModel createImpl() {
    DeepWaterParameters parms = parameters.createImpl();
    return new DeepWaterModel(Key.<DeepWaterModel>make() /*dest*/, parms, new DeepWaterModelOutput(null), null, null, 0);
  }

protected function _dsn()
    {
        $this->_checkRequiredOptions($this->_config);

        // check if using full connection string
        if (array_key_exists('host', $this->_config)) {
            $dsn = ';DATABASE=' . $this->_config['dbname']
            . ';HOSTNAME=' . $this->_config['host']
            . ';PORT='     . $this->_config['port']
            // PDO_IBM supports only DB2 TCPIP protocol
            . ';PROTOCOL=' . 'TCPIP;';
        } else {
            // catalogued connection
            $dsn = $this->_config['dbname'];
        }
        return $this->_pdoType . ': ' . $dsn;
    }

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


Question:
// Error can be either of the following types:
//
//   - InvalidObjectFault
//   - RuntimeFault

func (service *VboxPortType) IPerformanceMetricgetPeriod(request *IPerformanceMetricgetPeriod) (*IPerformanceMetricgetPeriodResponse, error) {
	response := new(IPerformanceMetricgetPeriodResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

public function get($tag)
    {
        if (!isset($this->styles[$tag])) {
            throw new OutOfBoundsException(sprintf(
                'The style tag "%s" does not exist.',
                $tag
            ));
        }

        return $this->styles[$tag];
    }

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


Question:
Checks whether the given container matches the current edit level.

@param container the container to check

@return true if the given container matches the current edit level

private boolean matchesCurrentEditLevel(I_CmsDropContainer container) {

        boolean result = !(container instanceof CmsContainerPageContainer)
            || (m_currentEditLevel == -1)
            || (m_currentEditLevel == ((CmsContainerPageContainer)container).getContainerLevel());
        return result;
    }

public function updateBlock(Block $block): void
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->update('ngbm_block')
            ->set('layout_id', ':layout_id')
            ->set('depth', ':depth')
            ->set('path', ':path')
            ->set('parent_id', ':parent_id')
            ->set('placeholder', ':placeholder')
            ->set('position', ':position')
            ->set('definition_identifier', ':definition_identifier')
            ->set('view_type', ':view_type')
            ->set('item_view_type', ':item_view_type')
            ->set('name', ':name')
            ->set('translatable', ':translatable')
            ->set('main_locale', ':main_locale')
            ->set('always_available', ':always_available')
            ->set('config', ':config')
            ->where(
                $query->expr()->eq('id', ':id')
            )
            ->setParameter('id', $block->id, Type::INTEGER)
            ->setParameter('layout_id', $block->layoutId, Type::INTEGER)
            ->setParameter('depth', $block->depth, Type::STRING)
            ->setParameter('path', $block->path, Type::STRING)
            ->setParameter('parent_id', $block->parentId, Type::INTEGER)
            ->setParameter('placeholder', $block->placeholder, Type::STRING)
            ->setParameter('position', $block->position, Type::INTEGER)
            ->setParameter('definition_identifier', $block->definitionIdentifier, Type::STRING)
            ->setParameter('view_type', $block->viewType, Type::STRING)
            ->setParameter('item_view_type', $block->itemViewType, Type::STRING)
            ->setParameter('name', $block->name, Type::STRING)
            ->setParameter('translatable', $block->isTranslatable, Type::BOOLEAN)
            ->setParameter('main_locale', $block->mainLocale, Type::STRING)
            ->setParameter('always_available', $block->alwaysAvailable, Type::BOOLEAN)
            ->setParameter('config', $block->config, Type::JSON_ARRAY);

        $this->applyStatusCondition($query, $block->status);

        $query->execute();
    }

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


Question: convert rowResult from Hbase to Tick

def __rowResultToTick(self, row):
        ''' '''
        keyValues = row.columns
        for field in TICK_FIELDS:
            key = "%s:%s" % (HBaseDAM.TICK, field)
            if 'time' != field and keyValues[key].value:
                keyValues[key].value = float(keyValues[key].value)

        return Tick(*[keyValues["%s:%s" % (HBaseDAM.TICK, field)].value for field in TICK_FIELDS])

protected String getRowKeyValueAsString(final Object key) {
        final String result = key.toString();
        return "r_" + StringUtils.deleteWhitespace(result);
    }

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


Question:
Returns the default map of supported commands with their handlers.

@return array

protected function getDefaultCommands()
    {
        $getKeyFromFirstArgument = [$this, 'getKeyFromFirstArgument'];
        $getKeyFromAllArguments = [$this, 'getKeyFromAllArguments'];

        return [
            /* commands operating on the key space */
            'EXISTS' => $getKeyFromAllArguments,
            'DEL' => $getKeyFromAllArguments,
            'TYPE' => $getKeyFromFirstArgument,
            'EXPIRE' => $getKeyFromFirstArgument,
            'EXPIREAT' => $getKeyFromFirstArgument,
            'PERSIST' => $getKeyFromFirstArgument,
            'PEXPIRE' => $getKeyFromFirstArgument,
            'PEXPIREAT' => $getKeyFromFirstArgument,
            'TTL' => $getKeyFromFirstArgument,
            'PTTL' => $getKeyFromFirstArgument,
            'SORT' => [$this, 'getKeyFromSortCommand'],
            'DUMP' => $getKeyFromFirstArgument,
            'RESTORE' => $getKeyFromFirstArgument,

            /* commands operating on string values */
            'APPEND' => $getKeyFromFirstArgument,
            'DECR' => $getKeyFromFirstArgument,
            'DECRBY' => $getKeyFromFirstArgument,
            'GET' => $getKeyFromFirstArgument,
            'GETBIT' => $getKeyFromFirstArgument,
            'MGET' => $getKeyFromAllArguments,
            'SET' => $getKeyFromFirstArgument,
            'GETRANGE' => $getKeyFromFirstArgument,
            'GETSET' => $getKeyFromFirstArgument,
            'INCR' => $getKeyFromFirstArgument,
            'INCRBY' => $getKeyFromFirstArgument,
            'INCRBYFLOAT' => $getKeyFromFirstArgument,
            'SETBIT' => $getKeyFromFirstArgument,
            'SETEX' => $getKeyFromFirstArgument,
            'MSET' => [$this, 'getKeyFromInterleavedArguments'],
            'MSETNX' => [$this, 'getKeyFromInterleavedArguments'],
            'SETNX' => $getKeyFromFirstArgument,
            'SETRANGE' => $getKeyFromFirstArgument,
            'STRLEN' => $getKeyFromFirstArgument,
            'SUBSTR' => $getKeyFromFirstArgument,
            'BITOP' => [$this, 'getKeyFromBitOp'],
            'BITCOUNT' => $getKeyFromFirstArgument,
            'BITFIELD' => $getKeyFromFirstArgument,

            /* commands operating on lists */
            'LINSERT' => $getKeyFromFirstArgument,
            'LINDEX' => $getKeyFromFirstArgument,
            'LLEN' => $getKeyFromFirstArgument,
            'LPOP' => $getKeyFromFirstArgument,
            'RPOP' => $getKeyFromFirstArgument,
            'RPOPLPUSH' => $getKeyFromAllArguments,
            'BLPOP' => [$this, 'getKeyFromBlockingListCommands'],
            'BRPOP' => [$this, 'getKeyFromBlockingListCommands'],
            'BRPOPLPUSH' => [$this, 'getKeyFromBlockingListCommands'],
            'LPUSH' => $getKeyFromFirstArgument,
            'LPUSHX' => $getKeyFromFirstArgument,
            'RPUSH' => $getKeyFromFirstArgument,
            'RPUSHX' => $getKeyFromFirstArgument,
            'LRANGE' => $getKeyFromFirstArgument,
            'LREM' => $getKeyFromFirstArgument,
            'LSET' => $getKeyFromFirstArgument,
            'LTRIM' => $getKeyFromFirstArgument,

            /* commands operating on sets */
            'SADD' => $getKeyFromFirstArgument,
            'SCARD' => $getKeyFromFirstArgument,
            'SDIFF' => $getKeyFromAllArguments,
            'SDIFFSTORE' => $getKeyFromAllArguments,
            'SINTER' => $getKeyFromAllArguments,
            'SINTERSTORE' => $getKeyFromAllArguments,
            'SUNION' => $getKeyFromAllArguments,
            'SUNIONSTORE' => $getKeyFromAllArguments,
            'SISMEMBER' => $getKeyFromFirstArgument,
            'SMEMBERS' => $getKeyFromFirstArgument,
            'SSCAN' => $getKeyFromFirstArgument,
            'SPOP' => $getKeyFromFirstArgument,
            'SRANDMEMBER' => $getKeyFromFirstArgument,
            'SREM' => $getKeyFromFirstArgument,

            /* commands operating on sorted sets */
            'ZADD' => $getKeyFromFirstArgument,
            'ZCARD' => $getKeyFromFirstArgument,
            'ZCOUNT' => $getKeyFromFirstArgument,
            'ZINCRBY' => $getKeyFromFirstArgument,
            'ZINTERSTORE' => [$this, 'getKeyFromZsetAggregationCommands'],
            'ZRANGE' => $getKeyFromFirstArgument,
            'ZRANGEBYSCORE' => $getKeyFromFirstArgument,
            'ZRANK' => $getKeyFromFirstArgument,
            'ZREM' => $getKeyFromFirstArgument,
            'ZREMRANGEBYRANK' => $getKeyFromFirstArgument,
            'ZREMRANGEBYSCORE' => $getKeyFromFirstArgument,
            'ZREVRANGE' => $getKeyFromFirstArgument,
            'ZREVRANGEBYSCORE' => $getKeyFromFirstArgument,
            'ZREVRANK' => $getKeyFromFirstArgument,
            'ZSCORE' => $getKeyFromFirstArgument,
            'ZUNIONSTORE' => [$this, 'getKeyFromZsetAggregationCommands'],
            'ZSCAN' => $getKeyFromFirstArgument,
            'ZLEXCOUNT' => $getKeyFromFirstArgument,
            'ZRANGEBYLEX' => $getKeyFromFirstArgument,
            'ZREMRANGEBYLEX' => $getKeyFromFirstArgument,
            'ZREVRANGEBYLEX' => $getKeyFromFirstArgument,

            /* commands operating on hashes */
            'HDEL' => $getKeyFromFirstArgument,
            'HEXISTS' => $getKeyFromFirstArgument,
            'HGET' => $getKeyFromFirstArgument,
            'HGETALL' => $getKeyFromFirstArgument,
            'HMGET' => $getKeyFromFirstArgument,
            'HMSET' => $getKeyFromFirstArgument,
            'HINCRBY' => $getKeyFromFirstArgument,
            'HINCRBYFLOAT' => $getKeyFromFirstArgument,
            'HKEYS' => $getKeyFromFirstArgument,
            'HLEN' => $getKeyFromFirstArgument,
            'HSET' => $getKeyFromFirstArgument,
            'HSETNX' => $getKeyFromFirstArgument,
            'HVALS' => $getKeyFromFirstArgument,
            'HSCAN' => $getKeyFromFirstArgument,
            'HSTRLEN' => $getKeyFromFirstArgument,

            /* commands operating on HyperLogLog */
            'PFADD' => $getKeyFromFirstArgument,
            'PFCOUNT' => $getKeyFromAllArguments,
            'PFMERGE' => $getKeyFromAllArguments,

            /* scripting */
            'EVAL' => [$this, 'getKeyFromScriptingCommands'],
            'EVALSHA' => [$this, 'getKeyFromScriptingCommands'],

            /* commands performing geospatial operations */
            'GEOADD' => $getKeyFromFirstArgument,
            'GEOHASH' => $getKeyFromFirstArgument,
            'GEOPOS' => $getKeyFromFirstArgument,
            'GEODIST' => $getKeyFromFirstArgument,
            'GEORADIUS' => [$this, 'getKeyFromGeoradiusCommands'],
            'GEORADIUSBYMEMBER' => [$this, 'getKeyFromGeoradiusCommands'],
        ];
    }

protected function parse($file)
    {
        $search = '%%CURRENT_DIRECTORY%%';

        $yaml = file_get_contents($file);

        $yaml = str_replace($search, $this->root, $yaml);

        $result = Yaml::parse($yaml);

        $this->commands = $result['paths']['commands'];

        $this->namespace = $result['namespaces']['commands'];

        $this->templates = $result['paths']['templates'];
    }

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


Question:
Gets account by id - can include relations.

@param int $id
@param string $locale
@param array $includes

@throws EntityNotFoundException

@return AccountApi

public function getByIdAndInclude($id, $locale, $includes)
    {
        $account = $this->accountRepository->findAccountById($id, in_array('contacts', $includes));

        if (!$account) {
            throw new EntityNotFoundException($this->accountRepository->getClassName(), $id);
        }

        return $this->getApiObject($account, $locale);
    }

public Observable<ServiceResponse<LuisApp>> exportWithServiceResponseAsync(UUID appId, String versionId) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        if (appId == null) {
            throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
        }
        if (versionId == null) {
            throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.export(appId, versionId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LuisApp>>>() {
                @Override
                public Observable<ServiceResponse<LuisApp>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<LuisApp> clientResponse = exportDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question: // Set bit at offset o

func (b *BitSet) Set(o int) {
	bucketID := o / 8
	oInBucket := uint8(o % 8)
	if o >= b.size {
		return
	}
	b.set[bucketID] = (b.set[bucketID] | 0x1<<oInBucket)
}

public function getBytes()
    {
        if ($this->bytes === null) {
            $bytes = array();
            foreach ($this->getWords() as $word) {
                $bytes[] = $word >> 8;
                $bytes[] = $word & 0xff;
            }
            $this->bytes = $bytes;
        }

        return $this->bytes;
    }

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


Question:
Keep session alive

This will send an ascynchronous request to the server via AJAX on an interval in secs

@param   array   $config An optional array with configuration options
@return string    The html output

public function keepalive($config = array())
    {
        $config = new ObjectConfigJson($config);
        $config->append(array(
            'refresh' => 15 * 60, //default refresh is 15min
            'url'     => '',      //default to window.location.url
        ));

        $html = '';

        // Only load once
        if (!static::isLoaded('keepalive'))
        {
            $session = $this->getObject('user')->getSession();
            if($session->isActive())
            {
                //Get the config session lifetime
                $lifetime = $session->getLifetime();

                //Refresh time is 1 minute less than the lifetime
                $refresh =  ($lifetime <= 60) ? 30 : $lifetime - 60;
            }
            else $refresh = (int) $config->refresh;

            // Longest refresh period is one hour to prevent integer overflow.
            if ($refresh > 3600 || $refresh <= 0) {
                $refresh = 3600;
            }

            if(empty($config->url)) {
                $url = 'window.location.url';
            } else {
                $url = "'.$config->url.'";
            }

            // Build the keep alive script.
            $html  = $this->jquery();
            $html .=
                "<script>
                (function($){
                    var refresh = '" . $refresh . "';
                    setInterval(function() {
                        $.ajax({
                            url: $url,
                            method: 'HEAD',
                            cache: false
                        })
                    }, refresh * 1000);
                })(kQuery);</script>";

            static::setLoaded('keepalive');
        }
        return $html;
    }

public function run($data, $world)
    {
        $result = [];
        if (is_callable($this->define)) {
            $callback = $this->define;
            $result = $callback($data, $world);
        } elseif (is_array($this->define)) {
            $result = $this->define;
        }
        return $result;
    }

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


Question: Useful for merging other files in a custom logic.

def merge_asset(self, other):

        for asset in other.asset:
            asset_name = asset.get("name")
            asset_type = asset.tag
            # Avoids duplication
            pattern = "./{}[@name='{}']".format(asset_type, asset_name)
            if self.asset.find(pattern) is None:
                self.asset.append(asset)

func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl {
	return newFileWithCustomPathMakerAndCompletion(baseDir, pathMaker, pieceCompletionForDir(baseDir))
}

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


Question: Calls the evaluations in order, returning immediately if one returns ServiceMilestone.Recommendation.COMPLETE.

@Override
    public <M extends Enum<M>> ServiceMilestone.Recommendation evaluate(Class<M> type, String name, DataBinder binder, Reifier dict, Persistence persist) {
        if (first.evaluate(type, name, binder, dict, persist) == ServiceMilestone.Recommendation.CONTINUE) {
            return second.evaluate(type, name, binder, dict, persist);
        } else {
            return ServiceMilestone.Recommendation.COMPLETE;
        }
    }

func NewWorker(
	upgradeComplete gate.Lock,
	agent agent.Agent,
	apiConn api.Connection,
	jobs []multiwatcher.MachineJob,
	openState func() (*state.StatePool, error),
	preUpgradeSteps func(st *state.StatePool, agentConf agent.Config, isController, isMasterServer, isCaas bool) error,
	machine StatusSetter,
	isCaas bool,
) (worker.Worker, error) {
	w := &upgradesteps{
		upgradeComplete: upgradeComplete,
		agent:           agent,
		apiConn:         apiConn,
		jobs:            jobs,
		openState:       openState,
		preUpgradeSteps: preUpgradeSteps,
		machine:         machine,
		tag:             agent.CurrentConfig().Tag(),
		isCaas:          isCaas,
	}
	w.tomb.Go(w.run)
	return w, nil
}

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


Question: A decorator to commit to the storage if autocommit is set to True.

def autocommit(f):
    ""
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        result = f(self, *args, **kwargs)
        if self._meta.commit_ready():
            self.commit()
        return result
    return wrapper

def append(self, event, category=None):

        date = datetime.datetime.now()
        self.store.insert(0, (date, event, category))
        if len(self.store) > self.size:
            del self.store[-1]

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


Question:
Check if the given attribute is present an is not empty.
@param attributeName the attribute name
@return true if null or empty

public boolean isNullOrEmpty(String attributeName) {
        String attr = attributes.get(attributeName);
        if (attr == null || attr.isEmpty()) {
            return true;
        }
        return false;
    }

public function getValidAttribs()
    {
        return array_combine(
            array_keys($this->validAttribs),
            array_map(function ($ref) {
                return $ref['attrib'];
            }, array_values($this->validAttribs))
        );
    }

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


Question: Read headers from a Python 2 httplib message object.

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

def subject(self) -> Optional[UnstructuredHeader]:
        """"""
        try:
            return cast(UnstructuredHeader, self[b'subject'][0])
        except (KeyError, IndexError):
            return None

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