Question: //ReMapAll will re-apply all port mappings

func (pm *PortMapper) ReMapAll() {
	pm.lock.Lock()
	defer pm.lock.Unlock()
	logrus.Debugln("Re-applying all port mappings.")
	for _, data := range pm.currentMappings {
		containerIP, containerPort := getIPAndPort(data.container)
		hostIP, hostPort := getIPAndPort(data.host)
		if err := pm.AppendForwardingTableEntry(data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
			logrus.Errorf("Error on iptables add: %s", err)
		}
	}
}

def reset
      self.adapter        = DEFAULT_ADAPTER
      self.endpoint       = DEFAULT_ENDPOINT
      self.format         = DEFAULT_FORMAT
      self.user_agent     = DEFAULT_USER_AGENT
      self.proxy          = DEFAULT_PROXY
      self.debug          = DEFAULT_DEBUG
    end

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


Question:
:calls: `GET /repos/:owner/:repo/traffic/popular/referrers <https://developer.github.com/v3/repos/traffic/>`_
        :rtype: :class:`list` of :class:`github.Referrer.Referrer`

def get_top_referrers(self):

        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/traffic/popular/referrers"
        )
        if isinstance(data, list):
            return [
                github.Referrer.Referrer(self._requester, headers, item, completed=True)
                for item in data
            ]

func ConvertWorkItemLinkTypeFromModel(request *http.Request, modelLinkType link.WorkItemLinkType) app.WorkItemLinkTypeSingle {
	spaceTemplateRelatedURL := rest.AbsoluteURL(request, app.SpaceTemplateHref(modelLinkType.SpaceTemplateID.String()))
	spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(space.SystemSpace.String()))

	topologyStr := modelLinkType.Topology.String()
	var converted = app.WorkItemLinkTypeSingle{
		Data: &app.WorkItemLinkTypeData{
			Type: link.EndpointWorkItemLinkTypes,
			ID:   &modelLinkType.ID,
			Attributes: &app.WorkItemLinkTypeAttributes{
				Name:               &modelLinkType.Name,
				Description:        modelLinkType.Description,
				Version:            &modelLinkType.Version,
				CreatedAt:          &modelLinkType.CreatedAt,
				UpdatedAt:          &modelLinkType.UpdatedAt,
				ForwardName:        &modelLinkType.ForwardName,
				ForwardDescription: modelLinkType.ForwardDescription,
				ReverseName:        &modelLinkType.ReverseName,
				ReverseDescription: modelLinkType.ReverseDescription,
				Topology:           &topologyStr,
			},
			Relationships: &app.WorkItemLinkTypeRelationships{
				Space:         app.NewSpaceRelation(space.SystemSpace, spaceRelatedURL),
				SpaceTemplate: app.NewSpaceTemplateRelation(modelLinkType.SpaceTemplateID, spaceTemplateRelatedURL),
			},
		},
	}
	return converted
}

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


Question: predicate: iri | rdfType

def predicate_to_IRI(self, predicate: ShExDocParser.PredicateContext) -> ShExJ.IRIREF:

        if predicate.iri():
            return self.iri_to_iriref(predicate.iri())
        else:
            return RDF_TYPE

def rk_create(self, im, im_type, timeout=60):

        params = {
            'typeid': im_type,
            'timeout': timeout,
        }
        params.update(self.base_params)
        files = {'image': ('check_code.png', im)}
        r = requests.post('http://api.ruokuai.com/create.json', data=params, files=files, headers=self.headers)
        return r.json()

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


Question:
Quits the Application.

        :param exit_code: Exit code.
        :type exit_code: int
        :param event: QEvent.
        :type event: QEvent

def quit(self, exit_code=0, event=None):

        # --- Running on_close components methods. ---
        for component in reversed(self.__components_manager.list_components()):
            interface = self.__components_manager.get_interface(component)
            if not interface:
                continue

            if not interface.activated:
                continue

            if not hasattr(interface, "on_close"):
                continue

            if not interface.on_close():
                event and event.ignore()
                return

        # Storing current layout.
        self.__layouts_manager.store_startup_layout()
        self.__settings.settings.sync()

        # Stopping worker threads.
        for worker_thread in self.__worker_threads:
            LOGGER.debug("> Stopping worker thread: '{0}'.".format(worker_thread))
            if not worker_thread.isFinished():
                worker_thread.quit()
            worker_thread.wait()

        foundations.verbose.remove_logging_handler(self.__logging_file_handler)
        foundations.verbose.remove_logging_handler(self.__logging_session_handler)
        # foundations.verbose.remove_logging_handler(self.__logging_console_handler)

        # Stopping the Application timer.
        self.__timer.stop()
        self.__timer = None

        self.deleteLater()
        event and event.accept()

        exit(exit_code)

def toogle_breakpoint(self, line_number=None, condition=None,
                          edit_condition=False):
        """"""
        if not self.editor.is_python_like():
            return
        if line_number is None:
            block = self.editor.textCursor().block()
        else:
            block = self.editor.document().findBlockByNumber(line_number-1)
        data = block.userData()
        if not data:
            data = BlockUserData(self.editor)
            data.breakpoint = True
        elif not edit_condition:
            data.breakpoint = not data.breakpoint
            data.breakpoint_condition = None
        if condition is not None:
            data.breakpoint_condition = condition
        if edit_condition:
            condition = data.breakpoint_condition
            condition, valid = QInputDialog.getText(self.editor,
                                                    _('Breakpoint'),
                                                    _("Condition:"),
                                                    QLineEdit.Normal,
                                                    condition)
            if not valid:
                return
            data.breakpoint = True
            data.breakpoint_condition = str(condition) if condition else None
        if data.breakpoint:
            text = to_text_string(block.text()).strip()
            if len(text) == 0 or text.startswith(('#', '"', "'")):
                data.breakpoint = False
        block.setUserData(data)
        self.editor.sig_flags_changed.emit()
        self.editor.sig_breakpoints_changed.emit()

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


Question:
Creates a NumberMap for Integers.

@param <K>
@return NumberMap<K, Integer>

public static <K> NumberMap<K, Integer> newIntegerMap() {
		return new NumberMap<K, Integer>() {
			@Override
			public void add(K key, Integer addend) {
				put(key, containsKey(key) ? (get(key) + addend) : addend);
			}
			@Override
			public void sub(K key, Integer subtrahend) {
				put(key, (containsKey(key) ? get(key) : 0) - subtrahend);
			}
		};
	}

func (i *GetWAFRuleStatusesInput) formatFilters() map[string]string {
	input := i.Filters
	result := map[string]string{}
	pairings := map[string]interface{}{
		"filter[status]":           input.Status,
		"filter[rule][accuracy]":   input.Accuracy,
		"filter[rule][maturity]":   input.Maturity,
		"filter[rule][message]":    input.Message,
		"filter[rule][revision]":   input.Revision,
		"filter[rule][rule_id]":    input.RuleID,
		"filter[rule][tags]":       input.TagID,
		"filter[rule][tags][name]": input.TagName,
		"filter[rule][version]":    input.Version,
		"include":                  input.Tags,
		"page[size]":               input.MaxResults,
		"page[number]":             input.Page, // starts at 1, not 0
	}
	// NOTE: This setup means we will not be able to send the zero value
	// of any of these filters. It doesn't appear we would need to at present.
	for key, value := range pairings {
		switch t := reflect.TypeOf(value).String(); t {
		case "string":
			if value != "" {
				result[key] = value.(string)
			}
		case "int":
			if value != 0 {
				result[key] = strconv.Itoa(value.(int))
			}
		case "[]int":
			// convert ints to strings
			toStrings := []string{}
			values := value.([]int)
			for _, i := range values {
				toStrings = append(toStrings, strconv.Itoa(i))
			}
			// concat strings
			if len(values) > 0 {
				result[key] = strings.Join(toStrings, ",")
			}
		}
	}
	return result
}

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


Question:
Predict next action by Q-Learning.

        Args:
            state_key:          The key of state in `self.t+1`.
            next_action_list:   The possible action in `self.t+1`.

        Returns:
            The key of action.

def predict_next_action(self, state_key, next_action_list):
        '''

        '''
        if self.q_df is not None:
            next_action_q_df = self.q_df[self.q_df.state_key == state_key]
            next_action_q_df = next_action_q_df[next_action_q_df.action_key.isin(next_action_list)]
            if next_action_q_df.shape[0] == 0:
                return random.choice(next_action_list)
            else:
                if next_action_q_df.shape[0] == 1:
                    max_q_action = next_action_q_df["action_key"].values[0]
                else:
                    next_action_q_df = next_action_q_df.sort_values(by=["q_value"], ascending=False)
                    max_q_action = next_action_q_df.iloc[0, :]["action_key"]
                return max_q_action
        else:
            return random.choice(next_action_list)

public java.lang.String getOnload() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.onload);

    }

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


Question: Returns a partial {@link Ordering} over {@link Multiset.Entry}s by their count.

public static <ElementType> Ordering<Multiset.Entry<ElementType>> byCountOrdering() {
    return Ordering.natural().onResultOf(MultisetUtils.<ElementType>toCountFunction());
  }

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: Changes the working directory

def change_dir(self, session, path):

        if path == "-":
            # Previous directory
            path = self._previous_path or "."

        try:
            previous = os.getcwd()
            os.chdir(path)
        except IOError as ex:
            # Can't change directory
            session.write_line("Error changing directory: {0}", ex)
        else:
            # Store previous path
            self._previous_path = previous
            session.write_line(os.getcwd())

