Question:
Returns true if the qualified permission exists.
@param permissionName the permission name
@param orgQualifier the org qualifier
@return true if has qualified permission

public boolean hasQualifiedPermission(PermissionType permissionName, String orgQualifier) {
        String key = createQualifiedPermissionKey(permissionName, orgQualifier);
        return qualifiedPermissions.contains(key);
    }

protected function _addRules($type, array $rules, $resource, $resourceName) {
        if (!$type) {
            $type = Zend_Acl::TYPE_ALLOW;
        }
        foreach ($rules as $privilege => $ruleProperties) {
            // If the user sets the privilege value to a string, we will consider
            // this as the list of roles.
            if (!is_array($ruleProperties)) {
                $ruleProperties = array('roles' => $ruleProperties);
            }

            if ($privilege === 'all') {
                $privilege = null;
            }

            $roles = $ruleProperties['roles'];

            if (is_null($roles) || empty($roles)) {
                $section = 'rules';
                if ($type === Zend_Acl::TYPE_ALLOW) {
                    $section = 'allow ' . $section;
                } else {
                    $section = 'deny ' . $section;
                }

                throw new Zend_Application_Resource_Exception(
                    sprintf(
                        $this->_missingPropertyMessage,
                        'roles',
                        $section,
                        'resource ' . $resourceName
                    )
                );
            }

            $roles = explode(',', $roles);

            if ($roles[0] === 'all') {
                $roles = null;
            }

            $assert = null;

            if (isset($ruleProperties['assert']) && !empty($ruleProperties['assert'])) {
                $assert = $ruleProperties['assert'];
                $assert = new $assert();
            }

            $this->_acl->setRule(
                Zend_Acl::OP_ADD,
                $type,
                $roles,
                $resource,
                $privilege,
                $assert
            );
        }
    }

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


Question: // Open open a pid file and return this process.

func Open(pidfile string) (*os.Process, error) {
	pid, err := readPidFile(pidfile)
	if err != nil {
		return nil, fmt.Errorf("open pid file %s falied, %s", pidfile, err)
	}
	return os.FindProcess(pid)
}

func Stop() {
	flag.Parse()

	var status string
	if KillPID(*DaemonPIDFile) {
		status = "Status: Stopped."
	} else {
		status = fmt.Sprintf("Failed to stop. Status: %s", StatusPID(*DaemonPIDFile))
	}

	LogDaemon(status)
}

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


Question:
Adds current user to locals
@param {Object} req
@param {Object} res
@param {Function} next

function addUser(req, res, next) {
  res.locals.user = req.user;
  next();
}

function initModelCreate (args) {
    var controller = this
    var model = this.model
    // get accountId column
    var accountIdColumn = model.columnName('accountId')
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // get relations to create from args if any
    var relations = args.create && args.create.relations
    // validate relations
    _.each(relations, (createArgs, relation) => {
        // this will throw error on invalid relation
        model.relation(relation)
    })
    // index inputs
    var input = {
        // whether or not create data includes meta columns
        meta: 'query.meta',
        // url to redirect to on success
        redirect: ['body.redirect', 'query.redirect'],
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // controller spec
    var node = {
        input: input,
        method: function (args) {
            return create(controller, args, node, relations)
        },
        methodName: 'create',
        role: role,
        template: 'instance',
    }
    // add handler for POST / to create instance
    this.paths['/'].post = [node]
}

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


Question: // listHostCloudRegions lists all the cloud regions that this cluster has worker nodes/instances running in.

func (k *kubernetesClient) listHostCloudRegions() (string, set.Strings, error) {
	// we only check 5 worker nodes as of now just run in the one region and
	// we are just looking for a running worker to sniff its region.
	nodes, err := k.client().CoreV1().Nodes().List(v1.ListOptions{Limit: 5})
	if err != nil {
		return "", nil, errors.Annotate(err, "listing nodes")
	}
	result := set.NewStrings()
	var cloudResult string
	for _, n := range nodes.Items {
		var nodeCloud, region string
		if nodeCloud, region = getCloudRegionFromNodeMeta(n); nodeCloud == "" {
			continue
		}
		cloudResult = nodeCloud
		result.Add(region)
	}
	return cloudResult, result, nil
}

func dataSourceComputeFlavorV2Attributes(
	d *schema.ResourceData, computeClient *gophercloud.ServiceClient, flavor *flavors.Flavor) error {

	log.Printf("[DEBUG] Retrieved openstack_compute_flavor_v2 %s: %#v", flavor.ID, flavor)

	d.SetId(flavor.ID)
	d.Set("name", flavor.Name)
	d.Set("flavor_id", flavor.ID)
	d.Set("disk", flavor.Disk)
	d.Set("ram", flavor.RAM)
	d.Set("rx_tx_factor", flavor.RxTxFactor)
	d.Set("swap", flavor.Swap)
	d.Set("vcpus", flavor.VCPUs)
	d.Set("is_public", flavor.IsPublic)

	es, err := flavors.ListExtraSpecs(computeClient, d.Id()).Extract()
	if err != nil {
		return err
	}

	if err := d.Set("extra_specs", es); err != nil {
		log.Printf("[WARN] Unable to set extra_specs for openstack_compute_flavor_v2 %s: %s", d.Id(), err)
	}

	return nil
}

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


Question:
Sorts an array of BasicObject.

@param BasicObject[] $contents Object properties to sort
@param int           $sort

@return BasicObject[]

public static function sortProperties(array $contents, $sort)
    {
        switch ($sort) {
            case self::SORT_VISIBILITY:
                /** @var array<array-key, BasicObject[]> Containers to quickly stable sort by type */
                $containers = array(
                    BasicObject::ACCESS_PUBLIC => array(),
                    BasicObject::ACCESS_PROTECTED => array(),
                    BasicObject::ACCESS_PRIVATE => array(),
                    BasicObject::ACCESS_NONE => array(),
                );

                foreach ($contents as $item) {
                    $containers[$item->access][] = $item;
                }

                return \call_user_func_array('array_merge', $containers);
            case self::SORT_FULL:
                \usort($contents, array('Kint\\Renderer\\Renderer', 'sortPropertiesFull'));
                // no break
            default:
                return $contents;
        }
    }

function validateProp(key, value) {
  const type = typeof value;

  switch (key) {
  case 'orderByKey':
  case 'orderByPriority':
  case 'orderByValue':
    if (!value) {
      throw new Error(`"query.${key}" should not be set to false. Set it off by setting an other order.`);
    }
    break;

  case 'orderByChild':
    if (value == null) {
      throw new Error('"query.orderByChild" should not be set to null. Set it off by setting an other order.');
    }
    if (type !== 'string') {
      throw new Error('"query.orderByChild" should be a string or null.');
    }
    break;

  case 'startAt':
  case 'endAt':
  case 'equalTo':
    if (
      value !== null &&
      type !== 'string' &&
      type !== 'number' &&
      type !== 'boolean'
    ) {
      throw new Error(`query.${key} should be a string, a number, a boolean or null.`);
    }
    break;

  case 'limitToFirst':
  case 'limitToLast':
    if (value != null && type !== 'number') {
      throw new Error(`query.${key} should be a number or null.`);
    }
    break;

  default:
    throw new Error(`"${key}" is not a query parameter.`);
  }
}

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


Question: Clone all objects within the given array structure.

private function cloneStructure(array & $struct): void
    {
        foreach ($struct as & $v) {
            if (is_object($v)) {
                $v = clone $v;
            } elseif (is_array($v)) {
                $this->cloneStructure($v);
            }
        }
    }

def name(self):
        '''

        '''
        clonify_ids = [p.heavy['clonify']['id'] for p in self.heavies if 'clonify' in p.heavy]
        if len(clonify_ids) > 0:
            return clonify_ids[0]
        return None

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


Question:
Get files from the answer area file.

@param bool $includedirs whether or not include directories
@param int $updatedsince return files updated since this time
@return array list of stored_file objects
@since  Moodle 3.2

public function get_files($includedirs = true, $updatedsince = 0) {

        $lesson = lesson::load($this->properties->lessonid);
        $fs = get_file_storage();
        $answerfiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_answers', $this->properties->id,
                                            'itemid, filepath, filename', $includedirs, $updatedsince);
        $responsefiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_responses', $this->properties->id,
                                            'itemid, filepath, filename', $includedirs, $updatedsince);
        return array_merge($answerfiles, $responsefiles);
    }

public function can_create() {
        return in_array($this->mode, array(tool_uploadcourse_processor::MODE_CREATE_ALL,
            tool_uploadcourse_processor::MODE_CREATE_NEW,
            tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE)
        );
    }

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


Question:
@param string $name     The event name.
@param string $category The event category.

@return StopwatchEvent

public function start( $name, $category = null ): StopwatchEvent {
		return $this->stopwatch->start( $name, $category );
	}

