Question:
Toggle the Tooltip of an element.

@param elem Element
@param type Event type

protected void toggleTooltip(Element elem, String type) {
    String csscls = elem.getAttribute(SVGConstants.SVG_CLASS_ATTRIBUTE);
    if(SVGConstants.SVG_MOUSEOVER_EVENT_TYPE.equals(type)) {
      if(TOOLTIP_HIDDEN.equals(csscls)) {
        SVGUtil.setAtt(elem, SVGConstants.SVG_CLASS_ATTRIBUTE, TOOLTIP_VISIBLE);
      }
    }
    else if(SVGConstants.SVG_MOUSEOUT_EVENT_TYPE.equals(type)) {
      if(TOOLTIP_VISIBLE.equals(csscls)) {
        SVGUtil.setAtt(elem, SVGConstants.SVG_CLASS_ATTRIBUTE, TOOLTIP_HIDDEN);
      }
    }
    else if(SVGConstants.SVG_CLICK_EVENT_TYPE.equals(type)) {
      if(TOOLTIP_STICKY.equals(csscls)) {
        SVGUtil.setAtt(elem, SVGConstants.SVG_CLASS_ATTRIBUTE, TOOLTIP_HIDDEN);
      }
      if(TOOLTIP_HIDDEN.equals(csscls) || TOOLTIP_VISIBLE.equals(csscls)) {
        SVGUtil.setAtt(elem, SVGConstants.SVG_CLASS_ATTRIBUTE, TOOLTIP_STICKY);
      }
    }
  }

function (out, delegateId, cssClassPostfix, skinIcon, label, focusable) {
            // --------------------------------------------------- destructuring

            var cfg = this._cfg;
            var skinnableClass = this._skinnableClass;

            var waiAria = cfg.waiAria;

            // ------------------------------------------------------ processing

            // wrapper (opening) -----------------------------------------------

            var attributes = [];

            // Adding atdraggable="" to make sure clicking on the button does not start the drag operation
            // Using the atdraggable attribute directly instead of the aria.utils.Mouse.DRAGGABLE_ATTRIBUTE
            // variable because aria.utils.Mouse may not be loaded yet.
            attributes.push('atdraggable=""');

            attributes.push('class="' + [
                'x' + skinnableClass + '_' + cssClassPostfix,
                'x' + skinnableClass + '_' + cfg.sclass + '_' + cssClassPostfix
            ].join(' ') + '"');

            attributes.push(ariaUtilsDelegate.getMarkup(delegateId));

            var openingTagMarkup = '<span ' + attributes.join(' ') + '>';

            out.write(openingTagMarkup);

            // button ----------------------------------------------------------

            var iconConfiguration = {
                icon : this._skinObj[skinIcon],
                waiAria : waiAria
            };

            if (label) {
                iconConfiguration.tooltip = label;
                iconConfiguration.label = label;
            }

            if (label || focusable) {
                iconConfiguration.role = 'button';
            }

            if (focusable) {
                iconConfiguration.tabIndex = 0;
            }

            var button = new ariaWidgetsIcon(iconConfiguration, this._context, this._lineNumber);

            out.registerBehavior(button);

            button.writeMarkup(out);

            // wrapper (closing) -----------------------------------------------

            out.write('</span>');

            // ---------------------------------------------------------- return

            return button;
        }

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


Question: // typeifyParsedLine attempts to cast numbers in the event to floats or ints

func typeifyParsedLine(pl map[string]string) map[string]interface{} {
	// try to convert numbers, if possible
	msi := make(map[string]interface{}, len(pl))
	for k, v := range pl {
		switch {
		case strings.Contains(v, "."):
			f, err := strconv.ParseFloat(v, 64)
			if err == nil {
				msi[k] = f
				continue
			}
		case v == "-":
			// no value, don't set a "-" string
			continue
		default:
			i, err := strconv.ParseInt(v, 10, 64)
			if err == nil {
				msi[k] = i
				continue
			}
		}
		msi[k] = v
	}
	return msi
}

func parseLine(line string) (cmd string, args string) {
  if idx := strings.Index(line, " "); idx > 0 {
    cmd = strings.ToUpper(line[:idx])
    args = strings.TrimSpace(line[idx+1:])
  } else {
    cmd = strings.ToUpper(line)
  }
  return
}

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


Question:
Returns whether or not the page is in the current section.
@param string|array $Section

public static function InSection($Section) {
      $Section = (array)$Section;
      foreach ($Section as $Name) {
         if (isset(self::$_Section[$Name]))
            return TRUE;
      }
      return FALSE;
   }

public function settings_page() {
		?>

<?php echo esc_html( self::get_page_title() ); ?>

		<form method="POST" action="options.php">
			<?php
			settings_fields( self::get_page_name() );
			do_settings_sections( self::get_page_name() );
			submit_button();
			?>
		</form>
		<?php
	}

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


Question:
Fetches the relationships between the columns in this table and the
give table
@param string $table
@return array

public function getTableRelationships($table) {
        $table = $this->connection->getTablePrefix() . Util::camelTo_($table);
        $relationships = array();
        foreach ($this->references as $columnName => $info) {
            if ($info['constraintName'] == 'PRIMARY' || $info['refTable'] != $table)
                    continue;
            $this->setupRelationship($columnName, $info['refColumn'],
                    $info['refTable'], $relationships, false);
        }
        foreach ($this->backReferences as $columnName => $infoArray) {
            foreach ($infoArray as $info) {
                if ($info['refTable'] != $table) continue;
                $this->setupRelationship($columnName, $info['refColumn'],
                        $info['refTable'], $relationships, true);
            }
        }
        return $relationships[$table];
    }

private function getBaseSelect($storeId, $type)
    {
        $connection = $this->getConnection();
        $select     = $connection->select();

        $select->from(['thesaurus' => $this->getMainTable()], [])
            ->join(
                ['terms' => $this->getTable(ThesaurusInterface::EXPANSION_TABLE_NAME)],
                'thesaurus.thesaurus_id = terms.thesaurus_id',
                []
            )
            ->join(
                ['store' => $this->getTable(ThesaurusInterface::STORE_TABLE_NAME)],
                'store.thesaurus_id = thesaurus.thesaurus_id',
                []
            )
            ->group(['thesaurus.thesaurus_id', 'terms.term_id'])
            ->where("thesaurus.type = ?", $type)
            ->where('thesaurus.is_active = 1')
            ->where('store.store_id IN (?)', [0, $storeId]);

        return $select;
    }

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


Question:
Start corona job tracker on the machine provided by using the corona
task tracker API.
@param jobConf The job configuration.
@param grant The grant that specifies the remote machine.
@return A boolean indicating success.
@throws InterruptedException

private boolean startRemoteJT(
    JobConf jobConf,
    ResourceGrant grant) throws InterruptedException {
    org.apache.hadoop.corona.InetAddress ttAddr =
      Utilities.appInfoToAddress(grant.appInfo);
    CoronaTaskTrackerProtocol coronaTT = null;
    try {
      coronaTT = jt.getTaskTrackerClient(ttAddr.getHost(), ttAddr.getPort());
    } catch (IOException e) {
      LOG.error("Error while trying to connect to TT at " + ttAddr.getHost() +
        ":" + ttAddr.getPort(), e);
      return false;
    }
    LOG.warn("Starting remote JT for " + attemptJobId
        + " on " + ttAddr.getHost());

    // Get a special map id for the JT task.
    Path systemDir = new Path(jt.getSystemDir());
    LOG.info("startRemoteJT:systemDir "+systemDir.toString());
    String jobFile = CoronaJobInProgress.getJobFile(systemDir, attemptJobId)
        .toString();
    LOG.info("startRemoteJT:jobFile " + jobFile);
    String splitClass = JobClient.RawSplit.class.getName();
    BytesWritable split = new BytesWritable();
    Task jobTask = new MapTask(
        jobFile, currentAttemptId, currentAttemptId.getTaskID().getId(),
        splitClass, split, 1, jobConf.getUser());
    CoronaSessionInfo info = new CoronaSessionInfo(jt.getSessionId(),
        jt.getJobTrackerAddress(), jt.getJobTrackerAddress());
    synchronized (this) {
      try {
        coronaTT.startCoronaJobTracker(jobTask, info);
      } catch (IOException e) {
        // Increment the attempt so that the older attempt will get an error
        // in reportRemoteCoronaJobTracker().
        incrementAttemptUnprotected();
        LOG.error("Error while performing RPC to TT at " + ttAddr.getHost() +
          ":" + ttAddr.getPort(), e);
        return false;
      }
    }

    // Now wait for the remote CJT to report its address.
    final long waitStart = System.currentTimeMillis();
    final long timeout = RemoteJTProxy.getRemotJTTimeout(jobConf);
    synchronized (this) {
      while (client == null) {
        LOG.warn("Waiting for remote JT to start on " + ttAddr.getHost());
        this.wait(1000);
        if (client == null &&
            System.currentTimeMillis() - waitStart > timeout) {
          // Increment the attempt so that the older attempt will get an error
          // in reportRemoteCoronaJobTracker().
          incrementAttemptUnprotected();
          LOG.warn("Could not start remote JT on " + ttAddr.getHost());
          return false;
        }
      }
    }
    return true;
  }

