Question:
Set the configuration item as specified.

@param   string      $key        The configuration key to set.
@param   mixed       $value      The new value for the configuration item.
@return  $this

public function set_config($key, $value) {
        if ($this->config === null) {
            $this->config = (object) array();
        }
        $this->config->$key = $value;
        $this->dirty = true;

        return $this;
    }

public function deriveProductTree(SKU $sku) {
    static $cache = [];

    if (isset($cache[$sku->language()->getId()], $cache[$sku->language()->getId()][$sku->id()])) {
      return $cache[$sku->language()->getId()][$sku->id()];
    }

    $tree = [
      'parent' => $sku,
      'products' => self::getChildren($sku),
      'combinations' => [],
    ];

    $configurables = unserialize(
      $sku->get('field_configurable_attributes')->getString()
    );

    $tree['configurables'] = [];
    foreach ($configurables as $configurable) {
      $tree['configurables'][$configurable['code']] = $configurable;
    }

    $configurable_codes = array_keys($tree['configurables']);

    foreach ($tree['products'] ?? [] as $sku_code => $sku_entity) {
      $attributes = $sku_entity->get('attributes')->getValue();
      $attributes = array_column($attributes, 'value', 'key');
      foreach ($configurable_codes as $code) {
        $value = $attributes[$code] ?? '';

        if (empty($value)) {
          continue;
        }

        $tree['combinations']['by_sku'][$sku_code][$code] = $value;
      }
    }

    /** @var \Drupal\acm_sku\CartFormHelper $helper */
    $helper = \Drupal::service('acm_sku.cart_form_helper');

    $configurable_weights = $helper->getConfigurableAttributeWeights(
      $sku->get('attribute_set')->getString()
    );

    // Sort configurables based on the config.
    uasort($tree['configurables'], function ($a, $b) use ($configurable_weights) {
      return $configurable_weights[$a['code']] - $configurable_weights[$b['code']];
    });

    $tree['options'] = Configurable::recursiveConfigurableTree(
      $tree,
      $tree['configurables']
    );

    $cache[$sku->language()->getId()][$sku->id()] = $tree;

    return $tree;
  }

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


Question:
Makes and inserts a new tailored node into the list, after the one at index.
Skips over nodes of weaker strength to maintain collation order
("postpone insertion").
@return the new node's index

private int insertTailoredNodeAfter(int index, int strength) {
        assert(0 <= index && index < nodes.size());
        if(strength >= Collator.SECONDARY) {
            index = findCommonNode(index, Collator.SECONDARY);
            if(strength >= Collator.TERTIARY) {
                index = findCommonNode(index, Collator.TERTIARY);
            }
        }
        // Postpone insertion:
        // Insert the new node before the next one with a strength at least as strong.
        long node = nodes.elementAti(index);
        int nextIndex;
        while((nextIndex = nextIndexFromNode(node)) != 0) {
            node = nodes.elementAti(nextIndex);
            if(strengthFromNode(node) <= strength) { break; }
            // Skip the next node which has a weaker (larger) strength than the new one.
            index = nextIndex;
        }
        node = IS_TAILORED | nodeFromStrength(strength);
        return insertNodeBetween(index, nextIndex, node);
    }

func (q *collectionQueue) processBlock(bh *blockHashHeight) {
	hash := bh.hash
	height := bh.height

	// Ensure that the received block (bh.hash, bh.height) connects to the
	// previously connected block (q.prevHash, q.prevHeight).
	if bh.prevHash != q.prevHash {
		log.Infof("Received block at %d (%v) does not connect to %d (%v). "+
			"This is normal before reorganization.",
			height, hash, q.prevHeight, q.prevHash)
		return
	}

	start := time.Now()

	// Run synchronous block connected handlers in order.
	for _, h := range q.syncHandlers {
		if err := h(&hash); err != nil {
			log.Errorf("synchronous handler failed: %v", err)
			return
		}
	}

	// Record this block as the best block connected by the collectionQueue.
	q.SetPreviousBlock(hash, height)

	log.Debugf("Synchronous handlers of collectionQueue.processBlock() completed in %v", time.Since(start))

	// Signal to mempool monitors that a block was mined.
	select {
	case NtfnChans.NewTxChan <- nil:
	default:
	}

	// API status update handler
	select {
	case NtfnChans.UpdateStatusNodeHeight <- uint32(height):
	default:
	}
}

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


Question: To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server.

def stop(self):
        """"""
        stopped = []
        for interface_id, proxy in self.proxies.items():
            if interface_id in self.failed_inits:
                LOG.warning("ServerThread.stop: Not performing de-init for %s" % interface_id)
                continue
            if proxy._callbackip and proxy._callbackport:
                callbackip = proxy._callbackip
                callbackport = proxy._callbackport
            else:
                callbackip = proxy._localip
                callbackport = self._localport
            remote = "http://%s:%i" % (callbackip, callbackport)
            LOG.debug("ServerThread.stop: init('%s')" % remote)
            if not callbackip in stopped:
                try:
                    proxy.init(remote)
                    stopped.append(callbackip)
                    LOG.info("Proxy de-initialized: %s" % remote)
                except Exception as err:
                    LOG.debug("proxyInit: Exception: %s" % str(err))
                    LOG.warning("Failed to de-initialize proxy")
        self.proxies.clear()
        LOG.info("Shutting down server")
        self.server.shutdown()
        LOG.debug("ServerThread.stop: Stopping ServerThread")
        self.server.server_close()
        LOG.info("Server stopped")

def prepare_destruction(self):

        if self.state_machine is None:
            logger.verbose("Multiple calls of prepare destruction for {0}".format(self))
        self.destruction_signal.emit()
        if self.history is not None:
            self.history.prepare_destruction()
        if self.auto_backup is not None:
            self.auto_backup.prepare_destruction()
        try:
            self.unregister_observer(self)
            self.root_state.unregister_observer(self)
        except KeyError:  # Might happen if the observer was already unregistered
            pass
        with self.state_machine.modification_lock():
            self.root_state.prepare_destruction()
        self.root_state = None
        self.state_machine = None
        super(StateMachineModel, self).prepare_destruction()

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


Question:
Adjacency is defined by two Markers being infinitesimally close to each other.
This means they must share the same value and have adjacent Bounds.

public boolean isAdjacent(Marker other)
    {
        checkTypeCompatibility(other);
        if (isUpperUnbounded() || isLowerUnbounded() || other.isUpperUnbounded() || other.isLowerUnbounded()) {
            return false;
        }
        if (type.compareTo(valueBlock.get(), 0, other.valueBlock.get(), 0) != 0) {
            return false;
        }
        return (bound == Bound.EXACTLY && other.bound != Bound.EXACTLY) ||
                (bound != Bound.EXACTLY && other.bound == Bound.EXACTLY);
    }

def _map_block_index_to_location(ir_blocks):
    """"""
    block_index_to_location = {}
    # MarkLocation blocks occur after the blocks related to that location.
    # The core approach here is to buffer blocks until their MarkLocation is encountered
    # after which all buffered blocks can be associated with the encountered MarkLocation.location.
    current_block_ixs = []
    for num, ir_block in enumerate(ir_blocks):
        if isinstance(ir_block, blocks.GlobalOperationsStart):
            if len(current_block_ixs) > 0:
                unassociated_blocks = [ir_blocks[ix] for ix in current_block_ixs]
                raise AssertionError(
                    u'Unexpectedly encountered global operations before mapping blocks '
                    u'{} to their respective locations.'.format(unassociated_blocks))
            break
        current_block_ixs.append(num)
        if isinstance(ir_block, blocks.MarkLocation):
            for ix in current_block_ixs:
                block_index_to_location[ix] = ir_block.location
            current_block_ixs = []
    return block_index_to_location

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


Question: Override just to set RequestContent(true)

@Override
    protected BasicHttpProcessor createHttpProcessor() {
        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        httpproc.addInterceptor(new RequestDefaultHeaders());
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent(true));
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestClientConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());
        // HTTP state management interceptors
        httpproc.addInterceptor(new RequestAddCookies());
        httpproc.addInterceptor(new ResponseProcessCookies());
        // HTTP authentication interceptors
        httpproc.addInterceptor(new RequestAuthCache());
        httpproc.addInterceptor(new RequestTargetAuthentication());
        httpproc.addInterceptor(new RequestProxyAuthentication());
        return httpproc;
    }