public static boolean makeDirs(final String filePath) {
        File f = new java.io.File(filePath);
        if (!f.exists()) {
            return f.mkdirs();
        }

        return true;
    }

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


Question: // first returns the first ID of this index

func (idx *UniqueIndex) first() []byte {
	c := idx.IndexBucket.Cursor()

	for val, ident := c.First(); val != nil; val, ident = c.Next() {
		return ident
	}
	return nil
}

private void moveToNext() {
        if (controller != null) {
            currentItemIndex = controller.nextItem(this, currentItemIndex);
        } else {
            currentItemIndex = defaultController.nextItem(this, currentItemIndex);
        }
    }

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


Question:
Computes the following the value of output such that:

divide(multiply(x,y),y)==x for any x and any nonzero y.

public int divide(int x , int y ) {
		if( y == 0 )
			throw new ArithmeticException("Divide by zero");
		if( x == 0 )
			return 0;

		return exp[ log[x] + max_value - log[y] ];
	}

def unit_vector(x):
    """"""
    y = np.array(x, dtype='float')
    return y/norm(y)

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


Question:
Show the form for editing the specified resource.

@param int $id

@return Response

public function edit($id)
    {
        if (! $role = $this->role->find($id)) {
            flash(trans('core::messages.resource.resource not found', ['name' => trans('user::roles.title.role')]));

            return redirect()->route('backend::user.role.index');
        }

        return view('user::backend.roles.edit', compact('role'));
    }

def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )

      @dbid, @pageid, @pagename, @pagetype, @pagebody, @ignoreError = dbid, pageid, pagename, pagetype, pagebody, ignoreError

      if pageid
         xmlRequestData = toXML( :pageid, @pageid )
      elsif pagename
         xmlRequestData = toXML( :pagename, @pagename )
      else
         raise "addReplaceDBPage: missing pageid or pagename"
      end

      xmlRequestData << toXML( :pagetype, @pagetype )
      xmlRequestData << toXML( :pagebody, encodeXML( @pagebody ) )
      xmlRequestData << toXML( :ignoreError, "1" ) if @ignoreError

      sendRequest( :addReplaceDBPage, xmlRequestData )

      @pageid = getResponseValue( :pageid )
      @pageid ||= getResponseValue( :pageID ) # temporary

      return self if @chainAPIcalls
      @pageid
    end

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


Question:
// PeerUserSession starts a gexec.Session as a peer user for the provided peer
// command. This is intended to be used by short running peer cli commands that
// execute in the context of a peer configuration.

func (n *Network) PeerUserSession(p *Peer, user string, command Command) (*gexec.Session, error) {
	cmd := n.peerCommand(
		command,
		fmt.Sprintf("FABRIC_CFG_PATH=%s", n.PeerDir(p)),
		fmt.Sprintf("CORE_PEER_MSPCONFIGPATH=%s", n.PeerUserMSPDir(p, user)),
	)
	return n.StartSession(cmd, command.SessionName())
}

private void initializeWeb3j(PropertyReader reader)
    {

        String endPoint = reader.getProperty(EthConstants.ETHEREUM_NODE_ENDPOINT);

        if (endPoint == null || endPoint.isEmpty())
        {
            LOGGER.error("Specify - " + EthConstants.ETHEREUM_NODE_ENDPOINT + " in "
                    + EthConstants.KUNDERA_ETHEREUM_PROPERTIES);
            throw new KunderaException("Specify - " + EthConstants.ETHEREUM_NODE_ENDPOINT + " in "
                    + EthConstants.KUNDERA_ETHEREUM_PROPERTIES);
        }

        else if (endPoint.contains(".ipc"))
        {
            String os = reader.getProperty(EthConstants.ETHEREUM_NODE_OS);
            LOGGER.info("Connecting using IPC socket. IPC Socket File location - " + endPoint);
            if (os != null && "windows".equalsIgnoreCase(os))
            {
                web3j = Web3j.build(new WindowsIpcService(endPoint));
            }
            else
            {
                web3j = Web3j.build(new UnixIpcService(endPoint));
            }
        }

        else
        {
            LOGGER.info("Connecting via Endpoint - " + endPoint);
            web3j = Web3j.build(new HttpService(endPoint));
        }
    }

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


Question: // RandomPolicy implmentes randomly chose the slave of slaves

func RandomPolicy() GroupPolicyHandler {
	var r = rand.New(rand.NewSource(time.Now().UnixNano()))
	return func(g *EngineGroup) *Engine {
		return g.Slaves()[r.Intn(len(g.Slaves()))]
	}
}

def untranslated_policy(self, default):
        ''''''
        return self.generator.settings.get(self.info.get('policy', None),
                                           default)

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


Question:
Evaluate() method
@param paretoFrontApproximation
@return

@Override public Double evaluate(List<S> paretoFrontApproximation) {
    if (paretoFrontApproximation == null) {
      throw new JMetalException("The pareto front approximation is null") ;
    }

    return hypervolume(new ArrayFront(paretoFrontApproximation), referenceParetoFront);  }

public function train(Dataset $dataset) : void
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This estimator requires a'
                . ' labeled training set.');
        }

        $this->network = new FeedForward(
            new Placeholder1D($dataset->numColumns()),
            [],
            new Continuous($this->alpha, $this->costFn),
            $this->optimizer
        );

        $this->steps = [];

        $this->partial($dataset);
    }

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


Question:
Loads a country from the database
@param string $code
@return array

public function get($code)
    {
        $result = &gplcart_static("country.get.$code");

        if (isset($result)) {
            return $result;
        }

        $this->hook->attach('country.get.before', $code, $result, $this);

        if (isset($result)) {
            return $result;
        }

        $sql = 'SELECT * FROM country WHERE code=?';
        $result = $this->db->fetch($sql, array($code), array('unserialize' => 'format'));

        if (isset($result['format'])) {
            $default_format = $this->getDefaultFormat();
            $result['format'] = gplcart_array_merge($default_format, $result['format']);
            gplcart_array_sort($result['format']);
        }

        $this->hook->attach('country.get.after', $code, $result, $this);
        return $result;
    }

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

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

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


Question: // WithHTTPClient adds the HTTPClient to the delete fqdn cache params

func (o *DeleteFqdnCacheParams) WithHTTPClient(client *http.Client) *DeleteFqdnCacheParams {
	o.SetHTTPClient(client)
	return o
}

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: object to convert X-10 house codes from numbers to strings and back

function HouseCode(houseCode) {
	this.raw = null;

	switch (typeof houseCode) {
	case "string":
		if (houseCode !== "" && houseCode.length === 1) {
			var index = houseCode.charCodeAt(0) - 65;
			if ((index >= 0) && (index <= (deviceCodes.length - 1))) {
				this.raw = deviceCodes[index];
			} else {
				throw new Error("House code string out of range.");
			}
		} else {
			throw new Error("Invalid house code.");
		}
		break;
	default:
		if (deviceCodes.indexOf(houseCode) !== -1) {
			this.raw = houseCode;
		} else {
			throw new Error("House code number out of range.");
		}
		break;
	}
	return this.raw;
}

@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "notanumber")
    public JAXBElement<ConstantType> createNotanumber(ConstantType value) {
        return new JAXBElement<ConstantType>(_Notanumber_QNAME, ConstantType.class, null, value);
    }

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


Question: re-compute ts on a daily basis

def daily_returns(ts, **kwargs):
    '''  '''
    relative = kwargs.get('relative', 0)
    return returns(ts, delta=BDay(), relative=relative)

func NewStats() *Stats {
	bps := &Stats{}
	bps.Timings = stats.NewTimings("", "", "")
	bps.Rates = stats.NewRates("", bps.Timings, 15, 60e9)
	bps.History = history.New(3)
	bps.SecondsBehindMaster.Set(math.MaxInt64)
	return bps
}

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


Question: Percolates element down heap from the array position given by the index.

final void percolateDownMinHeap(final int index) {
        final int element = elements[index];
        final float key = keys[index];
        int hole = index;

        while (hole * 2 <= size) {
            int child = hole * 2;

            // if we have a right child and that child can not be percolated
            // up then move onto other child
            if (child != size && keys[child + 1] < keys[child]) {
                child++;
            }

            // if we found resting place of bubble then terminate search
            if (keys[child] >= key) {
                break;
            }

            elements[hole] = elements[child];
            keys[hole] = keys[child];
            hole = child;
        }

        elements[hole] = element;
        keys[hole] = key;
    }

private int getDataIndexOfKey(Object key) {
    int dataSize = this.size << 1;
    Object[] data = this.data;
    for (int i = 0; i < dataSize; i += 2) {
      Object k = data[i];
      if (key == null ? k == null : key.equals(k)) {
        return i;
      }
    }
    return -2;
  }

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


Question: // ScriptPath implementation of communicator.Communicator interface

func (c *Communicator) ScriptPath() string {
	return strings.Replace(
		c.connInfo.ScriptPath, "%RAND%",
		strconv.FormatInt(int64(c.rand.Int31()), 10), -1)
}

public function execute($command, callable $next)
    {
        if ($command instanceof FallbackCommand) {
            $command->message = new TextTemplate();
            $command->message->text = "Oops! I dont know wath you say.";
        }

        return $next($command);
    }

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


Question: Calculates the Iy operator

public IMatrix getIy() {
        return (new IMatrix(getIplus().sub(getIminus()))).mul(new Complex(0d, 1d)).mul(new Complex(0.5, 0d));
    }

