Question:
Checks if the date is a holiday

@param dateString the date
@return true if it is a holiday, false otherwise

public boolean isHoliday(String dateString) {
        boolean isHoliday = false;
        for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) {
            if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) {
                isHoliday = true;
            }
        }
        return isHoliday;
    }

function f_kalem_onay_durumu(_kalem_id, _tahta_id) {

        var defer = result.dbQ.Q.defer();

        //noinspection JSValidateTypes
        if (!_tahta_id && _tahta_id === 0) {
            defer.resolve({Id: 2, Baslik: "İlk Kayıt"});
            //throw new exception.Istisna("Kalem onay durumu çekilemedi", "Tahta_id bilgisi kalemin onay durumu çekilirken boş bırakılamaz!");
        }

        // birden fazla satir_id için hmget_json_parse ile çekilebilir şekilde yazılacak
        (Array.isArray(_kalem_id)
            ? result.dbQ.hmget_json_parse(result.kp.tahta.hsetKalemOnayDurumlari(_tahta_id), _kalem_id)
            : result.dbQ.hget_json_parse(result.kp.tahta.hsetKalemOnayDurumlari(_tahta_id), _kalem_id))
            .then(function (_durum) {

                function f_kalem_durumu(_kalemDurumu) {
                    return _kalemDurumu || {Id: 2, Baslik: "İlk Kayıt"};
                }

                return Array.isArray(_durum)
                    ? _durum.map(f_kalem_durumu)
                    : f_kalem_durumu(_durum)

            })
            .then(function (_res) {
                defer.resolve(_res);
            })
            .fail(function (_err) {
                defer.reject("Kalem onay durumu çekilirken hata alındı:", _err);
            });

        return defer.promise;
    }

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


Question: // CleanUp removes the TXT record matching the specified parameters.

func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
	fqdn, _ := dns01.GetRecord(domain, keyAuth)

	zone, err := d.getHostedZone(fqdn)
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}

	records, err := d.findTxtRecords(zone, fqdn)
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}

	if len(records) == 0 {
		return nil
	}

	_, err = d.client.Changes.Create(d.config.Project, zone, &dns.Change{Deletions: records}).Do()
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}
	return nil
}

def do_rm(self, params):

        for path in params.paths:
            try:
                self.client_context.delete(path)
            except NotEmptyError:
                self.show_output("%s is not empty.", path)
            except NoNodeError:
                self.show_output("%s doesn't exist.", path)

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


Question: Try several parserSyntax-es in a row. All must succeed; otherwise, return null. This is the only eager one.

function sequence ( parserSyntax ) {
				var i, res,
					originalPos = pos,
					result = [];

				for ( i = 0; i < parserSyntax.length; i++ ) {
					res = parserSyntax[i]();

					if ( res === null ) {
						pos = originalPos;

						return null;
					}

					result.push( res );
				}

				return result;
			}

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

      valid
    end

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