def text_result(text: str,
                extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,
                filename: str = None) -> WSGI_TUPLE_TYPE:

    extraheaders = extraheaders or []
    if filename:
        extraheaders.append(
            ('content-disposition', 'inline; filename="{}"'.format(filename))
        )
    contenttype = 'text/plain; charset=utf-8'
    if filename:
        contenttype += '; filename="{}"'.format(filename)
    return contenttype, extraheaders, text.encode("utf-8")

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


Question:
Initialize the database with the according schema

@param rcube_db $db Database connection

@return boolen True on success, False on error

public function init_db($db)
    {
        $engine = $db->db_provider;

        // read schema file from /SQL/*
        $fname = INSTALL_PATH . "SQL/$engine.initial.sql";
        if ($sql = @file_get_contents($fname)) {
            $db->set_option('table_prefix', $this->config['db_prefix']);
            $db->exec_script($sql);
        }
        else {
            $this->fail('DB Schema', "Cannot read the schema file: $fname");
            return false;
        }

        if ($err = $this->get_error()) {
            $this->fail('DB Schema', "Error creating database schema: $err");
            return false;
        }

        return true;
    }

func (conn *FakeVTGateConn) AddQuery(
	sql string,
	bindVariables map[string]*querypb.BindVariable,
	session *vtgatepb.Session,
	expectedResult *sqltypes.Result) {
	conn.execMap[sql] = &queryResponse{
		execQuery: &queryExecute{
			SQL:           sql,
			BindVariables: bindVariables,
			Session:       session,
		},
		reply: expectedResult,
	}
}

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


Question:
Get the count of the result set and close it

@param resultSet
result set
@return count

protected int count(UserCustomResultSet resultSet) {
		int count = 0;
		try {
			count = resultSet.getCount();
		} finally {
			resultSet.close();
		}
		return count;
	}

private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final JpaAction action) {

        String controllerId = null;
        LOG.debug("handleAddUpdateActionStatus for action {}", action.getId());

        // information status entry - check for a potential DOS attack
        assertActionStatusQuota(action);
        assertActionStatusMessageQuota(actionStatus);

        switch (actionStatus.getStatus()) {
        case ERROR:
            final JpaTarget target = (JpaTarget) action.getTarget();
            target.setUpdateStatus(TargetUpdateStatus.ERROR);
            handleErrorOnAction(action, target);
            break;
        case FINISHED:
            controllerId = handleFinishedAndStoreInTargetStatus(action);
            break;
        case DOWNLOADED:
            controllerId = handleDownloadedActionStatus(action);
            break;
        default:
            break;
        }

        actionStatus.setAction(action);
        actionStatusRepository.save(actionStatus);
        final Action savedAction = actionRepository.save(action);

        if (controllerId != null) {
            requestControllerAttributes(controllerId);
        }

        return savedAction;
    }

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


Question:
Creates an environment details object with system information
@param application The configured application name
@param environment The configured application environment
@return The EnvironmentDetail object

public static EnvironmentDetail getEnvironmentDetail(final String application, final String environment) {

		// lookup the host name

		String hostName = getHostName();

		// lookup the current path

		String currentPath = System.getProperty("user.dir");

		// build the environment details

		EnvironmentDetail.Builder environmentBuilder = EnvironmentDetail.newBuilder();
		environmentBuilder.deviceName(hostName);
		environmentBuilder.appLocation(currentPath);
		environmentBuilder.configuredAppName(application);
		environmentBuilder.configuredEnvironmentName(environment);

		return environmentBuilder.build();
	}

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

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


Question: Return valid quotes for the given value, or None if unneeded.

def _value_needs_quotes(val):
        """"""
        if not val:
            return None
        val = "".join(str(node) for node in val.filter_text(recursive=False))
        if not any(char.isspace() for char in val):
            return None
        if "'" in val and '"' not in val:
            return '"'
        if '"' in val and "'" not in val:
            return "'"
        return "\"'"

def select_optional_row(statement, build_arg = nil)
    rows = select(statement, build_arg)
    raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 0 or 1" if rows.size > 1
    if rows.empty? then nil else rows[0] end
  end

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


Question:
Find the proper Converter for the given UIOutput component.
@return the Converter or null if no Converter specified or needed
@throws FacesException if the Converter could not be created

public static Converter findUIOutputConverter(FacesContext facesContext,
            UIOutput component) throws FacesException
    {
        return _SharedRendererUtils.findUIOutputConverter(facesContext,
                component);
    }

func (ue UnpackingError) Error() string {
	var dv string
	var dt string
	k := ue.Destination.Kind()
	switch k {
	case reflect.Ptr:
		dt = fmt.Sprintf("%s", ue.Destination.Type().Elem())
		if !ue.Destination.IsNil() {
			dv = fmt.Sprintf("%v", ue.Destination.Elem().Interface())
		} else {
			dv = "nil"

		}
	case reflect.Invalid:
		dv = "invalid"
		dt = dv
	default:
		dv = fmt.Sprintf("%v", ue.Destination.Interface())
		dt = fmt.Sprintf("%s", ue.Destination.Type())
	}

	return fmt.Sprintf("Error unpacking %v(%T) into %s(%s):%v",
		ue.Source,
		ue.Source,
		dv,
		dt,
		ue.Err)
}

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


Question:
// Detect returns the language code for detected language
// in the given text.

func Detect(text string) string {
	cs := C.CString(text)
	res := C.DetectLang(cs, -1)
	C.free(unsafe.Pointer(cs))
	var lang string
	if res != nil {
		lang = C.GoString(res)
	}
	return lang
}

public function create()
	{

		$GLOBALS['TL_DCA']['tl_content']['palettes'][$this->element] .= ';{section-'. $this->id . (($this->hidden) ? ':hide' : ''). '}';
		$GLOBALS['TL_LANG']['tl_content']['section-' . $this->id] = $this->label;
	}

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


Question:
自定义异常理

@param $e

public function exception($e) {
        $type = "system";
        if (isset($_GET['type'])) {
            $type = $_GET['type'];
        }
        switch ($type) {
        case 'dapi':
        case 'api':
            $this->exception[] = $e;
            break;
        case 'page':
        default:
            require __DIR__ . '/exception.php';
            break;
        }
    }

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question:
Prepend the HTTP response header to the file.

        Args:
            filename: The path of the file
            response: Response

def save_headers(cls, filename: str, response: HTTPResponse):
        '''
        '''
        new_filename = filename + '-new'

        with open('wb') as new_file:
            new_file.write(response.header())

            with wpull.util.reset_file_offset(response.body):
                response.body.seek(0)
                shutil.copyfileobj(response.body, new_file)

        os.remove(filename)
        os.rename(new_filename, filename)

func (tw *Writer) writeRawHeader(blk *block, size int64, flag byte) error {
	if err := tw.Flush(); err != nil {
		return err
	}
	if _, err := tw.w.Write(blk[:]); err != nil {
		return err
	}
	if isHeaderOnlyType(flag) {
		size = 0
	}
	tw.curr = &regFileWriter{tw.w, size}
	tw.pad = blockPadding(size)
	return nil
}

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


Question: // WithHTTPClient overrides the client http client with the specified one

func WithHTTPClient(client *http.Client) Opt {
	return func(c *Client) error {
		if client != nil {
			c.client = client
		}
		return nil
	}
}

func (in *WebhookThrottleConfig) DeepCopy() *WebhookThrottleConfig {
	if in == nil {
		return nil
	}
	out := new(WebhookThrottleConfig)
	in.DeepCopyInto(out)
	return out
}

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


Question:
Cache the column name and its index.

@param resultSetMetaData
@throws SQLException

private void cacheMetadata(ResultSetMetaData resultSetMetaData) throws SQLException {
        cachedColumnNames = new LinkedHashMap<String, Integer>();
        for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
            final String fieldTypeName = resultSetMetaData.getColumnTypeName(i);
            if (!fieldTypeName.equalsIgnoreCase("geometry")
                    && isSupportedPropertyType(resultSetMetaData.getColumnType(i), fieldTypeName)) {
                cachedColumnNames.put(resultSetMetaData.getColumnName(i).toUpperCase(), i);
                columnCountProperties++;
            }
        }
    }