private SoyList newListFromIterable(Iterable<?> items) {
    // Create a list backed by a Java list which has eagerly converted each value into a lazy
    // value provider. Specifically, the list iteration is done eagerly so that the lazy value
    // provider can cache its value.
    ImmutableList.Builder<SoyValueProvider> builder = ImmutableList.builder();
    for (Object item : items) {
      builder.add(convertLazy(item));
    }
    return ListImpl.forProviderList(builder.build());
  }

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


Question:
// GetFieldKind returns the kind of the provided obj field. obj can whether
// be a structure or pointer to structure.

func GetFieldKind(obj interface{}, name string) (reflect.Kind, error) {
	field, err := getInnerField(obj, name)
	if err != nil {
		return reflect.Invalid, err
	}

	return field.Kind(), nil
}

public function parseType(string $input)
    {
        $matches = $properties = [];
        if (\preg_match(self::STRUCT, trim($input), $matches)) {
            /* Optional parse properties of the struct, could be empty complex types */
            \preg_match_all(self::PROPERTY, $matches['properties'], $properties);

            $struct = new Struct();
            $struct->setName($matches['name']);

            for ($x = 0, $max = count($properties['name']); $x < $max; $x++) {
                $type = $this->convertWsdlTypeToPhpType($properties['type'][$x]);
                $name = $this->covertNameToPhpName($properties['name'][$x]);
                $struct->addProperty(new Property($name, $type));
            }

            return $struct;
        } elseif (\preg_match(self::ARRAY_OF_COMPLEX_TYPE, trim($input), $matches)) {
            $struct = new Struct();
            $struct->setName($matches['name']);
            $struct->addProperty(new Property($matches['type'], $matches['type'] . '[]'));
            return $struct;
        } elseif (\preg_match(self::SIMPLE_TYPE, trim($input), $matches)) {
            return new Property($matches['name'], $matches['type']);
        } else {
            throw new \Exception(sprintf('Unable to parse input [%s]', $input));
        }
    }

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


Question:
// ValidateTrace is identical to ValidTrace, except instead of returning
// a boolean, it returns a non-nil error if the SSFSpan cannot be interpreted
// as a span, and nil otherwise.

func ValidateTrace(span *ssf.SSFSpan) error {
	if !ValidTrace(span) {
		return &InvalidTrace{span}
	}
	return nil
}

def load_training_data
      File.open(@training_file) {|file|
        @training_set = Nimbus::TrainingSet.new({}, {})
        file.each do |line|
          next if line.strip == ''
          data_feno, data_id, *snp_list = line.strip.split
          raise Nimbus::InputFileError, "Individual ##{data_id} from training set has no value for all #{@tree_SNP_total_count} SNPs" unless snp_list.size == @tree_SNP_total_count
          raise Nimbus::InputFileError, "There are individuals with no ID, please check data in training file." unless (!data_id.nil? && data_id.strip != '')
          raise Nimbus::InputFileError, "Individual ##{data_id} has no fenotype value, please check data in training file." unless (!data_feno.nil? && data_feno.strip != '')
          raise Nimbus::InputFileError, "Individual ##{data_id} has invalid class (not in [#{classes*', '}]), please check data in training file." unless (@classes.nil? || @classes.include?(data_feno))

          data_feno = (@classes ? data_feno.to_s : data_feno.to_f)
          @training_set.individuals[data_id.to_i] = Nimbus::Individual.new(data_id.to_i, data_feno, snp_list.map{|snp| snp.to_i})
          @training_set.ids_fenotypes[data_id.to_i] = data_feno
        end
      }
    end

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


Question:
Partition keys by slot-hash. The resulting map honors order of the keys.

@param codec codec to encode the key
@param keys iterable of keys
@param <K> Key type.
@param <V> Value type.
@result map between slot-hash and an ordered list of keys.

static <K, V> Map<Integer, List<K>> partition(RedisCodec<K, V> codec, Iterable<K> keys) {

        Map<Integer, List<K>> partitioned = new HashMap<>();
        for (K key : keys) {
            int slot = getSlot(codec.encodeKey(key));
            if (!partitioned.containsKey(slot)) {
                partitioned.put(slot, new ArrayList<>());
            }
            Collection<K> list = partitioned.get(slot);
            list.add(key);
        }
        return partitioned;
    }

def deserialize(self, to_deserialize: PrimitiveJsonType) \
            -> Optional[Union[SerializableType, List[SerializableType]]]:

        if to_deserialize is None:
            # Implements #17
            return None
        elif isinstance(to_deserialize, List):
            deserialized = []
            for item in to_deserialize:
                item_deserialized = self.deserialize(item)
                deserialized.append(item_deserialized)
            return deserialized
        else:
            mappings_not_set_in_constructor = []    # type: List[PropertyMapping]

            init_kwargs = dict()    # type: Dict[str, Any]
            for mapping in self._property_mappings:
                if mapping.object_constructor_parameter_name is not None:
                    value = mapping.serialized_property_getter(to_deserialize)
                    if not (mapping.optional and value is None):
                        decoded_value = self._deserialize_property_value(value, mapping.deserializer_cls)
                        if isinstance(decoded_value, list):
                            collection = mapping.collection_factory(decoded_value)
                            decoded_value = collection

                        argument = mapping.object_constructor_argument_modifier(decoded_value)
                        init_kwargs[mapping.object_constructor_parameter_name] = argument
                else:
                    mappings_not_set_in_constructor.append(mapping)

            decoded = self._deserializable_cls(**init_kwargs)
            assert type(decoded) == self._deserializable_cls

            for mapping in mappings_not_set_in_constructor:
                assert mapping.object_constructor_parameter_name is None
                if mapping.serialized_property_getter is not None and mapping.object_property_setter is not None:
                    value = mapping.serialized_property_getter(to_deserialize)
                    if not (mapping.optional and value is None):
                        decoded_value = self._deserialize_property_value(value, mapping.deserializer_cls)
                        if isinstance(decoded_value, list):
                            collection = mapping.collection_factory(decoded_value)
                            decoded_value = collection

                        mapping.object_property_setter(decoded, decoded_value)

            return decoded

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


Question: Load atomtyping rules from a forcefield into SMARTSGraphs.

def _load_rules(forcefield):

    rules = dict()
    for rule_name, smarts in forcefield.atomTypeDefinitions.items():
        overrides = forcefield.atomTypeOverrides.get(rule_name)
        if overrides is not None:
            overrides = set(overrides)
        else:
            overrides = set()
        rules[rule_name] = SMARTSGraph(smarts_string=smarts,
                                       parser=forcefield.parser,
                                       name=rule_name,
                                       overrides=overrides)
    return rules

def draw_jointplot(figname, x, y, data=None, kind="reg", color=None,
                   xlim=None, ylim=None, format="pdf"):

    import seaborn as sns
    sns.set_context('talk')
    plt.clf()

    register = {"MeanCoverage": "Sample Mean Coverage",
                "HD.FDP": "Depth of full spanning reads",
                "HD.PDP": "Depth of partial spanning reads",
                "HD.PEDP": "Depth of paired-end reads",
                "HD.2": "Repeat size of the longer allele"}

    g = sns.jointplot(x, y, data=data, kind=kind, color=color,
                      xlim=xlim, ylim=ylim)
    g.ax_joint.set_xlabel(register.get(x, x))
    g.ax_joint.set_ylabel(register.get(y, y))
    savefig(figname + "." + format, cleanup=False)

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


Question: Get the current observation. If none and not done wait for a short time.