public void render() throws IOException {
		if (isDisposed()) {
			LOG.debug("Skipping render phase.");
			return;
		}

		try {
			// Check user context has been prepared
			if (getNewConversation() == null) {
				throw new IllegalStateException(
						"User context has not been prepared before the render phase");
			}

			prepareRender();

			UIContext uic = getUIContext();
			if (uic == null) {
				throw new IllegalStateException("No user context set for the render phase.");
			}

			UIContextHolder.pushContext(uic);
			prepareRequest();

			// Handle errors from the action phase now.
			if (havePropogatedError()) {
				handleError(getPropogatedError());
				return;
			}

			WComponent uiComponent = getUI();

			if (uiComponent == null) {
				throw new SystemException("No UI Component exists.");
			}

			Environment environment = uiComponent.getEnvironment();

			if (environment == null) {
				throw new SystemException("No WEnvironment exists.");
			}

			getInterceptor().attachResponse(getResponse());
			getInterceptor().preparePaint(getRequest());

			String contentType = getUI().getHeaders().getContentType();
			Response response = getResponse();
			response.setContentType(contentType);

			addGenericHeaders(uic, getUI());

			PrintWriter writer = getPrintWriter();
			getInterceptor().paint(new WebXmlRenderContext(writer, uic.getLocale()));

			// The following only matters for a Portal context
			String title = uiComponent instanceof WApplication ? ((WApplication) uiComponent).
					getTitle() : null;

			if (title != null) {
				setTitle(title);
			}
		} catch (Escape esc) {
			LOG.debug("Escape performed during render phase.");
			handleEscape(esc);
		} catch (Throwable t) {
			// We try not to let any exception propagate to container.
			String message = "Caught exception during render phase.";
			LOG.error(message, t);
			handleError(t);
		} finally {
			UIContextHolder.reset();
			dispose();
		}
	}

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


Question:
Send a POST request to the node table.

    This makes a new node for the participant, it calls:
        1. exp.get_network_for_participant
        2. exp.create_node
        3. exp.add_node_to_network
        4. exp.node_post_request

def create_node(participant_id):

    exp = experiment(session)

    # Get the participant.
    try:
        participant = models.Participant.\
            query.filter_by(id=participant_id).one()
    except NoResultFound:
        return error_response(error_type="/node POST no participant found",
                              status=403)

    # replace any duplicate assignments
    check_for_duplicate_assignments(participant)

    # Make sure the participant status is working
    if participant.status != "working":
        error_type = "/node POST, status = {}".format(participant.status)
        return error_response(error_type=error_type,
                              participant=participant)

    try:
        # execute the request
        network = exp.get_network_for_participant(participant=participant)

        if network is None:
            return Response(dumps({"status": "error"}), status=403)

        node = exp.create_node(
            participant=participant,
            network=network)

        assign_properties(node)

        exp.add_node_to_network(
            node=node,
            network=network)

        session.commit()

        # ping the experiment
        exp.node_post_request(participant=participant, node=node)
        session.commit()
    except:
        return error_response(error_type="/node POST server error",
                              status=403,
                              participant=participant)

    # return the data
    return success_response(field="node",
                            data=node.__json__(),
                            request_type="/node POST")

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:
通过识别jar的形式将其下的所有class添加到classSet集合中.
@param classLoader 类加载器
@param url URL实例
@param packageName 包名
@param packageDirName 包路径名

private void addClassByJar(ClassLoader classLoader, URL url, String packageName, String packageDirName) {
        // 从url中获取jar，然后从此jar包得到一个枚举类，然后进行迭代.
        JarFile jar;
        try {
            jar = ((JarURLConnection) url.openConnection()).getJarFile();
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                // 如果是以/开头的,则获取后面的字符串
                if (name.charAt(0) == '/') {
                    name = name.substring(1);
                }

                // 如果前半部分和定义的包名相同.
                if (name.startsWith(packageDirName)) {
                    int index = name.lastIndexOf('/');
                    // 如果以"/"结尾，则是一个包，获取包名并把"/"替换成"."
                    if (index != -1) {
                        packageName = name.substring(0, index).replace('/', '.');
                    }
                    // 如果可以迭代下去 并且是一个包,如果是一个.class文件 而且不是目录
                    if (index != -1 && name.endsWith(".class") && !entry.isDirectory()) {
                        // 去掉后面的".class" 获取真正的类名
                        String className = name.substring(packageName.length() + 1, name.length() - 6);
                        this.addClassByName(classLoader, packageName + '.' + className);
                    }
                }
            }
        } catch (IOException expected) {
            // 此处不打印堆栈信息.
            log.warn("从jar文件中读取class出错.");
        }
    }

def install(package_name):

    holodeck_path = util.get_holodeck_path()
    binary_website = "https://s3.amazonaws.com/holodeckworlds/"

    if package_name not in packages:
        raise HolodeckException("Unknown package name " + package_name)
    package_url = packages[package_name]

    print("Installing " + package_name + " at " + holodeck_path)
    install_path = os.path.join(holodeck_path, "worlds")
    binary_url = binary_website + util.get_os_key() + "_" + package_url
    _download_binary(binary_url, install_path)
    if os.name == "posix":
        _make_binary_excecutable(package_name, install_path)

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


Question:
ProgressBar::write

Write progress bar.

protected function write()
    {
        $this->updateSize();
        $this->writeStatus($this->units, $this->total, $this->columns, $this->columns);
    }

@Override
	public void open(int taskNumber, int numTasks) throws IOException {
		super.open(taskNumber, numTasks);
		this.wrt = this.charsetName == null ? new OutputStreamWriter(new BufferedOutputStream(this.stream, 4096)) :
				new OutputStreamWriter(new BufferedOutputStream(this.stream, 4096), this.charsetName);
	}

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


Question:
stop buffering and flush buffer text
{@inheritdoc}
@see Console::stopBuffer()

public function stopBuffer(bool $flush = true, $nl = false, $quit = false, array $opts = []): void
    {
        Console::stopBuffer($flush, $nl, $quit, $opts);
    }

private function unlisten(string $channel): Promise
    {
        \assert(isset($this->listeners[$channel]), "Not listening on that channel");

        $emitter = $this->listeners[$channel];
        unset($this->listeners[$channel]);

        if (!$this->handle) {
            $promise = new Success; // Connection already closed.
        } else {
            $promise = new Coroutine($this->send([$this->handle, "unlistenAsync"], $channel));
        }

        $promise->onResolve([$emitter, "complete"]);
        return $promise;
    }

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


Question: // Format formats the node.

func (node *SetExpr) Format(buf *TrackedBuffer) {
	// We don't have to backtick set variable names.
	if node.Name.EqualString("charset") || node.Name.EqualString("names") {
		buf.Myprintf("%s %v", node.Name.String(), node.Expr)
	} else if node.Name.EqualString(TransactionStr) {
		sqlVal := node.Expr.(*SQLVal)
		buf.Myprintf("%s %s", node.Name.String(), strings.ToLower(string(sqlVal.Val)))
	} else {
		buf.Myprintf("%s = %v", node.Name.String(), node.Expr)
	}
}

def changed(self):

        if not self.parents:
            return []
        return ChangedFileNodesGenerator([n for n in
                                self._get_paths_for_status('modified')], self)

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


Question: Returns the geometric attenuation term defined in equation 3

def _get_geometric_attenuation_term(self, C, mag, rrup):

        return (C["c5"] + C["c6"] * mag) * np.log(np.sqrt((rrup ** 2.) +
                                                          (C["c7"] ** 2.)))

public static <T extends ImageGray<T>> void down(Planar<T> input ,
												  int sampleWidth , Planar<T> output )
	{
		for( int band = 0; band < input.getNumBands(); band++ ) {
			down(input.getBand(band), sampleWidth, output.getBand(band));
		}
	}

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


Question: Looks for a label configured on the model and returns it  var Model = Backbone.Model.extend({ validation: { someAttribute: { required: true } },  labels: { someAttribute: 'Custom label' } });

function(attrName, model) {
      return (model.labels && model.labels[attrName]) || defaultLabelFormatters.sentenceCase(attrName, model);
    }

def blueprint(self, blueprint, **options):
        '''
        '''
        if blueprint.name in self.blueprints:
            assert self.blueprints[blueprint.name] is blueprint, \
                'A blueprint with the name "%s" is already registered.  ' \
                'Blueprint names must be unique.' % \
                (blueprint.name,)
        else:
            self.blueprints[blueprint.name] = blueprint
            self._blueprint_order.append(blueprint)
        blueprint.register(self, options)

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


Question:
Возвращает IP-адрес клиентского запроса

@return string|null

public static function getUserIp()
    {
        $ipHeaders = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        ];

        foreach ($ipHeaders as $ipHeader){
            if (array_key_exists($ipHeader, $_SERVER) === true){

                foreach (explode(',', $_SERVER[$ipHeader]) as $ip){

                    $ip = trim($ip);

                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                        return $ip;
                    }

                }

            }
        }

        return null;
    }