Question: /* Query Commands ... INSERT, UPDATE, DELETE

function insert($table, $data) {
		$q = "INSERT INTO $table ";
		$v=''; $n='';
		foreach($data as $key=>$val) {
			$n .=" ".$this->encapsulate_column_name($key).", ";
			if(strtolower($val)=='null') {
				$v.="NULL, ";
			} elseif(strtolower($val)=='now()') {
				$v.="NOW(), ";
			} else {
				$v.= "'".$this->escape($val)."', ";
			}
		}
		$q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");";
		return $this->query($q);
	}

public function commit(string  $objectType, $objectsIds, string  $action, string  $userName = 'Unknown User', string  $comment = '')
    {
        //==============================================================================
        //      Create Event Object
        $event = new ObjectsCommitEvent(
            $this->getWebserviceId(),
            $objectType,
            $objectsIds,
            $action,
            $userName,
            $comment
        );
        //==============================================================================
        //      Dispatch Event
        $this->getEventDispatcher()->dispatch(ObjectsCommitEvent::NAME, $event);
    }

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


Question: // Release frees all resources associated with the route.

func (r *Route) Release() {
	if r.ref != nil {
		r.ref.decRef()
		r.ref = nil
	}
}

public function any( $uri, $action = null )
	{
		$verbs = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];

		return $this->addRoute( $verbs, $uri, $action );
	}

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


Question: // sqrt3 sets z to sqrt(3) and returns z.

func sqrt3(z *decimal.Big, ctx decimal.Context) *decimal.Big {
	if ctx.Precision <= constPrec {
		return ctx.Set(z, _Sqrt3)
	}
	// TODO(eric): get rid of this allocation.
	return ctx.Set(z, Sqrt(decimal.WithContext(ctx), three))
}

def _turn(self, speed, degrees, brake=True, block=True):

        # The distance each wheel needs to travel
        distance_mm = (abs(degrees) / 360) * self.circumference_mm

        # The number of rotations to move distance_mm
        rotations = distance_mm/self.wheel.circumference_mm

        log.debug("%s: turn() degrees %s, distance_mm %s, rotations %s, degrees %s" %
            (self, degrees, distance_mm, rotations, degrees))

        # If degrees is positive rotate clockwise
        if degrees > 0:
            MoveTank.on_for_rotations(self, speed, speed * -1, rotations, brake, block)

        # If degrees is negative rotate counter-clockwise
        else:
            rotations = distance_mm / self.wheel.circumference_mm
            MoveTank.on_for_rotations(self, speed * -1, speed, rotations, brake, block)

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


Question:
Prepara la sentencia interna para su uso exterior.

@throws \Exception

@return \PDOStatement

public function preparar()
    {
        // Validamos la sentencia a preparar
        if (empty($this->sentencia)) {
            if ($this->arrojarExcepciones) {
                throw new \InvalidArgumentException('La sentencia a preparar se encuentra vacia.');
            }
        }

        return $this->pdo->prepare($this->sentencia);
    }

private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day)
   {
      ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate());
      if (day.isIsDayWorking())
      {
         for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())
         {
            mpxjException.addRange(new DateRange(period.getFrom(), period.getTo()));
         }
      }
   }

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


Question:
Access the engagements

        :returns: twilio.rest.studio.v1.flow.engagement.EngagementList
        :rtype: twilio.rest.studio.v1.flow.engagement.EngagementList

def engagements(self):

        if self._engagements is None:
            self._engagements = EngagementList(self._version, flow_sid=self._solution['sid'], )
        return self._engagements

@Override
    public boolean regiserService(NaviRpcExporter exporter) {
        Class<?> interf = exporter.getServiceInterface();
        Object bean = exporter.getServiceBean();
        List<AppIdToken> appIdTokens = getAuthIfPossible(bean);
        String interfSimpleName = interf.getSimpleName();
        try {
            exporters.put(exporter.getName(), exporter);
            if (interf.isAssignableFrom(bean.getClass())) {
                Method[] ms = ReflectionUtil.getAllInstanceMethods(bean.getClass());
                for (Method m : ms) {
                    if (methodResolver.isSupport(m)) {
                        MethodWrapper methodWrapper = new MethodWrapper(interf.getName(),
                                m.getName(), MethodUtil.getArgsTypeName(m));
                        MethodWrapper defaultMethodWrapper = new MethodWrapper(interf.getName(),
                                m.getName(), StringUtil.EMPTY);
                        String key = methodWrapper.toString();
                        MethodDescriptor<String> desc = new MethodDescriptor<String>();
                        desc.setServiceId(key).setMethod(m).setTarget(bean)
                                .setArgumentClass(m.getParameterTypes())
                                .setReturnClass(m.getReturnType()).setInterfClass(interf).setAppIdTokens(appIdTokens);
                        serviceRegistry.addServiceDescriptor(key, desc);
                        serviceRegistry.addServiceDescriptor(defaultMethodWrapper.toString(), desc);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(String.format(
                                    "Register service key=[%s], %s %s#%s(%s) successfully", key, m
                                            .getReturnType().getSimpleName(), interf.getName(), m
                                            .getName(), StringUtil.toString4Array(m
                                            .getParameterTypes())));
                        }
                    }
                }
                LOG.info("Find rpc service configured, interface is "
                        + interfSimpleName + " , implementation is "
                        + AopUtils.getTargetClass(bean).getName());
                return true;
            } else {
                LOG.error("The interface " + interfSimpleName + " is not compatible with the bean "
                        + bean.getClass().getName());
            }
        } catch (Exception e) {
            LOG.error(
                    "The interface " + interfSimpleName + " is configured wrongly."
                            + e.getMessage(), e);
        }
        return false;
    }

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


Question:
@param string $modelClass

@return string

protected function getTableNameForClass(string $modelClass): string
    {
        assert(
            $this->getModelSchemas()->hasClass($modelClass),
            "Class `$modelClass` is not found in model Schemas."
        );

        $tableName = $this->getModelSchemas()->getTable($modelClass);

        return $tableName;
    }

public function setRoute(DataSourceViewInterface $dataSource, $route, array $additional_parameters = [])
    {
        $this->routes[$dataSource->getName()] = $route;
        $this->additional_parameters[$dataSource->getName()] = $additional_parameters;
    }

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


Question:
Prepare the template.

@param ContaoBackendViewTemplate $template    The template to populate.
@param EnvironmentInterface      $environment The environment.

@return void

protected function renderTemplate(ContaoBackendViewTemplate $template, EnvironmentInterface $environment)
    {
        $inputProvider  = $environment->getInputProvider();
        $dataDefinition = $environment->getDataDefinition();

        $languageDomain = 'contao_' . $dataDefinition->getName();

        $this->getViewSection($dataDefinition)->getListingConfig()->setShowColumns(false);

        parent::renderTemplate($template, $environment);

        $template
            ->set(
                'subHeadline',
                \sprintf(
                    '%s: %s',
                    $this->translate('MSC.' . $inputProvider->getParameter('mode') . 'Selected', $languageDomain),
                    $this->translate('MSC.edit_all_select_properties', $languageDomain)
                )
            )
            ->set('mode', 'none')
            ->set('floatRightSelectButtons', true)
            ->set('selectCheckBoxName', 'properties[]')
            ->set('selectCheckBoxIdPrefix', 'properties_');

        if ((null !== $template->get('action'))
            && (false !== \strpos($template->get('action'), 'select=properties'))
        ) {
            $template->set('action', \str_replace('select=properties', 'select=edit', $template->get('action')));
        }

        if (\count($this->messages) > 0) {
            foreach (\array_keys($this->messages) as $messageType) {
                $template->set($messageType, $this->messages[$messageType]);
            }
        }
    }

public function fire()
    {
        $OUTPUT = [];
        $CHANGES = [];

        $fileUser = base_path('.env');
        if (file_exists($fileUser)) {
            $autodetect = ini_get('auto_detect_line_endings');
            ini_set('auto_detect_line_endings', '1');
            $lines = file($fileUser, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            ini_set('auto_detect_line_endings', $autodetect);
            foreach ($lines as $line) {
                $line = explode('=', $line, 2);
                if (count($line) == 2) {
                    $OUTPUT[$line[0]] = $line[1];
                }
            }
        }

        $file = base_path('.env.example');
        if (! file_exists($file)) {
            $this->error('.env.example don\'t exists');

            return;
        }
        $autodetect = ini_get('auto_detect_line_endings');
        ini_set('auto_detect_line_endings', '1');
        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        ini_set('auto_detect_line_endings', $autodetect);

        $values = [];
        foreach ($lines as $line) {
            $line = explode('=', $line, 2);
            if (count($line) == 2) {
                $values[$line[0]] = $line[1];
            }
        }

        foreach ($values as $key => $value) {
            if (preg_match('/^\\(([^\\)]+)\\)({([^\\}]+)})?$/us', $value, $matches)) {
                if (! isset($OUTPUT[$key]) || $this->option('overwrite') && $this->confirm('Do you want to overwrite existing value of '.strtoupper($key).' = '.$OUTPUT[$key].'?', false)) {
                    $choice = '';
                    if (isset($matches[3]) && $matches[3] != '') {
                        $defaults = explode('|', $matches[3]);
                        $default = null;
                        foreach ($defaults as $d) {
                            $rule = [];
                            $tmp = explode(':', $d);
                            $rule['value'] = $tmp[1];
                            $tmp = explode('=', $tmp[0]);
                            $rule['var'] = $tmp[0];
                            $rule['is'] = $tmp[1];

                            if ($OUTPUT[$rule['var']] == $rule['is']) {
                                $default = $rule['value'];
                            }
                        }
                        if (! is_null($default)) {
                            if (! $this->option('defaults') || $this->confirm('Do you want to use default value for '.strtoupper($key).' = '.$default.'?', true)) {
                                $choice = $default;
                                $OUTPUT[$key] = $choice;
                                $CHANGES[$key] = $choice;
                            }
                        }
                    }
                    if ($choice == '') {
                        $choices = explode('|', $matches[1]);
                        $choices = array_combine(range(1, count($choices)), array_values($choices));
                        if (count($choices) == 1) {
                            $choice = $choices[1];
                        } else {
                            $choice = $this->choice($key, $choices);
                        }
                        switch ($choice) {
                            case 'PASSWORD':
                                $choice = $this->secret('Enter value for '.strtoupper($key).':');
                                break;
                            case 'TEXT':
                                $choice = $this->ask('Enter value for '.strtoupper($key).':');
                                break;
                        }
                        $OUTPUT[$key] = $choice;
                        $CHANGES[$key] = $choice;
                    }
                }
            } else {
                if (! isset($OUTPUT[$key])) {
                    $OUTPUT[$key] = $value;
                    $CHANGES[$key] = $value;
                }
            }
        }

        if (count($CHANGES) > 0) {
            $GROUPS = [];

            foreach ($OUTPUT as $key => $val) {
                $tmp = explode('_', $key);
                if (count($tmp) == 1) {
                    $GROUPS['OTHER'][$key] = $val;
                } else {
                    $GROUPS[$tmp[0]][$key] = $val;
                }
            }
            $TABLE = [];
            $OUTPUT = [];
            foreach ($GROUPS as $name => $GROUP) {
                $o = [];
                $o[] = '# '.$name;
                foreach ($GROUP as $key => $val) {
                    $o[] = $key.'='.$val;
                    $TABLE[] = [$name, $key, $val];
                }
                $OUTPUT[] = implode(PHP_EOL, $o);
            }
            $OUTPUT = implode("\n\n", $OUTPUT);

            $this->info($OUTPUT);
            // DEBUG: $this->table(['Group','Key','Value'],$TABLE);
            if ($this->confirm('Do you want to write above content to .env file?', true)) {
                file_put_contents($fileUser, $OUTPUT);
                $this->info('File written.');
            }
        } else {
            $this->info('There is nothing to write.');
        }
    }

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


Question: Return valid kwargs to function func

def get_valid_kwargs(func, potential_kwargs):

    kwargs = {}
    for name in get_kwarg_names(func):
        with suppress(KeyError):
            kwargs[name] = potential_kwargs[name]
    return kwargs

def _ensure_values(data: Mapping[str, Any]) -> Tuple[Dict[str, Any], bool]:

    to_return = {}
    should_write = False
    for keyname, typekind, default in REQUIRED_DATA:
        if keyname not in data:
            LOG.debug(f"Defaulted config value {keyname} to {default}")
            to_return[keyname] = default
            should_write = True
        elif not isinstance(data[keyname], typekind):
            LOG.warning(
                f"Config value {keyname} was {type(data[keyname])} not"
                f" {typekind}, defaulted to {default}")
            to_return[keyname] = default
            should_write = True
        else:
            to_return[keyname] = data[keyname]
    return to_return, should_write

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


Question: // GetUser - get user credentials

func (sys *IAMSys) GetUser(accessKey string) (cred auth.Credentials, ok bool) {
	sys.RLock()
	defer sys.RUnlock()

	cred, ok = sys.iamUsersMap[accessKey]
	return cred, ok && cred.IsValid()
}

public function hasCredentials($strategy, $kuid, array $options = [])
    {
        $options['httpParams'][':strategy'] = $strategy;
        $options['httpParams'][':kuid'] = $kuid;

        return $this->kuzzle->query($this->buildQueryArgs('hasCredentials'), [], $options)['result'];
    }

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


Question: // FragmentNodes returns a list of nodes that own a shard.

func (c *InternalClient) FragmentNodes(ctx context.Context, index string, shard uint64) ([]*pilosa.Node, error) {
	span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.FragmentNodes")
	defer span.Finish()

	// Execute request against the host.
	u := uriPathToURL(c.defaultURI, "/internal/fragment/nodes")
	u.RawQuery = (url.Values{"index": {index}, "shard": {strconv.FormatUint(shard, 10)}}).Encode()

	// Build request.
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, errors.Wrap(err, "creating request")
	}

	req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
	req.Header.Set("Accept", "application/json")

	// Execute request.
	resp, err := c.executeRequest(req.WithContext(ctx))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var a []*pilosa.Node
	if err := json.NewDecoder(resp.Body).Decode(&a); err != nil {
		return nil, fmt.Errorf("json decode: %s", err)
	}
	return a, nil
}

def _get_network(self, network_info):

        org_name = network_info.get('organizationName', '')
        part_name = network_info.get('partitionName', '')
        segment_id = network_info['segmentId']
        url = self._network_url % (org_name, part_name, segment_id)
        return self._send_request('GET', url, '', 'network')

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


Question: distance between two positions defined by (separation, PA)

def distance(pos0, pos1):

    r0, pa0 = pos0
    #logging.debug('r0={}, pa0={} (from {})'.format(r0, pa0, self))
    ra0 = r0*np.sin(pa0*np.pi/180)
    dec0 = r0*np.cos(pa0*np.pi/180)

    r1, pa1 = pos1
    #logging.debug('r1={}, pa1={} (from {})'.format(r0, pa0, other))
    ra1 = r1*np.sin(pa1*np.pi/180)
    dec1 = r1*np.cos(pa1*np.pi/180)

    dra = (ra1 - ra0)
    ddec = (dec1 - dec0)
    return np.sqrt(dra**2 + ddec**2)

public function symDifference(Geometry $other): Geometry {
        $event = new ProcessOpEvent($this, ['other' => $other]);
        $this->fireOperationEvent(ProcessOpEvent::SYM_DIFFERENCE_EVENT, $event);
        return $event->getResults();
    }

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


Question:
Parses the content of the file separating the errors into a single array.

@param  string  $content
@param  string  $allowedEnvironment
@param  array   $allowedLevel

@return array

protected function parseLog($content, $allowedEnvironment = null, $allowedLevel = [])
    {
        $log = [];

        $parsed = $this->parser->parseLogContent($content);

        extract($parsed, EXTR_PREFIX_ALL, 'parsed');

        if (empty($parsed_headerSet)) {
            return $log;
        }

        $needReFormat = in_array('Next', $parsed_headerSet);
        $newContent   = null;

        foreach ($parsed_headerSet as $key => $header) {
            if (empty($parsed_dateSet[$key])) {
                $parsed_dateSet[$key]  = $parsed_dateSet[$key-1];
                $parsed_envSet[$key]   = $parsed_envSet[$key-1];
                $parsed_levelSet[$key] = $parsed_levelSet[$key-1];
                $header                = str_replace("Next", $parsed_headerSet[$key-1], $header);
            }

            $newContent .= $header.' '.$parsed_bodySet[$key];

            if ((empty($allowedEnvironment) || $allowedEnvironment == $parsed_envSet[$key]) && $this->levelable->filter($parsed_levelSet[$key], $allowedLevel)) {
                $log[] = [
                    'environment' => $parsed_envSet[$key],
                    'level'       => $parsed_levelSet[$key],
                    'date'        => $parsed_dateSet[$key],
                    'file_path'   => $this->getCurrentLogPath(),
                    'header'      => $header,
                    'body'        => $parsed_bodySet[$key]
                ];
            }
        }

        if ($needReFormat) {
            file_put_contents($this->getCurrentLogPath(), $newContent);
        }

        return $log;
    }

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

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


Question: Override the next() error/passthrough handler to clean up before leaving. This way, the timer doesn't go off / the subscriber doesn't handle messages after we've sent the response, and the server doesn't crash as a result.

function next(err) {
      return finish(function (finishErr) {
        if (err) return topnext(err);
        else if (finishErr) return topnext(finishErr);
        else return topnext();
      });
    }

function unsubscribeError(message, exceptionMessage, exceptionType) {
		reply(proto.writeUnsubscribeException(
			message.id, exceptionMessage, exceptionType));
		dequeueSubUnsubRequest(message.itemName);
		fireFirstSubUnsubEvent(message.itemName);
	}

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


Question: Delegate to the appropriate method of the underlying logger.

public void debug(String msg) {
        if (!logger.isDebugEnabled())
            return;

        if (instanceofLAL) {
            ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null);
        } else {
            logger.debug(msg);
        }
    }

public void trace(Object message) {
        doLog(Level.TRACE, FQCN, message, null, null);
    }

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


Question:
掘金实现方式
    save current day's stock_min data

def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):

    # 导入掘金模块且进行登录
    try:
        from gm.api import set_token
        from gm.api import history
        # 请自行将掘金量化的 TOKEN 替换掉 GMTOKEN
        set_token("9c5601171e97994686b47b5cbfe7b2fc8bb25b09")
    except:
        raise ModuleNotFoundError

    # 股票代码格式化
    code_list = list(
        map(
            lambda x: "SHSE." + x if x[0] == "6" else "SZSE." + x,
            QA_fetch_get_stock_list().code.unique().tolist(),
        ))
    coll = client.stock_min
    coll.create_index([
        ("code", pymongo.ASCENDING),
        ("time_stamp", pymongo.ASCENDING),
        ("date_stamp", pymongo.ASCENDING),
    ])
    err = []

    def __transform_gm_to_qa(df, type_):
        """
        将掘金数据转换为 qa 格式
        """

        if df is None or len(df) == 0:
            raise ValueError("没有掘金数据")

        df = df.rename(columns={
            "eob": "datetime",
            "volume": "vol",
            "symbol": "code"
        }).drop(["bob", "frequency", "position", "pre_close"], axis=1)
        df["code"] = df["code"].map(str).str.slice(5, )
        df["datetime"] = pd.to_datetime(df["datetime"].map(str).str.slice(
            0, 19))
        df["date"] = df.datetime.map(str).str.slice(0, 10)
        df = df.set_index("datetime", drop=False)
        df["date_stamp"] = df["date"].apply(lambda x: QA_util_date_stamp(x))
        df["time_stamp"] = (
            df["datetime"].map(str).apply(lambda x: QA_util_time_stamp(x)))
        df["type"] = type_

        return df[[
            "open",
            "close",
            "high",
            "low",
            "vol",
            "amount",
            "datetime",
            "code",
            "date",
            "date_stamp",
            "time_stamp",
            "type",
        ]]

    def __saving_work(code, coll):
        QA_util_log_info(
            "##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
        try:
            for type_ in ["1min", "5min", "15min", "30min", "60min"]:
                col_filter = {"code": str(code)[5:], "type": type_}
                ref_ = coll.find(col_filter)
                end_time = str(now_time())[0:19]
                if coll.count_documents(col_filter) > 0:
                    start_time = ref_[coll.count_documents(
                        col_filter) - 1]["datetime"]
                    print(start_time)
                    QA_util_log_info(
                        "##JOB03.{} Now Saving {} from {} to {} == {}".format(
                            ["1min",
                             "5min",
                             "15min",
                             "30min",
                             "60min"
                             ].index(type_),
                            str(code)[5:],
                            start_time,
                            end_time,
                            type_,
                        ),
                        ui_log=ui_log,
                    )
                    if start_time != end_time:
                        df = history(
                            symbol=code,
                            start_time=start_time,
                            end_time=end_time,
                            frequency=MIN_SEC[type_],
                            df=True
                        )
                        __data = __transform_gm_to_qa(df, type_)
                        if len(__data) > 1:
                            # print(QA_util_to_json_from_pandas(__data)[1::])
                            # print(__data)
                            coll.insert_many(
                                QA_util_to_json_from_pandas(__data)[1::])
                else:
                    start_time = "2015-01-01 09:30:00"
                    QA_util_log_info(
                        "##JOB03.{} Now Saving {} from {} to {} == {}".format(
                            ["1min",
                             "5min",
                             "15min",
                             "30min",
                             "60min"
                             ].index(type_),
                            str(code)[5:],
                            start_time,
                            end_time,
                            type_,
                        ),
                        ui_log=ui_log,
                    )
                    if start_time != end_time:
                        df = history(
                            symbol=code,
                            start_time=start_time,
                            end_time=end_time,
                            frequency=MIN_SEC[type_],
                            df=True
                        )
                        __data = __transform_gm_to_qa(df, type_)
                        if len(__data) > 1:
                            # print(__data)
                            coll.insert_many(
                                QA_util_to_json_from_pandas(__data)[1::])
                            # print(QA_util_to_json_from_pandas(__data)[1::])
        except Exception as e:
            QA_util_log_info(e, ui_log=ui_log)
            err.append(code)
            QA_util_log_info(err, ui_log=ui_log)

    executor = ThreadPoolExecutor(max_workers=2)
    res = {
        executor.submit(__saving_work, code_list[i_], coll)
        for i_ in range(len(code_list))
    }
    count = 0
    for i_ in concurrent.futures.as_completed(res):
        QA_util_log_info(
            'The {} of Total {}'.format(count,
                                        len(code_list)),
            ui_log=ui_log
        )

        strProgress = "DOWNLOAD PROGRESS {} ".format(
            str(float(count / len(code_list) * 100))[0:4] + "%")
        intProgress = int(count / len(code_list) * 10000.0)
        QA_util_log_info(
            strProgress,
            ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=intProgress
        )
        count = count + 1
    if len(err) < 1:
        QA_util_log_info("SUCCESS", ui_log=ui_log)
    else:
        QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
        QA_util_log_info(err, ui_log=ui_log)

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:
Perform the refund to transfer the amount from seller
to buyer

@param string $refundAmount   amount to refund to the buyer
@param string $refundCurrency currency of the refund

@return void

public function refundToBuyer($refundAmount, $refundCurrency)
    {
        $refund = new OffAmazonPaymentsService_Model_Price();
        $refund->setCurrencyCode($refundCurrency);
        $refund->setAmount($refundAmount);

        $refundRequest = new OffAmazonPaymentsService_Model_RefundRequest();
        $refundRequest->setSellerId($this->_sellerId);
        $refundRequest->setAmazonCaptureId($this->_amazonCaptureId);
        $refundRequest->setRefundReferenceId($this->_refundReferenceId);
        $refundRequest->setRefundAmount($refund);

        return $this->_service->refund($refundRequest);
    }

protected function getBodyParametersFromDocBlock(array $tags)
    {
        $parameters = collect($tags)
            ->filter(function ($tag) {
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
            })
            ->mapWithKeys(function ($tag) {
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
                if (empty($content)) {
                    // this means only name and type were supplied
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
                    $required = false;
                    $description = '';
                } else {
                    list($_, $name, $type, $required, $description) = $content;
                    $description = trim($description);
                    if ($description == 'required' && empty(trim($required))) {
                        $required = $description;
                        $description = '';
                    }
                    $required = trim($required) == 'required' ? true : false;
                }

                $type = $this->normalizeParameterType($type);
                list($description, $example) = $this->parseDescription($description, $type);
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;

                return [$name => compact('type', 'description', 'required', 'value')];
            })->toArray();

        return $parameters;
    }

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


Question: Return a formula representation of a SEXT instruction.

def _translate_sext(self, oprnd1, oprnd2, oprnd3):

        assert oprnd1.size and oprnd3.size

        op1_var = self._translate_src_oprnd(oprnd1)
        op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)

        if oprnd3.size > oprnd1.size:
            result = smtfunction.sign_extend(op1_var, op3_var.size)
        elif oprnd3.size < oprnd1.size:
            raise Exception("Operands size mismatch.")
        else:
            result = op1_var

        return [op3_var == result] + op3_var_constrs

func (c *SQLiteContext) ResultInt(i int) {
	if i64 && (i > math.MaxInt32 || i < math.MinInt32) {
		C.sqlite3_result_int64((*C.sqlite3_context)(c), C.sqlite3_int64(i))
	} else {
		C.sqlite3_result_int((*C.sqlite3_context)(c), C.int(i))
	}
}

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


Question: Configure a new drag_cols state

def _config_drag_cols(self, drag_cols):
        """"""
        self._drag_cols = drag_cols
        # remove/display drag icon
        if self._drag_cols:
            self._im_drag.paste(self._im_draggable)
        else:
            self._im_drag.paste(self._im_not_draggable)
        self.focus_set()
        self.update_idletasks()

def dict_row_strategy(column_names):

    # replace empty column names with indices
    column_names = [(name or idx) for idx, name in enumerate(column_names)]

    def row_factory(row):
        return dict(zip(column_names, row))

    return row_factory

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


Question:
Decodes a Double object from exactly 8 bytes.

@param src source of encoded bytes
@param srcOffset offset into source array
@return Double object or null

public static Double decodeDoubleObjDesc(byte[] src, int srcOffset)
        throws CorruptEncodingException
    {
        long bits = DataDecoder.decodeDoubleBits(src, srcOffset);
        if (bits >= 0) {
            bits ^= 0x7fffffffffffffffL;
        }
        return bits == 0x7fffffffffffffffL ? null : Double.longBitsToDouble(bits);
    }

public Metadata readNextMetadata() throws IOException {
        Metadata metadata = null;

        boolean isLast = (bitStream.readRawUInt(Metadata.STREAM_METADATA_IS_LAST_LEN) != 0);
        int type = bitStream.readRawUInt(Metadata.STREAM_METADATA_TYPE_LEN);
        int length = bitStream.readRawUInt(Metadata.STREAM_METADATA_LENGTH_LEN);

        if (type == Metadata.METADATA_TYPE_STREAMINFO) {
        	metadata = streamInfo = new StreamInfo(bitStream, length, isLast);
            pcmProcessors.processStreamInfo((StreamInfo)metadata);
        } else if (type == Metadata.METADATA_TYPE_SEEKTABLE) {
        	metadata = seekTable = new SeekTable(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_APPLICATION) {
            metadata = new Application(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_PADDING) {
            metadata = new Padding(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_VORBIS_COMMENT) {
            metadata = vorbisComment = new VorbisComment(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_CUESHEET) {
	    metadata = new CueSheet(bitStream, length, isLast);
	} else if (type == Metadata.METADATA_TYPE_PICTURE) {
	    metadata = new Picture(bitStream, length, isLast);
        } else {
            metadata = new Unknown(bitStream, length, isLast);
        }
        frameListeners.processMetadata(metadata);
        //if (isLast) state = DECODER_SEARCH_FOR_FRAME_SYNC;
        return metadata;
    }

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


Question: // GetLevel returns the currently set log level of the logger

func (lr *logRegistry) GetLevel(logger string) (string, error) {
	logVal := lr.getLoggerFromMapping(logger)
	if logVal == nil {
		return "", fmt.Errorf("logger %s not found", logger)
	}
	return logVal.GetLevel().String(), nil
}

public void trace(Object message) {
        doLog(Level.TRACE, FQCN, message, null, null);
    }

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


Question:
Unset mapped attribute.

@param  string $key
@return void

protected function forget($key)
    {
        $mapping = $this->getMappingForAttribute($key);

        list($target, $attribute) = $this->parseMappedColumn($mapping);

        $target = $target ? $this->getTarget($this, explode('.', $target)) : $this;

        unset($target->{$attribute});
    }

public function setValue($value, RequestAbstract $request)
    {
        if (!$request->hasParam($this->getHtmlName() . '_change')) {
            $this->value = false;
        } else if ($request->hasParam($this->getHtmlName() . '_change')) {
            $this->value = true;
        }
    }

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


Question:
Adds a query to a multi-query batch. Returns index into results array from RunQueries() call.

@param $query
@param string $index
@param string $comment

@return int

public function addQuery($query, $index = '*', $comment = '')
    {
        // mbstring workaround
        $this->_MBPush();

        // build request
        $req = pack('NNNN', $this->_offset, $this->_limit, $this->_mode, $this->_ranker);
        if ($this->_ranker == SPH_RANK_EXPR) {
            $req .= pack('N', strlen($this->_rankexpr)).$this->_rankexpr;
        }
        $req .= pack('N', $this->_sort); // (deprecated) sort mode
        $req .= pack('N', strlen($this->_sortby)).$this->_sortby;
        $req .= pack('N', strlen($query)).$query; // query itself
        $req .= pack('N', count($this->_weights)); // weights
        foreach ($this->_weights as $weight) {
            $req .= pack('N', (int) $weight);
        }
        $req .= pack('N', strlen($index)).$index; // indexes
        $req .= pack('N', 1); // id64 range marker
        $req .= $this->sphPackU64($this->_min_id).$this->sphPackU64($this->_max_id); // id64 range

        // filters
        $req .= pack('N', count($this->_filters));
        foreach ($this->_filters as $filter) {
            $req .= pack('N', strlen($filter['attr'])).$filter['attr'];
            $req .= pack('N', $filter['type']);
            switch ($filter['type']) {
                case SPH_FILTER_VALUES:
                    $req .= pack('N', count($filter['values']));
                    foreach ($filter['values'] as $value) {
                        $req .= $this->sphPackI64($value);
                    }
                    break;

                case SPH_FILTER_RANGE:
                    $req .= $this->sphPackI64($filter['min']).$this->sphPackI64($filter['max']);
                    break;

                case SPH_FILTER_FLOATRANGE:
                    $req .= $this->_PackFloat($filter['min']).$this->_PackFloat($filter['max']);
                    break;

                default:
                    assert(0 && 'internal error: unhandled filter type');
            }
            $req .= pack('N', $filter['exclude']);
        }

        // group-by clause, max-matches count, group-sort clause, cutoff count
        $req .= pack('NN', $this->_groupfunc, strlen($this->_groupby)).$this->_groupby;
        $req .= pack('N', $this->_maxmatches);
        $req .= pack('N', strlen($this->_groupsort)).$this->_groupsort;
        $req .= pack('NNN', $this->_cutoff, $this->_retrycount, $this->_retrydelay);
        $req .= pack('N', strlen($this->_groupdistinct)).$this->_groupdistinct;

        // anchor point
        if (empty($this->_anchor)) {
            $req .= pack('N', 0);
        } else {
            $a = &$this->_anchor;
            $req .= pack('N', 1);
            $req .= pack('N', strlen($a['attrlat'])).$a['attrlat'];
            $req .= pack('N', strlen($a['attrlong'])).$a['attrlong'];
            $req .= $this->_PackFloat($a['lat']).$this->_PackFloat($a['long']);
        }

        // per-index weights
        $req .= pack('N', count($this->_indexweights));
        foreach ($this->_indexweights as $idx => $weight) {
            $req .= pack('N', strlen($idx)).$idx.pack('N', $weight);
        }

        // max query time
        $req .= pack('N', $this->_maxquerytime);

        // per-field weights
        $req .= pack('N', count($this->_fieldweights));
        foreach ($this->_fieldweights as $field => $weight) {
            $req .= pack('N', strlen($field)).$field.pack('N', $weight);
        }

        // comment
        $req .= pack('N', strlen($comment)).$comment;

        // attribute overrides
        $req .= pack('N', count($this->_overrides));
        foreach ($this->_overrides as $entry) {
            $req .= pack('N', strlen($entry['attr'])).$entry['attr'];
            $req .= pack('NN', $entry['type'], count($entry['values']));
            foreach ($entry['values'] as $id => $val) {
                assert(is_numeric($id));
                assert(is_numeric($val));

                $req .= $this->sphPackU64($id);
                switch ($entry['type']) {
                    case SPH_ATTR_FLOAT:
                        $req .= $this->_PackFloat($val);
                        break;
                    case SPH_ATTR_BIGINT:
                        $req .= $this->sphPackI64($val);
                        break;
                    default:
                        $req .= pack('N', $val);
                        break;
                }
            }
        }

        // select-list
        $req .= pack('N', strlen($this->_select)).$this->_select;

        // mbstring workaround
        $this->_MBPop();

        // store request to requests array
        $this->_reqs[] = $req;

        return count($this->_reqs) - 1;
    }

public function execute(Input $input, Output $output)
    {
        $connector = $input->getArgument('connector') ?: $this->app->config->get('queue.connector', 'sync');

        $queue = $input->getOption('queue') ?: $this->app->config->get("queue.{$connector}", 'default');
        $delay = $input->getOption('delay');
        $sleep = $input->getOption('sleep');
        $tries = $input->getOption('tries');

        $this->listenForEvents();

        if ($input->getOption('once')) {
            $this->worker->runNextJob($connector, $queue, $delay, $sleep, $tries);
        } else {
            $memory  = $input->getOption('memory');
            $timeout = $input->getOption('timeout');
            $this->worker->daemon($connector, $queue, $delay, $sleep, $tries, $memory, $timeout);
        }
    }

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


Question: // subscribe consumes deliveries from an exclusive queue from a fanout exchange and sends to the application specific messages chan.

func subscribe(sessions chan chan session, messages chan<- message) {
	queue := identity()

	for session := range sessions {
		sub := <-session

		if _, err := sub.QueueDeclare(queue, false, true, true, false, nil); err != nil {
			log.Printf("cannot consume from exclusive queue: %q, %v", queue, err)
			return
		}

		routingKey := "application specific routing key for fancy toplogies"
		if err := sub.QueueBind(queue, routingKey, exchange, false, nil); err != nil {
			log.Printf("cannot consume without a binding to exchange: %q, %v", exchange, err)
			return
		}

		deliveries, err := sub.Consume(queue, "", false, true, false, false, nil)
		if err != nil {
			log.Printf("cannot consume from: %q, %v", queue, err)
			return
		}

		log.Printf("subscribed...")

		for msg := range deliveries {
			messages <- message(msg.Body)
			sub.Ack(msg.DeliveryTag, false)
		}
	}
}

def discussions_notifications(user):
    ''''''
    notifications = []

    # Only fetch required fields for notification serialization
    # Greatly improve performances and memory usage
    qs = discussions_for(user).only('id', 'created', 'title', 'subject')

    # Do not dereference subject (so it's a DBRef)
    # Also improve performances and memory usage
    for discussion in qs.no_dereference():
        notifications.append((discussion.created, {
            'id': discussion.id,
            'title': discussion.title,
            'subject': {
                'id': discussion.subject['_ref'].id,
                'type': discussion.subject['_cls'].lower(),
            }
        }))

    return notifications

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


Question: // ChannelMap.Valid returns true iff the channel map is considered valid.

func (m *ChannelMap) Valid() bool {
	cmap := m.toC()
	return C.pa_channel_map_valid(cmap) != 0
}

protected function validateConfig()
    {
        $message = null;
        if (empty($this->config['api_key'])) {
            $message = 'Geocoder Config: Api Key is mandatory for using Google API.';
        }
        elseif (empty($this->config['request_url'])) {
            $message = 'Geocoder Config: Request URL is mandatory for using Google API.';
        }
        elseif (empty($this->config['output_format'])) {
            $message = 'Geocoder Config: Output Format is mandatory for using Google API.';
        }
        elseif ( ! in_array($this->config['output_format'], self::SUPPORTED_FORMATS)) {
            $message = 'Geocoder Config: Given Format is not supported.';
        }

        if ($message) {
            throw  new \InvalidArgumentException($message);
        }
    }

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


Question:
@param (see #get)

 @return (see #call)

def post(url, params = {}, options = {})
      post_request = Net::HTTP::Post.new(url)
      post_request.body = Gateway.parsed_params( wrap(:post, url, params) )
      post_request.content_type = 'application/x-www-form-urlencoded'
      self.call( post_request, options.merge(:format => params[:format]) )
    end

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

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

        $generator->startList('Tag');

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

        $generator->endList('Tag');

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

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


Question:
Set complied path base on template path and config options

@param string $templatePath template view path
@param array $options config for volt engine

public function getCompiledPath($templatePath, $options = [])
    {
        $viewsDir = $this->getViewsDir();
        if (!isset($options['path'])) {
            $options['path'] = $viewsDir;
        }

        $relativeViewFile = trim(str_replace($viewsDir, '', $templatePath), DIRECTORY_SEPARATOR);
        if (!isset($options['hierarchical']) || !$options['hierarchical']) {
            $separator    = isset($options['separator']) ? $options['separator'] : '__';
            $compliedPath = str_replace(DIRECTORY_SEPARATOR, $separator, $relativeViewFile);
        } else {
            $relativeViewPath = substr($relativeViewFile, 0, strrpos($relativeViewFile, DIRECTORY_SEPARATOR));
            $absolutedPath    = $options['path'] . $relativeViewPath;
            if (!is_dir($absolutedPath)) {
                mkdir($absolutedPath, 0755, true);
            }

            if (!is_writable($absolutedPath)) {
                throw new Exception\RuntimeException(sprintf('Cannot write compile view to "%s"', $absolutedPath));
            }
            $compliedPath = $relativeViewFile;
        }

        $compliedPath = $options['path'] . $compliedPath;
        $compliedExt  = isset($options['extension']) ? $options['extension'] : '.php';
        $compliedPath .= $compliedExt;

        return $compliedPath;
    }

public function initVariant(CompilationContext $compilationContext)
    {
        if ($this->numberSkips) {
            --$this->numberSkips;

            return;
        }

        /*
         * Variables are allocated for the first time using ZEPHIR_INIT_VAR
         * the second, third, etc times are allocated using ZEPHIR_INIT_NVAR
         * Variables initialized for the first time in a cycle are always initialized using ZEPHIR_INIT_NVAR
         */
        if ('this_ptr' != $this->getName() && 'return_value' != $this->getName()) {
            if (false === $this->initBranch) {
                $this->initBranch = $compilationContext->currentBranch;
            }

            $compilationContext->headersManager->add('kernel/memory');

            if (!$this->isLocalOnly()) {
                $compilationContext->symbolTable->mustGrownStack(true);
                if ($compilationContext->insideCycle) {
                    $this->mustInitNull = true;
                    $compilationContext->backend->initVar($this, $compilationContext, true, true);
                } else {
                    if ($this->variantInits > 0) {
                        if (0 === $this->initBranch) {
                            $compilationContext->codePrinter->output('ZEPHIR_INIT_BNVAR('.$this->getName().');');
                        } else {
                            $this->mustInitNull = true;
                            $compilationContext->backend->initVar($this, $compilationContext, true, true);
                        }
                    } else {
                        $compilationContext->backend->initVar($this, $compilationContext);
                    }
                }
            } else {
                if ($this->variantInits > 0 || $compilationContext->insideCycle) {
                    $this->mustInitNull = true;
                    $compilationContext->codePrinter->output('ZEPHIR_SINIT_NVAR('.$this->getName().');');
                } else {
                    $compilationContext->codePrinter->output('ZEPHIR_SINIT_VAR('.$this->getName().');');
                }
            }

            ++$this->variantInits;
            $this->associatedClass = null;
        }
    }

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