private byte[] getObservation(boolean done) {
        byte[] obs = envState.obs;
        if (obs == null && !done) {
            try {
                cond.await(COND_WAIT_SECONDS, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
            }
            obs = envState.obs;
        }
        if (obs == null) {
            obs = new byte[0];
        }
        return obs;
    }

func (w *Watcher) Alive(key string) (bool, error) {
	result := make(chan bool, 1)
	w.sendReq(reqAlive{key, result})
	var alive bool
	select {
	case alive = <-result:
	case <-w.tomb.Dying():
		return false, errors.Errorf("cannot check liveness: watcher is dying")
	}
	logger.Tracef("[%s] Alive(%q) -> %v", w.modelUUID[:6], key, alive)
	return alive, nil
}

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


Question:
Validate lastName

@param mixed $lastName

@return bool

public function validateLastName($lastName)
    {
        if (empty($lastName)) {
            $this->addError('lastName', 'Last name cannot be empty');
            return false;
        }

        if (!is_string($lastName)) {
            $this->addError('lastName', 'Last name must be a string');
            return false;
        }

        if (mb_strlen($lastName, 'UTF-8') > 255) {
            $this->addError('lastName', 'Last name length has to be less or equal to 255');
            return false;
        }

        return true;
    }

public function composeValidationData(&$container, $constraints, $getters)
    {
        if (null == $container) {
            $container = array();
        }
        if ($getters) {
            if (!isset($container['getters'])) {
                $container['getters'] = array();
            }
            $container['getters'] = array_merge($container['getters'], $this->parseGetters($getters));
        }
        if ($constraints) {
            if (!isset($container['constraints'])) {
                $container['constraints'] = array();
            }
            $container['constraints'] = array_merge($container['constraints'], $this->parseConstraints($constraints));
        }
    }

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


Question:
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.

func (c *RetrieveCall) Context(ctx context.Context) *RetrieveCall {
	c.ctx_ = ctx
	return c
}

public static void main(String[] args) {
    System.out.println("Hello Stats World");
    System.out.println("Default Tags: " + tagger.empty());
    System.out.println("Current Tags: " + tagger.getCurrentTagContext());
    TagContext tags1 = tagger.emptyBuilder().put(K1, V1).put(K2, V2).build();
    try (Scope scopedTagCtx1 = tagger.withTagContext(tags1)) {
      System.out.println("  Current Tags: " + tagger.getCurrentTagContext());
      System.out.println(
          "  Current == Default + tags1: " + tagger.getCurrentTagContext().equals(tags1));
      TagContext tags2 = tagger.toBuilder(tags1).put(K3, V3).put(K4, V4).build();
      try (Scope scopedTagCtx2 = tagger.withTagContext(tags2)) {
        System.out.println("    Current Tags: " + tagger.getCurrentTagContext());
        System.out.println(
            "    Current == Default + tags1 + tags2: "
                + tagger.getCurrentTagContext().equals(tags2));
        statsRecorder.newMeasureMap().put(M1, 0.2).put(M2, 0.4).record();
      }
    }
    System.out.println(
        "Current == Default: " + tagger.getCurrentTagContext().equals(tagger.empty()));
  }

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


Question: // NodeAddresses implements Instances.NodeAddresses

func (i *Instances) NodeAddresses(ctx context.Context, name types.NodeName) ([]v1.NodeAddress, error) {
	klog.V(4).Infof("NodeAddresses(%v) called", name)

	addrs, err := getAddressesByName(i.compute, name)
	if err != nil {
		return nil, err
	}

	klog.V(4).Infof("NodeAddresses(%v) => %v", name, addrs)
	return addrs, nil
}

def create(cls, address, ospf_area=None, **kwargs):

        return super(LoopbackClusterInterface, cls).create(
            address=address,
            network_value='{}/32'.format(address),
            interface_id='Loopback Interface',
            ospfv2_area_ref=ospf_area,
            **kwargs)

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


Question: Send a private message to user.

def send(message, options = {})
      message_format = options[:message_format] ? options[:message_format] : 'text'
      notify         = options[:notify]         ? options[:notify]         : false

      response = self.class.post(@api.send_config[:url],
                                 :query => { :auth_token => @token },
                                 :body => {
                                     :message => message,
                                     :message_format => message_format,
                                     :notify => notify
                                 }.send(@api.send_config[:body_format]),
                                 :headers => @api.headers
      )
      ErrorHandler.response_code_to_exception_for :user, user_id, response
      true
    end

func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
	ius := make([]*IssueUser, 0, 10)
	err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
	return ius, err
}

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


Question: Command execution, facilitated by Backbone.Wreqr.Commands

function(){
    var args = Array.prototype.slice.apply(arguments);
    this.commands.execute.apply(this.commands, args);
  }

def start(**kwargs):

    if CORE_MANAGER.started:
        raise RuntimeConfigError('Current context has to be stopped to start '
                                 'a new context.')

    try:
        waiter = kwargs.pop('waiter')
    except KeyError:
        waiter = hub.Event()
    common_config = CommonConf(**kwargs)
    hub.spawn(CORE_MANAGER.start, *[], **{'common_conf': common_config,
                                          'waiter': waiter})
    return True

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


Question: Applies any defined transformation to the given value

def _transform(self, value):

        if self.transform:
            try:
                value = self.transform(value)
            except:
                import sys
                exc_type, exc_obj, exc_tb = sys.exc_info()
                raise AssertionError('Error applying transformation <{0}>: {2}: {3}'.format(
                    self.transform.__name__, value, exc_type.__name__, exc_obj))

        return value

public static double quantile(double val, double shape, double location, double scale) {
    return val < 0 || val > 1 ? Double.NaN : scale * FastMath.pow(val / (1. - val), 1. / shape) + location;
  }

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


Question: Generate time and date formats with different delimeters.

def create_date_formats():
    """"""
    # European style:
    base_formats = ['%d %m %Y', '%d %m %y', '%Y %m %d']
    # US style:
    base_formats += ['%m %d %Y', '%m %d %y', '%Y %m %d']
    # Things with words in
    base_formats += ['%d %b %Y', '%d %B %Y']

    date_formats = []
    for separator in ('-', '.', '/', ' '):
        for date_format in base_formats:
            date_formats.append((date_format.replace(' ', separator)))

    datetime_formats = []
    time_formats = ('%H:%M%Z', '%H:%M:%S', '%H:%M:%S%Z', '%H:%M%z',
                    '%H:%M:%S%z')

    for date_format in date_formats:
        for time_format in time_formats:
            for separator in ('', 'T', ' '):
                datetime_formats.append(date_format + separator + time_format)

    return tuple(date_formats), tuple(datetime_formats)

public function escapeDateTime($dt, $EMPTY_NULL = true) {
		/*if(!is_string($s)){
			$s='';
			}*/
		if (($EMPTY_NULL) && (empty($dt))) {
			return 'NULL';
		}
		$str = '"' . $dt->format('Y-m-d H:i:s') . '"';
		return $str;
	}

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