public void dataToField(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
    {
        if (componentCache.m_rgcompoments[iColumnIndex] != null)
        {
            String string = null;
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
                string = ((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).getText();
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
                if (((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).isSelected())
                    string = "1";
            //xif (string != null) if (string.length() > 0)
            this.getModel().setValueAt(string, iRowIndex, iColumnIndex);
        }
    }

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


Question:
Gets a question by its uuid.

@param string $uuid

@return Item|null

public function getQuestion($uuid)
    {
        $found = null;
        foreach ($this->stepQuestions as $stepQuestion) {
            if ($stepQuestion->getQuestion()->getUuid() === $uuid) {
                $found = $stepQuestion->getQuestion();
                break;
            }
        }

        return $found;
    }

func (s *service) RetrieveUserInfoByUserId(userId uint) (resDTO rest.ResponseDTOUserInfo, error *servicehelper.Error) {
	entity, err := s.repo.FindByID(userId)
	if err != nil {
		return rest.ResponseDTOUserInfo{}, &servicehelper.Error{Detail: errors.New("no result found"), Code: servicehelper.NotFound}
	}
	return rest.ResponseDTOUserInfo{
		UserId: entity.ID,
		Email:  entity.Email,
	}, nil
}

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


Question:
Sets the line style

@param float  $width
@param        $cap
@param string $join
@param array  $dash

@return void

protected function _set_line_style($width, $cap, $join, $dash)
    {
        if (count($dash) == 1) {
            $dash[] = $dash[0];
        }

        if ($this->getPDFLibMajorVersion() >= 9) {
            if (count($dash) > 1) {
                $this->_pdf->set_graphics_option("dasharray={" . implode(" ", $dash) . "}");
            } else {
                $this->_pdf->set_graphics_option("dasharray=none");
            }
        } else {
            if (count($dash) > 1) {
                $this->_pdf->setdashpattern("dasharray={" . implode(" ", $dash) . "}");
            } else {
                $this->_pdf->setdash(0, 0);
            }
        }

        switch ($join) {
            case "miter":
                if ($this->getPDFLibMajorVersion() >= 9) {
                    $this->_pdf->set_graphics_option('linejoin=0');
                } else {
                    $this->_pdf->setlinejoin(0);
                }
                break;

            case "round":
                if ($this->getPDFLibMajorVersion() >= 9) {
                    $this->_pdf->set_graphics_option('linejoin=1');
                } else {
                    $this->_pdf->setlinejoin(1);
                }
                break;

            case "bevel":
                if ($this->getPDFLibMajorVersion() >= 9) {
                    $this->_pdf->set_graphics_option('linejoin=2');
                } else {
                    $this->_pdf->setlinejoin(2);
                }
                break;

            default:
                break;
        }

        switch ($cap) {
            case "butt":
                if ($this->getPDFLibMajorVersion() >= 9) {
                    $this->_pdf->set_graphics_option('linecap=0');
                } else {
                    $this->_pdf->setlinecap(0);
                }
                break;

            case "round":
                if ($this->getPDFLibMajorVersion() >= 9) {
                    $this->_pdf->set_graphics_option('linecap=1');
                } else {
                    $this->_pdf->setlinecap(1);
                }
                break;

            case "square":
                if ($this->getPDFLibMajorVersion() >= 9) {
                    $this->_pdf->set_graphics_option('linecap=2');
                } else {
                    $this->_pdf->setlinecap(2);
                }
                break;

            default:
                break;
        }

        $this->_pdf->setlinewidth($width);
    }

func interpolationFuncDistinct() ast.Function {
	return ast.Function{
		ArgTypes:     []ast.Type{ast.TypeList},
		ReturnType:   ast.TypeList,
		Variadic:     true,
		VariadicType: ast.TypeList,
		Callback: func(args []interface{}) (interface{}, error) {
			var list []string

			if len(args) != 1 {
				return nil, fmt.Errorf("accepts only one argument.")
			}

			if argument, ok := args[0].([]ast.Variable); ok {
				for _, element := range argument {
					if element.Type != ast.TypeString {
						return nil, fmt.Errorf(
							"only works for flat lists, this list contains elements of %s",
							element.Type.Printable())
					}
					list = appendIfMissing(list, element.Value.(string))
				}
			}

			return stringSliceToVariableValue(list), nil
		},
	}
}

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


Question: // NewCpCode creates a new *CpCode

func NewCpCode(parent *CpCodes) *CpCode {
	cpcode := &CpCode{parent: parent}
	cpcode.Init()
	return cpcode
}

def start(self):
        """"""
        for i in range(self.min):
            self._threads.append(WorkerThread(self.server))
        for worker in self._threads:
            worker.setName("CP Server " + worker.getName())
            worker.start()
        for worker in self._threads:
            while not worker.ready:
                time.sleep(.1)

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


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

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

	return response, nil
}

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

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

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


Question: initial script processing

function process (ev) {
				ev = ev || global.event;
				// detect when it's done loading
				// ev.type == 'load' is for all browsers except IE6-9
				// IE6-9 need to use onreadystatechange and look for
				// el.readyState in {loaded, complete} (yes, we need both)
				if (ev.type == 'load' || readyStates[el.readyState]) {
					delete activeScripts[def.id];
					// release event listeners
					el.onload = el.onreadystatechange = el.onerror = ''; // ie cries if we use undefined
					success();
				}
			}

def _init_associations(self, fin_gpad, hdr_only=False):
        """"""
        ini = InitAssc(fin_gpad, self.godag)
        nts = ini.init_associations(hdr_only)
        self.hdr = ini.hdr
        return nts

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


Question:
Removes the last inode from the list. This is necessary when the last inode is deleted and we
want to continue using the inodepath. This operation is only supported when the path is
complete.

public void removeLastInode() {
    Preconditions.checkState(fullPathExists());

    if (!isImplicitlyLocked()) {
      // WRITE_EDGE pattern always implicitly locks the list when the full path exists, so the lock
      // list must end with an inode.
      mLockList.unlockLastInode();
      mLockList.unlockLastEdge();
    }
    mExistingInodes.remove(mExistingInodes.size() - 1);
  }

def find_write_predecessors(self, address):

        # A write operation must be preceded by:
        #   - The "enclosing writer", which is the writer at the address or
        #     the nearest writer higher (closer to the root) in the tree.
        #   - The "enclosing readers", which are the readers at the address
        #     or higher in the tree.
        #   - The "children writers", which include all writers which are
        #     lower in the tree than the address.
        #   - The "children readers", which include all readers which are
        #     lower in the tree than the address.
        #
        # The enclosing writer must be added as it may have modified a node
        # which must not happen after the current write.
        #
        # Writers which are higher in the tree than the enclosing writer may
        # have modified a node at or under the given address.  However, we do
        # not need to include them here as they will have been considered a
        # predecessor to the enclosing writer.
        #
        # Enclosing readers must be included.  Technically, we only need to add
        # enclosing readers which occurred after the enclosing writer, since
        # the readers preceding the writer will have been considered a
        # predecessor of the enclosing writer.  However, with the current
        # data structure we can not determine the difference between readers
        # so we specify them all; this is mostly harmless as it will not change
        # the eventual sort order generated by the scheduler.
        #
        # Children readers must be added, since their reads must happen prior
        # to the write.

        predecessors = set()

        enclosing_writer = None

        node_stream = self._tree.walk(address)

        address_len = len(address)

        # First, walk down from the root to the address, collecting all readers
        # and updating the enclosing_writer if needed.

        try:
            for node_address, node in node_stream:
                if node is not None:
                    predecessors.update(node.readers)

                    if node.writer is not None:
                        enclosing_writer = node.writer

                    if len(node_address) >= address_len:
                        break

        # If the address isn't on the tree, then there aren't any
        # predecessors below the node to worry about (because there
        # isn't anything at all), so return the predecessors that have
        # already been collected.
        except AddressNotInTree as err:
            if err.match is not None:
                return self.find_write_predecessors(err.match)

            return predecessors

        finally:
            if enclosing_writer is not None:
                predecessors.add(enclosing_writer)

        # Next, descend down the tree starting at the address node and
        # find all descendant readers and writers.

        for _, node in node_stream:
            if node is not None:
                if node.writer is not None:
                    predecessors.add(node.writer)

                predecessors.update(node.readers)

        return predecessors

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


Question:
Create a plot canvas with multiple box plots of given data.
@param data a data matrix of which each row will create a box plot.
@param labels the labels for each box plot.

public static PlotCanvas plot(double[][] data, String[] labels) {
        if (data.length != labels.length) {
            throw new IllegalArgumentException("Data size and label size don't match.");
        }

        double[] lowerBound = {0, Math.min(data)};
        double[] upperBound = {data.length, Math.max(data)};

        PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound);
        canvas.add(new BoxPlot(labels, data));

        double[] locations = new double[labels.length];
        for (int i = 0; i < labels.length; i++) {
            locations[i] = i + 0.5;
        }

        canvas.getAxis(0).addLabel(labels, locations);
        canvas.getAxis(0).setGridVisible(false);

        if (labels.length > 10) {
            canvas.getAxis(0).setRotation(-Math.PI / 2);
        }

        return canvas;
    }

def set_options(self, option_type, option_dict, force_options=False):

        if force_options:
            self.options[option_type].update(option_dict)
        elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list):
            # For multi-Axis
            self.options[option_type] = MultiAxis(option_type)
            for each_dict in option_dict:
                self.options[option_type].update(**each_dict)
        elif option_type == 'colors':
            self.options["colors"].set_colors(option_dict) # option_dict should be a list
        elif option_type in ["global" , "lang"]: #Highcharts.setOptions:
            self.setOptions[option_type].update_dict(**option_dict)
        else:
            self.options[option_type].update_dict(**option_dict)

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