def html(self):

        failure = ""
        skipped = None
        stdout = tag.text(self.stdout)
        stderr = tag.text(self.stderr)

        if self.skipped:
            skipped = """

Skipped: {msg}

{skip}

            """.format(msg=tag.text(self.skipped_msg),
                       skip=tag.text(self.skipped))

        if self.failed():
            failure = """

Failed: {msg}

{fail}

            """.format(msg=tag.text(self.failure_msg),
                       fail=tag.text(self.failure))

        properties = [x.html() for x in self.properties]

        return """

                {testname}

                {testclassname}

                Time Taken: {duration}s

            {skipped}
            {failure}

            {properties}

Stdout

{stdout}

Stderr

{stderr}

        """.format(anchor=self.anchor(),
                   testname=self.name,
                   testclassname=self.testclass.name,
                   duration=self.duration,
                   failure=failure,
                   skipped=skipped,
                   properties="".join(properties),
                   stdout=stdout,
                   stderr=stderr)

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


Question:
Args:
            graph (DFA): The DFA states
            access_strings_map (list): a dict containing all the access strings for each state
        Return:
            list: SMI transition table

def _init_smi(self, graph, access_strings_map):

        smi = []
        for selected_state in sorted(graph.states, key=attrgetter('initial'), reverse=True):
            # Initially gather all transitions of the state into a dictionary
            transitions_map = defaultdict(list)
            for character in self.alphabet:
                destination_state = self._delta(graph, selected_state, character)
                transitions_map[destination_state.stateid].append(character)

            chars_in_smi = []
            sorted_transitions = sorted(
                transitions_map.items(),
                key=lambda x: len(
                    x[1]))

            if len(sorted_transitions) == 1:
                # Just put 1 symbol is enough all other'input_string will be generalized
                # by the guardgen algorithm
                chars_in_smi.append(self.alphabet[0])
            else:
                # Otherwise insert in smi_vector all transitions as explicit except
                # the one from the sink transition where we add just enough
                # explicity transitions to make sure that this state will be
                # selected as the sink state.
                #
                # If no transition has a clear advantage in terms of symbols then
                # just add all transitions in explicit form because it may be the
                # case the guardgen() will generalize in the wrong transition.
                for (_, char_list) in sorted_transitions[:-1]:
                    chars_in_smi += char_list

                sink_chars = len(sorted_transitions[-2][1]) + 1
                chars_in_smi.extend(sorted_transitions[-1][1][:sink_chars])

            access_string = access_strings_map[selected_state.stateid]
            smi.extend([access_string + character for character in chars_in_smi])
        return smi

def get_tables_and_gsis():

    table_names = set()
    configured_tables = get_configured_tables()
    not_used_tables = set(configured_tables)

    # Add regexp table names
    for table_instance in list_tables():
        for key_name in configured_tables:
            try:
                if re.match(key_name, table_instance.table_name):
                    logger.debug("Table {0} match with config key {1}".format(
                        table_instance.table_name, key_name))

                    # Notify users about regexps that match multiple tables
                    if table_instance.table_name in [x[0] for x in table_names]:
                        logger.warning(
                            'Table {0} matches more than one regexp in config, '
                            'skipping this match: "{1}"'.format(
                                table_instance.table_name, key_name))
                    else:
                        table_names.add(
                            (
                                table_instance.table_name,
                                key_name
                            ))
                        not_used_tables.discard(key_name)
                else:
                    logger.debug(
                        "Table {0} did not match with config key {1}".format(
                            table_instance.table_name, key_name))
            except re.error:
                logger.error('Invalid regular expression: "{0}"'.format(
                    key_name))
                sys.exit(1)

    if not_used_tables:
        logger.warning(
            'No tables matching the following configured '
            'tables found: {0}'.format(', '.join(not_used_tables)))

    return sorted(table_names)

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


Question:
// String returns a formatted string including the remoteAddress for the Node and its current
// connection count

func (n *Node) String() string {
	return fmt.Sprintf("%v|%d|%d", n.addr, n.cm.count(), n.cm.q.count())
}

public function asEndpoint()
    {
        $graphVersionPrefix = '';
        if ($this->graphVersion) {
            $graphVersionPrefix = '/'.$this->graphVersion;
        }

        return $graphVersionPrefix.$this->graphNode->asUrl($this->appSecret);
    }

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


Question: // DefaultProfile defines the whitelist for the default seccomp profile.