Question:
/*
Exclude namespace declaration

protected int getNumAttr() {
        int num = element.tree.elemNodeNumAttributes[element.tree.nodeRepID[element.node]];
        return num >= 0 ? num : 0;
    }

private void processIgnoredLeadingTokens(ParseTreeNode node, int position, int line, MemoEntry progress)
	    throws TreeException, ParserException {
	if (ignoredLeading) {
	    processIgnoredTokens(node, position, line, progress);
	}
    }

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


Question:
Sets template directories.

@param templateDirs
directories where templates are stored.
@return this instance.

public OptionsBuilder templateDirs(File... templateDirs) {
        for (File templateDir : templateDirs) {
            this.options.setTemplateDirs(templateDir.getAbsolutePath());
        }
        return this;
    }

def __add_action(self, relative_directory, action):

        generator_action_container = self.__actions.retrieve_element_or_default(relative_directory, None)

        if generator_action_container is None:
            generator_action_container = GeneratorActionContainer()
            generator_action_container.add_generator_action(action)
            self.__actions.add_element(location=relative_directory, element=generator_action_container)
        else:
            generator_action_container.add_generator_action(action)

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


Question:
Sets the commerce wish list remote service.

@param commerceWishListService the commerce wish list remote service

public void setCommerceWishListService(
		com.liferay.commerce.wish.list.service.CommerceWishListService commerceWishListService) {
		this.commerceWishListService = commerceWishListService;
	}

public function create(array $options)
    {
        if (!isset($options['partner_trade_no'])) {
            throw new InvalidArgumentException('Missing Options -- [partner_trade_no]');
        }
        if (!isset($options['enc_bank_no'])) {
            throw new InvalidArgumentException('Missing Options -- [enc_bank_no]');
        }
        if (!isset($options['enc_true_name'])) {
            throw new InvalidArgumentException('Missing Options -- [enc_true_name]');
        }
        if (!isset($options['bank_code'])) {
            throw new InvalidArgumentException('Missing Options -- [bank_code]');
        }
        if (!isset($options['amount'])) {
            throw new InvalidArgumentException('Missing Options -- [amount]');
        }
        $this->params->offsetUnset('appid');
        return $this->callPostApi('https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank', [
            'amount'           => $options['amount'],
            'bank_code'        => $options['bank_code'],
            'partner_trade_no' => $options['partner_trade_no'],
            'enc_bank_no'      => $this->rsaEncode($options['enc_bank_no']),
            'enc_true_name'    => $this->rsaEncode($options['enc_true_name']),
            'desc'             => isset($options['desc']) ? $options['desc'] : '',
        ], true, 'MD5', false);
    }

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


Question:
Take the constructor argument and convert the Map and List values into read-only form.

@param attributes Map of attributes
@return Read-only map of attributes

protected Map<String, List<Object>> buildImmutableAttributeMap(final Map<String, List<Object>> attributes) {
        final Map<String, List<Object>> immutableValuesBuilder = this.createImmutableAttributeMap(attributes.size());
        final Pattern arrayPattern = Pattern.compile("\\{(.*)\\}");
        for (final Map.Entry<String, List<Object>> attrEntry : attributes.entrySet()) {
            final String key = attrEntry.getKey();
            List<Object> value = attrEntry.getValue();

            if (value != null) {
                if (!value.isEmpty()) {
                    final Object result = value.get(0);
                    if (Array.class.isInstance(result)) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Column {} is classified as a SQL array", key);
                        }
                        final String values = result.toString();
                        if (logger.isTraceEnabled()) {
                            logger.trace("Converting SQL array values {} using pattern {}", values, arrayPattern.pattern());
                        }
                        final Matcher matcher = arrayPattern.matcher(values);
                        if (matcher.matches()) {
                            final String[] groups = matcher.group(1).split(",");
                            value = Arrays.asList(groups);
                            if (logger.isTraceEnabled()) {
                                logger.trace("Converted SQL array values {}", values);
                            }
                        }
                    }
                }
                value = Collections.unmodifiableList(value);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Collecting attribute {} with value(s) {}", key, value);
            }
            immutableValuesBuilder.put(key, value);
        }

        return immutableValuesBuilder;
    }

private void ajaxGetPermissions(final Project project, final HashMap<String, Object> ret) {
    final ArrayList<HashMap<String, Object>> permissions =
        new ArrayList<>();
    for (final Pair<String, Permission> perm : project.getUserPermissions()) {
      final HashMap<String, Object> permObj = new HashMap<>();
      final String userId = perm.getFirst();
      permObj.put("username", userId);
      permObj.put("permission", perm.getSecond().toStringArray());

      permissions.add(permObj);
    }

    ret.put("permissions", permissions);
  }

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


Question: Get an interface of this port by instance name.

def get_interface_by_instance_name(self, name):
        ''''''
        with self._mutex:
            for intf in self.interfaces:
                if intf.instance_name == name:
                    return intf
            return None

def get_out_ip_addr(cls, tenant_id):

        if tenant_id not in cls.serv_obj_dict:
            LOG.error("Fabric not prepared for tenant %s", tenant_id)
            return
        tenant_obj = cls.serv_obj_dict.get(tenant_id)
        return tenant_obj.get_out_ip_addr()

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


Question:
Inits the.

@param resourceLoader the resource loader
@throws IOException Signals that an I/O exception has occurred.

private void init(ResourceLoader resourceLoader) throws IOException {
    if (config == null && configs == null) {
      if (resourceLoader == null) {
        return;
      } else if (configFileArgument == null && configArgument == null && analyzerArgument==null) {
        throw new IOException("no configuration");
      } else {
        if (configFileArgument != null) {
          try {
            config = MtasConfiguration.readConfiguration(
                resourceLoader.openResource(configFileArgument));
          } catch (IOException e) {
            throw new IOException(
                "Problem loading configuration from " + configFileArgument, e);
          }
        }
        if (configArgument != null) {
          try {
            configs = MtasConfiguration.readMtasTokenizerConfigurations(
                resourceLoader, configArgument);
          } catch (IOException e) {
            throw new IOException(
                "Problem loading configurations from " + configArgument, e);
          }
        }
        if (analyzerArgument != null) {
          configs = null;
          config = new MtasConfiguration();
          MtasConfiguration subConfig = new MtasConfiguration();
          subConfig.name = "parser";
          subConfig.attributes.put("name", analyzerArgument);
          subConfig.attributes.put(ARGUMENT_PARSER_ARGS, analyzerArgumentParserArgs);
          config.children.add(subConfig);
        }
      }
    }
  }

public void aput(Local<?> array, Local<Integer> index, Local<?> source) {
        addInstruction(new ThrowingInsn(Rops.opAput(source.type.ropType), sourcePosition,
                RegisterSpecList.make(source.spec(), array.spec(), index.spec()), catches));
    }

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


Question: // RegisterRPC registers the local discovery with a gRPC server

func (d *discovery) RegisterRPC(s *grpc.Server) {
	server := &discoveryServer{d}
	pb.RegisterDiscoveryServer(s, server)
}

def spawn(name)
      if all_services.include?(name)
        name = name.to_s
        require "geocoder/lookups/#{name}"
        Geocoder::Lookup.const_get(classify_name(name)).new
      else
        valids = all_services.map(&:inspect).join(", ")
        raise ConfigurationError, "Please specify a valid lookup for Geocoder " +
          "(#{name.inspect} is not one of: #{valids})."
      end
    end

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


Question:
Open a file descriptor stream to be used for writing.

@param Context $context Async execution context.
@param string $path Absolute path to the target file.
@return WritableDescriptorStream Async readable file stream.

protected function writeStreamTask(Context $context, string $path, bool $append = false): \Generator
    {
        if (!yield $this->pool->submit($context, new MethodCall(static::class, 'checkFileWritableJob', $path, !$append && !$this->fileTransferSupported))) {
            throw new FilesystemException(\sprintf('File is not writable: "%s"', $path));
        }

        if (!$this->fileTransferSupported) {
            return new WritableFileStream($this->pool, $path);
        }

        $file = yield $this->pool->submit($context, new MethodCall(FileDescriptor::class, 'open', $path, $append ? 'ab' : 'wb'));

        return new WritableDescriptorStream($this->pool, $path, $file);
    }

public static function run($version, $deployFile)
    {
        // Init Deployer
        $console = new Application('Deployer', $version);
        $input = new ArgvInput();
        $output = new ConsoleOutput();
        $deployer = new self($console);

        // Pretty-print uncaught exceptions in symfony-console
        set_exception_handler(function ($e) use ($input, $output, $deployer) {
            $io = new SymfonyStyle($input, $output);
            $io->block($e->getMessage(), get_class($e), 'fg=white;bg=red', ' ', true);
            $io->block($e->getTraceAsString());

            $deployer->logger->log('['. get_class($e) .'] '. $e->getMessage());
            $deployer->logger->log($e->getTraceAsString());
            exit(1);
        });

        // Require deploy.php file
        if (is_readable($deployFile)) {
            // Prevent variable leak into deploy.php file
            call_user_func(function () use ($deployFile) {
                require $deployFile;
            });
        }

        // Run Deployer
        $deployer->init();
        $console->run($input, $output);
    }

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


Question: try to figure out manifest list

def _get_manifest_list(self, image):
        """"""
        if image in self.manifest_list_cache:
            return self.manifest_list_cache[image]

        manifest_list = get_manifest_list(image, image.registry,
                                          insecure=self.parent_registry_insecure,
                                          dockercfg_path=self.parent_registry_dockercfg_path)
        if '@sha256:' in str(image) and not manifest_list:
            # we want to adjust the tag only for manifest list fetching
            image = image.copy()

            try:
                config_blob = get_config_from_registry(
                    image, image.registry, image.tag, insecure=self.parent_registry_insecure,
                    dockercfg_path=self.parent_registry_dockercfg_path
                )
            except (HTTPError, RetryError, Timeout) as ex:
                self.log.warning('Unable to fetch config for %s, got error %s',
                                 image, ex.response.status_code)
                raise RuntimeError('Unable to fetch config for base image')

            release = config_blob['config']['Labels']['release']
            version = config_blob['config']['Labels']['version']
            docker_tag = "%s-%s" % (version, release)
            image.tag = docker_tag

            manifest_list = get_manifest_list(image, image.registry,
                                              insecure=self.parent_registry_insecure,
                                              dockercfg_path=self.parent_registry_dockercfg_path)
        self.manifest_list_cache[image] = manifest_list
        return self.manifest_list_cache[image]

func (s *TrainingJob) SetFinalMetricDataList(v []*MetricData) *TrainingJob {
	s.FinalMetricDataList = v
	return s
}

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


Question:
Sets a warning message in azkaban.warn.message in the cookie. This will be used by the web
client javascript to somehow display the message

protected void setWarnMessageInCookie(final HttpServletResponse response,
      final String errorMsg) {
    final Cookie cookie = new Cookie(AZKABAN_WARN_MESSAGE, errorMsg);
    cookie.setPath("/");
    response.addCookie(cookie);
  }

def handle_moban_file(moban_file, options):

    moban_file_configurations = load_data(None, moban_file)
    if moban_file_configurations is None:
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_INVALID_MOBAN_FILE % moban_file
        )
    if (
        constants.LABEL_TARGETS not in moban_file_configurations
        and constants.LABEL_COPY not in moban_file_configurations
    ):
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_NO_TARGETS % moban_file
        )
    check_none(moban_file_configurations, moban_file)
    version = moban_file_configurations.get(
        constants.MOBAN_VERSION, constants.DEFAULT_MOBAN_VERSION
    )
    if version == constants.DEFAULT_MOBAN_VERSION:
        mobanfile.handle_moban_file_v1(moban_file_configurations, options)
    else:
        raise exceptions.MobanfileGrammarException(
            constants.MESSAGE_FILE_VERSION_NOT_SUPPORTED % version
        )
    HASH_STORE.save_hashes()

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


Question: The <tt>place_id</tt> of the first matching result, or <tt>null</tt> if there were no matching results ({@link #getStatus()} did not return {@link GeocodeApiResponse.Status#OK ok}.

public String getPlaceId() {
        final GeocodeApiResponse.Result firstResult = firstResult(apiResponse);
        return firstResult != null? firstResult.getPlace_id(): null;
    }

def get_content(api, rebuild_cache=False):
    """"""
    if hasattr(get_content, 'cache') and not rebuild_cache:
        return get_content.cache
    if not os.path.exists(CONTENT_JSON) or rebuild_cache:
        import locale
        content_endpoint = api.content.get
        # pylint: disable=protected-access
        try_langs = []
        try:
            lang = get_translation_for('habitipy').info()['language']
            try_langs.append(lang)
        except KeyError:
            pass
        try:
            loc = locale.getdefaultlocale()[0]
            if loc:
                try_langs.append(loc)
                try_langs.append(loc[:2])
        except IndexError:
            pass
        server_lang = content_endpoint._node.params['query']['language']
        # handle something like 'ru_RU' not available - only 'ru'
        for lang in try_langs:
            if lang in server_lang.possible_values:
                loc = {'language': lang}
                break
        else:
            loc = {}
        get_content.cache = content = content_endpoint(**loc)
        with open(CONTENT_JSON, 'w') as f:
            json.dump(content, f)
        return content
    try:
        with open(CONTENT_JSON) as f:
            get_content.cache = content = json.load(f)
        return content
    except JSONDecodeError:
        return get_content(api, rebuild_cache=True)

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


Question:
Get the fault of the service result

@param checkHash should the result be checked
@return deserialized fault of the service result
@throws FoxHttpResponseException Exception during the deserialization

public ServiceFault getFault(boolean checkHash) throws FoxHttpResponseException {
        try {

            String body = getStringBody();

            ServiceResult<ServiceFault> result = parser.fromJson(body, new TypeToken<ServiceResult<ServiceFault>>() {
            }.getType());
            foxHttpClient.getFoxHttpLogger().log("processFault(" + result + ")");

            checkHash(checkHash, body, result);

            return result.getContent();
        } catch (IOException e) {
            throw new FoxHttpResponseException(e);
        }

    }

function decodeStream( $request, $stream, $headers=false, $cookies=array(), $statuscode="200" )
    {
        $this->decodeStreamCommon( $request, $stream, $headers, $cookies, $statuscode );

        $contentType = $this->ContentType;
        $charset = $this->Charset;

        // allow request to force an expected response type
        // this is useful if servers do respond with eg. text/plain content-header for json or xml
        if ( ( $forcedType = $request->responseType() ) != '' )
        {
            list ( $contentType, $charset2 ) = $this->parseContentTypeHeader( $forcedType );
            $this->ContentType = $contentType . '; received="' . $this->ContentType . '"';
            if ( $charset2 != '' )
            {
                $charset = $charset2;
                $this->Charset = $charset . '; received="' . $this->Charset . '"';
            }
        }

        // Allow empty payloads regardless of declared content type, for 204 and 205 responses
        if ( $statuscode == '204' || $statuscode == '205' )
        {
            if ( $stream == '' && ( !isset( $headers['content-length'] ) || $headers['content-length'] == 0 ) )
            {
                $this->Value = null;
                return;
            }
            else
            {
                /// @todo this is not valid according to rfc 2616 - but we should leave that control to client really
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (received http response 204/205 with a body. Not valid http)";
            }
        }

        /// @todo take into account charset when decoding json / xml

        switch( $this->mimeTypeToEncodeType( $contentType ) )
        {
            case 'json':
            case 'application/json':
                $val = json_decode( $stream, true );
                if ( function_exists( 'json_last_error' ) )
                {
                    $err = json_last_error();
                }
                else
                {
                    $err = ( $val === null ) ? 1 : false;
                }
                if ( $err )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' json. Decoding error: ' . $err;
                }
                else
                {
                    $this->Value = $val;
                }
                break;
            case 'xml':
            case 'text/xml':
            case 'application/xml':
                try
                {
                    $doc = new DOMDocument();
                    $prev = libxml_use_internal_errors( true );
                    libxml_clear_errors();
                    $doc->loadXML( $stream );
                    $node = $doc->documentElement;
                    if ( $node == null )
                    {
                        $errors = libxml_get_errors();
                        libxml_use_internal_errors( $prev );
                        $errorText = '';
                        foreach( $errors as $error)
                        {
                            if ( $error->level > LIBXML_ERR_WARNING )
                            {
                                $errorText .= trim ( $error->message ) . ", line: $error->line" . " column: $error->column\n";
                            }
                        }
                        throw new Exception( $errorText );
                    }
                    libxml_use_internal_errors( $prev );
                    $this->Value = new ggSimpleTemplateXML( $node );

                }
                catch ( Exception $e )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' xml. ' . $e->getMessage();
                }
                break;
            case 'text/plain':
            case 'text/html':
                $this->Value = $stream;
                break;
            default:
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (unsupported format $contentType)";
        }
    }

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


Question: Update the template code.

public function updateTemplate()
    {
        $codeDb = $validationCode = $form = '';

        $form = $this->buildFormOpen();

        foreach ($this->columns as $key => $value) {
            if ($value['COLUMN_NAME'] !== 'id') {
                if ($this->isFormGenerator == false) {
                    $codeDb .= $this->generateDbCode($value);
                }

                $form .= $this->generateFormElements($value);
            }
        }

        $form .= $this->buildFormCloseTags();

        $this->setForm($form);
        $this->setDbCode($codeDb);
    }

public function getView($filename, $data = null)
    {
        // $data = ($data === null) ? $this->_data : $data;
        return $this->getTemplateFile($this->getTemplateFolder().$filename, $data);
    }

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


Question:
A function for validating an individual token record and extracting
        the decoded token.

def verify_token_record(token_record, public_key_or_address,
                        signing_algorithm="ES256K"):

    if "token" not in token_record:
        raise ValueError("Token record must have a token inside it")

    token = token_record["token"]

    decoded_token = verify_token(
        token, public_key_or_address, signing_algorithm=signing_algorithm)
    token_payload = decoded_token["payload"]
    issuer_public_key = token_payload["issuer"]["publicKey"]

    if "parentPublicKey" in token_record:
        if issuer_public_key == token_record["parentPublicKey"]:
            pass
        else:
            raise ValueError(
                "Verification of tokens signed with keychains is not yet supported")

    return decoded_token

func (*RecognitionAudio) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _RecognitionAudio_OneofMarshaler, _RecognitionAudio_OneofUnmarshaler, _RecognitionAudio_OneofSizer, []interface{}{
		(*RecognitionAudio_Content)(nil),
		(*RecognitionAudio_Uri)(nil),
	}
}

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


Question:
// Frequency checks if a given number of restarts happened during
// a given duration.

func (rs Recoverings) Frequency(num int, dur time.Duration) bool {
	if len(rs) >= num {
		first := rs[len(rs)-num].Time
		last := rs[len(rs)-1].Time
		return last.Sub(first) <= dur
	}
	return false
}

public function is_work_running($identifier, $bucket = self::DEFAULT_BUCKET)
	{
		foreach ($this->forked_children as $info)
		{
			if (($info['status'] != self::STOPPED) && ($info['identifier'] == $identifier) && ($info['bucket'] == $bucket))
			{
				return true;
			}
		}

		return false;
	}

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


Question:
Return events that matches to $begin && $end
$end date should be exclude.

@param \DateTime $begin
@param \DateTime $end
@param array     $options

@return \CalendR\Event\EventInterface

public function getEvents(\DateTime $begin, \DateTime $end, array $options = array())
    {
        $events = array();

        foreach ($this->providers as $provider) {
            $events = array_merge($events, $provider->getEvents($begin, $end, $options));
        }

        return $events;
    }

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question: Return a pretty formatted string of parsed DMAP data.

def pprint(data, tag_lookup, indent=0):
    """"""
    output = ''
    if isinstance(data, dict):
        for key, value in data.items():
            tag = tag_lookup(key)
            if isinstance(value, (dict, list)) and tag.type is not read_bplist:
                output += '{0}{1}: {2}\n'.format(indent*' ', key, tag)
                output += pprint(value, tag_lookup, indent+2)
            else:
                output += '{0}{1}: {2} {3}\n'.format(
                    indent*' ', key, str(value), tag)
    elif isinstance(data, list):
        for elem in data:
            output += pprint(elem, tag_lookup, indent)
    else:
        raise exceptions.InvalidDmapDataError(
            'invalid dmap data: ' + str(data))
    return output

def header_match(cls, header):
        '''

        '''
        mo = cls.header_re.match(header)
        if mo is None:
            msg = f'Expected {cls.header_re.pattern!r}, got {header!r}'
            raise ValueError(msg)
        return {
            'name': mo['name'].decode().strip(),
            'label': mo['label'].decode().strip(),
            'type': mo['type'].decode().strip(),
            'created': strptime(mo['created']),
            'modified': strptime(mo['modified']),
            'sas_version': float(mo['version']),
            'os_version': mo['os'].decode().strip(),
            'namestr_size': mo['descriptor_size'],
        }

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


Question:
compute features for training or prediction of a ranking model for suggestions
@param suggestions
@param word
@param sentence
@param startPos
@return correction candidates, features for the match in general, features specific to candidates

public Pair<List<SuggestedReplacement>, SortedMap<String, Float>> computeFeatures(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) {
    if (suggestions.isEmpty()) {
      return Pair.of(Collections.emptyList(), Collections.emptySortedMap());
    }
    if (topN <= 0) {
      topN = suggestions.size();
    }
    List<String> topSuggestions = suggestions.subList(0, Math.min(suggestions.size(), topN));
    //EditDistance<Integer> levenshteinDistance = new LevenshteinDistance(4);
    EditDistance levenstheinDistance = new EditDistance(word, EditDistance.DistanceAlgorithm.Damerau);
    SimilarityScore<Double> jaroWrinklerDistance = new JaroWinklerDistance();
    List<Feature> features = new ArrayList<>(topSuggestions.size());

    for (String candidate : topSuggestions) {
      double prob1 = languageModel.getPseudoProbability(Collections.singletonList(candidate)).getProb();
      double prob3 = LanguageModelUtils.get3gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
      //double prob4 = LanguageModelUtils.get4gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
      long wordCount = ((BaseLanguageModel) languageModel).getCount(candidate);
      int levenstheinDist = levenstheinDistance.compare(candidate, 3);
      double jaroWrinklerDist = jaroWrinklerDistance.apply(word, candidate);
      DetailedDamerauLevenstheinDistance.Distance detailedDistance = DetailedDamerauLevenstheinDistance.compare(word, candidate);

      features.add(new Feature(prob1, prob3, wordCount, levenstheinDist, detailedDistance, jaroWrinklerDist, candidate));
    }
    if (!"noop".equals(score)) {
      features.sort(Feature::compareTo);
    }
    //logger.trace("Features for '%s' in '%s': %n", word, sentence.getText());
    //features.stream().map(Feature::toString).forEach(logger::trace);
    List<String> words = features.stream().map(Feature::getWord).collect(Collectors.toList());

    // compute general features, not tied to candidates
    SortedMap<String, Float> matchData = new TreeMap<>();
    matchData.put("candidateCount", (float) words.size());

    List<SuggestedReplacement> suggestionsData = features.stream().map(f -> {
      SuggestedReplacement s = new SuggestedReplacement(f.getWord());
      s.setFeatures(f.getData());
      return s;
    }).collect(Collectors.toList());
    return Pair.of(suggestionsData, matchData);
  }

func (p *Parser) listType() (*ast.ListType, error) {
	defer un(trace(p, "ParseListType"))

	// we assume that the currently scanned token is a LBRACK
	l := &ast.ListType{}

	for {
		tok := p.scan()
		switch tok.Type {
		case token.NUMBER, token.FLOAT, token.STRING:
			node, err := p.literalType()
			if err != nil {
				return nil, err
			}

			l.Add(node)
		case token.COMMA:
			continue
		case token.LBRACE:
			node, err := p.objectType()
			if err != nil {
				return nil, err
			}

			l.Add(node)
		case token.BOOL:
			// TODO(arslan) should we support? not supported by HCL yet
		case token.LBRACK:
			// TODO(arslan) should we support nested lists? Even though it's
			// written in README of HCL, it's not a part of the grammar
			// (not defined in parse.y)
		case token.RBRACK:
			// finished
			return l, nil
		default:
			return nil, fmt.Errorf("unexpected token while parsing list: %s", tok.Type)
		}

	}
}

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


Question:
// NewFromRows creates Frame from rows.
// Pass 'nil' header if first row is used as header strings.
// Pass 'non-nil' header if the data starts from the first row, without header strings.

func NewFromRows(header []string, rows [][]string) (Frame, error) {
	if len(rows) < 1 {
		return nil, fmt.Errorf("empty row %q", rows)
	}
	fr := New()
	headerN := len(header)
	if headerN > 0 { // use this as header
		// assume no header string at top
		cols := make([]Column, headerN)
		for i := range cols {
			cols[i] = NewColumn(header[i])
		}
		for _, row := range rows {
			rowN := len(row)
			if rowN > headerN {
				return nil, fmt.Errorf("header %q is not specified correctly for %q", header, row)
			}
			for j, v := range row {
				cols[j].PushBack(NewStringValue(v))
			}
			if rowN < headerN { // fill in empty values
				for k := rowN; k < headerN; k++ {
					cols[k].PushBack(NewStringValue(""))
				}
			}
		}
		for _, c := range cols {
			if err := fr.AddColumn(c); err != nil {
				return nil, err
			}
		}
		return fr, nil
	}
	// use first row as header
	// assume header string at top
	header = rows[0]
	headerN = len(header)
	cols := make([]Column, headerN)
	for i := range cols {
		cols[i] = NewColumn(header[i])
	}
	for i, row := range rows {
		if i == 0 {
			continue
		}
		rowN := len(row)
		if rowN > headerN {
			return nil, fmt.Errorf("header %q is not specified correctly for %q", header, row)
		}
		for j, v := range row {
			cols[j].PushBack(NewStringValue(v))
		}
		if rowN < headerN { // fill in empty values
			for k := rowN; k < headerN; k++ {
				cols[k].PushBack(NewStringValue(""))
			}
		}
	}
	for _, c := range cols {
		if err := fr.AddColumn(c); err != nil {
			return nil, err
		}
	}
	return fr, nil
}

def _init_nt_hdr(self, line):
        """"""
        line = line.replace('.', '_')
        line = line.replace(' ', '_')
        line = line.replace('#', 'N')
        line = line.replace('-', '_')
        line = line.replace('"', '')
        #line = re.sub(r"_$", r"", line)
        hdrs = re.split(self.sep, line)
        if '' in hdrs:
            hdrs = NCBIgeneFileReader.replace_nulls(hdrs)
        # Init indexes which will be converted to int or float
        self.idxs_int = [idx for idx, hdr in enumerate(hdrs) if hdr in self.int_hdrs]
        self.idxs_float = [idx for idx, hdr in enumerate(hdrs) if hdr in self.float_hdrs]
        assert hdrs[6] == 'Aliases'
        return namedtuple('ntncbi', ' '.join(hdrs))

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


Question: to create loading progress bar

def task(ft):

	ft.pack(expand = True,  fill = BOTH,  side = TOP)
	pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate')
	pb_hD.pack(expand = True, fill = BOTH, side = TOP)
	pb_hD.start(50)
	ft.mainloop()

public void setShowIcon(final boolean showIcon) {
        if (!showIcon)
            attrMixin.setAttribute(SHOW_ICON, Boolean.toString(false));
        else
            attrMixin.removeAttribute(SHOW_ICON);
    }

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


Question: // Format formats the node.

func (node TableName) Format(buf *TrackedBuffer) {
	if node.IsEmpty() {
		return
	}
	if !node.Qualifier.IsEmpty() {
		buf.Myprintf("%v.", node.Qualifier)
	}
	buf.Myprintf("%v", node.Name)
}

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:
Creates a new mail message model object from message headers.
@param messageHeaders
@param body
@param contentType
@return

protected MailMessage createMailMessage(Map<String, Object> messageHeaders, String body, String contentType) {
        return MailMessage.request(messageHeaders)
                .marshaller(marshaller)
                .from(messageHeaders.get(CitrusMailMessageHeaders.MAIL_FROM).toString())
                .to(messageHeaders.get(CitrusMailMessageHeaders.MAIL_TO).toString())
                .cc(messageHeaders.get(CitrusMailMessageHeaders.MAIL_CC).toString())
                .bcc(messageHeaders.get(CitrusMailMessageHeaders.MAIL_BCC).toString())
                .subject(messageHeaders.get(CitrusMailMessageHeaders.MAIL_SUBJECT).toString())
                .body(body, contentType);
    }

@Override
    public void setHeader(String name, String value) {
        this._getHttpServletResponse().setHeader(name, value);
    }

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


Question:
@param \Interpro\Core\Contracts\Ref\ARef $ref
@param bool $asUnitMember

@return \Interpro\Extractor\Items\AItem

public function loadItem(ARef $ref, $asUnitMember = false)
    {
        $family = $ref->getType()->getFamily();
        $Amapper = $this->mappersMediator->getAMapper($family);

        return $Amapper->getByRef($ref, $asUnitMember);
    }

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

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

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

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

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

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

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


Question:
Removes and returns the object at the beginning of the queue.
@return mixed the item at the beginning of the queue
@throws CException if the queue is empty

public function dequeue()
	{
		if($this->_c===0)
			throw new CException(Yii::t('yii','The queue is empty.'));
		else
		{
			--$this->_c;
			return array_shift($this->_d);
		}
	}

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question: Returns true if the relation holds.

static boolean pointRelatePoint_(Point point_a, Point point_b,
			double tolerance, String scl, ProgressTracker progress_tracker) {
		Point2D pt_a = point_a.getXY();
		Point2D pt_b = point_b.getXY();
		int[] matrix = new int[9];

		for (int i = 0; i < 9; i++)
			matrix[i] = -1;

		if (Point2D.sqrDistance(pt_a, pt_b) <= tolerance * tolerance) {
			matrix[MatrixPredicate.InteriorInterior] = 0;
		} else {
			matrix[MatrixPredicate.InteriorExterior] = 0;
			matrix[MatrixPredicate.ExteriorInterior] = 0;
		}

		matrix[MatrixPredicate.ExteriorExterior] = 2;

		boolean bRelation = relationCompare_(matrix, scl);
		return bRelation;
	}

public function prevTypeIsAnyOf(array $types): bool
    {
        return isset($this->tokens[$this->position - 2]) && $this->tokens[$this->position - 2]->typeEqualsAnyOf($types);
    }

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


Question:
@memberof RecordApi#

@description Begin a server request to destroy the resource.

The request's promise can be accessed using the `$asPromise` method.

@return {RecordApi} this

function() {
      return this.$action(function() {
        var url = this.$url('destroy');
        if(url)
        {
          var request = { method: 'DELETE', url: url };

          this
            .$dispatch('before-destroy', [request])
            .$send(request, function(_response) {

              // remove from scope
              if(this.$scope.$remove) {
                this.$scope.$remove(this);
              }

              this.$dispatch('after-destroy', [_response]);
            }, function(_response) {
              this.$dispatch('after-destroy-error', [_response]);
            });
        }
        else
        {
          // If not yet bound, just remove from parent
          if(this.$scope.$remove) this.$scope.$remove(this);
        }
      });
    }

private LogRecord doToModel(LogRecordDO logRecordDo) {
        LogRecord logRecord = new LogRecord();
        try {

            logRecord.setId(logRecordDo.getId());
            if (logRecordDo.getPipelineId() > 0 && logRecordDo.getChannelId() > 0) {
                try {
                    Channel channel = channelService.findByPipelineId(logRecordDo.getPipelineId());
                    logRecord.setChannel(channel);
                    for (Pipeline pipeline : channel.getPipelines()) {
                        if (pipeline.getId().equals(logRecordDo.getPipelineId())) {
                            logRecord.setPipeline(pipeline);
                        }
                    }
                } catch (Exception e) {
                    // 可能历史的log记录对应的channel/pipeline已经被删除了，直接忽略吧
                    Channel channel = new Channel();
                    channel.setId(0l);
                    logRecord.setChannel(channel);
                    Pipeline pipeline = new Pipeline();
                    pipeline.setId(0l);
                    logRecord.setPipeline(pipeline);
                }
            } else {
                Channel channel = new Channel();
                channel.setId(-1l);
                logRecord.setChannel(channel);
                Pipeline pipeline = new Pipeline();
                pipeline.setId(-1l);
                logRecord.setPipeline(pipeline);
            }

            logRecord.setTitle(logRecordDo.getTitle());
            logRecord.setNid(logRecordDo.getNid());
            logRecord.setMessage(logRecordDo.getMessage());
            logRecord.setGmtCreate(logRecordDo.getGmtCreate());
            logRecord.setGmtModified(logRecordDo.getGmtModified());

        } catch (Exception e) {
            logger.error("ERROR ## ");
            throw new ManagerException(e);
        }

        return logRecord;
    }

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


Question:
// Levels return all numbers in 0..255 to indicate that the LogBuffer will
// handle log messages of any level.

func (buf *LogBuffer) Levels() []log.Level {
	res := make([]log.Level, 256)
	for i := 0; i < len(res); i++ {
		res[int(i)] = log.Level(i)
	}
	return res
}

func (buffer *Buffer) sendGenMsg(routine string, flags int, args ...float32) error {
	msg := osc.Message{
		Address: bufferGenAddress,
		Arguments: osc.Arguments{
			osc.Int(buffer.Num),
			osc.String(routine),
			osc.Int(int32(flags)),
		},
	}
	for _, arg := range args {
		msg.Arguments = append(msg.Arguments, osc.Float(arg))
	}
	if err := buffer.client.oscConn.Send(msg); err != nil {
		return err
	}
	return nil
}

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


Question: // Close terminates this stream.

func (s *Stream) Close() error {
	_, err := s.c.srvServ.TerminateStream(s.c.ctx, &services.TerminateStreamRequest{
		Project:       coordinatorTest.AllAccessProject,
		Id:            s.streamID,
		Secret:        s.secret,
		TerminalIndex: s.streamIndex - 1,
	})
	return err
}

private final boolean block(Data data, Body body) throws TemplateException {
	if (!data.srcCode.forwardIfCurrent('{')) return false;
	comments(data);
	if (data.srcCode.forwardIfCurrent('}')) {

	    return true;
	}
	statements(data, body, false);

	if (!data.srcCode.forwardIfCurrent('}')) throw new TemplateException(data.srcCode, "Missing ending [}]");
	return true;
    }

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


Question:
This function loops through a CF compliant rapid streamflow
    file to produce a netCDF file with a seasonal average for
    365 days a year

def generate_seasonal_averages(qout_file, seasonal_average_file,
                               num_cpus=multiprocessing.cpu_count()):

    with RAPIDDataset(qout_file) as qout_nc_file:
        print("Generating seasonal average file ...")
        seasonal_avg_nc = Dataset(seasonal_average_file, 'w')

        seasonal_avg_nc.createDimension('rivid', qout_nc_file.size_river_id)
        seasonal_avg_nc.createDimension('day_of_year', 365)

        time_series_var = seasonal_avg_nc.createVariable('rivid', 'i4',
                                                         ('rivid',))
        time_series_var.long_name = (
            'unique identifier for each river reach')

        average_flow_var = \
            seasonal_avg_nc.createVariable('average_flow', 'f8',
                                           ('rivid', 'day_of_year'))
        average_flow_var.long_name = 'seasonal average streamflow'
        average_flow_var.units = 'm3/s'

        std_dev_flow_var = \
            seasonal_avg_nc.createVariable('std_dev_flow', 'f8',
                                           ('rivid', 'day_of_year'))
        std_dev_flow_var.long_name = 'seasonal std. dev. streamflow'
        std_dev_flow_var.units = 'm3/s'

        std_dev_flow_var = \
            seasonal_avg_nc.createVariable('max_flow', 'f8',
                                           ('rivid', 'day_of_year'))
        std_dev_flow_var.long_name = 'seasonal max streamflow'
        std_dev_flow_var.units = 'm3/s'

        std_dev_flow_var = \
            seasonal_avg_nc.createVariable('min_flow', 'f8',
                                           ('rivid', 'day_of_year'))
        std_dev_flow_var.long_name = 'seasonal min streamflow'
        std_dev_flow_var.units = 'm3/s'

        lat_var = seasonal_avg_nc.createVariable('lat', 'f8', ('rivid',),
                                                 fill_value=-9999.0)

        lon_var = seasonal_avg_nc.createVariable('lon', 'f8', ('rivid',),
                                                 fill_value=-9999.0)
        add_latlon_metadata(lat_var, lon_var)

        seasonal_avg_nc.variables['lat'][:] = \
            qout_nc_file.qout_nc.variables['lat'][:]
        seasonal_avg_nc.variables['lon'][:] = \
            qout_nc_file.qout_nc.variables['lon'][:]

        river_id_list = qout_nc_file.get_river_id_array()
        seasonal_avg_nc.variables['rivid'][:] = river_id_list
        seasonal_avg_nc.close()

    # generate multiprocessing jobs
    mp_lock = multiprocessing.Manager().Lock()  # pylint: disable=no-member
    job_combinations = []
    for day_of_year in range(1, 366):
        job_combinations.append((qout_file,
                                 seasonal_average_file,
                                 day_of_year,
                                 mp_lock
                                 ))

    pool = multiprocessing.Pool(num_cpus)
    pool.map(generate_single_seasonal_average,
             job_combinations)
    pool.close()
    pool.join()

def retrieveVals(self):
        """"""
        file_stats = self._fileInfo.getContainerStats()
        for contname in self._fileContList:
            stats = file_stats.get(contname)
            if stats is not None:
                if self.hasGraph('rackspace_cloudfiles_container_size'):
                    self.setGraphVal('rackspace_cloudfiles_container_size', contname,
                                     stats.get('size'))
                if self.hasGraph('rackspace_cloudfiles_container_count'):
                    self.setGraphVal('rackspace_cloudfiles_container_count', contname,
                                     stats.get('count'))

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


Question:
Makes a request from a Request object directly.

@param Request $request       A Request instance
@param bool    $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())

@return Crawler

protected function requestFromRequest(Request $request, $changeHistory = true)
    {
        return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
    }

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

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


Question:
Set the helptext of the field if needed
@param {Boolean} enable Whether to enable it or not

function (enable) {
            var cfg = this._cfg;
            // check for disposal
            if (!cfg) {
                return;
            }
            var helpText = cfg.helptext, helpTextConfig = this._skinObj.helpText;
            // stops if no helptext, or trying to disable an helptext that as
            // not been set
            if (!helpText || !this._helpTextSet && !enable || (this._hasFocus || this._keepFocus) && enable) {
                return;
            }

            var field = this.getTextInputField();

            // stops if trying to set a helptext in a field with a value
            if (field.value && enable) {
                return;
            }

            this._helpTextSet = enable;

            if (!field) {
                return;
            }

            // determine new styles and value
            var color = enable ? helpTextConfig.color : this._getTextFieldColor();
            var value = enable ? helpText : "";

            var helpTextClass = "x" + this._skinnableClass + "_" + cfg.sclass + "_helpText";
            var classNames = field.className.split(/\s+/);
            ariaUtilsArray.remove(classNames, helpTextClass);
            if (enable) {
                classNames.push(helpTextClass);
            }
            field.className = classNames.join(' ');

            // update styles
            var style = field.style;
            style.color = color;

            // update field value
            field.value = value;
        }

public function pauseChecks($check_ids) {
    $this->ensureParameters(array('check_ids' => $check_ids), __METHOD__);
    $parameters = array(
      'paused' => TRUE,
    );
    return $this->modifyChecks($check_ids, $parameters);
  }

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


Question:
// RecvCompress returns the compression algorithm applied to the inbound
// message. It is empty string if there is no compression applied.

func (s *Stream) RecvCompress() string {
	if err := s.waitOnHeader(); err != nil {
		return ""
	}
	return s.recvCompress
}

public void encode(AsnOutputStream aos) throws EncodeException {
        if (this.userType == null && this.providerType == null)
            throw new EncodeException("Error encoding ResultSourceDiagnostic: Value not set");

        try {
            aos.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG);
            int pos = aos.StartContentDefiniteLength();

            if (this.userType != null) {
                aos.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG_U);
                int pos2 = aos.StartContentDefiniteLength();
                aos.writeInteger(this.userType.getType());
                aos.FinalizeContent(pos2);
            } else {
                aos.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG_P);
                int pos2 = aos.StartContentDefiniteLength();
                aos.writeInteger(this.providerType.getType());
                aos.FinalizeContent(pos2);
            }

            aos.FinalizeContent(pos);

        } catch (IOException e) {
            throw new EncodeException("IOException while encoding ResultSourceDiagnostic: " + e.getMessage(), e);
        } catch (AsnException e) {
            throw new EncodeException("AsnException while encoding ResultSourceDiagnostic: " + e.getMessage(), e);
        }

    }

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


Question: // Parse will create a Database using the file at the given path.

func ParseConfig(filename string) (Database, error) {
	f, err := os.Open(filename)
	if err != nil {
		return Database{}, err
	}
	return parseConfig(f)
}

public function open($filename)
    {
        if (!$this->exists($filename) || false === $content = file_get_contents($filename)) {
            throw new FileNotFoundException($filename);
        }

        return $this->makeFile($filename, $content);
    }

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


Question:
Get a Jaxon request to a given class.

@param  string  $classname the class name

@return Jaxon\Request\Request|null  The request to the class

public function request($classname)
    {
        $instance = $this->instance($classname);
        return ($instance != null ? $instance->request() : null);
    }

public void marshall(ListThingsRequest listThingsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(listThingsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getAttributeName(), ATTRIBUTENAME_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getAttributeValue(), ATTRIBUTEVALUE_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getThingTypeName(), THINGTYPENAME_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.