Question:
ask the pattern for info so we can open the modal window and populate it
@param  {Boolean}      if the dropdown text should be changed

function(switchText) {

    // note that the modal is active and set switchText
    if ((switchText === undefined) || (switchText)) {
      switchText = true;
      DataSaver.updateValue('modalActive', 'true');
      modalViewer.active = true;
    }

    // send a message to the pattern
    var obj = JSON.stringify({ 'event': 'patternLab.patternQuery', 'switchText': switchText });
    document.getElementById('sg-viewport').contentWindow.postMessage(obj, modalViewer.targetOrigin);

  }

private function getOptionHtml($title, $name, $options)
    {
        $block = $this->_view->getLayout()->createBlock(\Magento\Framework\View\Element\Html\Select::class);
        $block->setOptions($options)
            ->setId('')
            ->setClass('')
            ->setTitle($title)
            ->setName($name)
            ->setExtraParams('style="width:160px"');

        return $block->toHtml();
    }

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


Question: // Parse parses the input and extract the frontmatter

func (m *Matter) Parse(input io.Reader) (front map[string]interface{}, body string, err error) {
	return m.parse(input)
}

public function toHeading()
    {
        $results = '';

        foreach ($this->getParser()->toArray() as $name => $types) {
            if (in_array($name, $this->ignores)) {
                continue;
            }

            $results .= "\t\t\t".'<th>'.ucwords($name).'</th>'.PHP_EOL;
        }

        return $results;
    }

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


Question:
Set a pagination link

@param string $name  The name of the link
@param string $value The link

@return self

private function setPaginationLink($name, $value)
    {
        if (! is_object($value) and ! is_string($value) and ! is_null($value)) {
            throw new ValidationException(
                'property "' . $name . '" has to be an object, a string or null, "' .
                gettype($value) . '" given.'
            );
        }

        if (is_string($value)) {
            $this->set($name, strval($value));
        } elseif (is_object($value)) {
            $this->setLink($name, $value);
        }
    }

def all(path, options = {}, &block)
      all = []
      list_type, list_item = get_list_types(path)

      result = request('GET', path, options)
      raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil?

      total = result.parsed[list_type]['totalItems'].to_i
      items = result.parsed[list_type]['itemsInPage'].to_i
      return all if total == 0

      pages = (total / config.page_size) + 1
      (0 .. pages - 1).each do |i|
        options[:query][:pgNum] = i
        result     = request('GET', path, options)
        raise RequestError.new result.status if result.status_code != 200
        list_items = result.parsed[list_type][list_item]
        list_items = [ list_items ] if items == 1
        list_items.each { |item| yield item if block_given? }
        all.concat list_items
      end
      all
    end

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


Question: // ThemeDir 主题所在文件夹的路径

func (s *Application) ThemeDir(args ...string) string {
	if len(args) < 1 {
		return filepath.Join(s.TemplateDir, s.theme)
	}
	return filepath.Join(s.TemplateDir, args[0])
}

def read_directories(dir = "")
      base = site.in_source_dir(dir)

      return unless File.directory?(base)

      dot_dirs = []
      dot_pages = []
      dot_static_files = []

      dot = Dir.chdir(base) { filter_entries(Dir.entries("."), base) }
      dot.each do |entry|
        file_path = @site.in_source_dir(base, entry)
        if File.directory?(file_path)
          dot_dirs << entry
        elsif Utils.has_yaml_header?(file_path)
          dot_pages << entry
        else
          dot_static_files << entry
        end
      end

      retrieve_posts(dir)
      retrieve_dirs(base, dir, dot_dirs)
      retrieve_pages(dir, dot_pages)
      retrieve_static_files(dir, dot_static_files)
    end

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


Question:
Retrieve a folder by its compound slug

@param $slug

@return mixed
@throws \Exception