func DefaultProfile() *types.Seccomp {
	syscalls := []*types.Syscall{
		{
			Names: []string{
				"accept",
				"accept4",
				"access",
				"adjtimex",
				"alarm",
				"bind",
				"brk",
				"capget",
				"capset",
				"chdir",
				"chmod",
				"chown",
				"chown32",
				"clock_getres",
				"clock_gettime",
				"clock_nanosleep",
				"close",
				"connect",
				"copy_file_range",
				"creat",
				"dup",
				"dup2",
				"dup3",
				"epoll_create",
				"epoll_create1",
				"epoll_ctl",
				"epoll_ctl_old",
				"epoll_pwait",
				"epoll_wait",
				"epoll_wait_old",
				"eventfd",
				"eventfd2",
				"execve",
				"execveat",
				"exit",
				"exit_group",
				"faccessat",
				"fadvise64",
				"fadvise64_64",
				"fallocate",
				"fanotify_mark",
				"fchdir",
				"fchmod",
				"fchmodat",
				"fchown",
				"fchown32",
				"fchownat",
				"fcntl",
				"fcntl64",
				"fdatasync",
				"fgetxattr",
				"flistxattr",
				"flock",
				"fork",
				"fremovexattr",
				"fsetxattr",
				"fstat",
				"fstat64",
				"fstatat64",
				"fstatfs",
				"fstatfs64",
				"fsync",
				"ftruncate",
				"ftruncate64",
				"futex",
				"futimesat",
				"getcpu",
				"getcwd",
				"getdents",
				"getdents64",
				"getegid",
				"getegid32",
				"geteuid",
				"geteuid32",
				"getgid",
				"getgid32",
				"getgroups",
				"getgroups32",
				"getitimer",
				"getpeername",
				"getpgid",
				"getpgrp",
				"getpid",
				"getppid",
				"getpriority",
				"getrandom",
				"getresgid",
				"getresgid32",
				"getresuid",
				"getresuid32",
				"getrlimit",
				"get_robust_list",
				"getrusage",
				"getsid",
				"getsockname",
				"getsockopt",
				"get_thread_area",
				"gettid",
				"gettimeofday",
				"getuid",
				"getuid32",
				"getxattr",
				"inotify_add_watch",
				"inotify_init",
				"inotify_init1",
				"inotify_rm_watch",
				"io_cancel",
				"ioctl",
				"io_destroy",
				"io_getevents",
				"io_pgetevents",
				"ioprio_get",
				"ioprio_set",
				"io_setup",
				"io_submit",
				"ipc",
				"kill",
				"lchown",
				"lchown32",
				"lgetxattr",
				"link",
				"linkat",
				"listen",
				"listxattr",
				"llistxattr",
				"_llseek",
				"lremovexattr",
				"lseek",
				"lsetxattr",
				"lstat",
				"lstat64",
				"madvise",
				"memfd_create",
				"mincore",
				"mkdir",
				"mkdirat",
				"mknod",
				"mknodat",
				"mlock",
				"mlock2",
				"mlockall",
				"mmap",
				"mmap2",
				"mprotect",
				"mq_getsetattr",
				"mq_notify",
				"mq_open",
				"mq_timedreceive",
				"mq_timedsend",
				"mq_unlink",
				"mremap",
				"msgctl",
				"msgget",
				"msgrcv",
				"msgsnd",
				"msync",
				"munlock",
				"munlockall",
				"munmap",
				"nanosleep",
				"newfstatat",
				"_newselect",
				"open",
				"openat",
				"pause",
				"pipe",
				"pipe2",
				"poll",
				"ppoll",
				"prctl",
				"pread64",
				"preadv",
				"preadv2",
				"prlimit64",
				"pselect6",
				"pwrite64",
				"pwritev",
				"pwritev2",
				"read",
				"readahead",
				"readlink",
				"readlinkat",
				"readv",
				"recv",
				"recvfrom",
				"recvmmsg",
				"recvmsg",
				"remap_file_pages",
				"removexattr",
				"rename",
				"renameat",
				"renameat2",
				"restart_syscall",
				"rmdir",
				"rt_sigaction",
				"rt_sigpending",
				"rt_sigprocmask",
				"rt_sigqueueinfo",
				"rt_sigreturn",
				"rt_sigsuspend",
				"rt_sigtimedwait",
				"rt_tgsigqueueinfo",
				"sched_getaffinity",
				"sched_getattr",
				"sched_getparam",
				"sched_get_priority_max",
				"sched_get_priority_min",
				"sched_getscheduler",
				"sched_rr_get_interval",
				"sched_setaffinity",
				"sched_setattr",
				"sched_setparam",
				"sched_setscheduler",
				"sched_yield",
				"seccomp",
				"select",
				"semctl",
				"semget",
				"semop",
				"semtimedop",
				"send",
				"sendfile",
				"sendfile64",
				"sendmmsg",
				"sendmsg",
				"sendto",
				"setfsgid",
				"setfsgid32",
				"setfsuid",
				"setfsuid32",
				"setgid",
				"setgid32",
				"setgroups",
				"setgroups32",
				"setitimer",
				"setpgid",
				"setpriority",
				"setregid",
				"setregid32",
				"setresgid",
				"setresgid32",
				"setresuid",
				"setresuid32",
				"setreuid",
				"setreuid32",
				"setrlimit",
				"set_robust_list",
				"setsid",
				"setsockopt",
				"set_thread_area",
				"set_tid_address",
				"setuid",
				"setuid32",
				"setxattr",
				"shmat",
				"shmctl",
				"shmdt",
				"shmget",
				"shutdown",
				"sigaltstack",
				"signalfd",
				"signalfd4",
				"sigreturn",
				"socket",
				"socketcall",
				"socketpair",
				"splice",
				"stat",
				"stat64",
				"statfs",
				"statfs64",
				"statx",
				"symlink",
				"symlinkat",
				"sync",
				"sync_file_range",
				"syncfs",
				"sysinfo",
				"tee",
				"tgkill",
				"time",
				"timer_create",
				"timer_delete",
				"timerfd_create",
				"timerfd_gettime",
				"timerfd_settime",
				"timer_getoverrun",
				"timer_gettime",
				"timer_settime",
				"times",
				"tkill",
				"truncate",
				"truncate64",
				"ugetrlimit",
				"umask",
				"uname",
				"unlink",
				"unlinkat",
				"utime",
				"utimensat",
				"utimes",
				"vfork",
				"vmsplice",
				"wait4",
				"waitid",
				"waitpid",
				"write",
				"writev",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
		},
		{
			Names:  []string{"ptrace"},
			Action: types.ActAllow,
			Includes: types.Filter{
				MinKernel: "4.8",
			},
		},
		{
			Names:  []string{"personality"},
			Action: types.ActAllow,
			Args: []*types.Arg{
				{
					Index: 0,
					Value: 0x0,
					Op:    types.OpEqualTo,
				},
			},
		},
		{
			Names:  []string{"personality"},
			Action: types.ActAllow,
			Args: []*types.Arg{
				{
					Index: 0,
					Value: 0x0008,
					Op:    types.OpEqualTo,
				},
			},
		},
		{
			Names:  []string{"personality"},
			Action: types.ActAllow,
			Args: []*types.Arg{
				{
					Index: 0,
					Value: 0x20000,
					Op:    types.OpEqualTo,
				},
			},
		},
		{
			Names:  []string{"personality"},
			Action: types.ActAllow,
			Args: []*types.Arg{
				{
					Index: 0,
					Value: 0x20008,
					Op:    types.OpEqualTo,
				},
			},
		},
		{
			Names:  []string{"personality"},
			Action: types.ActAllow,
			Args: []*types.Arg{
				{
					Index: 0,
					Value: 0xffffffff,
					Op:    types.OpEqualTo,
				},
			},
		},
		{
			Names: []string{
				"sync_file_range2",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Arches: []string{"ppc64le"},
			},
		},
		{
			Names: []string{
				"arm_fadvise64_64",
				"arm_sync_file_range",
				"sync_file_range2",
				"breakpoint",
				"cacheflush",
				"set_tls",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Arches: []string{"arm", "arm64"},
			},
		},
		{
			Names: []string{
				"arch_prctl",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Arches: []string{"amd64", "x32"},
			},
		},
		{
			Names: []string{
				"modify_ldt",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Arches: []string{"amd64", "x32", "x86"},
			},
		},
		{
			Names: []string{
				"s390_pci_mmio_read",
				"s390_pci_mmio_write",
				"s390_runtime_instr",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Arches: []string{"s390", "s390x"},
			},
		},
		{
			Names: []string{
				"open_by_handle_at",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_DAC_READ_SEARCH"},
			},
		},
		{
			Names: []string{
				"bpf",
				"clone",
				"fanotify_init",
				"lookup_dcookie",
				"mount",
				"name_to_handle_at",
				"perf_event_open",
				"quotactl",
				"setdomainname",
				"sethostname",
				"setns",
				"syslog",
				"umount",
				"umount2",
				"unshare",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_ADMIN"},
			},
		},
		{
			Names: []string{
				"clone",
			},
			Action: types.ActAllow,
			Args: []*types.Arg{
				{
					Index:    0,
					Value:    unix.CLONE_NEWNS | unix.CLONE_NEWUTS | unix.CLONE_NEWIPC | unix.CLONE_NEWUSER | unix.CLONE_NEWPID | unix.CLONE_NEWNET,
					ValueTwo: 0,
					Op:       types.OpMaskedEqual,
				},
			},
			Excludes: types.Filter{
				Caps:   []string{"CAP_SYS_ADMIN"},
				Arches: []string{"s390", "s390x"},
			},
		},
		{
			Names: []string{
				"clone",
			},
			Action: types.ActAllow,
			Args: []*types.Arg{
				{
					Index:    1,
					Value:    unix.CLONE_NEWNS | unix.CLONE_NEWUTS | unix.CLONE_NEWIPC | unix.CLONE_NEWUSER | unix.CLONE_NEWPID | unix.CLONE_NEWNET,
					ValueTwo: 0,
					Op:       types.OpMaskedEqual,
				},
			},
			Comment: "s390 parameter ordering for clone is different",
			Includes: types.Filter{
				Arches: []string{"s390", "s390x"},
			},
			Excludes: types.Filter{
				Caps: []string{"CAP_SYS_ADMIN"},
			},
		},
		{
			Names: []string{
				"reboot",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_BOOT"},
			},
		},
		{
			Names: []string{
				"chroot",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_CHROOT"},
			},
		},
		{
			Names: []string{
				"delete_module",
				"init_module",
				"finit_module",
				"query_module",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_MODULE"},
			},
		},
		{
			Names: []string{
				"acct",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_PACCT"},
			},
		},
		{
			Names: []string{
				"kcmp",
				"process_vm_readv",
				"process_vm_writev",
				"ptrace",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_PTRACE"},
			},
		},
		{
			Names: []string{
				"iopl",
				"ioperm",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_RAWIO"},
			},
		},
		{
			Names: []string{
				"settimeofday",
				"stime",
				"clock_settime",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_TIME"},
			},
		},
		{
			Names: []string{
				"vhangup",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_TTY_CONFIG"},
			},
		},
		{
			Names: []string{
				"get_mempolicy",
				"mbind",
				"set_mempolicy",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYS_NICE"},
			},
		},
		{
			Names: []string{
				"syslog",
			},
			Action: types.ActAllow,
			Args:   []*types.Arg{},
			Includes: types.Filter{
				Caps: []string{"CAP_SYSLOG"},
			},
		},
	}

	return &types.Seccomp{
		DefaultAction: types.ActErrno,
		ArchMap:       arches(),
		Syscalls:      syscalls,
	}
}

func (t *Template) GetAWSCognitoUserPoolGroupWithName(name string) (*resources.AWSCognitoUserPoolGroup, error) {
	if untyped, ok := t.Resources[name]; ok {
		switch resource := untyped.(type) {
		case *resources.AWSCognitoUserPoolGroup:
			return resource, nil
		}
	}
	return nil, fmt.Errorf("resource %q of type AWSCognitoUserPoolGroup not found", name)
}

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


Question:
Sort collection of objects by order or class name.

@param $objects

@return array

protected function sortCollection($objects)
    {
        $class = false;

        if ($objects instanceof Arrayable) {
            $class = get_class($objects);

            $objects = $objects->toArray();
        }

        usort($objects, function ($aObj, $bObj) {
            list($aRank, $bRank) = $this->getRanks($aObj, $bObj);

            if ($this->equals($aRank, $bRank)) {
                return $this->sortByName($aObj, $bObj);
            }

            return $this->sortByValue($aRank, $bRank);
        });

        return $class ? $class::make($objects) : $objects;
    }

public function changeSort(int $id, ?int $prevId, ?int $nextId)
	{
		$this->mapper->changeSort('position', $id, $prevId, $nextId);
	}

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


Question:
Wrapper around Requests for PUT requests

        Returns:
            Response:
                A Requests Response object

def _put(self, *args, **kwargs):

        if 'timeout' not in kwargs:
            kwargs['timeout'] = self.timeout

        req = self.session.put(*args, **kwargs)
        return req

public function build(): SetRequestInterceptionRequest
	{
		$instance = new SetRequestInterceptionRequest();
		if ($this->patterns === null) {
			throw new BuilderException('Property [patterns] is required.');
		}
		$instance->patterns = $this->patterns;
		return $instance;
	}

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


Question:
Parse a string representation of a reaction equation.

    Converts undefined compartments to the default compartment.

def parse_reaction_equation_string(equation, default_compartment):

    def _translate_compartments(reaction, compartment):
        """Translate compound with missing compartments.

        These compounds will have the specified compartment in the output.
        """
        left = (((c.in_compartment(compartment), v)
                 if c.compartment is None else (c, v))
                for c, v in reaction.left)
        right = (((c.in_compartment(compartment), v)
                  if c.compartment is None else (c, v))
                 for c, v in reaction.right)
        return Reaction(reaction.direction, left, right)

    eq = _REACTION_PARSER.parse(equation).normalized()
    return _translate_compartments(eq, default_compartment)

def check_arg_compatibility(args: argparse.Namespace):

    if args.lhuc is not None:
        # Actually this check is a bit too strict
        check_condition(args.encoder != C.CONVOLUTION_TYPE or args.decoder != C.CONVOLUTION_TYPE,
                        "LHUC is not supported for convolutional models yet.")
        check_condition(args.decoder != C.TRANSFORMER_TYPE or C.LHUC_STATE_INIT not in args.lhuc,
                        "The %s options only applies to RNN models" % C.LHUC_STATE_INIT)

    if args.decoder_only:
        check_condition(args.decoder != C.TRANSFORMER_TYPE and args.decoder != C.CONVOLUTION_TYPE,
                        "Decoder pre-training currently supports RNN decoders only.")

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


Question: // SetDetectedText sets the DetectedText field's value.

func (s *TextDetection) SetDetectedText(v string) *TextDetection {
	s.DetectedText = &v
	return s
}

def _init_metadata(self):
        """"""

        # pylint: disable=attribute-defined-outside-init
        # this method is called from descendent __init__
        self._mdata.update(default_mdata.get_osid_form_mdata())
        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)
        for element_name in self._mdata:
            self._mdata[element_name].update(
                {'element_id': Id(self._authority,
                                  self._namespace,
                                  element_name)})
        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]
        self._validation_messages = {}

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