func (b *redisBroker) Connect() error {
	if b.pool != nil {
		return nil
	}

	var addr string

	if len(b.opts.Addrs) == 0 || b.opts.Addrs[0] == "" {
		addr = "redis://127.0.0.1:6379"
	} else {
		addr = b.opts.Addrs[0]

		if !strings.HasPrefix("redis://", addr) {
			addr = "redis://" + addr
		}
	}

	b.addr = addr

	b.pool = &redis.Pool{
		MaxIdle:     b.bopts.maxIdle,
		MaxActive:   b.bopts.maxActive,
		IdleTimeout: b.bopts.idleTimeout,
		Dial: func() (redis.Conn, error) {
			return redis.DialURL(
				b.addr,
				redis.DialConnectTimeout(b.bopts.connectTimeout),
				redis.DialReadTimeout(b.bopts.readTimeout),
				redis.DialWriteTimeout(b.bopts.writeTimeout),
			)
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}

	return nil
}

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


Question:
Build api call url.

@return string

public function buildUrl()
    {
        $url = $this->getApiUrl();
        if ($endpoint = $this->getEndpoint()) {
            $url .= $endpoint;
        }
        if ($id = $this->getId()) {
            $url .= '/'.$id;
        }
        $parameters = [];
        if ($include = $this->getInclude()) {
            if (is_array($include)) {
                $include = implode(',', $include);
            }
            $parameters['include'] = $include;
        }
        if ($filters = $this->getFilters()) {
            if (!empty($filters)) {
                $parameters['filter'] = $filters;
            }
        }
        if ($pageSize = $this->getPageSize()) {
            if (!empty($pageSize)) {
                $parameters['page'] = ['size' => $pageSize];
            }
        }
        if ($sort = $this->getSort()) {
            if (!empty($sort)) {
                $parameters['sort'] = $sort;
            }
        }
        if ($parameters) {
            $url .= '?'.http_build_query($parameters);
        }
        return $url;
    }

public function getComment($issue, $commentId, $expand = false)
    {
        $path = "/issue/{$issue}/comment/{$commentId}" . ($expand ? '?expand' : '');

        try {
            $result = $this->client->callGet($path);

            return new Comment($this->client, $result->getData());
        } catch (Exception $e) {
            throw new JiraException("Failed to get issue '{$issue}' commens", $e);
        }
    }

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


Question:
// processRemoveMultiObjectsResponse - parse the remove multi objects web service
// and return the success/failure result status for each object

func processRemoveMultiObjectsResponse(body io.Reader, objects []string, errorCh chan<- RemoveObjectError) {
	// Parse multi delete XML response
	rmResult := &deleteMultiObjectsResult{}
	err := xmlDecoder(body, rmResult)
	if err != nil {
		errorCh <- RemoveObjectError{ObjectName: "", Err: err}
		return
	}

	// Fill deletion that returned an error.
	for _, obj := range rmResult.UnDeletedObjects {
		errorCh <- RemoveObjectError{
			ObjectName: obj.Key,
			Err: ErrorResponse{
				Code:    obj.Code,
				Message: obj.Message,
			},
		}
	}
}

public function leave(ResponseInterface $response = null)
    {
        $this->ends = [
            'wt' => microtime(true),
            'mu' => memory_get_usage(),
            'pmu' => memory_get_peak_usage(),
        ];
        if ($response) {
            $this->response = [
                'headers' => $response->getHeaders(),
                'statusCode' => $response->getStatusCode(),
                'body' => (string)$response->getBody(),
            ];
        }
    }

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


Question: // SetSubnetGroupName sets the SubnetGroupName field's value.

func (s *UpdateSubnetGroupInput) SetSubnetGroupName(v string) *UpdateSubnetGroupInput {
	s.SubnetGroupName = &v
	return s
}

func LoadNetworks(source map[string]interface{}, version string) (map[string]types.NetworkConfig, error) {
	networks := make(map[string]types.NetworkConfig)
	err := Transform(source, &networks)
	if err != nil {
		return networks, err
	}
	for name, network := range networks {
		if !network.External.External {
			continue
		}
		switch {
		case network.External.Name != "":
			if network.Name != "" {
				return nil, errors.Errorf("network %s: network.external.name and network.name conflict; only use network.name", name)
			}
			if versions.GreaterThanOrEqualTo(version, "3.5") {
				logrus.Warnf("network %s: network.external.name is deprecated in favor of network.name", name)
			}
			network.Name = network.External.Name
			network.External.Name = ""
		case network.Name == "":
			network.Name = name
		}
		network.Extras = loadExtras(name, source)
		networks[name] = network
	}
	return networks, nil
}

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


Question:
// Next returns the next rune.
// It returns 0, false if the end of the text has been reached.

func (s *scanner) Next() (rune, bool) {
	if s.i >= len(s.s) {
		return 0, false
	}
	r := s.s[s.i]
	s.i++
	return r, true
}

def rdtxt_gos(go_file, prt):
        """"""
        goids_all = set()
        if not os.path.exists(go_file):
            raise RuntimeError("CAN NOT READ GO FILE: {FILE}\n".format(FILE=go_file))
        re_go = re.compile(r'(GO:\d{7})+?')
        re_com = re.compile(r'^\s*#')  # Lines starting with a '#' are comment lines and ignored
        with open(go_file) as ifstrm:
            for line in ifstrm:
                # Skip lines that are comments
                if re_com.search(line):
                    continue
                # Search for GO IDs on the line
                goids_found = re_go.findall(line)
                if goids_found:
                    goids_all.update(goids_found)
            if prt:
                prt.write("  {N} GO IDs READ: {TXT}\n".format(N=len(goids_all), TXT=go_file))
        return goids_all

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


Question:
Determines the ranking score for each node, allowing for a sorting of nodes
within one sphere.

@param  sphereNodes The nodes for which the score is to be calculated.
@exception  org.openscience.cdk.exception.CDKException  Thrown if something goes wrong.

private void calculateNodeScores(List<TreeNode> sphereNodes) throws CDKException {
        TreeNode treeNode = null;
        for (int i = 0; i < sphereNodes.size(); i++) {
            treeNode = (TreeNode) sphereNodes.get(i);
            treeNode.score += getElementRank(treeNode.symbol);
            if (treeNode.bondType <= 4) {
                treeNode.score += bondRankings[(int) treeNode.bondType];
            } else {
                throw new CDKException("Unknown bond type encountered in HOSECodeGenerator");
            }
        }
    }

public function validateSeedProducerCode(ErrorElement $errorElement, $object)
    {
        $code = $object->getSeedProducerCode();
        $container = $this->getConfigurationPool()->getContainer();
        $is_new = empty($object->getId());

        if (empty($code)) {
            // Check if organism is a seed producer (belongs to the seed_producers app circle)
            $app_circles = $container->get('librinfo_crm.app_circles');
            if ($app_circles->isInCircle($object, 'seed_producers') && !$is_new) {
                $errorElement
                    ->with('seedProducerCode')
                        ->addViolation('A seed producer code is required for seed producers')
                    ->end()
                ;
            }
        } else {
            $registry = $container->get('blast_core.code_generators');
            $codeGenerator = $registry->getCodeGenerator(Organism::class, 'seedProducerCode');
            if (!$codeGenerator->validate($code)) {
                $errorElement
                    ->with('seedProducerCode')
                        ->addViolation('Wrong format for seed producer code. It shoud be: ' . $codeGenerator::getHelp())
                    ->end()
                ;
            }
        }
    }

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


Question: Find template-file by path

def find_file(path)
			caller_path = caller_locations(4..4).first.path

			caller_dir =
				begin
					File.dirname(caller_path).sub(views_dir, '') if Tilt[caller_path]
				rescue LoadError
					nil
				end

			find_files(path, controller_dirs | Array(caller_dir))
				.find { |file| Tilt[file] }
		end

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

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


Question:
/*!
\static
Returns all subdirectories in a folder

static function findSubitems( $dir, $types = false, $fullPath = false, $includeHidden = false, $excludeItems = false )
    {
        if ( !$types )
            $types = 'dfl';
        $dirArray = array();
        if ( $handle = @opendir( $dir ) )
        {
            while ( ( $element = readdir( $handle ) ) !== false )
            {
                if ( $element === '.' || $element === '..' )
                    continue;
                if ( !$includeHidden && $element[0] === '.' )
                    continue;
                if ( $excludeItems && preg_match( $excludeItems, $element ) )
                    continue;
                if ( strpos( $types, 'd' ) === false && is_dir( $dir . '/' . $element ) )
                    continue;
                if ( strpos( $types, 'l' ) === false && is_link( $dir . '/' . $element ) )
                    continue;
                if ( strpos( $types, 'f' ) === false && is_file( $dir . '/' . $element ))
                    continue;
                if ( $fullPath )
                {
                    if ( is_string( $fullPath ) )
                        $dirArray[] = $fullPath . '/' . $element;
                    else
                        $dirArray[] = $dir . '/' . $element;
                }
                else
                    $dirArray[] = $element;
            }
            @closedir( $handle );
        }
        return $dirArray;
    }

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

        original_path = PurePath(name)

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

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

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

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

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

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


Question:
Return a new raw REST interface to network resources

        :rtype: :py:class:`ns1.rest.ipam.Networks`

def networks(self):

        import ns1.rest.ipam
        return ns1.rest.ipam.Networks(self.config)

def rewind_body(body, body_pos):

    body_seek = getattr(body, 'seek', None)
    if body_seek is not None and isinstance(body_pos, integer_types):
        try:
            body_seek(body_pos)
        except (IOError, OSError):
            raise UnrewindableBodyError("An error occurred when rewinding request "
                                        "body for redirect/retry.")
    elif body_pos is _FAILEDTELL:
        raise UnrewindableBodyError("Unable to record file position for rewinding "
                                    "request body during a redirect/retry.")
    else:
        raise ValueError("body_pos must be of type integer, "
                         "instead it was %s." % type(body_pos))

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


Question:
Retorna o objeto de conversão de identificadores de URL.

Caso objeto tenha sido definido pelo método, a classe {@see UriFormater}
será instanciada.

@return UriFormaterInterface

protected function getUriFormater() : UriFormaterInterface
    {
        if ($this->formater === null)
        {
            $this->formater = new UriFormater();
        }

        return $this->formater;
    }

private static Class<?> convertToObject(Class<?> type) {
        if (type == int.class) {
            return Integer.class;
        }
        else if (type == boolean.class) {
            return Boolean.class;
        }
        else if (type == byte.class) {
            return Byte.class;
        }
        else if (type == char.class) {
            return Character.class;
        }
        else if (type == short.class) {
            return Short.class;
        }
        else if (type == long.class) {
            return Long.class;
        }
        else if (type == float.class) {
            return Float.class;
        }
        else if (type == double.class) {
            return Double.class;
        }
        else if (type == void.class) {
            return Void.class;
        }
        else {
            return type;
        }
    }

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


Question: create image element, load image and set its size

function(source, width, height) {
      return this.put(new SVG.Image).load(source).size(width || 0, height || width || 0)
    }

public function setFileAvatar($file_avatar){
        if(!$this->setModified('file_avatar', $file_avatar)->isModified()){
            return $this;
        }
        $this->file_avatar = $file_avatar;
        return $this;
    }

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


Question:
Get the child details of this object

@access private

protected function trait_get_child_details() {
		$table = self::trait_get_child_database_table();

		if ($table === null) {
			return;
		}

		if (!isset($this->id) OR $this->id === null) {
			throw new \Exception('Could not fetch ' . $table . ' data: id not set');
		}

		$db = self::trait_get_database();
		$child_details = $db->get_row('SELECT * FROM ' . $db->quote_identifier($table) . ' WHERE ' . self::trait_get_parent_table_field_id() . '=?', [$this->id]);

		if ($child_details === null) {
			throw new \Exception('Could not fetch ' . $table . ' data: none found with id ' . $this->id);
		}

		$this->child_details = $child_details;
		$this->reset_dirty_fields();
	}

public function addCondition($name, $options)
    {
        if ($this instanceof DataAccessInterface) {
            $condition = ConditionFactory::factory($name, $options);
            $condition->setDecorator($this);
            $this->attachCondition($condition);
            return $this;
        }
    }

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


Question: // Delete deletes and item in the cache

func (c *Cache) Delete(_ context.Context, key dataloader.Key) bool {
	if _, found := c.c.Get(key.String()); found {
		c.c.Delete(key.String())
		return true
	}
	return false
}

protected function action($method, array $data = [], $flush = null)
    {
        $data = $this->data($data);

        $this->clearCache($flush);

        return $this->client->$method($data);
    }

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


Question:
generate the HTML for the page links only

@return	string	Markup for the pagination block

public function pages_render()
	{
		// no links if we only have one page
		if ($this->config['total_pages'] == 1)
		{
			return '';
		}

		$html = '';

		// calculate start- and end page numbers
		$start = $this->config['calculated_page'] - floor($this->config['num_links'] * $this->config['link_offset']);
		$end = $this->config['calculated_page'] + floor($this->config['num_links'] * ( 1 - $this->config['link_offset']));

		// adjust for the first few pages
		if ($start < 1)
		{
			$end -= $start - 1;
			$start = 1;
		}

		// make sure we don't overshoot the current page due to rounding issues
		if ($end < $this->config['calculated_page'])
		{
			$start++;
			$end++;
		}

		// make sure we don't overshoot the total
		if ($end > $this->config['total_pages'])
		{
			$start = max(1, $start - $end + $this->config['total_pages']);
			$end = $this->config['total_pages'];
		}

		for($i = intval($start); $i <= intval($end); $i++)
		{
			if ($this->config['calculated_page'] == $i)
			{
				$html .= str_replace(
				    '{link}',
				    str_replace(array('{uri}', '{page}'), array('#', $i), $this->template['active-link']),
				    $this->template['active']
				);
				$this->raw_results[] = array('uri' => '#', 'title' => $i, 'type' => 'active');
			}
			else
			{
				$html .= str_replace(
				    '{link}',
				    str_replace(array('{uri}', '{page}'), array($this->_make_link($i), $i), $this->template['regular-link']),
				    $this->template['regular']
				);
				$this->raw_results[] = array('uri' => $this->_make_link($i), 'title' => $i, 'type' => 'regular');
			}
		}

		return $html;
	}

public function check()
    {
        $this->pingBinFactory();

        $ipAddress = ip_address_from_hostname($this->target->hostname);

        $latency = $this->ping($ipAddress);

        $latencyFormatted = $latency ? "{$latency}ms" : 'error!';

        $this->target->setDisplay(
            "{$this->target->name} ({$latencyFormatted})"
        );

        if ($latency === false || $latency > $this->target->acceptedLatency) {
            $result = $this->makeResult(
                false,
                sprintf(
                    $this->target->getErrorMessage(),
                    $this->hosnameAndIp($this->target->hostname, $ipAddress),
                    $latency === false ? '[ping error]' : $latency,
                    $this->target->acceptedLatency
                )
            );
        } else {
            $result = $this->makeHealthyResult();
        }

        return $result->setValue($latency)->setValueHuman("{$latency}ms");
    }

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


Question:
Get the root item for the requested title

@param $title
@return Item

public function getRoot($title)
    {
        if (array_key_exists($title, $this->menu)) {
            return $this->menu[$title];
        }

        return null;
    }

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: Call the iteratee for all values of the object

function forEachValue (obj, iteratee) {
  Object.keys(obj).forEach((key) => iteratee(obj[key], key, obj))
}

public static <T> DiGraphIterator<T> getInstance(T root, Function<? super T, ? extends Collection<T>> edges)
    {
        return new DiGraphIterator<>(root, (y)->edges.apply(y).stream());
    }

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


Question:
// UpgradeSeriesValidate validates that the incoming arguments correspond to a
// valid series upgrade for the target machine.
// If they do, a list of the machine's current units is returned for use in
// soliciting user confirmation of the command.

func (mm *MachineManagerAPI) UpgradeSeriesValidate(
	args params.UpdateSeriesArgs,
) (params.UpgradeSeriesUnitsResults, error) {
	err := mm.checkCanRead()
	if err != nil {
		return params.UpgradeSeriesUnitsResults{}, err
	}

	results := make([]params.UpgradeSeriesUnitsResult, len(args.Args))
	for i, arg := range args.Args {
		tag := arg.Entity.Tag
		machine, err := mm.machineFromTag(tag)
		if err != nil {
			results[i].Error = common.ServerError(err)
			continue
		}

		if machine.IsManager() {
			results[i].Error = common.ServerError(
				errors.Errorf("%s is a controller and cannot be targeted for series upgrade", tag))
			continue
		}

		err = mm.validateSeries(arg.Series, machine.Series(), tag)
		if err != nil {
			results[i].Error = common.ServerError(err)
			continue
		}

		unitNames, err := mm.verifiedUnits(machine, arg.Series, arg.Force)
		if err != nil {
			results[i].Error = common.ServerError(err)
			continue
		}
		results[i].UnitNames = unitNames
	}

	return params.UpgradeSeriesUnitsResults{Results: results}, nil
}

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question:
create an instance of RedirectReponse if a success url is present, return null otherwise

@param  BaseForm                                        $form
@return null|\Symfony\Component\HttpFoundation\Response

protected function generateSuccessRedirect(BaseForm $form = null)
    {
        if (null !== $url = $this->retrieveSuccessUrl($form)) {
            return $this->generateRedirect($url);
        }

        return null;
    }

protected function notFound(ServerRequestInterface $request, ResponseInterface $response)
    {
        $notFound = $response
            ->withProtocolVersion($request->getProtocolVersion())
            ->withStatus(404);

        $notFound->getBody()->write('Not Found');

        return $notFound;
    }

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


Question:
\x1b[1mNAME\x1b[0m
        rm - Remove the znode

\x1b[1mSYNOPSIS\x1b[0m
        rm <path> [path] [path] ... [path]

\x1b[1mEXAMPLES\x1b[0m
        > rm /foo
        > rm /foo /bar

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)

def _clean_path(path):
        """"""
        path = path.replace('"', '')
        path = path.replace("'", '')
        # Replace ~ with /home/user
        path = os.path.expanduser(path)
        # Replace environment variables
        path = os.path.expandvars(path)
        # If the path is relative, assume it is relative to the config file directory
        if not os.path.isabs(path):
            path = os.path.join(config.global_config.path, path)
        # Clean path, e.g. replace /./ with /
        path = os.path.abspath(path)
        # Eliminate symbolic links
        path = os.path.realpath(path)
        return path

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


Question: Get logged-in user information.

function get(ignored, cb) {
  assert(this.$session);
  const ugRequest = {
    userId: this.$session.userId,
  };
  this.syscall('UserManager', 'get', ugRequest, (err, userInfo, curVersion) => {
    if (err) return cb(err);

    // Strip security-sensitive information.
    delete userInfo.hashedPassword;
    _.forEach(userInfo.securityEvents, (secEvt) => {
      if (secEvt.eventType === 'password_reset_requested') {
        delete secEvt.data.resetCode;
      }
    });

    return cb(null, userInfo, curVersion);
  });
}

func (s *DescribePermissionsInput) SetIamUserArn(v string) *DescribePermissionsInput {
	s.IamUserArn = &v
	return s
}

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


Question:
This method is called when there is a problem with the
connectAsync call further down the stack. This will just
be used as a pass through.

@param e

public void destroy(Exception e) {
        if (this.appCallback != null) {
            this.appCallback.destroy(e);
            this.appCallback = null;
        }
    }

@Process(actionType = CreateConnection.class)
    public void createConnection(final CreateConnection action, final Dispatcher.Channel channel) {
        create(action.getAddressTemplate(), action.getInstanceName(), action.getNewModel(),
                getModelsFor(action.getAddressTemplate()), channel);
    }

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


Question: // String returns the decision in human readable format

func (d Decision) String() string {
	if v, exists := decisionToString[d]; exists {
		return v
	}
	return ""
}

function _printItem (item) {
  switch(item.type) {
    case 'option':
      console.log(item.index + ': ' + item.label);
      break;
    case 'break':
      for (var breakString = ''; breakString.length < item.charCount;) {
        breakString += item.character;
      }

      console.log(breakString);
      break;
    case 'text':
      console.log(item.text);
      break;
    default:
      console.error('Invalid item type: ' + item.type);
      process.exit();
  }
}

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


Question: // Set is part of the flag.Value interface.

func (ttf *TabletTypeFlag) Set(v string) error {
	t, err := ParseTabletType(v)
	*ttf = TabletTypeFlag(t)
	return err
}

func (c *Clientset) SchedulingV1() schedulingv1.SchedulingV1Interface {
	return &fakeschedulingv1.FakeSchedulingV1{Fake: &c.Fake}
}

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


Question: Add a new field at once

protected function submitAddField()
    {
        $this->setSubmitted(null, $this->getParam());
        $this->validateComponent('field');
        $this->addField();
    }

public function down()
    {
        $results = '';
        foreach ($this->toArray() as $column => $attributes) {
            $results .= $this->createField($column, $attributes, 'remove');
        }

        return $results;
    }

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


Question:
Returns the HTML img tags to display the prefix of the current node.

@return string

protected function getPrefix()
  {
    $prefix = "";

    if(count($this->currSib))
    {
      $last = array_pop($this->currSib);

      foreach($this->currSib as $sibling)
      {
        $prefix .=  ($sibling) ? $this->getImage("tree_line.gif") : $this->getImage("tree_blank.png");
      }

      $prefix .= ($last) ? $this->getImage("tree_end.gif") : $this->getImage("tree_mid.gif");
    }

    return $prefix;
  }

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question:
数据XML编码
@param mixed $data 数据
@return string

public static function data_to_xml($data) {
        $xml = '';
        foreach ($data as $key => $val) {
            is_numeric($key) && $key = "item id=\"$key\"";
            $xml    .=  "<$key>";
            $xml    .=  ( is_array($val) || is_object($val)) ? self::data_to_xml($val)  : self::xmlSafeStr($val);
            list($key, ) = explode(' ', $key);
            $xml    .=  "</$key>";
        }
        return $xml;
    }

public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) {

        if (operation == null)
            throw new IllegalArgumentException(
                    "The operation parameter must be specified!");

        ShapeMarshaller marshaller = new ShapeMarshaller()
                .withAction(operation.getName())
                .withVerb(operation.getHttp().getMethod())
                .withRequestUri(operation.getHttp().getRequestUri());
        Input input = operation.getInput();
        if (input != null) {
            marshaller.setLocationName(input.getLocationName());
            // Pass the xmlNamespace trait from the input reference
            XmlNamespace xmlNamespace = input.getXmlNamespace();
            if (xmlNamespace != null) {
                marshaller.setXmlNameSpaceUri(xmlNamespace.getUri());
            }
        }
        if (!StringUtils.isNullOrEmpty(service.getTargetPrefix()) && Metadata.isNotRestProtocol(service.getProtocol())) {
            marshaller.setTarget(service.getTargetPrefix() + "." + operation.getName());
        }
        return marshaller;

    }

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


Question: // Update pushes exec statistics onto ch

func (c *execCollector) Update(ch chan<- prometheus.Metric) error {
	for _, m := range c.sysctls {
		v, err := m.Value()
		if err != nil {
			return err
		}

		ch <- prometheus.MustNewConstMetric(
			prometheus.NewDesc(
				namespace+"_"+m.name,
				m.description,
				nil, nil,
			), prometheus.CounterValue, v)
	}

	return nil
}

public function collStats($options)
    {
        $cmd = ['collStats' => $options['table']];
        $command = new Command($cmd);
        $this->log('cmd', 'collStats', $cmd);
        return $command;
    }

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


Question:
获取返回的Content-Disposition
@return string

public function getContentDisposition() {
        if (!isset($this->metadata[OSSHeaders::CONTENT_DISPOSITION])) {
            return null;
        }
        return $this->metadata[OSSHeaders::CONTENT_DISPOSITION];
    }

public void marshall(CodeContentDescription codeContentDescription, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(codeContentDescription.getTextContent(), TEXTCONTENT_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getCodeMD5(), CODEMD5_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getCodeSize(), CODESIZE_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getS3ApplicationCodeLocationDescription(), S3APPLICATIONCODELOCATIONDESCRIPTION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Returns a method name from the {@code android.content.res.Resources} class for array resource
binding, null if the element type is not supported.

private static @Nullable FieldResourceBinding.Type getArrayResourceMethodName(Element element) {
    TypeMirror typeMirror = element.asType();
    if (TYPED_ARRAY_TYPE.equals(typeMirror.toString())) {
      return FieldResourceBinding.Type.TYPED_ARRAY;
    }
    if (TypeKind.ARRAY.equals(typeMirror.getKind())) {
      ArrayType arrayType = (ArrayType) typeMirror;
      String componentType = arrayType.getComponentType().toString();
      if (STRING_TYPE.equals(componentType)) {
        return FieldResourceBinding.Type.STRING_ARRAY;
      } else if ("int".equals(componentType)) {
        return FieldResourceBinding.Type.INT_ARRAY;
      } else if ("java.lang.CharSequence".equals(componentType)) {
        return FieldResourceBinding.Type.TEXT_ARRAY;
      }
    }
    return null;
  }

public MultiFileResource add(File... files) {
		for (File file : files) {
			this.add(new FileResource(file));
		}
		return this;
	}

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


Question: // IDFromContext returns the unique id associated to the request if any.

func IDFromContext(ctx context.Context) (xid.ID, bool) {
	id, ok := ctx.Value(idKey).(xid.ID)
	return id, ok
}

public function context(ContextInterface $context)
    {
        if (!empty($this->vary)) {
            $this->varyValue = $context->get($this->vary);
        }
    }

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


Question: Violates rules not to use java.util.logging & that loggers should be private static final

public void printToStandardStream() throws FileNotFoundException {
        System.out.println("I'm gonna print to the command line"); // Violates rule not to write to standard streams
        System.err.println("I'm gonna print to the command line"); // Violates rule not to write to standard streams
        new SomeCustomException().printStackTrace(); // Violates rule not to write to standard streams

        new SomeCustomException().printStackTrace(new PrintStream("/some/file")); // this is okay, since it's a custom PrintStream
        new SomeCustomException().printStackTrace(new PrintWriter("/some/file")); // this is okay, since it's a custom PrintWriter
    }

public void infov(String format, Object param1) {
        if (isEnabled(Level.INFO)) {
            doLog(Level.INFO, FQCN, format, new Object[] { param1 }, null);
        }
    }

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


Question:
Add a file extension that shoul be parsed for BPMN 2.0 process definitions.

The deployment mechanism will parse ".bpmn" files by default.

public function addExtensions($extensions): self
    {
        $this->fileExtensions = \array_unique(\array_merge($this->fileExtensions, \array_map('strtolower', (array) $extensions)));

        return $this;
    }

def __create_translation_migration(self):

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

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


Question:
rendering row as a html

@return string

private function renderRowHtml()
    {
        $data = $this->getTable()->getData();
        $headers = $this->getTable()->getHeaders();
        $render = '';

        foreach ($data as $rowData) {
            $this->setActualRow($rowData);
            $rowRender = '';

            foreach ($headers as $name => $options) {
                $rowRender .= $this->getTable()->getHeader($name)->getCell()->render('html');
            }

            foreach ($this->decorators as $decorator) {
                $decorator->render('');
            }

            $render .= sprintf('<tr %s>%s</tr>', $this->getAttributes(), $rowRender);
            $this->clearVar();
        }
        return $render;
    }

public function getRow($sql, $params = null)
    {
        $stmt = $this->execute($sql, $params);

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

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


Question:
Fügt ein Property hinzu

added das Property, seine Setter und gegebenfalls auch einen Eintrag im Constructor

public function compile(GClass $gClass, $flags = 0x000000) {
    // das ist okay, wenn man getters oder setters oder den constructor adden will (imo)
    //if ($gClass->hasProperty($this->property->name)) {
    //  throw new \InvalidArgumentException('Property: '.$this->property->name. ' besteht bereits in Klasse '.$gClass);
    //}
    $this->createClassBuilder($gClass);

    $this->cProperty = $this->classBuilder->addProperty($this->property->name, $this->property->type);
    if ($this->property->upcaseName) {
      $this->cProperty->setUpcaseName($this->property->upcaseName);
    }

    if ($this->generateSetter) {
      $this->classBuilder->generateSetter($this->cProperty, NULL, ClassBuilder::INHERIT);
    }

    if ($this->generateGetter) {
      $this->classBuilder->generateGetter($this->cProperty, NULL, ClassBuilder::INHERIT);
    }

    if (($cs = $this->generateInConstructor) !== FALSE) {
      $constructor = $this->classBuilder->getConstructor(TRUE);

      if (!$constructor->hasParameter($this->property->name)) {
        $parameter = new GParameter($this->property->name,
                                    $this->property->type ? $this->property->type->getPHPHint() : NULL,
                                    $this->constructorDefaultValue
                                   );
        $constructor->addParameter($parameter, $this->generateInConstructor);

        if ($this->dependencyInjection === self::DEPENDENCY_INJECTION_CONSTRUCTOR) {
          if (!($this->property->type instanceof ObjectType) || !$this->property->type->hasClass()) {
            throw new \InvalidArgumentException('Wenn DependencyInjection CONSTRUCTOR ist, muss der property-type ein ObjectType sein mit einer Klasse. Type ist: '.Code::varInfo($this->property->type));
          }

          $objectValue = new Expression(sprintf('$%s ?: new %s()', $parameter->getName(), $this->property->type->getGClass()->getClassName()));
        } else {
          $objectValue = new AST\Variable($parameter->getName(), new AST\LType('Mixed'));
        }

        $constructor->appendBodyLines(array(
          $this->codeWriter->callSetter(
                                        new AST\Variable('this', new AST\LType('Object')),
                                        $this->cProperty->getUpcaseName(),
                                        $objectValue
                                       ).';'
          )
        );
      }
    }

    $this->classBuilder->generateDocBlocks();

    return $gClass;
  }

public function addVar($name, $type = '', $description = '')
    {
        $this->var_types[$name] = $type == '' ? $type : $type.' ';
        $this->var_descriptions[$name] = $description;
        return $this;
    }

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


Question:
错误的下标时显示的消息

@param index 下标
@param size 长度
@param desc 异常时的消息模板
@param params 参数列表
@return 消息

private static String badIndexMsg(int index, int size, String desc, Object... params) {
		if (index < 0) {
			return StrUtil.format("{} ({}) must not be negative", StrUtil.format(desc, params), index);
		} else if (size < 0) {
			throw new IllegalArgumentException("negative size: " + size);
		} else { // index >= size
			return StrUtil.format("{} ({}) must be less than size ({})", StrUtil.format(desc, params), index, size);
		}
	}

private static function _doResponse($type, $objects, $echoResponse, $format) {
        $ret = array();
        $ret['status'] = $type;
        if (is_array($objects)) {
            foreach ($objects as $k => $v) {
                $ret[$k] = $v;
            }
        } else {
            $ret[] = $objects;
        }

        switch ($format) {
            case 'xml':
                require_once 'XML/Serializer.php';
                $options = array(
                    "indent" => "    ",
                    "linebreak" => "\n",
                    "typeHints" => false,
                    "addDecl" => true,
                    "encoding" => "UTF-8",
                    "rootName" => "data",
//					"rootAttributes"  => array("version" => "0.91"),
                    "defaultTagName" => "item",
                    "attributesArray" => "_attributes"
                );

                $serializer = new \XML_Serializer($options);

                $rc = $serializer->serialize($ret);
                if ($rc !== TRUE) {

                }
                $ret = $serializer->getSerializedData();
                break;

            case 'json':
            default:
                $ret = json_encode($ret);
                break;
        }

        if ($echoResponse) {
            echo $ret;
        }
        return $ret;
    }

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


Question:
This action will:
- call the expired method that will extract all expired and elegible classifieds
- for each of them, trigger the expired event
( the mailer module will will bind this event with mailsend )

public function expiredAction()
	{
		$classifiedService = $this->getServiceLocator()->get('document.service.classified');

		try {
			$ids = $classifiedService->expired(3);
			$data = array(
				'status' => 'success',
				'message' => implode(", ", $ids)
			);
		} catch(\Exception $e) {
			$this->getResponse()
				->setStatusCode(Response::STATUS_CODE_500);
			$data = array(
				'status' => 'danger',
				'message' => $e->getMessage()
			);
		}

//         $viewModel = new ViewModel();
//         $viewModel->setTemplate('neobazaar/index/index');
//         return $viewModel;
		return new JsonModel($data);
	}

public function admin_init() {
		add_settings_section(
			'soter_general',
			'General Settings',
			[ $this, 'render_section_general' ],
			'soter'
		);

		add_settings_section(
			'soter_email',
			'Email Settings',
			[ $this, 'render_section_email' ],
			'soter'
		);

		add_settings_section(
			'soter_slack',
			'Slack Settings',
			[ $this, 'render_section_slack' ],
			'soter'
		);

		add_settings_field(
			'soter_should_nag',
			'Notification Frequency',
			[ $this, 'render_should_nag' ],
			'soter',
			'soter_general'
		);

		add_settings_field(
			'soter_ignored_plugins',
			'Ignored Plugins',
			[ $this, 'render_ignored_plugins' ],
			'soter',
			'soter_general'
		);

		add_settings_field(
			'soter_ignored_themes',
			'Ignored Themes',
			[ $this, 'render_ignored_themes' ],
			'soter',
			'soter_general'
		);

		add_settings_field(
			'soter_email_enabled',
			'Send Email Notifications',
			[ $this, 'render_email_enabled' ],
			'soter',
			'soter_email'
		);

		add_settings_field(
			'soter_email_address',
			'Email Address',
			[ $this, 'render_email_address' ],
			'soter',
			'soter_email'
		);

		add_settings_field(
			'soter_email_type',
			'Email Type',
			[ $this, 'render_email_type' ],
			'soter',
			'soter_email'
		);

		add_settings_field(
			'soter_slack_enabled',
			'Send Slack Notifications',
			[ $this, 'render_slack_enabled' ],
			'soter',
			'soter_slack'
		);

		add_settings_field(
			'soter_slack_url',
			'WebHook URL',
			[ $this, 'render_slack_url' ],
			'soter',
			'soter_slack'
		);
	}

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


Question: Split line into leading indent and main.

def split_trailing_indent(line, max_indents=None):
    """"""
    indent = ""
    while (
        (max_indents is None or max_indents > 0)
        and line.endswith((openindent, closeindent))
    ) or line.rstrip() != line:
        if max_indents is not None and (line.endswith(openindent) or line.endswith(closeindent)):
            max_indents -= 1
        indent = line[-1] + indent
        line = line[:-1]
    return line, indent

function _toggleIndentType() {
        var current = EditorManager.getActiveEditor(),
            fullPath = current && current.document.file.fullPath;

        Editor.setUseTabChar(!Editor.getUseTabChar(fullPath), fullPath);
        _updateIndentType(fullPath);
        _updateIndentSize(fullPath);
    }

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


Question:
Insted of using magic we define each method function.

@param  string $pattern
@param  array  $param
@return void

public function post(string $pattern, array $param) : void
    {
        $this->call('post', $pattern, $param[0], $param[1], $param);
    }

public function registerPaymentMethodMapper(PaymentMethodMapperInterface $paymentMethodMapper)
    {
        $paymentMethodMapper->setStandardParameter($this->standardParameter);
        $paymentMethodMapper->setSequenceNumberProvider($this->sequenceNumberProvider);
        $paymentMethodMapper->setUrlHmacGenerator($this->urlHmacGenerator);
        $this->registeredMethodMappers[$paymentMethodMapper->getName()] = $paymentMethodMapper;
    }

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


Question:
// Parse parses a timestamp string into a time.Time object.
// The only time this can fail is if Discord changes their timestamp format.

func (t Timestamp) Parse() (time.Time, error) {
	return time.Parse(time.RFC3339, string(t))
}

protected static function _getDateString($value)
    {
        $formatted = '';
        if (isset($value['year'], $value['month'], $value['day']) &&
            (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
        ) {
            $formatted .= sprintf('%d-%02d-%02d ', $value['year'], $value['month'], $value['day']);
        }

        if (isset($value['hour'])) {
            if (isset($value['meridian']) && (int)$value['hour'] === 12) {
                $value['hour'] = 0;
            }
            if (isset($value['meridian'])) {
                $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
            }
            $value += ['minute' => 0, 'second' => 0];
            if (is_numeric($value['hour']) && is_numeric($value['minute']) && is_numeric($value['second'])) {
                $formatted .= sprintf('%02d:%02d:%02d', $value['hour'], $value['minute'], $value['second']);
            }
        }

        return trim($formatted);
    }

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


Question:
Find the closest node or path to an the arbitrary path that is
        supplied down the tree from the given node. The mode argument
        may be either 'node' or 'path' which determines the return
        type.

def find(self, path, mode='node'):

        path = path.split('.') if isinstance(path, str) else list(path)
        item = self

        for child in path:
            escaped_child = sanitize_identifier(child, escape=False)
            matching_children = [c for c in item.children
                                 if child.endswith(c) or escaped_child.endswith(c)]
            matching_children = sorted(matching_children, key=lambda x: -len(x))
            if matching_children:
                item = item[matching_children[0]]
            else:
                continue
        return item if mode == 'node' else item.path

def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]

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


Question: // SetExports sets the Exports field's value.

func (s *ListExportsOutput) SetExports(v []*Export) *ListExportsOutput {
	s.Exports = v
	return s
}

def set_output(self,filename,pass_to_command_line=True):

    self.__output = filename
    if pass_to_command_line:
      self.add_var_opt('output', filename)
    self.add_output_file(filename)

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


Question: Get the root directory for the application.

def get_root_path():
    """"""
    return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))

def process
      FileUtils.mkdir_p(output_path.dirname)
      output_path.open('w') do |f|
        f.write render
      end
    end

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


Question:
Set whether the server should be hidden from the public server list.
Only available to Admin.
@param int $visibility 0: visible, 1: always hidden, 2: hidden from nations
@param bool $multicall
@return bool
@throws InvalidArgumentException

function setHideServer($visibility, $multicall = false)
    {
        if (!is_int($visibility) || $visibility < 0 || $visibility > 2) {
            throw new InvalidArgumentException('visibility = ' . print_r($visibility, true));
        }

        return $this->execute(ucfirst(__FUNCTION__), array($visibility), $multicall);
    }

protected function getPermissionsRole()
    {
        $arguments = $this->getArguments();

        if (count($arguments) < 2) {
            $this->errorAndExit($this->text('Invalid command'));
        }

        $role_id = array_shift($arguments);

        if (!is_numeric($role_id)) {
            $this->errorAndExit($this->text('Invalid argument'));
        }

        $role = $this->role->get($role_id);

        if (!isset($role['permissions'])) {
            $this->errorAndExit($this->text('Unexpected result'));
        }

        return array($role_id, $role['permissions'], $arguments);
    }

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


Question:
Template -case- tag handler
@return string
@param $node array

protected function _case(array $node) {
		$attrib=$node['@attrib'];
		unset($node['@attrib']);
		return
			'<?php case '.(preg_match('/\{\{(.+?)\}\}/',$attrib['value'])?
				$this->token($attrib['value']):
				Base::instance()->stringify($attrib['value'])).': ?>'.
				$this->build($node).
			'<?php '.(isset($attrib['break'])?
				'if ('.$this->token($attrib['break']).') ':'').
				'break; ?>';
	}

function renderTemplate(type) {
    var lcType = lodash.lowerCase(type);
    if (lodash.size(stats[lcType])) {
      return statsTemplate({
        title: '### ' + type,
        items: output(lcType)
      });
    } else {
      return '';
    }
  }

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


Question: Offside instance id Offside instance private methods

function() {

                    // beforeOpen callback
                    offsideSettings.beforeOpen();

                    // Turn on CSS transitions on first interaction with an Offside instance
                    if ( firstInteraction ) {
                        firstInteraction = false;
                        turnOnCssTransitions();
                    }

                    // If another Offside instance is already open,
                    // close it before going on
                    closeAll();

                    // Set global body active class for current Offside instance
                    addClass( body, offsideBodyOpenClass );
                    addClass( body, offsideBodyOpenSideClass );

                    // Add Offside instance open class
                    addClass( offside, offsideOpenClass );

                    // Update open Offside instances tracker
                    openOffsidesId.push( id );

                    // afterOpen callback
                    offsideSettings.afterOpen();
                }

public function enable(User $user, $area)
    {
        $area = app(AreaManager::class)->getById($area);
        request()->session()->set('return_url', request()->headers->get('referer'));
        return $this->processor->enable($this, $user, $area);
    }

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


Question:
Babbles like a user
    Syntax: {command} [nick] [--length <1|2>] [--start <word>]

def cmd(send, msg, args):

    parser = arguments.ArgParser(args['config'])
    parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
    parser.add_argument('--length', type=int, choices=[1, 2], default=2)
    parser.add_argument('--start', nargs='*')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    if args['db'].query(Babble).count():
        send(build_msg(args['db'], cmdargs.speaker, cmdargs.length, cmdargs.start))
    else:
        send("Please run ./scripts/gen_babble.py to initialize the babble cache")

def run(cmd, descr=None, data=None, checks=None, region=None, log_error=True,
        log_stdout=False, env=None):

    if descr:
      descr = _descr_str(descr, data, region)
      logger.debug(descr)
    cmd_id = diagnostics.start_cmd(cmd, descr or "", data)
    try:
        logger_cl.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, six.string_types) else cmd)
        _do_run(cmd, checks, log_stdout, env=env)
    except:
        diagnostics.end_cmd(cmd_id, False)
        if log_error:
            logger.exception()
        raise
    finally:
        diagnostics.end_cmd(cmd_id)

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


public static Long getPropertyLong(Class<?> aClass, String key,  long aDefault)
	{
		return getSettings().getPropertyLong(aClass, key, aDefault);
	}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
十六进制转二进制

@param bool $hex

@return string

private function hex2bin($hex = false)
    {
        $ret = $hex !== false && preg_match('/^[0-9a-fA-F]+$/i', $hex) ? pack("H*", $hex) : false;
        return $ret;
    }

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

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


Question: /* - Functions - Utils

function APIRequest(method, url) {
	var data, callback, opts, req, headers = messageHeaders(this);
	callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) );

	if (isNode) {
		opts = URL.parse(url);
		opts.method = method;
		opts.headers = headers;

		req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) {
			var chunks = [];
			res.on('data', function(c) { chunks[chunks.length] = c; });
			res.once('end', function() {
				chunks = Buffer.concat(chunks);
				Zlib.gunzip(chunks, function(err, uc) {
					if (!err) uc = uc.toString();
					try { res.body = JSON.parse(uc || chunks); } catch(e) {}
					return callback(null, res);
				});
			});
		});
		if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8");
		if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
		if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' );
		req.end();

		return req.once('error', function(e) { return callback(e.message); });
	}

	req = new XMLHttpRequest();
	req.open(method.toUpperCase(), url, true);
	for (var key in headers) {
		req.setRequestHeader(key, headers[key]);
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			req.statusCode = req.status;
			req.statusMessage = req.statusText;
			try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); }
			callback(null, req);
		}
	};
	if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
	if (data) return req.send( data.result ? data.result : JSON.stringify(data) );
	req.send(null);
}

def versions(mode=None, add_pckg=None, ncol=4):

    """
    # Issue warning
    mesg = ("\n    Func `versions` is deprecated and will " +
            "be removed; use Class `Versions` instead.")
    warnings.warn(mesg, DeprecationWarning)

    return Versions(add_pckg, ncol)

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


Question:
stores a new target.
        :param targetId: the target to store.
        :return:

def put(self, targetId):

        json = request.get_json()
        if 'hinge' in json:
            logger.info('Storing target ' + targetId)
            if self._targetController.storeFromHinge(targetId, json['hinge']):
                logger.info('Stored target ' + targetId)
                return None, 200
            else:
                return None, 500
        else:
            return None, 400

def build_collection_query_object(name, additional_parameters, *args)
    root = "/#{name.to_s}"
    if args.empty?
      #nothing to add
    elsif args.size == 1
      if args.first.to_s =~ /\d+/
        id_metadata = find_id_metadata(name.to_s)
        root << build_id_path(args.first, id_metadata)
      else
        root << "(#{args.first})"
      end
    else
      root << "(#{args.join(',')})"
    end
    QueryBuilder.new(root, additional_parameters)
  end

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


Question:
Retrieve a club

@link    https://strava.github.io/api/v3/clubs/#get-details
@param   int $id
@return  array
@throws  Exception

public function getClub($id)
    {
        try {
            return $this->service->getClub($id);
        } catch (ServiceException $e) {
            throw new ClientException('[SERVICE] ' . $e->getMessage());
        }
    }

public function params($params) {

		if(false === is_array($params)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		$this -> params = $params;

		return $this;
	}

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


Question:
By invitation action, that it can executes the "by_invitation" specification.

@param Request $request   The request
@param string  $userClass Extra parameter that contains the user type

@return \Symfony\Component\HttpFoundation\JsonResponse

public function byInvitationAction(Request $request, $userClass)
    {
        $invitationToken = $request->query->get('token');
        try {
            // we need to know if the invitation token given exists in
            // database, in case that it isn't, it throws 404.
            $user = $this->get('bengor_user.' . $userClass . '.by_invitation_token_query')->__invoke(
                new UserOfInvitationTokenQuery($invitationToken)
            );
        } catch (UserDoesNotExistException $exception) {
            return new JsonResponse(null, 404);
        } catch (UserTokenExpiredException $exception) {
            return new JsonResponse(null, 404);
        } catch (\InvalidArgumentException $exception) {
            return new JsonResponse(null, 404);
        }

        $form = $this->get('form.factory')->createNamedBuilder('', SignUpByInvitationType::class, null, [
            'roles'            => $this->getParameter('bengor_user.' . $userClass . '_default_roles'),
            'invitation_token' => $invitationToken,
            'csrf_protection'  => false,
        ])->getForm();

        $form->handleRequest($request);
        if ($form->isValid()) {
            $commandBus = $this->get('bengor_user.' . $userClass . '.api_command_bus');

            try {
                $commandBus->handle(
                    $form->getData()
                );
                $commandBus->handle(
                    new LogInUserCommand(
                        $user['email'],
                        $form->getData()->password()
                    )
                );
            } catch (UserDoesNotExistException $exception) {
                return new JsonResponse(null, 404);
            } catch (UserInactiveException $exception) {
                return new JsonResponse(null, 404);
            } catch (UserPasswordInvalidException $exception) {
                return new JsonResponse('Bad credentials', 400);
            } catch (UserAlreadyExistException $exception) {
                return new JsonResponse('Bad credentials', 400);
            }
            $token = $this->get('lexik_jwt_authentication.encoder.default')->encode(['email' => $user['email']]);

            return new JsonResponse(['token' => $token]);
        }

        return new JsonResponse(FormErrorSerializer::errors($form), 400);
    }

public function boot(Application $app)
    {
        $app->flush();

        /* @var $routes \Symfony\Component\Routing\RouteCollection */
        $routes = $app['routes'];

        /* @var $route \Silex\Route */
        foreach ($routes->getIterator() as $id => $route) {
            $path = $route->getPath();

            $headers = implode(',', [
                'Authorization',
                'Accept',
                'X-Request-With',
                'Content-Type',
                'X-Session-Token',
                'X-Hmac-Hash',
                'X-Time',
                'X-Url'
            ]);

            /* @var $controller \Silex\Controller */
            $controller = $app->match(
                $path,
                function () use ($headers) {
                    return new Response(
                        null,
                        204,
                        [
                            "Allow" => "GET,POST,PUT,DELETE",
                            "Access-Control-Max-Age" => 84600,
                            "Access-Control-Allow-Origin" => "*",
                            "Access-Control-Allow-Credentials" => "false",
                            "Access-Control-Allow-Methods" => "GET,POST,PUT,DELETE",
                            "Access-Control-Allow-Headers" => $headers
                        ]
                    );
                }
            );

            $controller->method('OPTIONS');

            /* @var $controllerRoute \Silex\Route */
            $controllerRoute = $controller->getRoute();
            $controllerRoute->setCondition($route->getCondition());
            $controllerRoute->setSchemes($route->getSchemes());
            $controllerRoute->setMethods('OPTIONS');
        }
    }

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