public function getDocumentFolderBySlug($slug)
    {
        if ($slug === '/') {
            $path = $slug;
        } else {
            $path = '/' . $slug;
        }

        return $this->repository->getContentRepository()->getDocumentByPath($this->repository, $path, 'unpublished');
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question:
supply an array of files to the multibuffer. These will be read
  as the user presses next or last etc.

def add_files filearray, config={}
      filearray.each do |e| add_content(e, config.dup); end
    end

func newReadBuffer(path string, num int32, c *Client) *Buffer {
	buffers.RLock()
	// return the existing buffer if there is one
	if existing, exists := buffers.m[path]; exists {
		buffers.RUnlock()
		return existing
	}
	buffers.RUnlock()

	// make a new one
	b := &Buffer{Num: num, client: c}

	// add it to the global map
	buffers.Lock()
	buffers.m[path] = b
	buffers.Unlock()

	return b
}

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


Question:
Extract field

@param target is used to get object data.
@param key is used to get key value.
@param delimeter key delimeter
@return is used to return object data.

public static Object extract(Object target, String key, String delimeter)
    {
        if (target == null)
        {
            return target;
        }

        String keyHead = extractKeyHead(key, delimeter); // the return value of keyHead
        String keyTail = extractKeyTail(key, delimeter); // the return value of keyTail

        Object innerObject = null;

        // checking if the "Object: target" is Map or not
        if (target instanceof Map)
        {
            Map<?, ?> targetMap = (Map<?, ?>) target;
            innerObject = targetMap.get(keyHead); // get the object inside "keyHead"
        }
        else
        {
            BeanWrapperImpl baseWapper = new BeanWrapperImpl(target); // this is the reflection for getting the field value.
            innerObject = baseWapper.getPropertyValue(keyHead); // get the value from the field if the "keyHead" is not Map
        }

        if (innerObject == null)
        {
            return innerObject;
        }

        if (StringUtils.isEmpty(keyTail) == true)
        {
            return innerObject;
        }
        else
        {
            return extract(innerObject, keyTail, delimeter); // recursive method for calling self function again.
        }
    }

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question: // GetUniques returns the Uniques field if it's non-nil, zero value otherwise.

func (t *TrafficViews) GetUniques() int {
	if t == nil || t.Uniques == nil {
		return 0
	}
	return *t.Uniques
}

private function checkVisitorUuid()
    {
        if ( ! isset($this->visitorInfo['uuid']) || ! $this->visitorInfo['uuid'])
            $this->visitorInfo['uuid'] = $this->getVisitorIdFromSystem();
    }

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


Question:
Copies a directory recursively from $source path to $target directory path.
A Regex $fileFilter can be used as whitelist.

@param string $source
@param string $target
@param string $fileFilter

@return void

public function copyRecursive($source, $target, $fileFilter = '/.*/')
    {
        $filesystem = new Filesystem();
        $finder = new Finder();
        $finder->files()->in($source)->name($fileFilter);

        /** @var SplFileInfo $file */
        foreach ($finder as $file) {
            $filesystem->copy($file, $target . DIRECTORY_SEPARATOR . $file->getRelativePathname());
        }
    }

func (in *SecurityContext) DeepCopyInto(out *SecurityContext) {
	*out = *in
	if in.Capabilities != nil {
		in, out := &in.Capabilities, &out.Capabilities
		*out = new(Capabilities)
		(*in).DeepCopyInto(*out)
	}
	if in.Privileged != nil {
		in, out := &in.Privileged, &out.Privileged
		*out = new(bool)
		**out = **in
	}
	if in.SELinuxOptions != nil {
		in, out := &in.SELinuxOptions, &out.SELinuxOptions
		*out = new(SELinuxOptions)
		**out = **in
	}
	if in.WindowsOptions != nil {
		in, out := &in.WindowsOptions, &out.WindowsOptions
		*out = new(WindowsSecurityContextOptions)
		**out = **in
	}
	if in.RunAsUser != nil {
		in, out := &in.RunAsUser, &out.RunAsUser
		*out = new(int64)
		**out = **in
	}
	if in.RunAsGroup != nil {
		in, out := &in.RunAsGroup, &out.RunAsGroup
		*out = new(int64)
		**out = **in
	}
	if in.RunAsNonRoot != nil {
		in, out := &in.RunAsNonRoot, &out.RunAsNonRoot
		*out = new(bool)
		**out = **in
	}
	if in.ReadOnlyRootFilesystem != nil {
		in, out := &in.ReadOnlyRootFilesystem, &out.ReadOnlyRootFilesystem
		*out = new(bool)
		**out = **in
	}
	if in.AllowPrivilegeEscalation != nil {
		in, out := &in.AllowPrivilegeEscalation, &out.AllowPrivilegeEscalation
		*out = new(bool)
		**out = **in
	}
	if in.ProcMount != nil {
		in, out := &in.ProcMount, &out.ProcMount
		*out = new(ProcMountType)
		**out = **in
	}
	return
}

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


Question:
Compile top-level Geography dictionary.
    :param d:
    :return:

def compile_geo(d):

    logger_excel.info("enter compile_geo")
    d2 = OrderedDict()

    # get max number of sites, or number of coordinate points given.
    num_loc = _get_num_locations(d)

    # if there's one more than one location put it in a collection
    if num_loc > 1:
        d2["type"] = "FeatureCollection"
        features = []
        for idx in range(0, num_loc):
            # Do process for one site
            site = _parse_geo_locations(d, idx)
            features.append(site)
        d2["features"] = features

    # if there's only one location
    elif num_loc == 1:
        d2 = _parse_geo_location(d)

    logger_excel.info("exit compile_geo")
    return d2

@Override
	public void cacheResult(
		List<CPDefinitionLocalization> cpDefinitionLocalizations) {
		for (CPDefinitionLocalization cpDefinitionLocalization : cpDefinitionLocalizations) {
			if (entityCache.getResult(
						CPDefinitionLocalizationModelImpl.ENTITY_CACHE_ENABLED,
						CPDefinitionLocalizationImpl.class,
						cpDefinitionLocalization.getPrimaryKey()) == null) {
				cacheResult(cpDefinitionLocalization);
			}
			else {
				cpDefinitionLocalization.resetOriginalValues();
			}
		}
	}

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


Question:
Parses the given log file.

@param {string} filename File to parse

function (filename) {
		var resume = filename === true; // should only ever be set by resume calls
		var fd = this._fd = resume ? this._fd : fs.openSync(filename, 'r');
		var buffer = new Buffer(4096);
		var bytesRead;
		var current = '';
		var remainder = resume ? this._remainder : '';

		while (!this._paused && (bytesRead = fs.readSync(fd, buffer, 0, buffer.length))) {
			current = buffer.toString('utf-8');
			if (current.length > bytesRead) {
				current = current.slice(0, bytesRead);
			}
			remainder = this._remainder = this._parseLines(remainder + current);
		}

		// The loop will end either when EOF is reached, or pause was called.
		// In the former case, close the file; in the latter case, leave it
		// open with the expectation that we'll pick up where we left off.
		if (!this._paused) {
			fs.closeSync(fd);
		}
	}

public static BufferedReader newBufferedReader(Path path, Charset charset) throws IOException {
        return new BufferedReader(new InputStreamReader(newInputStream(path), charset));
    }

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


Question: Get the dataset ids from the config.

def load_ds_ids_from_config(self):
        """"""
        ids = []
        for dataset in self.datasets.values():
            # xarray doesn't like concatenating attributes that are lists
            # https://github.com/pydata/xarray/issues/2060
            if 'coordinates' in dataset and \
                    isinstance(dataset['coordinates'], list):
                dataset['coordinates'] = tuple(dataset['coordinates'])
            # Build each permutation/product of the dataset
            id_kwargs = []
            for key in DATASET_KEYS:
                val = dataset.get(key)
                if key in ["wavelength", "modifiers"] and isinstance(val,
                                                                     list):
                    # special case: wavelength can be [min, nominal, max]
                    # but is still considered 1 option
                    # it also needs to be a tuple so it can be used in
                    # a dictionary key (DatasetID)
                    id_kwargs.append((tuple(val), ))
                elif key == "modifiers" and val is None:
                    # empty modifiers means no modifiers applied
                    id_kwargs.append((tuple(), ))
                elif isinstance(val, (list, tuple, set)):
                    # this key has multiple choices
                    # (ex. 250 meter, 500 meter, 1000 meter resolutions)
                    id_kwargs.append(val)
                elif isinstance(val, dict):
                    id_kwargs.append(val.keys())
                else:
                    # this key only has one choice so make it a one
                    # item iterable
                    id_kwargs.append((val, ))
            for id_params in itertools.product(*id_kwargs):
                dsid = DatasetID(*id_params)
                ids.append(dsid)

                # create dataset infos specifically for this permutation
                ds_info = dataset.copy()
                for key in DATASET_KEYS:
                    if isinstance(ds_info.get(key), dict):
                        ds_info.update(ds_info[key][getattr(dsid, key)])
                    # this is important for wavelength which was converted
                    # to a tuple
                    ds_info[key] = getattr(dsid, key)
                self.ids[dsid] = ds_info

        return ids

func (s *SubscribeToDatasetInput) SetDeviceId(v string) *SubscribeToDatasetInput {
	s.DeviceId = &v
	return s
}

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


Question:
this function verify the existence of the type and adds it. it's called one time when the cache is cleared
@param string $name

public function initialize($name = "Unknown", $icon = null){
        if($this->em->getRepository(PageType::class)->findOneByTitle($name) === null){
            $type = new PageType();
            $type->setTitle($name);
            $type->setIcon($icon);
            $this->em->persist($type);
            $this->em->flush();
        }
    }

public static function arrayOf(IType $elementType) : ArrayType
    {
        $elementTypeString = $elementType->asTypeString();

        if (!isset(self::$arrays[$elementTypeString])) {
            self::$arrays[$elementTypeString] = new ArrayType($elementType);
        }

        return self::$arrays[$elementTypeString];
    }

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

public ResultType createResultTypeFromString(EDataType eDataType, String initialValue) {
		ResultType result = ResultType.get(initialValue);
		if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
		return result;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
// ServeDelivery handles AMQP Delivery messages
// It is strongly recommended to use *amqp.Channel as the
// Channel interface implementation.

func (s Subscriber) ServeDelivery(ch Channel) func(deliv *amqp.Delivery) {
	return func(deliv *amqp.Delivery) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		pub := amqp.Publishing{}

		for _, f := range s.before {
			ctx = f(ctx, &pub, deliv)
		}

		request, err := s.dec(ctx, deliv)
		if err != nil {
			s.errorHandler.Handle(ctx, err)
			s.errorEncoder(ctx, err, deliv, ch, &pub)
			return
		}

		response, err := s.e(ctx, request)
		if err != nil {
			s.errorHandler.Handle(ctx, err)
			s.errorEncoder(ctx, err, deliv, ch, &pub)
			return
		}

		for _, f := range s.after {
			ctx = f(ctx, deliv, ch, &pub)
		}

		if err := s.enc(ctx, &pub, response); err != nil {
			s.errorHandler.Handle(ctx, err)
			s.errorEncoder(ctx, err, deliv, ch, &pub)
			return
		}

		if err := s.responsePublisher(ctx, deliv, ch, &pub); err != nil {
			s.errorHandler.Handle(ctx, err)
			s.errorEncoder(ctx, err, deliv, ch, &pub)
			return
		}
	}

}

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

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

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

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

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

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

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

        methods = {}

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

        service.methods = methods

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

        return service

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


Question:
After a shipping address is edited, validate it and store the result.

@listen controller_action_postdispatch_adminhtml_sales_order_addressSave
@param Varien_Event_Observer $observer

public function validateAdminOrderAddressSave(Varien_Event_Observer $observer)
    {
        /** @var Fontis_Australia_Helper_Address $helper */
        $helper = Mage::helper('australia/address');
        if (!$helper->isValidationOrderSaveEnabled()) {
            return;
        }

        /** @var Mage_Adminhtml_Model_Session $session */
        $session = Mage::getSingleton('adminhtml/session');
        $errors = $session->getMessages()->getErrors();

        if (count($errors) > 0) {
            // We had an error when saving the address, so we'll skip validation
            $session->addWarning('Address validation has been skipped.');
            return;
        }

        try {
            /** @var Mage_Adminhtml_Controller_Action $controller */
            $controller = $observer->getControllerAction();
            if (!$controller) {
                return;
            }

            $addressId = $controller->getRequest()->getParam('address_id');
            /** @var Mage_Sales_Model_Order_Address $address */
            $address = Mage::getModel('sales/order_address')->load($addressId);
            if ($address->getAddressType() !== Mage_Sales_Model_Order_Address::TYPE_SHIPPING) {
                return;
            }
            $order = $address->getOrder();
            if (!$order) {
                return;
            }

            $ignoreValidation = $controller->getRequest()->getParam('override_validation');

            if ($ignoreValidation) {
                $result = array(
                    Fontis_Australia_Helper_Address::ADDRESS_OVERRIDE_FLAG => true
                );
                $order->setAddressValidated(Fontis_Australia_Helper_Address::ADDRESS_OVERRIDE);
            } else {
                // Validate the address and store the result on the order.
                $result = $helper->validateOrderAddress($order);
            }

            $order->save();

            // Use the result to add a message to the session telling the
            // admin about the validation status.
            $helper->addValidationMessageToSession($result, $session);
        } catch (Exception $err) {
            Mage::logException($err);
        }
    }

public function save(UserStructure $user)
    {
        $event = new Event\Save();
        $event->setUser($user);
        $this->getEventManager()->trigger($event);
        return $event->getResult();
    }

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


Question:
Take a UTF8 string and reverse it.

@param string  $str             the string to be reversed.
@param boolean $reverse_numbers whether to reverse numbers.

@return string The reversed string.

public function utf8Strrev($str, $reverse_numbers = false)
    {
        preg_match_all('/./us', $str, $ar);
        if ($reverse_numbers) {
            return join('', array_reverse($ar[0]));
        } else {
            $temp = array();
            foreach ($ar[0] as $value) {
                if (is_numeric($value) && !empty($temp[0]) && is_numeric($temp[0])) {
                    foreach ($temp as $key => $value2) {
                        if (is_numeric($value2)) {
                            $pos = ($key + 1);
                        } else {
                            break;
                        }
                    }
                    $temp2 = array_splice($temp, $pos);
                    $temp  = array_merge($temp, array($value), $temp2);
                } else {
                    array_unshift($temp, $value);
                }
            }
            return implode('', $temp);
        }
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: Marshall the given parameter object.

public void marshall(InputSourceRequest inputSourceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(inputSourceRequest.getPasswordParam(), PASSWORDPARAM_BINDING);
            protocolMarshaller.marshall(inputSourceRequest.getUrl(), URL_BINDING);
            protocolMarshaller.marshall(inputSourceRequest.getUsername(), USERNAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
// monotoneChain iterates through the points, selecting the maximal subset of points
// such that the edge chain makes only left (CCW) turns.

func (q *ConvexHullQuery) monotoneChain() []Point {
	var output []Point
	for _, p := range q.points {
		// Remove any points that would cause the chain to make a clockwise turn.
		for len(output) >= 2 && RobustSign(output[len(output)-2], output[len(output)-1], p) != CounterClockwise {
			output = output[:len(output)-1]
		}
		output = append(output, p)
	}
	return output
}

func (p *pinner) Flush() error {
	p.lock.Lock()
	defer p.lock.Unlock()

	ctx := context.TODO()

	internalset := cid.NewSet()
	recordInternal := internalset.Add

	root := &mdag.ProtoNode{}
	{
		n, err := storeSet(ctx, p.internal, p.directPin.Keys(), recordInternal)
		if err != nil {
			return err
		}
		if err := root.AddNodeLink(linkDirect, n); err != nil {
			return err
		}
	}

	{
		n, err := storeSet(ctx, p.internal, p.recursePin.Keys(), recordInternal)
		if err != nil {
			return err
		}
		if err := root.AddNodeLink(linkRecursive, n); err != nil {
			return err
		}
	}

	// add the empty node, its referenced by the pin sets but never created
	err := p.internal.Add(ctx, new(mdag.ProtoNode))
	if err != nil {
		return err
	}

	err = p.internal.Add(ctx, root)
	if err != nil {
		return err
	}

	k := root.Cid()

	internalset.Add(k)
	if err := p.dstore.Put(pinDatastoreKey, k.Bytes()); err != nil {
		return fmt.Errorf("cannot store pin state: %v", err)
	}
	p.internalPin = internalset
	return nil
}

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


Question:
格式化URL各部分

@param array $fullUrlInfo
@return void

private function formatUrlData(array &$fullUrlInfo): void
    {
        if (! isset($fullUrlInfo['scheme'])) {
            if (! isset($_SERVER['HTTPS'])) {
                $fullUrlInfo['scheme'] = 'http';
            } elseif ($_SERVER['HTTPS'] == 'off') {
                $fullUrlInfo['scheme'] = 'http';
            } else {
                $fullUrlInfo['scheme'] = 'https';
            }
        }
        if (! isset($fullUrlInfo['host'])) {
            $fullUrlInfo['host'] = 'localhost';
            if (isset($_SERVER['HTTP_HOST'])) {
                $fullUrlInfo['host'] = $_SERVER['HTTP_HOST'];
            }
        }
        if (! isset($fullUrlInfo['port'])) {
            $fullUrlInfo['port'] = 80;
            if (isset($_SERVER['SERVER_PORT'])) {
                $fullUrlInfo['port'] = $_SERVER['SERVER_PORT'];
            }
        }
    }

protected function prepareCurl()
    {
        $this->curl = curl_init();
        $this->complete = Complete::factory(function() {
            if ($this->curl) {
                curl_close($this->curl);
            }
            $this->curl     = null;
            $this->complete = null;
        });

        foreach(self::$curlOptions as $option => $value) {
            curl_setopt($this->curl, $option, $value);
        }
        if ($this->method === HttpMethods::POST) {
            curl_setopt($this->curl, CURLOPT_POST, true);
        }
        if (!empty($this->auth)) {
            curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
                "%s:%s",
                $this->auth["user"],
                $this->auth["pass"]
            ));
        }
    }

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


Question:
Initializes the repository's prepared statements.

@return void

public function init()
    {

        // initialize the prepared statements
        $this->customerAddressDatetimesStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::CUSTOMER_ADDRESS_DATETIMES));
    }