Question: Get the blocks that need to be migrated

def getBlocks(self):

        try:
            conn = self.dbi.connection()
            result = self.buflistblks.execute(conn)
            return result
        finally:
            if conn:
                conn.close()

func (ps *PeerState) SetHasProposalBlockPart(height int64, round int, index int) {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()

	if ps.PRS.Height != height || ps.PRS.Round != round {
		return
	}

	ps.PRS.ProposalBlockParts.SetIndex(index, true)
}

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


Question:
Returns a list of image data for images which match img_name. Will
    optionally take a list of images from a docker.Client.images
    query to avoid multiple docker queries.

def image_by_name(img_name, images=None):

    i_reg, i_rep, i_tag = _decompose(img_name)

    # Correct for bash-style matching expressions.
    if not i_reg:
        i_reg = '*'
    if not i_tag:
        i_tag = '*'

    # If the images were not passed in, go get them.
    if images is None:
        c = docker.Client(**kwargs_from_env())
        images = c.images(all=False)

    valid_images = []
    for i in images:
        for t in i['RepoTags']:
            reg, rep, tag = _decompose(t)
            if matches(reg, i_reg) \
                    and matches(rep, i_rep) \
                    and matches(tag, i_tag):
                valid_images.append(i)
                break
            # Some repo after decompose end up with the img_name
            # at the end.  i.e. rhel7/rsyslog
            if rep.endswith(img_name):
                valid_images.append(i)
                break
    return valid_images

func FromServices(services []*v1.Service) []v1.EnvVar {
	var result []v1.EnvVar
	for i := range services {
		service := services[i]

		// ignore services where ClusterIP is "None" or empty
		// the services passed to this method should be pre-filtered
		// only services that have the cluster IP set should be included here
		if !v1helper.IsServiceIPSet(service) {
			continue
		}

		// Host
		name := makeEnvVariableName(service.Name) + "_SERVICE_HOST"
		result = append(result, v1.EnvVar{Name: name, Value: service.Spec.ClusterIP})
		// First port - give it the backwards-compatible name
		name = makeEnvVariableName(service.Name) + "_SERVICE_PORT"
		result = append(result, v1.EnvVar{Name: name, Value: strconv.Itoa(int(service.Spec.Ports[0].Port))})
		// All named ports (only the first may be unnamed, checked in validation)
		for i := range service.Spec.Ports {
			sp := &service.Spec.Ports[i]
			if sp.Name != "" {
				pn := name + "_" + makeEnvVariableName(sp.Name)
				result = append(result, v1.EnvVar{Name: pn, Value: strconv.Itoa(int(sp.Port))})
			}
		}
		// Docker-compatible vars.
		result = append(result, makeLinkVariables(service)...)
	}
	return result
}

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


Question:
Add new users to the list.

        :param new_user: name of a GitHub user to include in
            the ranking
        :type new_user: str.

def __addUser(self, new_user):

        self.__lockReadAddUser.acquire()
        if new_user not in self.__cityUsers and \
                new_user not in self.__excludedUsers:
            self.__lockReadAddUser.release()
            self.__logger.debug("__addUser: Adding " + new_user)
            self.__cityUsers.add(new_user)

            myNewUser = GitHubUser(new_user)
            myNewUser.getData()
            myNewUser.getRealContributions()

            userLoc = myNewUser.location
            if not any(s in userLoc for s in self.__excludedLocations):
                self.__processedUsers.append(myNewUser)
        else:
            self.__logger.debug("__addUser: Excluding " + new_user)
            self.__lockReadAddUser.release()

func (cmd *Command) Suggestions(path string) []string {
	if cmd.parent != nil {
		return cmd.Root().Suggestions(path)
	}

	var (
		cmds    = []*Command{cmd}
		targets = []string{}
	)
	for len(cmds) > 0 {
		if cmds[0].nochild() {
			cmds = cmds[1:]
		} else {
			for _, child := range cmds[0].children {
				targets = append(targets, child.Path())
			}
			cmds = append(cmds[0].children, cmds[1:]...)
		}
	}

	dists := []editDistanceRank{}
	for i, size := 0, len(targets); i < size; i++ {
		if d, ok := match(path, targets[i]); ok {
			dists = append(dists, editDistanceRank{s: targets[i], d: d})
		}
	}
	sort.Sort(editDistanceRankSlice(dists))
	for i := 0; i < len(dists); i++ {
		targets[i] = dists[i].s
	}
	return targets[:len(dists)]
}

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


Question:
Setup provisions to watch a specified signal

        :param signal:
            The :class:`Signal` to watch for.

        After calling this method you can use :meth:`assertSignalFired()`
        and :meth:`assertSignalNotFired()` with the same signal.

def watchSignal(self, signal):

        self._extend_state()

        def signal_handler(*args, **kwargs):
            self._events_seen.append((signal, args, kwargs))
        signal.connect(signal_handler)
        if hasattr(self, 'addCleanup'):
            self.addCleanup(signal.disconnect, signal_handler)

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question: // StringSlice returns an []string from the map if it exists otherwise returns nil

func (fsm *MapInputSource) StringSlice(name string) ([]string, error) {
	otherGenericValue, exists := fsm.valueMap[name]
	if !exists {
		otherGenericValue, exists = nestedVal(name, fsm.valueMap)
		if !exists {
			return nil, nil
		}
	}

	otherValue, isType := otherGenericValue.([]interface{})
	if !isType {
		return nil, incorrectTypeForFlagError(name, "[]interface{}", otherGenericValue)
	}

	var stringSlice = make([]string, 0, len(otherValue))
	for i, v := range otherValue {
		stringValue, isType := v.(string)

		if !isType {
			return nil, incorrectTypeForFlagError(fmt.Sprintf("%s[%d]", name, i), "string", v)
		}

		stringSlice = append(stringSlice, stringValue)
	}

	return stringSlice, nil
}

function extractMessage(error) {
	var {message} = error
	if (error.plugin === 'babel') {
		// Hey Babel, you're not helping!
		var filepath = error.id
		var message = error.message
		function stripFilePath() {
			var index = message.indexOf(filepath)
			console.log(index, filepath.length)
			message = message.slice(0, index) + message.slice(filepath.length + 1)
			message = message.trim()
		}
		if (message.includes(filepath)) {
			stripFilePath()
		} else {
			filepath = filepath.replace(/\\/g, '/')
			if (message.includes(filepath))
				stripFilePath()
		}
	}
	return message
}

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


Question:
Get/Set Orientation.

@param null|string $orientation orientation to set
@return mixed

public function orientation($orientation = null)
    {
        if ($orientation === null) {
            return $this->_orientation;
        }
        $this->_orientation = $orientation;

        return $this;
    }

private function setDefinitionProperties(Definition $definition, array $array)
    {
        if (isset($array['public'])) {
            $definition->setPublic($array['public']);
        }

        if (isset($array['abstract'])) {
            $definition->setAbstract($array['abstract']);
        }

        if (isset($array['scope'])) {
            $definition->setScope($array['scope']);
        }

        if (isset($array['file'])) {
            $definition->setFile($array['file']);
        }
    }

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


Question:
validateTemplatePath
Validate the template directories.

@return void
@throws \InvalidArgumentException

protected function validateTemplatePath()
    {
        array_walk($this->templatePath, function($val, $key) {
            if (!is_dir($val)) {
                throw new \InvalidArgumentException(sprintf('Invalid template path: %s', $val));
            }
        });
    }

def regular_folder() -> Callable:

    def check_regular_directory(value_to_check):
        value_to_check = str(value_to_check)
        if not os.path.isdir(value_to_check):
            raise argparse.ArgumentTypeError("must be a directory.")
        return value_to_check

    return check_regular_directory

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


Question:
Restore soft-deleted data

@param  mixed $terms

@return int|false