Question: // CheckVersion is used to check if the ProtocolVersion is valid

func (c *Config) CheckVersion() error {
	if c.ProtocolVersion < ProtocolVersionMin {
		return fmt.Errorf("Protocol version '%d' too low. Must be in range: [%d, %d]",
			c.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
	} else if c.ProtocolVersion > ProtocolVersionMax {
		return fmt.Errorf("Protocol version '%d' too high. Must be in range: [%d, %d]",
			c.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
	}
	return nil
}

func newGWMetaV1() (gwMeta gwMetaV1) {
	gwMeta = gwMetaV1{}
	gwMeta.Version = gwMetaVersion
	gwMeta.Format = gwMetaFormat
	return gwMeta
}

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


Question:
@param mixed $offset

@return bool

public function offsetExists($offset)
  {
    if (!$this->container instanceof ArrayAccess)
    {
      $this->iteratorToList();
    }

    return $this->container->offsetExists($offset);
  }

func (m *Millipede) getPadding(i uint64) string {
	if len(m.paddingOffsets) == 0 {
		m.paddingOffsets = append(m.paddingOffsets, "")
		//m.paddingOffsets = make([]string)
		if m.Curve > 0 {
			for n := uint64(1); n < m.Curve*2; n++ {
				size := int(math.Min(float64(n%(m.Curve*2)), float64(m.Curve*2-n%(m.Curve*2))))
				m.paddingOffsets = append(m.paddingOffsets, strings.Repeat(" ", size))
			}

			// --opposite support
			if m.Opposite {
				m.paddingOffsets = append(m.paddingOffsets[m.Curve:], m.paddingOffsets[:m.Curve]...)
			}
		}
	}
	if len(m.paddingOffsets) > 0 && m.Curve > 0 {
		return m.paddingOffsets[(m.Steps+i)%(m.Curve*2)]
	}
	return ""
}

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


Question:
Creates MavenResolvedArtifact based on ArtifactResult.

@param artifactResult
@return

static MavenResolvedArtifact fromArtifactResult(final ArtifactResult artifactResult) {
        final Artifact artifact = artifactResult.getArtifact();
        final DependencyNode root = artifactResult.getRequest().getDependencyNode();

        // SHRINKRES-143 lets ignore invalid scope
        ScopeType scopeType = ScopeType.RUNTIME;
        try {
            scopeType = ScopeType.fromScopeType(root.getDependency().getScope());
        } catch (IllegalArgumentException e) {
            // let scope be RUNTIME
            log.log(Level.WARNING, "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>",
                    new Object[] { root.getDependency().getScope(), root.getDependency().getArtifact() });
        }

        final List<DependencyNode> children = root.getChildren();
        final boolean optional = root.getDependency().isOptional();
        return new MavenResolvedArtifactImpl(artifact, scopeType, children, optional);
    }

def resources_by_type(ast)
      raise_unless_xpath!(ast)
      result = Hash.new { |hash, key| hash[key] = Array.new }
      find_resources(ast).each do |resource|
        result[resource_type(resource)] << resource
      end
      result
    end

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


Question:
Create service

@param ServiceLocatorInterface $serviceLocator
@return mixed

public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /** @var \GkSmarty\ModuleOptions $options */
        $options = $serviceLocator->get('GkSmarty\ModuleOptions');
        $smartyManagerOptions = $options->getHelperManager();
        $smartyManagerConfigs = isset($smartyManagerOptions['configs']) ? $smartyManagerOptions['configs'] : array();

        $zfManager = $serviceLocator->get('ViewHelperManager');
        $smartyManager = new HelperPluginManager(new Config($smartyManagerOptions));
        $smartyManager->setServiceLocator($serviceLocator);
        $smartyManager->addPeeringServiceManager($zfManager);

        foreach ($smartyManagerConfigs as $configClass) {
            if (is_string($configClass) && class_exists($configClass)) {
                $config = new $configClass;

                if (!$config instanceof ConfigInterface) {
                    throw new Exception\RuntimeException(
                        sprintf(
                            'Service manager configuration classes must implement %s; received %s',
                            'Zend\ServiceManager\ConfigInterface',
                            is_object($configClass) ? get_class($configClass) : gettype($configClass)
                        )
                    );
                }

                $config->configureServiceManager($smartyManager);
            }
        }

        return $smartyManager;
    }

func ResourceLocation(getter ResourceGetter, rt http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {
	// Allow ID as "podname" or "podname:port" or "scheme:podname:port".
	// If port is not specified, try to use the first defined port on the pod.
	scheme, name, port, valid := utilnet.SplitSchemeNamePort(id)
	if !valid {
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid pod request %q", id))
	}
	// TODO: if port is not a number but a "(container)/(portname)", do a name lookup.

	pod, err := getPod(getter, ctx, name)
	if err != nil {
		return nil, nil, err
	}

	// Try to figure out a port.
	if port == "" {
		for i := range pod.Spec.Containers {
			if len(pod.Spec.Containers[i].Ports) > 0 {
				port = fmt.Sprintf("%d", pod.Spec.Containers[i].Ports[0].ContainerPort)
				break
			}
		}
	}

	if err := proxyutil.IsProxyableIP(pod.Status.PodIP); err != nil {
		return nil, nil, errors.NewBadRequest(err.Error())
	}

	loc := &url.URL{
		Scheme: scheme,
	}
	if port == "" {
		loc.Host = pod.Status.PodIP
	} else {
		loc.Host = net.JoinHostPort(pod.Status.PodIP, port)
	}
	return loc, rt, nil
}

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


Question:
Checks the readOnly fields and sets error in event if needed

@param ConstraintEventSchema $event event class

@return void

public function checkVersionField(ConstraintEventSchema $event)
    {
        if (!$this->isVersioningService()) {
            return;
        }

        $data = $event->getElement();

        // get the current record
        if ($currentRecord = $this->utils->getCurrentEntity([self::FIELD_NAME])) {
            $userVersion = $this->getUserVersion($data);
            $storedVersion = $this->getVersionFromObject($currentRecord);
            if ($userVersion !== $storedVersion) {
                $event->addError(
                    sprintf(
                        'The value you provided does not match current version of the document. '.
                        'See the \'%s\' header in this response to determine current version.',
                        self::HEADER_NAME
                    ),
                    self::FIELD_NAME
                );

                // store version for response header
                $this->version = $storedVersion;
            }
        }
    }

private function validate()
    {
        if (!array_key_exists('type', $this->properties)) {
            throw new StatusException(sprintf('Key %s in %s missing', 'type', __CLASS__), 100, null);
        }

        $type = $this->properties['type'];

        // the type specified must be valid
        if (!in_array($this->properties['type'], $this->types)) {
            throw new StatusException('The type specified is invalid', 100, null);
        }

        switch ($type) {
            case StatusInterface::TYPE_INITIAL:
            case StatusInterface::TYPE_EXCEPTION:
                $mandatoryKeys = ['name'];
                break;

            default:
                $mandatoryKeys = ['name', 'transitions_from', 'transitions_to'];
                break;
        }

        foreach ($mandatoryKeys as $key) {
            if (!array_key_exists($key, $this->properties)) {
                throw new StatusException(sprintf('Key %s in %s missing', $key, __CLASS__), 100, null);
            }
        }

        if (StatusInterface::TYPE_INITIAL != $type && StatusInterface::TYPE_EXCEPTION != $type) {
            $keysMustBeArray = ['transitions_from', 'transitions_to'];
            foreach ($keysMustBeArray as $key) {
                if (!is_array($this->properties[$key])) {
                    throw new StatusException(sprintf('Key %s is not an array', $key), 100, null);
                }
            }
        }
    }

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