Question: Removes element from queue, sends next request

function dequeue(id) {
        var i = qq.indexOf(queue, id),
            max = options.maxConnections,
            nextId;

        delete requestData[id];
        queue.splice(i, 1);

        if (queue.length >= max && i < max) {
            nextId = queue[max - 1];
            sendRequest(nextId);
        }
    }

public synchronized List<LocalQueue> updatedQueues()
    {
    	List<LocalQueue> updatedQueues = new ArrayList<>(items.size());
    	for (int i = 0 ; i < items.size() ; i++)
        {
    		TransactionItem item = items.get(i);
            LocalQueue localQueue = item.getDestination();
            if (!updatedQueues.contains(localQueue))
                updatedQueues.add(localQueue);
        }

    	return updatedQueues;
    }

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


Question:
Implementation of Blade "stacks".

@param string $stack

@return string

public static function stack(string $stack): string
    {
        $content = implode('', self::$stacks[$stack] ?? []);

        self::$stacks[$stack] = [];

        return $content;
    }

function(depth, parts, strict) {
    if (!depth) {
      this.pushStackLiteral('data');
    } else {
      this.pushStackLiteral('container.data(data, ' + depth + ')');
    }

    this.resolvePath('data', parts, 0, true, strict);
  }

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


Question:
@param $input