public function buildResultSet(Response $response, Query $query): ResultSet
    {
        $resultSet = $this->builder->buildResultSet($response, $query);

        $this->processor->process($resultSet);

        return $resultSet;
    }

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


Question:
Method: write_wmc_Layer
Create a Layer node given a layer context object. This method adds
elements specific to version 1.1.0.

Parameters:
context - {Object} A layer context object.}

Returns:
{Element} A WMC Layer element node.

function(context) {
        var node = OpenLayers.Format.WMC.v1.prototype.write_wmc_Layer.apply(
            this, [context]
        );

        // min/max scale denominator elements go before the 4th element in v1
        if(context.maxScale) {
            var minSD = this.createElementNS(
                this.namespaces.sld, "sld:MinScaleDenominator"
            );
            minSD.appendChild(this.createTextNode(context.maxScale.toPrecision(16)));
            node.appendChild(minSD);
        }

        if(context.minScale) {
            var maxSD = this.createElementNS(
                this.namespaces.sld, "sld:MaxScaleDenominator"
            );
            maxSD.appendChild(this.createTextNode(context.minScale.toPrecision(16)));
            node.appendChild(maxSD);
        }

        // optional SRS element(s)
        if (context.srs) {
            for(var name in context.srs) {
                node.appendChild(this.createElementDefaultNS("SRS", name));
            }
        }

        // optional FormatList element
        node.appendChild(this.write_wmc_FormatList(context));

        // optional StyleList element
        node.appendChild(this.write_wmc_StyleList(context));

        // optional DimensionList element
        if (context.dimensions) {
            node.appendChild(this.write_wmc_DimensionList(context));
        }

        // OpenLayers specific properties go in an Extension element
        node.appendChild(this.write_wmc_LayerExtension(context));

        return node;

    }