public static function restore($terms = null)
    {
        $self = self::newSelf();

        if ($self->softDeletes) {
            return $self->patch([self::DELETED => '0000-00-00 00:00:00'], $terms);
        }

        return false;
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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


Question:
Delete a domain

    CLI Example:

    .. code-block:: bash

        salt '*' keystoneng.domain_delete name=domain1
        salt '*' keystoneng.domain_delete name=b62e76fbeeff4e8fb77073f591cf211e

def domain_delete(auth=None, **kwargs):
    '''

    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.delete_domain(**kwargs)

public static base_response kill(nitro_service client, aaasession resource) throws Exception {
		aaasession killresource = new aaasession();
		killresource.username = resource.username;
		killresource.groupname = resource.groupname;
		killresource.iip = resource.iip;
		killresource.netmask = resource.netmask;
		killresource.all = resource.all;
		return killresource.perform_operation(client,"kill");
	}

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


Question:
// Allocate attempts to reserve the provided netid. ErrNotInRange or
// ErrAllocated will be returned if the netid is not valid for this range
// or has already been reserved.

func (r *Allocator) Allocate(id uint32) error {
	ok, offset := r.netIDRange.Contains(id)
	if !ok {
		return ErrNotInRange
	}

	allocated, err := r.alloc.Allocate(int(offset))
	if err != nil {
		return err
	}
	if !allocated {
		return ErrAllocated
	}
	return nil
}

func (info DefaultNodeInfo) CompatibleWith(other_ NodeInfo) error {
	other, ok := other_.(DefaultNodeInfo)
	if !ok {
		return fmt.Errorf("wrong NodeInfo type. Expected DefaultNodeInfo, got %v", reflect.TypeOf(other_))
	}

	if info.ProtocolVersion.Block != other.ProtocolVersion.Block {
		return fmt.Errorf("Peer is on a different Block version. Got %v, expected %v",
			other.ProtocolVersion.Block, info.ProtocolVersion.Block)
	}

	// nodes must be on the same network
	if info.Network != other.Network {
		return fmt.Errorf("Peer is on a different network. Got %v, expected %v", other.Network, info.Network)
	}

	// if we have no channels, we're just testing
	if len(info.Channels) == 0 {
		return nil
	}

	// for each of our channels, check if they have it
	found := false
OUTER_LOOP:
	for _, ch1 := range info.Channels {
		for _, ch2 := range other.Channels {
			if ch1 == ch2 {
				found = true
				break OUTER_LOOP // only need one
			}
		}
	}
	if !found {
		return fmt.Errorf("Peer has no common channels. Our channels: %v ; Peer channels: %v", info.Channels, other.Channels)
	}
	return nil
}

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


Question:
Track cell width for column width sizing if its enabled.

@param mixed $value
@param int   $cellIndex
@param Font  $font

private function updateColumnWidths($value, $cellIndex, Font $font)
    {
        if ($this->useCellAutosizing) {
            $cellWidth = $this->sizeCalculator->getCellWidth($font->getName(), $font->getSize(), $value);
            if (!isset($this->columnWidths[$cellIndex])
                || $this->columnWidths[$cellIndex] < $cellWidth
            ) {
                $this->columnWidths[$cellIndex] = $cellWidth;
            }
        }
    }

protected String getCellValue(final HtmlRenderingContext context, final int row, final int col,
            final Object value) {
        final String stringValue = LabelUtils.getValueLabel(value);
        return context.escapeHtml(stringValue);
    }

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


Question:
Enables the use of contraction hierarchies to reduce query times. Enabled by default.

@param weightingList A list containing multiple weightings like: "fastest", "shortest" or
your own weight-calculation type.

public LMAlgoFactoryDecorator setWeightingsAsStrings(List<String> weightingList) {
        if (weightingList.isEmpty())
            throw new IllegalArgumentException("It is not allowed to pass an emtpy weightingList");

        weightingsAsStrings.clear();
        for (String strWeighting : weightingList) {
            strWeighting = toLowerCase(strWeighting);
            strWeighting = strWeighting.trim();
            addWeighting(strWeighting);
        }
        return this;
    }

protected function rankFieldWeightLabel(Model $model, $field)
    {
        $label = $this->option($model, "rank.fields.$field");

        return collect(['A', 'B', 'C', 'D'])
            ->contains($label) ? $label : '';
    }

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


Question:
Concatenates multiple byte sources, skipping sources for which
opening an input stream fails.
@param first the first byte source
@param others other byte sources
@return the concatenated source

public static ByteSource concatOpenable(ByteSource first, ByteSource...others) {
        return concatOpenable(Lists.asList(first, others));
    }

private MethodCode getWriteToMethodCode() {
        MethodCode mc = new MethodCode();
        mc.setName("writeTo");
        mc.setReturnType("void");
        mc.setScope(ClassCode.SCOPE_PUBLIC);
        mc.addParameter(ClassHelper.getInternalName(cls.getCanonicalName()), "t");
        mc.addParameter("CodedOutputStream", "output");
        mc.addException("IOException");

        Set<Integer> orders = new HashSet<Integer>();
        for (FieldInfo field : fields) {

            boolean isList = field.isList();

            // check type
            if (!isList) {
                checkType(field.getFieldType(), field.getField());
            }

            if (orders.contains(field.getOrder())) {
                throw new IllegalArgumentException("Field order '" + field.getOrder() + "' on field"
                        + field.getField().getName() + " already exsit.");
            }
            // define field
            mc.appendLineCode0(CodedConstant.getMappedTypeDefined(field.getOrder(), field.getFieldType(),
                    getAccessByField("t", field.getField(), cls), isList));
            if (field.isRequired()) {
                mc.appendLineCode0(CodedConstant.getRequiredCheck(field.getOrder(), field.getField()));
            }
        }

        for (FieldInfo field : fields) {
            boolean isList = field.isList();
            // set write to byte
            mc.appendLineCode0(
                    CodedConstant.getMappedWriteCode(field, "output", field.getOrder(), field.getFieldType(), isList));
        }

        mc.appendLineCode1("output.flush()");

        return mc;
    }

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


Question: //Deprecated since 2.14. Use PackStart() instead.

func (v *Box) PackStartDefaults(child IWidget) {
	deprecated_since(2, 14, 0, "gtk_box_pack_start_defaults()")
	C.gtk_box_pack_start_defaults(BOX(v), ToNative(child))
}

def SetPackageView(self, directoryView):
        """"""
        self.directoryView = not self.directoryView
        self.packageMenuItem.Check(self.directoryView)
        self.packageViewTool.SetValue(self.directoryView)
        if self.loader:
            self.SetModel(self.loader)
        self.RecordHistory()

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


Question: // Must panics if err is non-nil or if win is nil. Otherwise, win is returned.

func Must(win *Window, err error) *Window {
	if err != nil {
		panic(err)
	}
	if win == nil {
		panic("win and err are nil")
	}
	return win
}

def cli(ctx, all, top, nostyle, nowarn, warn, project_dir):
    """"""

    exit_code = SCons(project_dir).lint({
        'all': all,
        'top': top,
        'nostyle': nostyle,
        'nowarn': nowarn,
        'warn': warn
    })
    ctx.exit(exit_code)

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


Question:
Updating All Data Source Caches With New Data Sets Or Errors
@param params
- currentTime
@param dsWithDocuments
@param dsWithNoDocuments
@param cb

function updateDataSourceCaches(params, dsWithDocuments, dsWithNoDocuments, cb) {
  //Updating All Of The Data Sources
  //Generating Hashes For The Incoming Data Set. Useful for determining if the stored data set has changed.
  dsWithDocuments = _.map(dsWithDocuments, function(dataSourceData) {
    dataSourceData.dataHash = dataSourceData.error ? null : misc.generateHash(dataSourceData.data);
    return dataSourceData;
  });

  async.map(dsWithDocuments, function(dataSourceWithDocument, cb) {
    return updateDataSourceEntry(params, dataSourceWithDocument, cb);
  }, function(err, updatedDocuments) {

    logger.debug("ARGUMENTS", arguments);
    //Documents are now either updated or failed
    var validInvalidDataSources = updateValidAndInvalidDataSources(updatedDocuments, dsWithNoDocuments);

    return cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid);
  });
}

func (s *SimulationJob) SetLastUpdatedAt(v time.Time) *SimulationJob {
	s.LastUpdatedAt = &v
	return s
}

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


Question:
Parse an RGB or RGBA CSS color string
@name parseRGB
@memberOf me.Color
@function
@param {String} color
@return {me.Color} Reference to this object for method chaining

function (rgbColor) {
            // TODO : Memoize this function by caching its input

            var match = rgbaRx.exec(rgbColor);
            if (match) {
                return this.setColor(+match[1], +match[2], +match[3], +match[5]);
            }

            return this.parseHex(rgbColor);
        }

public function render($type = 'html')
    {
        $row = $this->getTable()->getRow()->getActualRow();

        $value = '';

        if (is_array($row) || $row instanceof \ArrayAccess) {
            $value = (isset($row[$this->getHeader()->getName()])) ? $row[$this->getHeader()->getName()] : '';
        } elseif (is_object($row)) {
            $headerName = $this->getHeader()->getName();
            $methodName = 'get' . ucfirst($headerName);
            if (method_exists($row, $methodName)) {
                $value = $row->$methodName();
            } else {
                $value = (property_exists($row, $headerName)) ? $row->$headerName : '';
            }
        }

        foreach ($this->decorators as $decorator) {
            if ($decorator->validConditions()) {
                $value = $decorator->render($value);
            }
        }

        if ($type == 'html') {
            $ret = sprintf("<td %s>%s</td>", $this->getAttributes(), $value);
            $this->clearVar();
            return $ret;

        } else {
            return $value;
        }
    }

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


Question:
/*
Transform the given class definition into a class name and
a ReflectionClass instance.

private function getClassInfo($defClass) {
		if (is_object($defClass)) {
			if ($defClass instanceof ReflectionClass) {
				$className = $defClass->getName();
				$refClass = $defClass;
			} else {
				$className = get_class($defClass);
				$refClass = new ReflectionClass($className);
			}
		} else {
			$className = $defClass;
			$refClass = new ReflectionClass($className);
		}

		return [ $className, $refClass ];
	}

public function create($data)
    {
        $methodDescriptor = new MethodDescriptor();
        $methodDescriptor->setNamespace(
            substr(
                (string) $data->getFqsen(),
                0,
                -strlen($data->getName()) - 4
            )
        );
        $this->mapReflectorToDescriptor($data, $methodDescriptor);

        $this->assembleDocBlock($data->getDocBlock(), $methodDescriptor);
        $this->addArguments($data, $methodDescriptor);
        $this->addVariadicArgument($data, $methodDescriptor);

        return $methodDescriptor;
    }

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


Question: Create a jwt user session

function create_session($data){

		$key = Env::getConfig("jwt")->get('key');
		$expiration = Env::getConfig("jwt")->get('token_expiration');
		$cookie_key=   Env::getConfig("jwt")->get('cookie_key');
		$token = array(
				"iss" => $_SERVER['HTTP_HOST'],
				"iat" => time(),
				"nbf" => time(),
				"exp" => time()+($expiration),
				"data" =>  $data
		);

		$jwt = JWT::encode($token, $key);

		$this->setToken($jwt);
		$_SESSION[$cookie_key]=$jwt;
		setcookie($cookie_key,$jwt,time()+$expiration,'/');
		//var_dump($cookie_key);
		Env::getRequest()->setToken($jwt);
		$this->setDefaultDatas($data);
	}

func (ws *WebSessionV2) V1() *WebSessionV1 {
	return &WebSessionV1{
		ID:          ws.Metadata.Name,
		Priv:        ws.Spec.Priv,
		Pub:         ws.Spec.Pub,
		BearerToken: ws.Spec.BearerToken,
		Expires:     ws.Spec.Expires,
	}
}

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


Question:
Delete the sms user given

REST: DELETE /sms/{serviceName}/users/{login}
@param serviceName [required] The internal name of your SMS offer
@param login [required] The sms user login

public void serviceName_users_login_DELETE(String serviceName, String login) throws IOException {
		String qPath = "/sms/{serviceName}/users/{login}";
		StringBuilder sb = path(qPath, serviceName, login);
		exec(qPath, "DELETE", sb.toString(), null);
	}

public int handleMessage(BaseMessage message)
    {
        String strClassName = this.getMessageProcessorClassName(message);
        if ((strClassName == null) || (strClassName.length() == 0))
            return this.handleOtherMessage(message);
        message.consume();      // I'll be handling this one.
        String strParams = Utility.addURLParam(null, DBParams.PROCESS, strClassName);
        App application = m_application;
        if (message.getProcessedByClientSession() instanceof RemoteTask)
            if (message.getProcessedByClientSession() instanceof Task)  // Always
                application = ((Task)message.getProcessedByClientSession()).getApplication();    // If I have the task session, run this task under the same app
        MessageProcessRunnerTask task = new MessageProcessRunnerTask(application, strParams, null);
        task.setMessage(message);
        m_application.getTaskScheduler().addTask(task);
        return DBConstants.NORMAL_RETURN;   // No need to call super.
    }

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


Question:
Get the Error as a {@link Map}.

@return the error as a map

public Map<String, Object> asMap() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("statusCode", statusCode);
        map.put("statusMessage", statusMessage);
        map.put("requestMethod", requestMethod);
        map.put("requestUri", requestUri);

        if (!StringUtils.isNullOrEmpty(message)) {
            map.put("message", message);
        }
        if (!StringUtils.isNullOrEmpty(stacktrace)) {
            map.put("stacktrace", stacktrace);
        }

        return map;
    }

def onerror(self, emitter, message, source, lineno, colno):

        self._log.debug("""App.onerror event occurred in webpage:
            \nMESSAGE:%s\nSOURCE:%s\nLINENO:%s\nCOLNO:%s\n"""%(message, source, lineno, colno))

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


Question:
Send a single message over a UDP socket.

@param {Socket} client - Socket to send data with
@param {object} data - Details of the data to send
@param {Function} batchCallback - Function to call when done

function sendMessage (client, data, batchCallback) {
  var msg = data.msg;
  var offset = data.offset;
  var length = data.length;
  var port = data.port;
  var address = data.address;
  var callback = data.callback;

  client.send(msg, offset, length, port, address, function(err) {
    try {
      callback(err);
    } finally {
      batchCallback();
    }
  });
}

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

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


Question:
Call all of the after callbacks with check result.

@param  \Nova\Auth\UserInterface  $user
@param  string  $ability
@param  array  $arguments
@param  bool  $result
@return void

protected function callAfterCallbacks(User $user, $ability, array $arguments, $result)
    {
        $arguments = array_merge(array($user, $ability, $result), $arguments);

        foreach ($this->afterCallbacks as $callback) {
            call_user_func_array($callback, $arguments);
        }
    }

private function authenticate()
    {
        $form = new RemoteIdentityForm;
        $form->attributes = array(
            'adapter'  => $this->getUserProfile(),
            'provider' => $this->getProvider()
        );

        return $form->login();
    }

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


Question: Displays the link error message.

private void showLinkError() {
        Toast.makeText(mContext, mContext.getString(R.string.wings_dropbox__error_link), Toast.LENGTH_SHORT).show();
    }

protected function itemTypeError(string $method, $item): string
    {
        $itemType = is_object($item) ? get_class($item) : gettype($item);

        return sprintf(
            '%s::%s expects item type (%s); received (%s) %s',
            static::class,
            $method,
            $this->itemType(),
            $itemType,
            VarPrinter::toString($item)
        );
    }

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


Question: Marshall the given parameter object.

public void marshall(DetachTypedLinkRequest detachTypedLinkRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(detachTypedLinkRequest.getDirectoryArn(), DIRECTORYARN_BINDING);
            protocolMarshaller.marshall(detachTypedLinkRequest.getTypedLinkSpecifier(), TYPEDLINKSPECIFIER_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Use this API to fetch all the policyexpression resources that are configured on netscaler.
This uses policyexpression_args which is a way to provide additional arguments while fetching the resources.

public static policyexpression[] get(nitro_service service, policyexpression_args args) throws Exception{
		policyexpression obj = new policyexpression();
		options option = new options();
		option.set_args(nitro_util.object_to_string_withoutquotes(args));
		policyexpression[] response = (policyexpression[])obj.get_resources(service, option);
		return response;
	}

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

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

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

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

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

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

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


Question:
Find a domain item.
@param $id
@return Domain

public function get($id): Domain
    {
        if (!$model = Domain::findOne($id)) {
            throw new NotFoundException($this->i18n->t('setrun/sys/domain', 'Domain is not found'));
        }
        return $model;
    }

func (kl *Kubelet) GeneratePodHostNameAndDomain(pod *v1.Pod) (string, string, error) {
	clusterDomain := kl.dnsConfigurer.ClusterDomain

	hostname := pod.Name
	if len(pod.Spec.Hostname) > 0 {
		if msgs := utilvalidation.IsDNS1123Label(pod.Spec.Hostname); len(msgs) != 0 {
			return "", "", fmt.Errorf("Pod Hostname %q is not a valid DNS label: %s", pod.Spec.Hostname, strings.Join(msgs, ";"))
		}
		hostname = pod.Spec.Hostname
	}

	hostname, err := truncatePodHostnameIfNeeded(pod.Name, hostname)
	if err != nil {
		return "", "", err
	}

	hostDomain := ""
	if len(pod.Spec.Subdomain) > 0 {
		if msgs := utilvalidation.IsDNS1123Label(pod.Spec.Subdomain); len(msgs) != 0 {
			return "", "", fmt.Errorf("Pod Subdomain %q is not a valid DNS label: %s", pod.Spec.Subdomain, strings.Join(msgs, ";"))
		}
		hostDomain = fmt.Sprintf("%s.%s.svc.%s", pod.Spec.Subdomain, pod.Namespace, clusterDomain)
	}

	return hostname, hostDomain, nil
}

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


Question:
This method is called from within the constructor to initialize the form.
WARNING: Do NOT modify this code. The content of this method is always
regenerated by the Form Editor.

@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        colorChooser = new javax.swing.JColorChooser();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(colorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(colorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton))
                .addContainerGap())
        );

        pack();
    }

func UpdateLoginSource(source *LoginSource) error {
	if source.LocalFile == nil {
		if _, err := x.Id(source.ID).AllCols().Update(source); err != nil {
			return err
		} else {
			return ResetNonDefaultLoginSources(source)
		}

	}

	source.LocalFile.SetGeneral("name", source.Name)
	source.LocalFile.SetGeneral("is_activated", com.ToStr(source.IsActived))
	source.LocalFile.SetGeneral("is_default", com.ToStr(source.IsDefault))
	if err := source.LocalFile.SetConfig(source.Cfg); err != nil {
		return fmt.Errorf("LocalFile.SetConfig: %v", err)
	} else if err = source.LocalFile.Save(); err != nil {
		return fmt.Errorf("LocalFile.Save: %v", err)
	}
	return ResetNonDefaultLoginSources(source)
}

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


Question: Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.

public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) {
        assert length >= 0;
        if (length == 0) {
            return dst;
        }

        final int end = offset + length;
        final int endMinusOne = end - 1;
        int i;

        // Skip preceding zeroes.
        for (i = offset; i < endMinusOne; i++) {
            if (src[i] != 0) {
                break;
            }
        }

        byteToHexString(dst, src[i++]);
        int remaining = end - i;
        toHexStringPadded(dst, src, i, remaining);

        return dst;
    }

public void writeInt(int pInt) throws IOException {
        file.write(pInt & 0xFF);
        file.write((pInt >>> 8) & 0xFF);
        file.write((pInt >>> 16) & 0xFF);
        file.write((pInt >>> 24) & 0xFF);
    }

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


Question: // DetectHostAddr is used to detect the host address by asking the Consul agent

func (c *ConsulBackend) DetectHostAddr() (string, error) {
	agent := c.client.Agent()
	self, err := agent.Self()
	if err != nil {
		return "", err
	}
	addr, ok := self["Member"]["Addr"].(string)
	if !ok {
		return "", fmt.Errorf("unable to convert an address to string")
	}
	return addr, nil
}

def get_dns_servers(interface='Local Area Connection'):
    '''

    '''
    # remove any escape characters
    interface = interface.split('\\')
    interface = ''.join(interface)

    with salt.utils.winapi.Com():
        c = wmi.WMI()
        for iface in c.Win32_NetworkAdapter(NetEnabled=True):
            if interface == iface.NetConnectionID:
                iface_config = c.Win32_NetworkAdapterConfiguration(Index=iface.Index).pop()
                try:
                    return list(iface_config.DNSServerSearchOrder)
                except TypeError:
                    return []
    log.debug('Interface "%s" not found', interface)
    return False

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


Question:
Execute

@param InputInterface $input
@param OutputInterface $output

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $dryRun = $input->getOption('dry-run');
        $force = $input->getOption('force');
        $dumper = new Dumper();
        $file = sprintf('%s/../Resources/config/mime.yml', __DIR__);

        $result = array();

        if (false !== $content = file_get_contents(self::MIME_FILE)) {
            foreach (explode("\n", $content) as $line) {
                if (false == preg_match('/^#/', $line) && strlen(trim($line)) > 0) {
                    $data = preg_split('/\s+/', $line);
                    for ($i = 1; $i <= count($data) - 1; $i++) {
                        $result[$data[$i]] = $data[0];
                    }
                }
            }
        } else {
            throw new \RuntimeException(sprintf('could not open file: %s', self::MIME_FILE));
        }

        $ymlDump = $dumper->dump($result, 2);

        if ((false === file_exists($file) || $force) && !$dryRun) {
            if (false === file_put_contents($file, $ymlDump)) {
                throw new \RuntimeException(sprintf('could not write to file: %s', $file));
            } else {

                $output->writeln(sprintf('Successful writing file: <info>%s</info>', realpath($file)));
            }
        } elseif (file_exists($file) && !$dryRun) {
            $output->writeln('Mime file exists, use force options to overwrite');
        } elseif ($dryRun) {
            echo $ymlDump;
        }
    }

public static void main( String [] args )
    {
        if ( args.length > 0 ) {
            String filename = args[0];

            String [] bshArgs;
            if ( args.length > 1 ) {
                bshArgs = new String [ args.length -1 ];
                System.arraycopy( args, 1, bshArgs, 0, args.length-1 );
            } else
                bshArgs = new String [0];

            try {
                Interpreter interpreter = new Interpreter();
                interpreter.setu( "bsh.args", bshArgs );
                Object result =
                    interpreter.source( filename, interpreter.globalNameSpace );
                if ( result instanceof Class )
                    try {
                        invokeMain( (Class<?>)result, bshArgs );
                    } catch ( Exception e )
                    {
                        Object o = e;
                        if ( e instanceof InvocationTargetException )
                            o = e.getCause();
                        System.err.println(
                            "Class: "+result+" main method threw exception:"+o);
                    }
            } catch ( FileNotFoundException e ) {
                System.err.println("File not found: "+e);
            } catch ( TargetError e ) {
                System.err.println("Script threw exception: "+e);
                if ( e.inNativeCode() )
                    e.printStackTrace( DEBUG.get(), System.err );
            } catch ( EvalError e ) {
                System.err.println("Evaluation Error: "+e);
            } catch ( IOException e ) {
                System.err.println("I/O Error: "+e);
            }
        } else {
            @SuppressWarnings("resource")
            Interpreter interpreter =
            new Interpreter(new CommandLineReader(
                new FileReader(System.in)),
                System.out, System.err, true );
            interpreter.run();
        }
    }

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


Question:
This method validates that the url is valid

It allows the protocol to be ommitted, eg //www.edmondscommerce.co.uk

You can extend the list of allowed protocols as you see fit

protected static function validatorMetaForPropertyUrl(ValidatorClassMetaData $metadata): void
    {
        $metadata->addPropertyConstraint(
            UrlFieldInterface::PROP_URL,
            new Url([
                        'relativeProtocol' => true,
                        'protocols'        => ['http', 'https'],
                    ])
        );
    }

private function isMatching(RequestInterface $request, &$route): int
    {
        $match = -1;

        $pattern = str_replace('/', '\/', trim($route['pattern'], '/'));
        $pattern = str_replace(array_keys(self::$expressions), array_values(self::$expressions), $pattern);

        if (preg_match('/^' . $pattern . '$/', ltrim($request->getUri()->getPath(), '/'), $matches)) {
            $match = $this->rate($route['target'], $matches);
        }

        return $match;
    }

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


Question:
Save element ID list in cache
@param array $arElementIDList

protected function saveIDList($arElementIDList)
    {
        $arCacheTags = $this->getCacheTagList();
        $sCacheKey = $this->getCacheKey();

        //Set cache data
        CCache::forever($arCacheTags, $sCacheKey, $arElementIDList);
    }

func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]*resources.AWSElastiCacheParameterGroup {
	results := map[string]*resources.AWSElastiCacheParameterGroup{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSElastiCacheParameterGroup:
			results[name] = resource
		}
	}
	return results
}

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


Question:
<p>
Represents the response models of a route response.
</p>

@param responseModels
Represents the response models of a route response.
@return Returns a reference to this object so that method calls can be chained together.

public UpdateRouteResponseResult withResponseModels(java.util.Map<String, String> responseModels) {
        setResponseModels(responseModels);
        return this;
    }

public function path($name, array $parameters = [], $relative = false)
    {
        if ($name instanceof TreeNodeInterface) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ContentTreeContext) {
            return $this->router->generate($name->getNode(), $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ElementStructureValue) {
            if ($name->getType() === 'link') {
                $link = $name->getValue();
                if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                    $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                    if ($tree) {
                        $node = $tree->get($link['tid']);

                        return $this->router->generate(
                            $node,
                            $parameters,
                            $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                        );
                    }
                } elseif ($link['type'] === 'external') {
                    return $link['url'];
                } elseif ($link['type'] === 'mailto') {
                    return 'mailto:'.$link['recipient'];
                }
            }
        } elseif (is_array($name) && isset($name['type']) && in_array($name['type'], array('internal', 'intrasiteroot', 'external', 'mailto'))) {
            $link = $name;
            if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                if ($tree) {
                    $node = $tree->get($link['tid']);

                    return $this->router->generate(
                        $node,
                        $parameters,
                        $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                    );
                }
            } elseif ($link['type'] === 'external') {
                return $link['url'];
            } elseif ($link['type'] === 'mailto') {
                return 'mailto:'.$link['recipient'];
            }
        } elseif (strlen($name) && (is_int($name) || (int) $name)) {
            $tree = $this->contentTreeManager->findByTreeId((int) $name);
            if ($tree) {
                $node = $tree->get((int) $name);

                return $this->router->generate($node, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
            }
        } elseif (is_string($name)) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        }

        return '';
    }

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


Question:
Return the HTTP method to use.

        Returns:
            object: http_put (default) or http_post

def _get_update_method(self):

        if getattr(self, '_update_uses_post', False):
            http_method = self.gitlab.http_post
        else:
            http_method = self.gitlab.http_put
        return http_method

public function output($image_type = null, $quality = null)
    {
        $image_type = $image_type ?: $this->source_type;

        header('Content-Type: ' . image_type_to_mime_type($image_type));

        $this->save(null, $image_type, $quality);
    }

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


Question: Submit an event when compaction MR job completes

private void submitSlaEvent(Job job) {
    try {
      CompactionSlaEventHelper
          .getEventSubmitterBuilder(this.dataset, Optional.of(job), this.fs)
          .eventSubmitter(this.eventSubmitter)
          .eventName(CompactionSlaEventHelper.COMPACTION_COMPLETED_EVENT_NAME)
          .additionalMetadata(
              CompactionSlaEventHelper.LATE_RECORD_COUNT,
              Long.toString(this.lateOutputRecordCountProvider.getRecordCount(this.getApplicableFilePaths(this.dataset
                  .outputLatePath(), this.fs))))
          .additionalMetadata(
              CompactionSlaEventHelper.REGULAR_RECORD_COUNT,
              Long.toString(this.outputRecordCountProvider.getRecordCount(this.getApplicableFilePaths(this.dataset
                  .outputPath(), this.fs))))
          .additionalMetadata(CompactionSlaEventHelper.RECOMPATED_METADATA_NAME,
              Boolean.toString(this.dataset.needToRecompact())).build().submit();
    } catch (Throwable e) {
      LOG.warn("Failed to submit compaction completed event:" + e, e);
    }
  }

@Override
    public int doEndTag() throws JspException {

        if (m_firstOnPage || m_manualPlacement) {
            // only execute action for the first "editable" tag on the page (include file), or in manual mode
            editableTagAction(pageContext, m_provider, m_mode, m_file);
        }
        if (OpenCms.getSystemInfo().getServletContainerSettings().isReleaseTagsAfterEnd()) {
            // need to release manually, JSP container may not call release as required (happens with Tomcat)
            release();
        }

        return EVAL_PAGE;
    }

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


Question:
// Send will send a Chattable item to Telegram.
//
// It requires the Chattable to send.

func (bot *BotAPI) Send(c Chattable) (Message, error) {
	switch c.(type) {
	case Fileable:
		return bot.sendFile(c.(Fileable))
	default:
		return bot.sendChattable(c)
	}
}

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question:
Find minimum of a function on interval [a, b]
    using golden section search.

    If expand_bounds=True, expand the interval so that the function is
    first evaluated at x=a and x=b.

def golden_search(f, a, b, xatol=1e-6, ftol=1e-8, expand_bounds=False):

    ratio = 2 / (1 + math.sqrt(5))

    if not expand_bounds:
        x0 = a
        x3 = b
    else:
        x0 = (ratio * a - (1 - ratio) * b) / (2*ratio - 1)
        x3 = (ratio * b - (1 - ratio) * a) / (2*ratio - 1)

    x1 = ratio * x0 + (1 - ratio) * x3
    x2 = (1 - ratio) * x0 + ratio * x3

    f1 = f(x1)
    f2 = f(x2)

    f0 = max(abs(f1), abs(f2))

    while True:
        if abs(x0 - x3) < xatol or abs(f1 - f2) < ftol*f0:
            break

        if f2 < f1:
            x0 = x1
            x1 = x2
            x2 = ratio * x1 + (1 - ratio) * x3
            f1 = f2
            f2 = f(x2)
        else:
            x3 = x2
            x2 = x1
            x1 = ratio * x2 + (1 - ratio) * x0
            f2 = f1
            f1 = f(x1)

    if f2 < f1:
        return x2
    else:
        return x1

def num_rewards(self):

    # Pre-conditions: reward range is finite.
    #               : processed rewards are discrete.
    if not self.is_reward_range_finite:
      tf.logging.error("Infinite reward range, `num_rewards returning None`")
      return None
    if not self.is_processed_rewards_discrete:
      tf.logging.error(
          "Processed rewards are not discrete, `num_rewards` returning None")
      return None

    min_reward, max_reward = self.reward_range
    return max_reward - min_reward + 1

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


Question: // GetIP Get hostIP

func GetIP(daemonHost string) string {
	u, err := url.Parse(daemonHost)
	if err != nil {
		log.Errorf("[GetIP] GetIP %s failed %v", daemonHost, err)
		return ""
	}
	return u.Hostname()
}

func (ipv4 IPv4Addr) ContainsAddress(x IPv4Address) bool {
	return IPv4Address(ipv4.NetworkAddress()) <= x &&
		IPv4Address(ipv4.BroadcastAddress()) >= x
}

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


Question: Add a SuperColumnCounter insertion (or update)

public BatchMutation<K> addSuperCounterInsertion(K key, List<String> columnFamilies,
      CounterSuperColumn counterSuperColumn) {
    Mutation mutation = new Mutation();
    mutation.setColumn_or_supercolumn(new ColumnOrSuperColumn().setCounter_super_column(counterSuperColumn));
    addMutation(key, columnFamilies, mutation);
    return this;
  }

public function increment($id, $offset = 1)
	{
		$data = $this->_get($id);

		if ($data === FALSE)
		{
			$data = array('data' => 0, 'ttl' => 60);
		}
		elseif ( ! is_int($data['data']))
		{
			return FALSE;
		}

		$new_value = $data['data'] + $offset;
		return $this->save($id, $new_value, $data['ttl'])
			? $new_value
			: FALSE;
	}

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


Question: Register subscriptions

public static void registerSubscription(Subscription subscription) {
        mSubscriptions.add(subscription);
        if (isConnected()) {
            executeQuery(subscription.getQuery());
        }
    }

public GetSubscriptionDefinitionResult withTags(java.util.Map<String, String> tags) {
        setTags(tags);
        return this;
    }

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


Question:
Clear the values of a property or reference, setting it to null.

This operation can be useful when removing properties using "merge"
operation.

@param propertyName of the property as defined by the bean's schema.

public void clear(final String propertyName) {
        Preconditions.checkNotNull(propertyName);
        if (properties.containsKey(propertyName)) {
            properties.put(propertyName, null);
        } else if (references.containsKey(propertyName)) {
            references.put(propertyName, null);
        }
    }

public function modify(array $properties)
  {
    $properties["clid"] = $this->getId();

    $this->execute("clientedit", $properties);
    $this->resetNodeInfo();
  }

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


Question:
Reads an entry from cache.

@param string $key       The key to read data from
@param string $namespace The namespace used for that

@author Benjamin Carl <opensource@clickalicious.de>

@return bool|array The data from cache if set, otherwise FALSE

public function read($key, $namespace)
    {
        // Get internal used key
        $key = $this->calculateUuid($key);

        // Try to retrieve data from runtime cache ...
        $dataset = $this->getFromRuntimeCache($key, $namespace);

        // Check for result from runtime cache
        if ($dataset === false) {

            // get filename
            $filename = $this->getFilenameByKeyAndNamespace($key, $namespace);

            // if file does not exist -> then there is nothing to read
            if (!file_exists($filename)) {
                return false;
            }

            // Read (no lock = change possible from another process!)
            $dataset = $this->readFile($filename, false);
        }

        return $dataset;
    }

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

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


Question:
Ensure the database schema is up to date with the codebase.

    :param engine: SQLAlchemy engine of the underlying database.

def _upgrade_schema(engine):

    inspector = reflection.Inspector.from_engine(engine)
    with engine.connect() as conn:

        # Upgrade 1.  Add task_id column and index to tasks
        if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]:
            logger.warning('Upgrading DbTaskHistory schema: Adding tasks.task_id')
            conn.execute('ALTER TABLE tasks ADD COLUMN task_id VARCHAR(200)')
            conn.execute('CREATE INDEX ix_task_id ON tasks (task_id)')

        # Upgrade 2. Alter value column to be TEXT, note that this is idempotent so no if-guard
        if 'mysql' in engine.dialect.name:
            conn.execute('ALTER TABLE task_parameters MODIFY COLUMN value TEXT')
        elif 'oracle' in engine.dialect.name:
            conn.execute('ALTER TABLE task_parameters MODIFY value TEXT')
        elif 'mssql' in engine.dialect.name:
            conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TEXT')
        elif 'postgresql' in engine.dialect.name:
            if str([x for x in inspector.get_columns('task_parameters')
                    if x['name'] == 'value'][0]['type']) != 'TEXT':
                conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TYPE TEXT')
        elif 'sqlite' in engine.dialect.name:
            # SQLite does not support changing column types. A database file will need
            # to be used to pickup this migration change.
            for i in conn.execute('PRAGMA table_info(task_parameters);').fetchall():
                if i['name'] == 'value' and i['type'] != 'TEXT':
                    logger.warning(
                        'SQLite can not change column types. Please use a new database '
                        'to pickup column type changes.'
                    )
        else:
            logger.warning(
                'SQLAlcheny dialect {} could not be migrated to the TEXT type'.format(
                    engine.dialect
                )
            )

def db_command(parser_args):

    from synergy.db.manager import db_manager

    if parser_args.reset:
        db_manager.reset_db()
        # initialize DB with the context.process_context entries
        parser_args.update = True

    if parser_args.update:
        db_manager.update_db()

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


Question: // SetVersion sets the Version field's value.

func (s *CreateSlotTypeVersionOutput) SetVersion(v string) *CreateSlotTypeVersionOutput {
	s.Version = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
Process a JoinColumn Annotation, extract nullable.

@param JoinColumn $join_column
@param PropertyInformation $information

private function processJoinColumn(JoinColumn $join_column, PropertyInformation $information): void
    {
        $information->setNullable($join_column->nullable);
        $information->setUnique($join_column->unique);
    }

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.