@return array

protected function loc($input){
    $input = urlencode($input);
    $urlindex =  '/authorities/subjects/suggest/?q=' . $input;
    $baseurl = 'https://id.loc.gov';
    $remoteUrl = $baseurl.$urlindex;
    $options['headers']=['Accept' => 'application/json'];
    $body = $this->getRemoteJsonData($remoteUrl, $options);

    $jsondata = [];
    $results = [];
    $jsondata = json_decode($body, TRUE);
    $json_error = json_last_error();
    if ($json_error == JSON_ERROR_NONE) {
      //LoC will always return at least one, the query string
      if (count($jsondata) > 1) {
        foreach ($jsondata[1] as $key => $label) {
          $results[] = [
            'value' => $jsondata[3][$key],
            'label' => $label
          ];
        }
      }
      else {
          $results[] = [
            'value' => NULL,
            'label' => 'Sorry no Match from LoC Subject Headings'
          ];
        }
      return  $results;
    }
    $this->messenger->addError(
      $this->t('Looks like data fetched from @url is not in JSON format.
 JSON says: @$jsonerror
Please check your URL!',
        [
          '@url' => $remoteUrl,
          '@$jsonerror' => $json_error
        ]
      )
    );
    return [];
  }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question: //go:generate ego -o=command/ego.go -package=command -version=false command/templates