@Override
    public void executeQuery(
            final ObjectClass objClass,
            final Operand query,
            final ResultsHandler handler,
            final OperationOptions options) {

        if (LOG.isOk()) {
            LOG.ok("Execute query: " + query);
        }

        // check objectclass
        if (objClass == null || (!objClass.equals(ObjectClass.ACCOUNT))) {
            throw new IllegalArgumentException("Invalid objectclass");
        }

        // check handler
        if (handler == null) {
            throw new IllegalArgumentException("Invalid handler");
        }

        // get web service client
        final Provisioning provisioning = connection.getProvisioning();
        if (provisioning == null) {
            throw new IllegalStateException("Web Service client not found");
        }

        try {
            final List<WSUser> resultSet = provisioning.query(query);
            if (resultSet == null) {
                return;
            }

            boolean handle = true;
            for (final Iterator<WSUser> i = resultSet.iterator(); i.hasNext() && handle;) {
                final WSUser user = i.next();

                if (LOG.isOk()) {
                    LOG.ok("Found user: {0}", user);
                }

                try {
                    handle = handler.handle(buildConnectorObject(user.getAttributes()).build());
                    LOG.ok("Handle: {0}", handle);
                } catch (Exception e) {
                    LOG.error(e, "Error building connector object for {0}", user);
                }
            }
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

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


Question:
Parse bytes into a in-memory proto

    @params
    s is bytes containing serialized proto
    proto is a in-memory proto object

    @return
    The proto instance filled in by s

def _deserialize(s, proto):  # type: (bytes, _Proto) -> _Proto
    '''

    '''
    if not isinstance(s, bytes):
        raise ValueError('Parameter s must be bytes, but got type: {}'.format(type(s)))

    if not (hasattr(proto, 'ParseFromString') and callable(proto.ParseFromString)):
        raise ValueError('No ParseFromString method is detected. '
                         '\ntype is {}'.format(type(proto)))

    decoded = cast(Optional[int], proto.ParseFromString(s))
    if decoded is not None and decoded != len(s):
        raise google.protobuf.message.DecodeError(
            "Protobuf decoding consumed too few bytes: {} out of {}".format(
                decoded, len(s)))
    return proto

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

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

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

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


Question:
Returns the angle in degrees for the given ring, based on the hash.

@param integer $ring
@param string $hash

@return integer

private function getRingAngle($ring, $hash)
    {
        return 10 * pow(2, 3 - $ring) * array_reduce(
            str_split($hash, pow(2, 3 - $ring)),
            function ($total, $substr) {
                return $total + (hexdec($substr) % 2);
            },
            0
        );
    }

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:
/*
(non-Javadoc)

@see
com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java.
lang.String)

@Override
    protected Client instantiateClient(String persistenceUnit)
    {
        return new CouchbaseClient(kunderaMetadata, indexManager, reader, externalProperties, persistenceUnit,
                this.bucket, this.clientMetadata);
    }

public static Store get(final String _name)
        throws CacheReloadException
    {
        final Cache<String, Store> cache = InfinispanCache.get().<String, Store>getCache(Store.NAMECACHE);
        if (!cache.containsKey(_name)) {
            Store.getStoreFromDB(CIDB.Store.Name, _name);
        }
        return cache.get(_name);
    }

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


Question: // newNonrecursiveTree TODO(rjeczalik)

func newNonrecursiveTree(w watcher, c, rec chan EventInfo) *nonrecursiveTree {
	if rec == nil {
		rec = make(chan EventInfo, buffer)
	}
	t := &nonrecursiveTree{
		root: root{nd: newnode("")},
		w:    w,
		c:    c,
		rec:  rec,
	}
	go t.dispatch(c)
	go t.internal(rec)
	return t
}

def make_tree(self):

        self.tree['is_ready'] = False
        leaf_count = len(self.tree['leaves'])
        if leaf_count > 0:
            # skip this whole process if there are no leaves added to the tree
            self._unshift(self.tree['levels'], self.tree['leaves'])
            while len(self.tree['levels'][0]) > 1:
                self._unshift(self.tree['levels'], self._calculate_next_level())
        self.tree['is_ready'] = True

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


Question:
// WrapWriter wraps an http.ResponseWriter, returning a proxy that allows you to
// hook into various parts of the response process.

func WrapWriter(w http.ResponseWriter) WriterProxy {
	_, cn := w.(http.CloseNotifier)
	_, fl := w.(http.Flusher)
	_, hj := w.(http.Hijacker)
	_, rf := w.(io.ReaderFrom)

	bw := basicWriter{ResponseWriter: w}
	if cn && fl && hj && rf {
		return &fancyWriter{bw}
	}
	if fl {
		return &flushWriter{bw}
	}
	return &bw
}

func (wp *WorkerPool) JobWithOptions(name string, jobOpts JobOptions, fn interface{}) *WorkerPool {
	jobOpts = applyDefaultsAndValidate(jobOpts)

	vfn := reflect.ValueOf(fn)
	validateHandlerType(wp.contextType, vfn)
	jt := &jobType{
		Name:           name,
		DynamicHandler: vfn,
		JobOptions:     jobOpts,
	}
	if gh, ok := fn.(func(*Job) error); ok {
		jt.IsGeneric = true
		jt.GenericHandler = gh
	}

	wp.jobTypes[name] = jt

	for _, w := range wp.workers {
		w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
	}

	return wp
}

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


Question:
Helper method for generating key SQL snippets.

@param string $prefix The key prefix
@param array $data Key data.
@return string

protected function _keySql($prefix, $data)
    {
        $columns = array_map(
            [$this->_driver, 'quoteIdentifier'],
            $data['columns']
        );
        foreach ($data['columns'] as $i => $column) {
            if (isset($data['length'][$column])) {
                $columns[$i] .= sprintf('(%d)', $data['length'][$column]);
            }
        }
        if ($data['type'] === TableSchema::CONSTRAINT_FOREIGN) {
            return $prefix . sprintf(
                ' FOREIGN KEY (%s) REFERENCES %s (%s) ON UPDATE %s ON DELETE %s',
                implode(', ', $columns),
                $this->_driver->quoteIdentifier($data['references'][0]),
                $this->_convertConstraintColumns($data['references'][1]),
                $this->_foreignOnClause($data['update']),
                $this->_foreignOnClause($data['delete'])
            );
        }

        return $prefix . ' (' . implode(', ', $columns) . ')';
    }

func MakeKey(name []byte, tags Tags) []byte {
	return AppendMakeKey(nil, name, tags)
}

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


Question: Output a list of tuples(story, 1st continuation, 2nd continuation, label)

def load_rocstories_dataset(dataset_path):

    with open(dataset_path, encoding='utf_8') as f:
        f = csv.reader(f)
        output = []
        next(f) # skip the first line
        for line in tqdm(f):
            output.append((' '.join(line[1:5]), line[5], line[6], int(line[-1])-1))
    return output

def start_notebook_on_demand(self, name, context):

        if self.is_running(name):

            last_context = self.get_context(name)
            logger.info("Notebook context change detected for %s", name)
            if not self.is_same_context(context, last_context):
                self.stop_notebook(name)
                # Make sure we don't get race condition over context.json file
                time.sleep(2.0)
            else:
                return last_context, False

        err_log = os.path.join(self.get_work_folder(name), "notebook.stderr.log")
        logger.info("Launching new Notebook named %s, context is %s", name, context)
        logger.info("Notebook log is %s", err_log)

        self.start_notebook(name, context)
        time.sleep(1)
        context = self.get_context(name)
        if "notebook_name" not in context:
            # Failed to launch within timeout
            raise RuntimeError("Failed to launch IPython Notebook, see {}".format(err_log))

        return context, True

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


Question:
Create new instance of text protocol backend handler.

@param sql SQL to be executed
@param backendConnection backend connection
@return instance of text protocol backend handler

public static TextProtocolBackendHandler newInstance(final String sql, final BackendConnection backendConnection) {
        if (sql.toUpperCase().startsWith(ShardingCTLBackendHandlerFactory.SCTL)) {
            return ShardingCTLBackendHandlerFactory.newInstance(sql, backendConnection);
        }
        // TODO use sql parser engine instead of string compare
        Optional<TransactionOperationType> transactionOperationType = TransactionOperationType.getOperationType(sql.toUpperCase());
        if (transactionOperationType.isPresent()) {
            return new TransactionBackendHandler(transactionOperationType.get(), backendConnection);
        }
        if (sql.toUpperCase().contains(SET_AUTOCOMMIT_1)) {
            return backendConnection.getStateHandler().isInTransaction() ? new TransactionBackendHandler(TransactionOperationType.COMMIT, backendConnection) : new SkipBackendHandler();
        }
        SQLStatement sqlStatement = new SQLJudgeEngine(sql).judge();
        return SQLType.DAL == sqlStatement.getType() ? createDALBackendHandler(sqlStatement, sql, backendConnection) : new QueryBackendHandler(sql, backendConnection);
    }

def _PrintSessionsDetails(self, storage_reader):

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

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

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

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

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

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

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

      table_view.Write(self._output_writer)

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

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

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

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

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


Question:
true if water mark columns and water mark type provided

@return true if water mark exists

private boolean isWatermarkExists() {
    if (!Strings.isNullOrEmpty(this.state.getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY)) && !Strings
        .isNullOrEmpty(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE))) {
      return true;
    }
    return false;
  }

protected function setConnectedRelationOptions()
    {
        $pivotTable = $this->defaultOptions['pivot_table'];
        $foreignKey = $this->defaultOptions['foreign_key'];
        $relatedKey = $this->defaultOptions['related_key'];

        if (! $this->db->isTableExists($pivotTable)) {
            $question = "Can't find table {$this->text['pivot_table']} in the database as {$this->text['pivot_text']}, choice one!";
            $pivotTable = $this->options['pivot_table'] = $this->command->choice(
                $question, $this->getTables());

            $this->text['pivot_table'] = "[".$this->command->paintString($pivotTable, 'green')."]";
        }

        if (! $this->db->isFieldExists($pivotTable, $foreignKey)) {
            $question = "Can't find field {$this->text['foreign_key']} in the table {$this->text['pivot_table']} as {$this->text['foreign_text']} of table {$this->text['table']}, choice one!";
            $this->options['foreign_key'] = $this->command->choice($question, $this->getFields($pivotTable));
        }

        if (! $this->db->isFieldExists($pivotTable, $relatedKey)) {
            $question = "Can't find field {$this->text['related_key']} in the table {$this->text['pivot_table']} as {$this->text['related_text']} of table {$this->text['to_table']}, choice one!";
            $this->options['related_key'] = $this->command->choice($question, $this->getFields($pivotTable));
        }
    }

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


Question:
downloads a given file into a specified filename.
 If block is given returns download progress

def download
      raise "#{@source_url} is not accessible" unless @url.valid?
      f = open(@file_path,'wb')
      count = 0
      @url.net_http.request_get(@url.path) do |r|
        r.read_body do |s|
          @download_length += s.length
          f.write s
          if block_given?
            count += 1
            if count % 100 == 0
              yield @download_length
            end
          end
        end
      end
      f.close
      downloaded = @download_length
      @download_length = 0
      downloaded
    end

def _read_body_by_chunk(self, response, file, raw=False):
        '''
        '''
        reader = ChunkedTransferReader(self._connection)

        file_is_async = hasattr(file, 'drain')

        while True:
            chunk_size, data = yield from reader.read_chunk_header()

            self._data_event_dispatcher.notify_read(data)
            if raw:
                file.write(data)

            if not chunk_size:
                break

            while True:
                content, data = yield from reader.read_chunk_body()

                self._data_event_dispatcher.notify_read(data)

                if not content:
                    if raw:
                        file.write(data)

                    break

                content = self._decompress_data(content)

                if file:
                    file.write(content)

                    if file_is_async:
                        yield from file.drain()

        content = self._flush_decompressor()

        if file:
            file.write(content)

            if file_is_async:
                yield from file.drain()

        trailer_data = yield from reader.read_trailer()

        self._data_event_dispatcher.notify_read(trailer_data)

        if file and raw:
            file.write(trailer_data)

            if file_is_async:
                yield from file.drain()

        response.fields.parse(trailer_data)

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


Question: Flush using raw of buffered methods.

def _flush_raw_or_buffered(self):

        # Flush only if bytes written
        # This avoid no required process/thread
        # creation and network call.
        # This step is performed by raw stream.
        if self._buffer_seek and self._seek:
            self._seek += 1
            with handle_os_exceptions():
                self._flush()

        # If data lower than buffer size
        # flush data with raw stream to reduce IO calls
        elif self._buffer_seek:
            self._raw._write_buffer = self._get_buffer()
            self._raw._seek = self._buffer_seek
            self._raw.flush()

def _submit_results(self):

        if self._cur_res_id and self._cur_values:
            # Setting DefaultResult just because it is obligatory.
            self._addRawResult(self._cur_res_id, self._cur_values)
            self._reset()

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


Question: // Implementation of the stringer interface. Useful for exploration

func (r Response) String() string {
	return fmt.Sprintf("Response \nRequestId: %v, \nStatus: {%#v}, \nResult: {%#v}\n", r.RequestId, r.Status, r.Result)
}

def search_for_port(port_glob, req, expected_res):
    '''  '''

    # Check that the USB port actually exists, based on the known vendor and
    # product ID.
    if usb.core.find(idVendor=0x0403, idProduct=0x6001) is None:
        return None

    # Find ports matching the supplied glob.
    ports = glob.glob(port_glob)
    if len(ports) == 0:
        return None

    for port in ports:
        with r12_serial_port(port) as ser:
            if not ser.isOpen():
                ser.open()

            # Write a request out.
            if sys.version_info[0] == 2:
                ser.write(str(req).encode('utf-8'))
            else:
                ser.write(bytes(req, 'utf-8'))

            # Wait a short period to allow the connection to generate output.
            time.sleep(0.1)

            # Read output from the serial connection check if it's what we want.
            res = ser.read(ser.in_waiting).decode(OUTPUT_ENCODING)
            if expected_res in res:
                return port

    raise ArmException('ST Robotics connection found, but is not responsive.'
                       + ' Is the arm powered on?')
    return None

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


Question:
Set labels to span that can be used for tracing.
    :param span: Span object

def set_monitored_resource_attributes(span):

    resource = monitored_resource.get_instance()
    if resource is not None:
        resource_type = resource.get_type()
        resource_labels = resource.get_labels()

        if resource_type == 'gke_container':
            resource_type = 'k8s_container'
            set_attribute_label(span, resource_type, resource_labels,
                                'project_id')
            set_attribute_label(span, resource_type, resource_labels,
                                'cluster_name')
            set_attribute_label(span, resource_type, resource_labels,
                                'container_name')
            set_attribute_label(span, resource_type, resource_labels,
                                'namespace_id', 'namespace_name')
            set_attribute_label(span, resource_type, resource_labels,
                                'pod_id', 'pod_name')
            set_attribute_label(span, resource_type, resource_labels,
                                'zone', 'location')

        elif resource_type == 'gce_instance':
            set_attribute_label(span, resource_type, resource_labels,
                                'project_id')
            set_attribute_label(span, resource_type, resource_labels,
                                'instance_id')
            set_attribute_label(span, resource_type, resource_labels,
                                'zone')

        elif resource_type == 'aws_ec2_instance':
            set_attribute_label(span, resource_type, resource_labels,
                                'aws_account')
            set_attribute_label(span, resource_type, resource_labels,
                                'instance_id')
            set_attribute_label(span, resource_type, resource_labels,
                                'region', label_value_prefix='aws:')

def on_menu_clear_interpretation(self, event):
        '''

        '''

        #  delete all previous interpretation
        for sp in list(self.Data.keys()):
            del self.Data[sp]['pars']
            self.Data[sp]['pars'] = {}
            self.Data[sp]['pars']['lab_dc_field'] = self.Data[sp]['lab_dc_field']
            self.Data[sp]['pars']['er_specimen_name'] = self.Data[sp]['er_specimen_name']
            self.Data[sp]['pars']['er_sample_name'] = self.Data[sp]['er_sample_name']
        self.Data_samples = {}
        self.Data_sites = {}
        self.tmin_box.SetValue("")
        self.tmax_box.SetValue("")
        self.clear_boxes()
        self.draw_figure(self.s)

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


Question:
Checks if an OPTIONS request with the access-control-request-headers containing authorization is being made
@param request
@returns {boolean}

function validCorsPreflight(request) {
  if (request.method === 'OPTIONS' && request.headers.has('access-control-request-headers')) {
    return request.headers.get('access-control-request-headers').split(',').map(function (header) {
      return header.trim();
    }).includes('authorization');
  } else {
    return false;
  }
}

func (o *CreateOAuth2ClientParams) WithTimeout(timeout time.Duration) *CreateOAuth2ClientParams {
	o.SetTimeout(timeout)
	return o
}

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