func main() {
	app := cli.NewApp()
	app.Name = Name
	app.Version = Version
	app.Author = "kyokomi"
	app.Email = ""
	app.Usage = ""

	app.Flags = GlobalFlags
	app.Commands = Commands
	app.CommandNotFound = CommandNotFound

	app.Run(os.Args)
}

def _build_egg(egg, archive_filename, to_dir):
    """"""
    with archive_context(archive_filename):
        # building an egg
        log.warn('Building a Setuptools egg in %s', to_dir)
        _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
    # returning the result
    log.warn(egg)
    if not os.path.exists(egg):
        raise IOError('Could not build the egg.')

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


Question:
Construct a TaskID object from given string
@return constructed TaskID object or null if the given String is null
@throws IllegalArgumentException if the given string is malformed

public static TaskID forName(String str)
    throws IllegalArgumentException {
    if(str == null)
      return null;
    try {
      String[] parts = str.split("_");
      if(parts.length == 5) {
        if(parts[0].equals(TASK)) {
          boolean isMap = false;
          if(parts[3].equals("m")) isMap = true;
          else if(parts[3].equals("r")) isMap = false;
          else throw new Exception();
          return new org.apache.hadoop.mapred.TaskID(parts[1],
                                                     Integer.parseInt(parts[2]),
                                                     isMap,
                                                     Integer.parseInt(parts[4]));
        }
      }
    }catch (Exception ex) {//fall below
    }
    throw new IllegalArgumentException("TaskId string : " + str
        + " is not properly formed");
  }

private static List<InjectionData> processIdList(final String list) {
        /* find the individual topic ids */
        final String[] ids = list.split(",");

        List<InjectionData> retValue = new ArrayList<InjectionData>(ids.length);

        /* clean the topic ids */
        for (final String id : ids) {
            final String topicId = id.replaceAll(OPTIONAL_MARKER, "").trim();
            final boolean optional = id.contains(OPTIONAL_MARKER);

            try {
                final InjectionData topicData = new InjectionData(topicId, optional);
                retValue.add(topicData);
            } catch (final NumberFormatException ex) {
                /*
                 * these lists are discovered by a regular expression so we shouldn't have any trouble here with Integer.parse
                 */
                LOG.debug("Unable to convert Injection Point ID into a Number", ex);
                retValue.add(new InjectionData("-1", false));
            }
        }

        return retValue;
    }

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


Question: Compute the value (size) of each node by summing the associated links.

def computeNodeValues(cls, graph):

        for node in graph['nodes']:
            source_val = np.sum([l['value'] for l in node['sourceLinks']])
            target_val = np.sum([l['value'] for l in node['targetLinks']])
            node['value'] = max([source_val, target_val])

protected function instantiateNode()
    {
        return new IntegerNode($this->name, $this->parent, $this->min, $this->max, $this->pathSeparator);
    }

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