Question: // returns days since Jan 1st 0001 in Gregorian calendar

func gregorianDays(year, yearday int) int {
	year0 := year - 1
	return year0*365 + year0/4 - year0/100 + year0/400 + yearday - 1
}

protected function getFormat($format)
    {
        if ($format === false) {
            $format = 'none';
        }

        $types = [
            'none' => \IntlDateFormatter::NONE,
            'short' => \IntlDateFormatter::SHORT,
            'medium' => \IntlDateFormatter::MEDIUM,
            'long' => \IntlDateFormatter::LONG,
            'full' => \IntlDateFormatter::FULL
        ];

        return isset($types[$format]) ? $types[$format] : null;
    }

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


Question:
Check if item exist.
@param string $key
@return bool

public function has($key)
    {
        $key = trim($key, '.');
        if (strpos($key, '.') !== false) {
            $array =& $this->_items;
            foreach (explode('.', $key) as $v) {
                if (!isset($array[$v]))
                    return false;
                else
                    $array =& $array[$v];
            }
            return true;
        } else {
            return array_key_exists($key, $this->_items);
        }
    }

public function getSearchProduct()
    {
        if ($this->_oSearchProduct === null) {
            $this->_oSearchProduct = false;
            $sSearchArtNum = $this->getSearchProductArtNr();

            foreach ($this->getProductList() as $oProduct) {
                if ($oProduct->oxarticles__oxartnum->value == $sSearchArtNum) {
                    $this->_oSearchProduct = $oProduct;
                    break;
                }
            }
        }

        return $this->_oSearchProduct;
    }

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


Question:
Sets the theme for this chart by specifying a theme class.

A theme can only be set via one setTheme method. An
{@link IllegalStateException} will be thrown if you call two setTheme
methods.

@param theme the theme class.

public void setTheme(final Theme theme) {
        if (this.themeReference != null || this.themeUrl != null) {
            throw new IllegalStateException(
                    "A theme can only be defined once. Calling different setTheme methods is not allowed!");
        }
        this.theme = theme;
    }

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

    mainToolBar = new javax.swing.JToolBar();
    buttonLoad = new javax.swing.JButton();
    buttonSave = new javax.swing.JButton();
    buttonCopy = new javax.swing.JButton();
    buttonPaste = new javax.swing.JButton();
    buttonClearAll = new javax.swing.JButton();
    jPanel1 = new javax.swing.JPanel();
    labelCursorPos = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JSeparator();
    labelWrapMode = new javax.swing.JLabel();
    filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(16, 0), new java.awt.Dimension(16, 0), new java.awt.Dimension(16, 32767));

    setLayout(new java.awt.BorderLayout());

    mainToolBar.setFloatable(false);
    mainToolBar.setRollover(true);

    buttonLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/disk16.png"))); // NOI18N
    java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("com/igormaznitsa/nbmindmap/i18n/Bundle"); // NOI18N
    buttonLoad.setText(bundle.getString("PlainTextEditor.buttonImport")); // NOI18N
    buttonLoad.setToolTipText(bundle.getString("PlainTextEditor.buttonLoad.toolTipText")); // NOI18N
    buttonLoad.setFocusable(false);
    buttonLoad.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    buttonLoad.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    buttonLoad.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buttonLoadActionPerformed(evt);
      }
    });
    mainToolBar.add(buttonLoad);

    buttonSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/file_save16.png"))); // NOI18N
    buttonSave.setText(bundle.getString("PlaintextEditor.buttonExport")); // NOI18N
    buttonSave.setToolTipText(bundle.getString("PlainTextEditor.buttonSave.toolTipText")); // NOI18N
    buttonSave.setFocusable(false);
    buttonSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    buttonSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    buttonSave.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buttonSaveActionPerformed(evt);
      }
    });
    mainToolBar.add(buttonSave);

    buttonCopy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/page_copy16.png"))); // NOI18N
    buttonCopy.setText(bundle.getString("PlainTextEditor.buttonCopy.text")); // NOI18N
    buttonCopy.setToolTipText(bundle.getString("PlainTextEditor.buttonCopy.toolTipText")); // NOI18N
    buttonCopy.setFocusable(false);
    buttonCopy.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    buttonCopy.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    buttonCopy.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buttonCopyActionPerformed(evt);
      }
    });
    mainToolBar.add(buttonCopy);

    buttonPaste.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/paste_plain16.png"))); // NOI18N
    buttonPaste.setText(bundle.getString("PlainTextEditor.buttonPaste.text")); // NOI18N
    buttonPaste.setToolTipText(bundle.getString("PlainTextEditor.buttonPaste.toolTipText")); // NOI18N
    buttonPaste.setFocusable(false);
    buttonPaste.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    buttonPaste.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    buttonPaste.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buttonPasteActionPerformed(evt);
      }
    });
    mainToolBar.add(buttonPaste);

    buttonClearAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/nbmindmap/icons/cross16.png"))); // NOI18N
    buttonClearAll.setText(bundle.getString("PlainTextEditor.buttonClearAll.text")); // NOI18N
    buttonClearAll.setToolTipText(bundle.getString("PlainTextEditor.buttonClearAll.toolTipText")); // NOI18N
    buttonClearAll.setFocusable(false);
    buttonClearAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    buttonClearAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    buttonClearAll.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buttonClearAllActionPerformed(evt);
      }
    });
    mainToolBar.add(buttonClearAll);

    add(mainToolBar, java.awt.BorderLayout.PAGE_START);

    jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

    labelCursorPos.setText("...:..."); // NOI18N
    jPanel1.add(labelCursorPos);

    jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
    jSeparator2.setPreferredSize(new java.awt.Dimension(8, 16));
    jPanel1.add(jSeparator2);

    labelWrapMode.setText("..."); // NOI18N
    labelWrapMode.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    labelWrapMode.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        labelWrapModeMouseClicked(evt);
      }
    });
    jPanel1.add(labelWrapMode);
    jPanel1.add(filler1);

    add(jPanel1, java.awt.BorderLayout.PAGE_END);
  }

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


Question: Apply value of quality parameter.

def do_quality(self, quality):
        """"""
        infile = self.tmpfile
        outfile = self.basename + '.col'
        # Quality (bit-depth):
        if (quality == 'grey' or quality == 'gray'):
            if (self.shell_call('cat ' + infile + ' | ' + self.ppmtopgm + ' > ' + outfile)):
                raise IIIFError(
                    text="Oops... got nonzero output from ppmtopgm.")
            self.tmpfile = outfile
        elif (quality == 'bitonal'):
            if (self.shell_call('cat ' + infile + ' | ' + self.ppmtopgm + ' | ' + self.pamditherbw + ' > ' + outfile)):
                raise IIIFError(
                    text="Oops... got nonzero output from ppmtopgm.")
            self.tmpfile = outfile
        elif ((quality == 'native' and self.api_version < '2.0') or
              (quality == 'default' and self.api_version >= '2.0') or
              quality == 'color'):
            self.tmpfile = infile
        else:
            raise IIIFError(code=400, parameter='quality',
                            text="Unknown quality parameter value requested.")

def QA_SU_save_option_commodity_min(engine, client=DATABASE):
    '''

    '''
    engine = select_save_engine(engine)
    engine.QA_SU_save_option_commodity_min(client=client)

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


Question:
<p>
Collection of objects containing properties for each player session that matches the request.
</p>

@param playerSessions
Collection of objects containing properties for each player session that matches the request.

public void setPlayerSessions(java.util.Collection<PlayerSession> playerSessions) {
        if (playerSessions == null) {
            this.playerSessions = null;
            return;
        }

        this.playerSessions = new java.util.ArrayList<PlayerSession>(playerSessions);
    }

function(class_data) {

		var prototype = {},
			skeleton = class_data.skeleton,
			serialized_value,
			constructor_actions = [],
			name,
			source,
			constructor,
			object_properties,
			uses_references = false,
			is_monomorphic = class_data.is_monomorphic;

		for (name in skeleton) {

			switch (skeleton[name].type) {
				case this.MEMBER_TYPES.STRING:
					if (is_monomorphic) {
						serialized_value = Firestorm.String.quote(skeleton[name].value);
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number
					if (is_monomorphic) {
						serialized_value = skeleton[name].value + '';
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.EMPTY_ARRAY:
					serialized_value = "[]";
					break;
				case this.MEMBER_TYPES.INLINE_ARRAY:
					serialized_value = this._serializeInlineArray(skeleton[name].value);
					break;
				case this.MEMBER_TYPES.REGEXP:
				case this.MEMBER_TYPES.FUNCTION:
					prototype[name] = class_data.references[skeleton[name].index];
					break;
				case this.MEMBER_TYPES.SLICE_ARRAY:
					serialized_value = 'r[' + skeleton[name].index + '].slice()';
					uses_references = true;
					break;
				case this.MEMBER_TYPES.OBJECT:
					object_properties = [];
					if (this._serializeSkeleton(skeleton[name].skeleton, class_data, "\t", object_properties)) {
						uses_references = true;
					}
					serialized_value = object_properties.length
						? "{\n\t" + object_properties.join(",\n\t") + "\n}"
						: "{}";
					break;
				default:
					Lava.t("[_buildRealConstructor] unknown property descriptor type: " + skeleton[name].type);
			}

			if (serialized_value) {

				if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) {

					constructor_actions.push('this.' + name + ' = ' + serialized_value);

				} else {

					constructor_actions.push('this[' + Firestorm.String.quote(name) + '] = ' + serialized_value);

				}

				serialized_value = null;

			}

		}

		for (name in class_data.shared) {

			prototype[name] = class_data.shared[name];

		}

		prototype.Class = class_data;

		source = (uses_references ? ("var r=this.Class.references;\n") : '')
			+ constructor_actions.join(";\n")
			+ ";";

		if (class_data.skeleton.init) {

			source += "\nthis.init.apply(this, arguments);";

		}

		constructor = new Function(source);
		// for Chrome we could assign prototype object directly,
		// but in Firefox this will result in performance degradation
		Firestorm.extend(constructor.prototype, prototype);
		return constructor;

	}

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


Question:
copies template cell to result row into result column. Fills this cell with data from band

@param templateCell - template cell
@param resultRow    - result row
@param resultColumn - result column
@param band         - band

private HSSFCell copyCellFromTemplate(HSSFCell templateCell, HSSFRow resultRow, int resultColumn, BandData band) {
        checkThreadInterrupted();
        if (templateCell == null) return null;

        HSSFCell resultCell = resultRow.createCell(resultColumn);

        HSSFCellStyle templateStyle = templateCell.getCellStyle();
        HSSFCellStyle resultStyle = copyCellStyle(templateStyle);
        resultCell.setCellStyle(resultStyle);

        String templateCellValue = "";
        int cellType = templateCell.getCellType();

        if (cellType != HSSFCell.CELL_TYPE_FORMULA && cellType != HSSFCell.CELL_TYPE_NUMERIC) {
            HSSFRichTextString richStringCellValue = templateCell.getRichStringCellValue();
            templateCellValue = richStringCellValue != null ? richStringCellValue.getString() : "";

            templateCellValue = extractStyles(templateCell, resultCell, templateCellValue, band);
        }

        if (cellType == HSSFCell.CELL_TYPE_STRING && containsJustOneAlias(templateCellValue)) {
            updateValueCell(rootBand, band, templateCellValue, resultCell,
                    drawingPatriarchsMap.get(resultCell.getSheet()));
        } else {
            String cellValue = inlineBandDataToCellString(templateCell, templateCellValue, band);
            setValueToCell(resultCell, cellValue, cellType);
        }

        return resultCell;
    }

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case BpsimPackage.ELEMENT_PARAMETERS__TIME_PARAMETERS:
				return timeParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__CONTROL_PARAMETERS:
				return controlParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__RESOURCE_PARAMETERS:
				return resourceParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__PRIORITY_PARAMETERS:
				return priorityParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__COST_PARAMETERS:
				return costParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__PROPERTY_PARAMETERS:
				return propertyParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__VENDOR_EXTENSION:
				return vendorExtension != null && !vendorExtension.isEmpty();
			case BpsimPackage.ELEMENT_PARAMETERS__ELEMENT_REF:
				return ELEMENT_REF_EDEFAULT == null ? elementRef != null : !ELEMENT_REF_EDEFAULT.equals(elementRef);
			case BpsimPackage.ELEMENT_PARAMETERS__ID:
				return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
		}
		return super.eIsSet(featureID);
	}

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


Question:
Execute provided statement and checks if the schema migration has been propagated
to all nodes in the cluster. Use this method when executing schema migrations.
@param statement Statement to be executed
@throws SchemaAgreementException exception

protected void executeWithSchemaAgreement(Statement statement)
            throws SchemaAgreementException {
        ResultSet result = this.session.execute(statement);
        if (checkSchemaAgreement(result)) {
            return;
        }
        if (checkClusterSchemaAgreement()) {
            return;
        }

        throw new SchemaAgreementException(
                "Failed to propagate schema update to all nodes (schema agreement error)");
    }

public function handle()
    {
        $deploymentsPath = $this->option('path');
        if(!$deploymentsPath) {
            $deploymentsPath = base_path($this->deploymentsPath);
        }

        // Drop tables
        if($this->option('drop')) {
            $tables = DB::select('SHOW TABLES');
            if($tables) {
                $this->comment("\nDropping current tables");
                $this->dropAllTables();
                $this->info("Current tables dropped");
            }else{
                $this->comment("No tables to drop!");
            }
        }

        // Import sql files
        if(File::isDirectory($deploymentsPath)) {
            $sqlFiles = File::files($deploymentsPath);
            if ($sqlFiles) {
                $this->comment("\nImporting deployment SQL files");
                foreach ($sqlFiles as $file) {
                    if ($file->getExtension() == "sql") {
                        $command = 'mysql -h ' . env('DB_HOST') . ' -u ' . env('DB_USERNAME') . ' -p' . env('DB_PASSWORD') . ' ' . env('DB_DATABASE') . ' < ' . $file->getPathName();

                        $this->process->setCommandLine($command);
                        $this->process->setTimeout(null);
                        $this->process->run();

                        if (!$this->process->isSuccessful()) {
                            $this->error("Database '" . $file->getPathName() . "' not deployed!");
                            break;
                        }else{
                            // Delete file
                            File::delete($file->getPathName());
                        }
                    }
                }
                $this->info("Deployment SQL files imported!");
            }
        }
    }

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


Question: // IsTemporaryErr checks if the passed error indicates a transient error.

func IsTemporaryErr(err error) bool {
	t, ok := err.(net.Error)
	return ok && t.Temporary()
}

func InstrumentTransport(ctx context.Context, base http.RoundTripper, client string) http.RoundTripper {
	if base == nil {
		base = http.DefaultTransport
	}
	if store.IsNilStore(tsmon.GetState(ctx).Store()) {
		return base
	}
	return &instrumentedHTTPRoundTripper{ctx, base, client}
}

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


Question:
Notify interested listeners that a property has been resolved.

@param base     The object on which the property was resolved
@param property The property that was resolved

@since EL 3.0

public void notifyPropertyResolved(Object base, Object property) {
        for (EvaluationListener listener : listeners) {
            try {
                listener.propertyResolved(this, base, property);
            } catch (Throwable t) {
                Util.handleThrowable(t);
                // Ignore - no option to log
            }
        }
    }

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
Updates the items icon based on its state.

        :param      item | <QTreeWidgetItem>

def updateItemIcon(self, item):

        # update the column width
        self.setUpdatesEnabled(False)
        colwidth = self.columnWidth(0)
        self.resizeColumnToContents(0)
        new_colwidth = self.columnWidth(0)

        if new_colwidth < colwidth:
            self.setColumnWidth(0, colwidth)
        self.setUpdatesEnabled(True)

public static function get()
    {
        $widgets = [];
        foreach (Packages::all() as $package) {
            $dir = __DIR__.'/../../'.$package.'/src';
            $files = is_dir($dir) ? scandir($dir) : [];

            foreach ($files as $file) {
                if ($file == 'Widgets.json') {
                    $file_r = file_get_contents($dir.'/'.$file);
                    foreach (json_decode($file_r, true) as $w) {
                        $w['package'] = $package;
                        array_push($widgets, $w);
                    }
                    break;
                }
            }
        }

        $widgets = static::orderByPreference($widgets);

        return $widgets;
    }

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


Question: // ExecuteQueryWithMetadata implements method in VersionedDB interface

func (vdb *versionedDB) ExecuteQueryWithMetadata(namespace, query string, metadata map[string]interface{}) (statedb.QueryResultsIterator, error) {
	return nil, errors.New("ExecuteQueryWithMetadata not supported for leveldb")
}

public <T> List<T> query(String sql, Class<T> beanClass, Object... params) throws SQLException {
		return query(sql, new BeanListHandler<T>(beanClass), params);
	}

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


Question:
// Reject calls t.Error and prints a nice comparison message when have == want.
// Especially useful in table-based tests when passing the loop index as iter.

func Reject(t Errorf, have, want interface{}, iter ...int) {
	if reflect.DeepEqual(have, want) {
		file, line := caller()
		t.Errorf(unequal, file, line, exampleNum(iter), have, have, want, want)
	}
}

def _private_notes(self, key, value):

    def _is_for_cds(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'CDS' in normalized_c_values

    def _is_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'HAL' in normalized_c_values

    def _is_not_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'NOT HAL' in normalized_c_values

    _private_notes = self.get('_private_notes', [])
    _export_to = self.get('_export_to', {})

    for value in force_list(value):
        if _is_for_cds(value):
            _export_to['CDS'] = True

        if _is_for_hal(value):
            _export_to['HAL'] = True
        elif _is_not_for_hal(value):
            _export_to['HAL'] = False

        source = force_single_element(value.get('9'))
        for _private_note in force_list(value.get('a')):
            _private_notes.append({
                'source': source,
                'value': _private_note,
            })

    self['_export_to'] = _export_to
    return _private_notes

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


Question:
Attempts to convert the specified value to an instance of the
specified object type.

@exception Exception thrown if no field parser exists for the
target type or if an error occurs while parsing the value.

public static Object unmarshal (Class<?> type, String source)
        throws Exception
    {
        if (type.isEnum()) {
            // we need to use a dummy enum type here as there's no way to ask Enum.valueOf to
            // execute on an existentially typed enum; it all works out under the hood
            @SuppressWarnings("unchecked") Class<Dummy> etype = (Class<Dummy>)type;
            return Enum.valueOf(etype, source); // may throw an exception
        }
        // look up an argument parser for the field type
        Parser parser = _parsers.get(type);
        if (parser == null) {
            throw new Exception(
                "Don't know how to convert strings into values of type '" + type + "'.");
        }
        return parser.parse(source);
    }

private static void parseErrorPages(final ErrorPageType errorPageType, final WebApp webApp) {
		final WebAppErrorPage errorPage = new WebAppErrorPage();
		if (errorPageType.getErrorCode() != null) {
			errorPage.setErrorCode(errorPageType.getErrorCode().getValue().toString());
		}
		if (errorPageType.getExceptionType() != null) {
			errorPage.setExceptionType(errorPageType.getExceptionType().getValue());
		}
		if (errorPageType.getLocation() != null) {
			errorPage.setLocation(errorPageType.getLocation().getValue());
		}
		if (errorPage.getErrorCode() == null && errorPage.getExceptionType() == null) {
			errorPage.setExceptionType(ErrorPageModel.ERROR_PAGE);
		}
		webApp.addErrorPage(errorPage);
	}

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


Question:
Access the queries

@return \Twilio\Rest\Autopilot\V1\Assistant\QueryList

protected function getQueries() {
        if (!$this->_queries) {
            $this->_queries = new QueryList($this->version, $this->solution['sid']);
        }

        return $this->_queries;
    }

def services(device_id=nil, shared=false)
      params = { shared: shared }
      params[:deviceid] = device_id unless device_id.nil?

      response = get('/listServices', params)
      services = []
      response.body['services'].each do |s|
        services << Service.from_json(s, @token, @logger)
      end
      services
    end

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


Question:
Enters text in an EditText matching the specified index.

@param index the index of the {@link EditText}. {@code 0} if only one is available
@param text the text to enter in the {@link EditText} field

public void enterText(int index, String text) {
		if(config.commandLogging){
			Log.d(config.commandLoggingTag, "enterText("+index+", \""+text+"\")");
		}

		textEnterer.setEditText(waiter.waitForAndGetView(index, EditText.class), text);
	}

def create_content(self, cli, width, height):

        buffer = self._buffer(cli)

        # Get the document to be shown. If we are currently searching (the
        # search buffer has focus, and the preview_search filter is enabled),
        # then use the search document, which has possibly a different
        # text/cursor position.)
        def preview_now():
            """ True when we should preview a search. """
            return bool(self.preview_search(cli) and
                        cli.buffers[self.search_buffer_name].text)

        if preview_now():
            if self.get_search_state:
                ss = self.get_search_state(cli)
            else:
                ss = cli.search_state

            document = buffer.document_for_search(SearchState(
                text=cli.current_buffer.text,
                direction=ss.direction,
                ignore_case=ss.ignore_case))
        else:
            document = buffer.document

        get_processed_line = self._create_get_processed_line_func(cli, document)
        self._last_get_processed_line = get_processed_line

        def translate_rowcol(row, col):
            " Return the content column for this coordinate. "
            return Point(y=row, x=get_processed_line(row).source_to_display(col))

        def get_line(i):
            " Return the tokens for a given line number. "
            tokens = get_processed_line(i).tokens

            # Add a space at the end, because that is a possible cursor
            # position. (When inserting after the input.) We should do this on
            # all the lines, not just the line containing the cursor. (Because
            # otherwise, line wrapping/scrolling could change when moving the
            # cursor around.)
            tokens = tokens + [(self.default_char.token, ' ')]
            return tokens

        content = UIContent(
            get_line=get_line,
            line_count=document.line_count,
            cursor_position=translate_rowcol(document.cursor_position_row,
                                             document.cursor_position_col),
            default_char=self.default_char)

        # If there is an auto completion going on, use that start point for a
        # pop-up menu position. (But only when this buffer has the focus --
        # there is only one place for a menu, determined by the focussed buffer.)
        if cli.current_buffer_name == self.buffer_name:
            menu_position = self.menu_position(cli) if self.menu_position else None
            if menu_position is not None:
                assert isinstance(menu_position, int)
                menu_row, menu_col = buffer.document.translate_index_to_position(menu_position)
                content.menu_position = translate_rowcol(menu_row, menu_col)
            elif buffer.complete_state:
                # Position for completion menu.
                # Note: We use 'min', because the original cursor position could be
                #       behind the input string when the actual completion is for
                #       some reason shorter than the text we had before. (A completion
                #       can change and shorten the input.)
                menu_row, menu_col = buffer.document.translate_index_to_position(
                    min(buffer.cursor_position,
                        buffer.complete_state.original_document.cursor_position))
                content.menu_position = translate_rowcol(menu_row, menu_col)
            else:
                content.menu_position = None

        return content

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


Question: // NewPendingDeployment returns a new PendingDeployment object.

func NewPendingDeployment(deploymentID, templateID, poolID string) PendingDeployment {
	return PendingDeployment{
		status:       utils.NewValueChangePublisher("Starting"),
		templateID:   templateID,
		deploymentID: deploymentID,
		poolID:       poolID,
		mutex:        sync.RWMutex{},
	}
}

private function convertItemStatus(Shipping $shipping, $shippingStatusId)
    {
        foreach ($shipping->getItems() as $shippingItem) {
            // get item
            $item = $shippingItem->getItem();

            // set item status based on current shipping status
            switch ($shippingStatusId) {
                // created
                case ShippingStatusEntity::STATUS_CREATED:
                    // TODO: REMOVE PREVIOUS STATE
                    $this->itemManager->addStatus($item, Item::STATUS_CREATED);
                    break;
                // delivery note
                case ShippingStatusEntity::STATUS_DELIVERY_NOTE:
                    if ($this->isPartiallyItem($shippingItem, true)) {
                        $itemStatus = Item::STATUS_SHIPPING_NOTE_PARTIALLY;
                    } else {
                        $itemStatus = Item::STATUS_SHIPPING_NOTE;

                    }
                    $this->itemManager->addStatus($item, $itemStatus);
                    break;
                // shipped
                case ShippingStatusEntity::STATUS_SHIPPED:
                    if ($this->isPartiallyItem($shippingItem, false)) {
                        $itemStatus = Item::STATUS_SHIPPED_PARTIALLY;
                    } else {
                        $itemStatus = Item::STATUS_SHIPPED;

                    }
                    $this->itemManager->addStatus($item, $itemStatus);
                    break;
                case ShippingStatusEntity::STATUS_CANCELED:
                    // TODO: check  if still fully shipped
                    $this->itemManager->removeStatus($item, Item::STATUS_SHIPPED);
                    // TODO: check if partially shipped
                    break;
            }
        }
    }

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


Question:
Sends the login instructions email for the specified user.

    :param user: The user to send the instructions to
    :param token: The login token

def send_login_instructions(user):

    token = generate_login_token(user)
    login_link = url_for_security('token_login', token=token, _external=True)

    _security.send_mail(config_value('EMAIL_SUBJECT_PASSWORDLESS'), user.email,
                        'login_instructions', user=user, login_link=login_link)

    login_instructions_sent.send(app._get_current_object(), user=user,
                                 login_token=token)

public void marshall(ResetUserPasswordRequest resetUserPasswordRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(resetUserPasswordRequest.getDirectoryId(), DIRECTORYID_BINDING);
            protocolMarshaller.marshall(resetUserPasswordRequest.getUserName(), USERNAME_BINDING);
            protocolMarshaller.marshall(resetUserPasswordRequest.getNewPassword(), NEWPASSWORD_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Inicializa internamente los datos de una liquidación para autorizar

def CrearLiquidacion(self, cod_operacion, fecha_cbte, fecha_op, cod_motivo,
                         cod_localidad_procedencia, cod_provincia_procedencia,
                         cod_localidad_destino, cod_provincia_destino,
                         lugar_realizacion=None,
                         fecha_recepcion=None, fecha_faena=None,
                         datos_adicionales=None, **kwargs):
        ""
        # creo el diccionario con los campos generales de la liquidación:
        liq = { 'fechaComprobante': fecha_cbte, 'fechaOperacion': fecha_op,
                'lugarRealizacion': lugar_realizacion,
                'codMotivo': cod_motivo,
                'codLocalidadProcedencia': cod_localidad_procedencia,
                'codProvinciaProcedencia': cod_provincia_procedencia,
                'codLocalidadDestino': cod_localidad_destino,
                'codProvinciaDestino': cod_provincia_destino,
                'fechaRecepcion': fecha_recepcion,
                'fechaFaena': fecha_faena,
              }
        self.solicitud = dict(codOperacion=cod_operacion,
                              emisor={}, receptor={},
                              datosLiquidacion=liq,
                              itemDetalleLiquidacion=[],
                              guia=[], dte=[],
                              tributo=[], gasto=[],
                              datosAdicionales=datos_adicionales,
                             )
        return True

public function get(){
        $res= FALSE;
        try{
            //Armo y preparo la consulta
            $query= $this->prepareSelect($this->select, $this->from, $this->where, $this->group, $this->having, $this->order, $this->limit);
            //Ejecuto la consulta
            $query->execute($this->where_values);
            //Controlo que este todo bien
            if($this->isOk($query)){
                $res= $query;
            }
            //Limpio las variables del AR
            $this->cleanVars();
        } catch (\PDOException $e) {
            $this->cleanVars();
            throw $e;
        }
        return $res;
    }

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


Question:
Retrieve the currently active grouping mode.

@param EnvironmentInterface $environment The environment.

@return array|null

public static function getGroupingMode(EnvironmentInterface $environment)
    {
        $sorting = static::getCurrentSorting($environment);

        // If no sorting defined, exit.
        if ((!$sorting)
            || (!$sorting->getCount())
            || $sorting->get(0)->getSortingMode() === GroupAndSortingInformationInterface::SORT_RANDOM
        ) {
            return null;
        }
        $firstSorting = $sorting->get(0);

        // Use the information from the property, if given.
        if ('' !== $firstSorting->getGroupingMode()) {
            $groupMode   = $firstSorting->getGroupingMode();
            $groupLength = $firstSorting->getGroupingLength();
        } else {
            // No sorting? No grouping!
            $groupMode   = GroupAndSortingInformationInterface::GROUP_NONE;
            $groupLength = 0;
        }

        return [
            'mode'     => $groupMode,
            'length'   => $groupLength,
            'property' => $firstSorting->getProperty(),
            'sorting'  => $sorting
        ];
    }

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question:
@param FormView      $view
@param FormInterface $form
@param int           $depth

@return string|null

private function createLabelPrefix(FormView $view, FormInterface $form, $depth = 1)
    {
        if (($labelPrefix = $form->getConfig()->getOption('label_prefix')) === null) {
            return $this->createParentLabelPrefix($view, $form, $depth);
        }

        if ($depth === 1 && ($rootLabelPrefix = $this->createParentLabelPrefix($view, $form, $depth)) !== null) {
            return $rootLabelPrefix;
        }

        return $labelPrefix;
    }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question:
Get the value of a specified type as an array of strings. This is
mainly for plural TRANSLATED messages.

@param string $type PoToken constant

@return string[]|null

public function getAsStringArray(string $type): ?array
    {
        $plurals = $this->entry[$type];
        $plurals = is_array($plurals) ? $plurals : array('', '');
        $ret = array();
        foreach ($plurals as $i => $value) {
            if (is_array($value)) {
                $value = implode('', $value);
            }
            $ret[$i] = $value;
        }
        return $ret;
    }

public static function toMessage($code)
    {
        return isset(self::$message[$code]) ? self::$message[$code] : $code;
    }

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


Question: // SearchSubtitles searches OSDB with your own parameters.

func (c *Client) SearchSubtitles(params *[]interface{}) (Subtitles, error) {
	res := struct {
		Data Subtitles `xmlrpc:"data"`
	}{}

	if err := c.Call("SearchSubtitles", *params, &res); err != nil {
		if strings.Contains(err.Error(), "type mismatch") {
			return nil, err
		}
	}
	return res.Data, nil
}

def _parse_blob(self):
        """"""
        lineno = self.lineno
        mark = self._get_mark_if_any()
        data = self._get_data(b'blob')
        return commands.BlobCommand(mark, data, lineno)

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


Question: // SetId sets the Id field's value.

func (s *HostedZone) SetId(v string) *HostedZone {
	s.Id = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
NOTE: use this with care and only if necessary.

@param p the native object

protected void init(peer_info p) {
        client = Vectors.byte_vector2utf8(p.get_client());
        totalDownload = p.getTotal_download();
        totalUpload = p.getTotal_upload();
        flags = p.get_flags();
        source = p.get_source();
        upSpeed = p.getUp_speed();
        downSpeed = p.getDown_speed();
        connectionType = ConnectionType.fromSwig(p.getConnection_type());
        progress = p.getProgress();
        progressPpm = p.getProgress_ppm();
        ip = new TcpEndpoint(p.getIp()).toString();
    }

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

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


Question: remove a single role

def remove_role role
      raise ArgumentError, '#remove_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array)
      remove_roles role
    end

protected function internalRemoveItem(&$normalizedKey)
    {
        $filespec = $this->getFileSpec($normalizedKey);
        if (!file_exists($filespec . '.dat')) {
            return false;
        } else {
            $this->unlink($filespec . '.dat');
        }

        return true;
    }

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


Question: Initialize a new Nvim instance.

def with_decode(self, decode=True):
        """"""
        return Nvim(self._session, self.channel_id,
                    self.metadata, self.types, decode, self._err_cb)

def inject_nmi(self):

        cur_status = self.get_host_power_status()
        if cur_status != 'ON':
            raise exception.IloError("Server is not in powered on state.")

        self._perform_power_op("Nmi")

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


Question:
Creates an denying Rule.

@param \Caridea\Acl\Subject $subject The subject to allow access
@param array<string>|null $verbs Optional list of denied verbs.
Empty or `null` means *all*.
@return Rule The denying Rule

public static function deny(Subject $subject, array $verbs = null): Rule
    {
        return new self($subject, false, $verbs);
    }

private boolean printMissingRules(CollectRulesVisitor visitor) {
        Set<String> missingConcepts = visitor.getMissingConcepts();
        if (!missingConcepts.isEmpty()) {
            logger.info("Missing concepts [" + missingConcepts.size() + "]");
            for (String missingConcept : missingConcepts) {
                logger.warn(LOG_LINE_PREFIX + missingConcept);
            }
        }
        Set<String> missingConstraints = visitor.getMissingConstraints();
        if (!missingConstraints.isEmpty()) {
            logger.info("Missing constraints [" + missingConstraints.size() + "]");
            for (String missingConstraint : missingConstraints) {
                logger.warn(LOG_LINE_PREFIX + missingConstraint);
            }
        }
        Set<String> missingGroups = visitor.getMissingGroups();
        if (!missingGroups.isEmpty()) {
            logger.info("Missing groups [" + missingGroups.size() + "]");
            for (String missingGroup : missingGroups) {
                logger.warn(LOG_LINE_PREFIX + missingGroup);
            }
        }
        return missingConcepts.isEmpty() && missingConstraints.isEmpty() && missingGroups.isEmpty();
    }

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


Question:
Finds and returns the darkest color of the list.
@return darkest color or null if there're no entries yet.

function(){
		var darkest,
			minBrightness = Number.MAX_VALUE;
		this.each(function(c){
			var luma = c.luminance();
			if(luma < minBrightness){
				darkest = c;
				minBrightness = luma;
			}
		});
		return darkest;
	}

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->entityManager;
        $force = $input->getOption('force');
        $fixDepth = $input->getOption('fix-depth');

        $repo = $this->accountRepository;
        $verify = $repo->verify();

        $success = false;

        // fix nested tree
        if (true !== $verify) {
            $output->writeln(sprintf('<comment>%s errors were found.</comment>', count($verify)));

            if ($force) {
                $repo->recover();
                $em->flush();
                $success = true;
            }
        } else {
            $output->writeln('<info>Your tree is fine. No errors found.<info>');
        }

        // fix depths if -depth is defined
        if ($fixDepth) {
            // fix nodes without parents
            $numberParentLess = $this->findNodesWithoutParents();
            if ($numberParentLess > 0) {
                $output->writeln(
                    sprintf('<comment>%s nodes without parent were found.</comment>', $numberParentLess)
                );
                if ($force) {
                    $this->fixNodesWithoutParents();
                    $success = true;
                    $em->flush();
                }
            } else {
                $output->writeln('<info>No wrong depth gaps detected<info>');
            }

            // fix depth gaps
            $numberWrongDepth = $this->findInitialWrongDepthGap();
            if ($numberWrongDepth > 0) {
                $output->writeln(sprintf('<comment>%s wrong depths were found.</comment>', $numberWrongDepth));
                if ($force) {
                    // update depths
                    $affected = 1;
                    while ($affected > 0) {
                        $affected = $this->fixWrongDepthGap();
                    }
                    $success = true;
                    $em->flush();
                }
            } else {
                $output->writeln('<info>No nodes without parents detected<info>');
            }
        }

        if (!$force) {
            $output->writeln(sprintf('Call this command with <info>--force</info> option to perform recovery.'));
        }

        if (true === $success) {
            $output->writeln('<info>Recovery complete<info>');
        }
    }

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


Question: Pretty print lines

def pprint_lines(value):

    pformatted = pformat(value, width=1, indent=4)
    formatted = "{0}\n {1}\n{2}".format(
        pformatted[0],
        pformatted[1:-1],
        pformatted[-1]
    )
    return Markup(formatted)

protected function ol(array $items, string $marker = '<yellow>%s</yellow>.', int $writer = Output::STANDARD): void
	{
		(new OrderedList($this->output))->draw($items, $marker, $writer);
	}

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


Question:
Get a lead by email address

@param string $email
@return \stdClass
@throws LeadDoesNotExistException
@throws MarketoApiException

public function show($email)
    {
        $url = $this->client->url . '/rest/v1/leads.json';
        $queryParams = [
            'filterType' => 'email',
            'filterValues' => $email
        ];
        $response = parent::get($url, $queryParams);
        if ($response->success) {
            if (count($response->result) > 0) {
                return $response->result[0];
            } else {
                throw new LeadDoesNotExistException('Lead does not exist with email ' . $email);
            }
        } else {
            throw new MarketoApiException('Error retrieving lead: ' . $response->errors[0]->message);
        }
    }

func (c *Client) SendMailV31(data *MessagesV31) (*ResultsV31, error) {
	url := c.apiBase + ".1/send"
	req, err := createRequest("POST", url, data, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	req.SetBasicAuth(c.APIKeyPublic(), c.APIKeyPrivate())

	r, err := c.httpClient.SendMailV31(req)
	if err != nil {
		return nil, err
	}

	decoder := json.NewDecoder(r.Body)

	switch r.StatusCode {
	case http.StatusOK:

		var res ResultsV31
		if err := decoder.Decode(&res); err != nil {
			return nil, err
		}
		return &res, nil

	case http.StatusBadRequest, http.StatusForbidden:

		var apiFeedbackErr APIFeedbackErrorsV31
		if err := decoder.Decode(&apiFeedbackErr); err != nil {
			return nil, err
		}
		return nil, &apiFeedbackErr

	default:

		var errInfo ErrorInfoV31
		if err := decoder.Decode(&errInfo); err != nil {
			return nil, err
		}
		return nil, &errInfo
	}
}

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


Question:
Are all the values in the needle bag in the haystack bag

@param $needles

@return bool

public function containsAll($needles): bool
    {
        $needlesBag = $this->transformToBag($needles);

        return !array_diff($needlesBag, $this->bag);
    }

def serviceResponse(self, response):
        '''

        '''

        PARCEL_TRUE = "Result: Parcel(00000000 00000001   '........')\r\n"
        ''' The TRUE response parcel '''
        if DEBUG:
            print >>sys.stderr, "serviceResponse: comparing '%s' vs Parcel(%s)" % (response, PARCEL_TRUE)
        return response == PARCEL_TRUE

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


Question: // SetInstanceId sets the InstanceId field's value.

func (s *SingleInstanceHealth) SetInstanceId(v string) *SingleInstanceHealth {
	s.InstanceId = &v
	return s
}

public KeyArea setupKey(int iKeyArea)
    {
        KeyArea keyArea = null;
        if (iKeyArea == 0)
        {
            keyArea = this.makeIndex(DBConstants.UNIQUE, ID_KEY);
            keyArea.addKeyField(ID, DBConstants.ASCENDING);
        }
        if (iKeyArea == 1)
        {
            keyArea = this.makeIndex(DBConstants.UNIQUE, KEY_KEY);
            keyArea.addKeyField(KEY, DBConstants.ASCENDING);
        }
        if (keyArea == null)
            keyArea = super.setupKey(iKeyArea);
        return keyArea;
    }

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


Question:
Checks a query string to ensure all tls/ssl options are the same.

@param {string} key The key (tls or ssl) to check
@param {string} queryString The query string to check
@throws {MongoParseError}
@return The value of the tls/ssl option

function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) {
  const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1;

  let optionValue;
  if (Array.isArray(queryString[optionName])) {
    optionValue = queryString[optionName][0];
  } else {
    optionValue = queryString[optionName];
  }

  if (queryStringHasTLSOption) {
    if (Array.isArray(queryString[optionName])) {
      const firstValue = queryString[optionName][0];
      queryString[optionName].forEach(tlsValue => {
        if (tlsValue !== firstValue) {
          throw new MongoParseError('All values of ${optionName} must be the same.');
        }
      });
    }
  }

  return optionValue;
}

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:
Get an item at a given offset.

@param  mixed  $offset
@return mixed

public function & offsetGet( $offset )
	{
		if( ! isset($this->items[$offset]) )
		{
			$value = null;
		}

		else if( is_array($this->items[$offset]) )
		{
			return $this->items[$offset];
		}

		else
		{
			$value = $this->items[$offset];
		}

		return $value;
	}

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

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

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


Question:
Get navigation

@return \Zend\Navigation\AbstractContainer

public function getNavigation()
    {
        $service = $this->getServiceLocator();
        $config  = $service->get( 'Config' );

        if ( empty( $config['view_manager']['head_defaults']['headTitle']['content'] ) )
        {
            $info  = $service->get( 'SiteInfo' );
            $label = $info->getDomain();
        }
        else
        {
            $label = $config['view_manager']['head_defaults']['headTitle']['content'];
        }

        return new Navigation\Navigation( array(
            new Navigation\Page\Uri( array(
                'uri'       => '/',
                'label'     => $label,
                'active'    => true,
                'pages'     => $this->getMenuModel()
                                    ->findNavigation()
                                    ->getPages(),
            ) )
        ) );
    }

public function init()
    {
        parent::init();
        if (!$this->template->hasTag($this->item_tag)) {
            if (@$this->app->compat_42 && $this instanceof Menu_Basic) {
                // look for MenuItem

                $default = $this->item_tag;

                $this->item_tag = 'MenuItem';
                $this->container_tag = 'Item';
                if (!$this->template->hasTag($this->item_tag)) {
                    throw $this->template->exception('Template must have "'.$default.'" tag')
                        ->addMoreInfo('compat', 'Also tried for compatibility reason "'.$this->item_tag.'" tag');
                }
            } else {
                throw $this->template->exception('Template must have "'.$this->item_tag.'" tag');
            }
        }

        $this->row_t = $this->template->cloneRegion($this->item_tag);

        if ($this->template->hasTag('sep')) {
            $this->sep_html = $this->template->get('sep');
        }
    }

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


Question:
Make a request through an HTTP proxy
 @param [Array] proxy
 @raise [Request::Error] if HTTP proxy is invalid

def via(*proxy)
      proxy_hash = {}
      proxy_hash[:proxy_address]  = proxy[0] if proxy[0].is_a?(String)
      proxy_hash[:proxy_port]     = proxy[1] if proxy[1].is_a?(Integer)
      proxy_hash[:proxy_username] = proxy[2] if proxy[2].is_a?(String)
      proxy_hash[:proxy_password] = proxy[3] if proxy[3].is_a?(String)
      proxy_hash[:proxy_headers]  = proxy[2] if proxy[2].is_a?(Hash)
      proxy_hash[:proxy_headers]  = proxy[4] if proxy[4].is_a?(Hash)

      raise(RequestError, "invalid HTTP proxy: #{proxy_hash}") unless (2..5).cover?(proxy_hash.keys.size)

      branch default_options.with_proxy(proxy_hash)
    end

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--logfile', '-l',      GetoptLong::REQUIRED_ARGUMENT ],
          [ '--verbose', '-v',      GetoptLong::NO_ARGUMENT ],
          [ '--quiet',   '-q',      GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--port', '-p',         GetoptLong::REQUIRED_ARGUMENT ],
          [ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h',         GetoptLong::NO_ARGUMENT ],
          [ '--exit', '-x', 				GetoptLong::NO_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--logfile', '-l'
              @logfile = arg
              Log.logger = Logger.new(@logfile)
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--verbose', '-v'
              @verbose = true
            when '--quiet',   '-q'
              @quiet = true
            when '--port', '-p'
              @port = arg
            when '--bind-address', '-b'
              @bind_address = arg.to_s
            when '--help', '-h'
              help
            when '--exit', '-x'
              uri = "http://localhost:#{@port}/admin"
              response = RestClient.post uri, { 'shutdown' => true }.to_yaml
              exit 0
          end
        end
      rescue GetoptLong::InvalidOption => ex
        puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
        exit 1
      end

      #
      # Set up logging/verbosity
      #
      Chimp.set_verbose(@verbose, @quiet)

      if not @verbose
      	ENV['REST_CONNECTION_LOG'] = "/dev/null"
      	ENV['RESTCLIENT_LOG'] = "/dev/null"
        Log.threshold= Logger::INFO
      else
        Log.threshold= Logger::DEBUG
      end

      if @quiet
        Log.threshold = Logger::WARN
      end
    end

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


Question: // SetCmafPackage sets the CmafPackage field's value.

func (s *UpdateOriginEndpointOutput) SetCmafPackage(v *CmafPackage) *UpdateOriginEndpointOutput {
	s.CmafPackage = v
	return s
}

private function registerProviderMakeCommand()
    {
        $this->app->bindShared('command.make.package.provider', function ($app)
        {
            return new ProviderMakeCommand($app['files'], $app['packages']);
        });

        $this->commands('command.make.package.provider');
    }

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


Question: // SetTitle sets the Title field's value.

func (s *Message) SetTitle(v string) *Message {
	s.Title = &v
	return s
}

private String _write_single_line(String tag, String text) {
		assert tag.length() < HEADER_WIDTH;
		return StringManipulationHelper.padRight(tag, HEADER_WIDTH)
				+ text.replace('\n', ' ') + lineSep;
	}

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


Question:
Check if this entity is the same as another entity

@param Entity $entity
@return bool

protected function isSameAsEntity(Entity $entity): bool
    {
        return
            $this === $entity ||
            (
                $this instanceof IdentifiableEntity &&
                $entity instanceof IdentifiableEntity &&
                get_class($this) === get_class($entity) &&
                $this->getId() === $entity->getId()
            );
    }

static public function notEq($value1, $value2, $message = null, $propertyPath = null)
        {
            if ($value1 == $value2) {
                $message = $message ?: sprintf(
                    'Value "%s" is equal to expected value "%s".',
                    static::stringify($value1),
                    static::stringify($value2)
                );

                throw static::createException($value1, $message,static::INVALID_NOT_EQ, $propertyPath, array('expected' => $value2));
            }
        }

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


Question:
Get response cookie

@param  string $key The name of cookie
@param  mixed $default The default value when cookie not exists
@return mixed

public function getCookie($key, $default = null)
    {
        return isset($this->cookies[$key]) ? $this->cookies[$key]['value'] : $default;
    }

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

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


Question:
Create a new NotificationInstance

@param array|Options $options Optional Arguments
@return NotificationInstance Newly created NotificationInstance
@throws TwilioException When an HTTP error occurs.

public function create($options = array()) {
        $options = new Values($options);

        $data = Values::of(array(
            'Identity' => Serialize::map($options['identity'], function($e) { return $e; }),
            'Tag' => Serialize::map($options['tag'], function($e) { return $e; }),
            'Body' => $options['body'],
            'Priority' => $options['priority'],
            'Ttl' => $options['ttl'],
            'Title' => $options['title'],
            'Sound' => $options['sound'],
            'Action' => $options['action'],
            'Data' => Serialize::jsonObject($options['data']),
            'Apn' => Serialize::jsonObject($options['apn']),
            'Gcm' => Serialize::jsonObject($options['gcm']),
            'Sms' => Serialize::jsonObject($options['sms']),
            'FacebookMessenger' => Serialize::jsonObject($options['facebookMessenger']),
            'Fcm' => Serialize::jsonObject($options['fcm']),
            'Segment' => Serialize::map($options['segment'], function($e) { return $e; }),
            'Alexa' => Serialize::jsonObject($options['alexa']),
            'ToBinding' => Serialize::map($options['toBinding'], function($e) { return $e; }),
        ));

        $payload = $this->version->create(
            'POST',
            $this->uri,
            array(),
            $data
        );

        return new NotificationInstance($this->version, $payload, $this->solution['serviceSid']);
    }

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:
The core logic of the locator. Map a command index onto an absolute
COL/ROW cursor location.

@param index The commnd index.
@param width The terminal width.
@return

public CursorLocation locate(int index, int width) {
        // Upper lines location has been lost.
        if (isLocationInvalidated()) {
            return null;
        }
        int cumulated = 0;

        List<Integer> allLines = new ArrayList<>();
        allLines.addAll(linesSize);
        allLines.add(buffer.length());
        allLines.add(buffer.prompt().getLength());
        int lineIndex = 0;
        for (int i = 0; i < allLines.size(); i++) {
            int cmdSize = allLines.get(i++);
            int promptSize = allLines.get(i);
            lineIndex += 1;
            if (cumulated + cmdSize > index) {
                int part = index - cumulated;
                int col = (part + promptSize) % width;
                // if the part + prompt is longer than width, then
                // the row is in a lower line.
                lineIndex += (promptSize + part) / width;
                return new CursorLocation(lineIndex - 1, col);
            }
            cumulated += cmdSize;
            // Each line could be wrapped if longer than width.
            lineIndex += (cmdSize + promptSize) / width;
        }
        // we are on the last line at the last character.
        if (cumulated == index) {
            int cmdSize = allLines.get(allLines.size() - 2);
            int promptSize = allLines.get(allLines.size() - 1);
            int col = (cmdSize + promptSize) % width;
            return new CursorLocation(lineIndex - 1, col);
        } else {
            return null;
        }
    }

func (term Range) Value() (driver.Value, error) {
	if term.IsZero() {
		return "[,]", nil
	}
	if term.Start.IsZero() {
		return fmt.Sprintf("[,'%s']", term.End), nil
	}
	if term.End.IsZero() {
		return fmt.Sprintf("['%s',]", term.Start), nil
	}
	return fmt.Sprintf("['%s','%s']", term.Start, term.End), nil
}

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


Question:
Use this method to return a {@link SensorEvent} for use.

@return the {@link SensorEvent} object.

static SensorEvent obtain() {
        final SensorEvent event;
        synchronized (recyclerLock) {
            event = recyclerTop;
            if (event == null) {
                return new SensorEvent();
            }
            recyclerTop = event.next;
            recyclerUsed -= 1;
        }
        event.next = null;
        return event;
    }

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

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

        $generator->startList('Tag');

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

        $generator->endList('Tag');

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

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


Question: Check whether a SLURM job is finished or not

def finished(cls, jobid):
        """"""
        output = subprocess.check_output(
            [SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)]
        )
        end = output.strip().decode()
        return end not in {'Unknown', ''}

def _flush(self):

        # Upload segment with workers
        name = self._segment_name % self._seek
        response = self._workers.submit(
            self._client.put_object, self._container, name,
            self._get_buffer())

        # Save segment information in manifest
        self._write_futures.append(dict(
            etag=response, path='/'.join((self._container, name))))

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


Question:
深市代码分类

    Arguments:
        code {[type]} -- [description]

    Returns:
        [type] -- [description]

def for_sz(code):

    if str(code)[0:2] in ['00', '30', '02']:
        return 'stock_cn'
    elif str(code)[0:2] in ['39']:
        return 'index_cn'
    elif str(code)[0:2] in ['15']:
        return 'etf_cn'
    elif str(code)[0:2] in ['10', '11', '12', '13']:
        # 10xxxx 国债现货
        # 11xxxx 债券
        # 12xxxx 可转换债券
        # 12xxxx 国债回购
        return 'bond_cn'

    elif str(code)[0:2] in ['20']:
        return 'stockB_cn'
    else:
        return 'undefined'

public void warn (String msg, Object... args) {
    warn(format(msg, args), getCause(args));
  }

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


Question:
// Action handles retrying, approval of the first task and approval of the
// remaining tasks actions. It implements the interface ActionListener.

func (p *ParallelRunner) Action(ctx context.Context, path, name string) error {
	switch name {
	case actionNameRetry:
		// Extract the path relative to the root node.
		parts := strings.Split(path, "/")
		taskID := strings.Join(parts[2:], "/")
		return p.triggerRetry(taskID)
	case actionNameApproveFirstTask:
		p.mu.Lock()
		defer p.mu.Unlock()

		if p.firstTaskApproved != nil {
			close(p.firstTaskApproved)
			p.firstTaskApproved = nil
			return nil
		}
		return fmt.Errorf("ignored the approval action %v because no pending approval found: it might be already approved before", actionNameApproveFirstTask)
	case actionNameApproveRemainingTasks:
		p.mu.Lock()
		defer p.mu.Unlock()

		if p.remainingTasksApproved != nil {
			close(p.remainingTasksApproved)
			p.remainingTasksApproved = nil
			return nil
		}
		return fmt.Errorf("ignored the approval action %v because no pending approval found: it might be already approved before", actionNameApproveRemainingTasks)
	default:
		return fmt.Errorf("unknown action: %v", name)
	}
}

def process_file_object(file_obj, importer, progress):
    """"""

    logging.info("Processing schedule data.")

    try:
        handler = XmlCallbacks(importer, progress)
        parser = sax.make_parser()
        parser.setContentHandler(handler)
        parser.setErrorHandler(handler)
        parser.parse(file_obj)
    except:
        logging.exception("Parse failed.")
        raise

    logging.info("Schedule data processed.")

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


Question: Allow the module to be called from the cli.

def cli():

    import argparse

    parser = argparse.ArgumentParser(description='Send data to graphite')

    # Core of the application is to accept a metric and a value.
    parser.add_argument('metric', metavar='metric', type=str,
                        help='name.of.metric')
    parser.add_argument('value', metavar='value', type=int,
                        help='value of metric as int')

    args = parser.parse_args()
    metric = args.metric
    value = args.value

    graphitesend_instance = init()
    graphitesend_instance.send(metric, value)

def inject_nmi(self):

        cur_status = self.get_host_power_status()
        if cur_status != 'ON':
            raise exception.IloError("Server is not in powered on state.")

        self._perform_power_op("Nmi")

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


Question:
Delete an Address object

@param  int $id
@return \Illuminate\Http\Response JSON response with UUID of deleted Address

public function destroy($id)
    {
        $address = Address::findOrFail($id);
        $this->authorize('manage', $address);
        $address->delete();
        return fractal($id, new DeletedTransformer())
            ->withResourceName('deletedAddress')
            ->respond();
    }

func (c *Client) DeleteDomain(p *DeleteDomainParameter) (*Result, error) {
	obj, err := c.Request("deleteDomain", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Result), err
}

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


Question:
/*
(non-Javadoc)

@see java.io.Closeable#close()

@Override
  public void close() throws IOException {
    if (!closed) {
      objectOutputStream.close();
      fileOutputStream.close();
      closed = true;
    }
  }

private void exportInternalAPI(ClassLoader cl) {
        String[] packages = {
            "com.sun.tools.doclets",
            "com.sun.tools.doclets.standard",
            "com.sun.tools.doclets.internal.toolkit",
            "com.sun.tools.doclets.internal.toolkit.taglets",
            "com.sun.tools.doclets.internal.toolkit.builders",
            "com.sun.tools.doclets.internal.toolkit.util",
            "com.sun.tools.doclets.internal.toolkit.util.links",
            "com.sun.tools.doclets.formats.html",
            "com.sun.tools.doclets.formats.html.markup"
        };

        try {
            Method getModuleMethod = Class.class.getDeclaredMethod("getModule");
            Object thisModule = getModuleMethod.invoke(getClass());

            Class<?> moduleClass = Class.forName("java.lang.Module");
            Method addExportsMethod = moduleClass.getDeclaredMethod("addExports", String.class, moduleClass);

            Method getUnnamedModuleMethod = ClassLoader.class.getDeclaredMethod("getUnnamedModule");
            Object target = getUnnamedModuleMethod.invoke(cl);

            for (String pack : packages) {
                addExportsMethod.invoke(thisModule, pack, target);
            }
        } catch (Exception e) {
            // do nothing
        }
    }

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


Question:
Sets the view result

@param string $result The (usually HTML) view result
@param string $view
The view to set the result for. If omited, the current view is used

@return void
@see hasViewResult(), viewResult()

function setViewResult( $result, $view = '' )
    {
        if ( $view == '' )
            $view = $this->currentView();
        $this->ViewResult[$view] = $result;
    }

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:
Gets the options for the language selector.<p>

@param setLocale the locale for the select options

@return the options for the language selector

private String getOptionsForLanguage(Locale setLocale) {

        // get available locales from the workplace manager
        List<Locale> locales = OpenCms.getWorkplaceManager().getLocales();
        StringBuffer resultBuffer = new StringBuffer();
        int counter = 0;
        Iterator<Locale> i = locales.iterator();
        while (i.hasNext()) {
            Locale currentLocale = i.next();
            // add all locales to the select box
            String language = currentLocale.getDisplayLanguage(setLocale);
            if (CmsStringUtil.isNotEmpty(currentLocale.getCountry())) {
                language = language + " (" + currentLocale.getDisplayCountry(setLocale) + ")";
            }
            if (CmsStringUtil.isNotEmpty(currentLocale.getVariant())) {
                language = language + " (" + currentLocale.getDisplayVariant(setLocale) + ")";
            }
            if (counter != 0) {
                resultBuffer.append("|");
            }
            resultBuffer.append(currentLocale.toString()).append(":").append(language);
            counter++;
        }
        return resultBuffer.toString();
    }

@Override
	protected Annotation[] createParameterAnnotations(
			String parmName,
			MethodInfo methodInfo,
			java.lang.annotation.Annotation[] annotations,
			ConstPool parameterConstPool) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		List<Annotation> ctParmAnnotations = new LinkedList<Annotation>();

		for(java.lang.annotation.Annotation annotation : annotations) {
			Annotation clone = cloneAnnotation(parameterConstPool, annotation);

			// Special case: since Javaassist doesn't allow me to set the name of the parameter,
			// I need to ensure that RequestParam's value is set to the parm name if there isn't already
			// a value set
			//
			if (RequestParam.class.isAssignableFrom(annotation.annotationType())) {
				if ("".equals(((RequestParam)annotation).value()) && !StringUtils.isEmpty(parmName)) {
					MemberValue value = createMemberValue(parameterConstPool, parmName);
					clone.addMemberValue("value", value);
				}
			}

			ctParmAnnotations.add(clone);
		}
		return ctParmAnnotations.toArray(new Annotation[]{});
	}

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


Question: // AddSQLNullInt64Key adds a string to be encoded, must be used inside an object as it will encode a key

func (enc *Encoder) AddSQLNullInt64Key(key string, v *sql.NullInt64) {
	enc.Int64Key(key, v.Int64)
}

function write_BrtBeginTableStyles(cnt, defTableStyle, defPivotStyle) {
	var o = new_buf(4+256*2*4);
	o.write_shift(4, cnt);
	write_XLNullableWideString(defTableStyle, o);
	write_XLNullableWideString(defPivotStyle, o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

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


Question:
plugin a new plugins to current instance
@param {Function|Object} plugin
@chainable

function (plugin) {
                var self = this;
                if (typeof plugin === 'function') {
                    var Plugin = plugin;
                    plugin = new Plugin();
                }    // initialize plugin
                     //noinspection JSUnresolvedVariable
                // initialize plugin
                //noinspection JSUnresolvedVariable
                if (plugin.pluginInitializer) {
                    // noinspection JSUnresolvedFunction
                    plugin.pluginInitializer(self);
                }
                self.get('plugins').push(plugin);
                return self;
            }

public function addColor(Color $color)
    {
        if (!$this->colors->contains($color)) {
            $this->colors->add($color);
            $color->setInteractionSelection($this);
        }
    }

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


Question: Evaluator for CKEDITOR.dom.element::checkBoundaryOfElement, reject any text node and non-empty elements unless it's being bookmark text.

function elementBoundaryEval( node )
	{
		// Reject any text node unless it's being bookmark
		// OR it's spaces. (#3883)
		return node.type != CKEDITOR.NODE_TEXT
			    && node.getName() in CKEDITOR.dtd.$removeEmpty
			    || !CKEDITOR.tools.trim( node.getText() )
			    || !!node.getParent().data( 'cke-bookmark' );
	}

function(doc) {
    if (!doc) {
      doc = document;
    }
    if (doc === document && this.pool.length) {
      return this.pool.pop();
    }

    return View.makeInstanceOf(doc.importNode(this, true), this);
  }

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


Question:
Print the final line.

        Provides various options (length, human, datetime changes, ...).

def _outputLine(self, logevent, length=None, human=False):

        # adapt timezone output if necessary
        if self.args['timestamp_format'] != 'none':
            logevent._reformat_timestamp(self.args['timestamp_format'],
                                         force=True)
        if any(self.args['timezone']):
            if self.args['timestamp_format'] == 'none':
                self.args['timestamp_format'] = logevent.datetime_format
            logevent._reformat_timestamp(self.args['timestamp_format'],
                                         force=True)

        if self.args['json']:
            print(logevent.to_json())
            return
        line = logevent.line_str

        if length:
            if len(line) > length:
                line = (line[:int(length / 2 - 2)] + '...' +
                        line[int(-length / 2 + 1):])
        if human:
            line = self._changeMs(line)
            line = self._formatNumbers(line)

        print(line)

def format(self, record: logging.LogRecord) -> str:

        if platform.system() != 'Linux':  # Avoid funny logs on Windows & MacOS
            return super().format(record)

        record.msg = (
            self.STYLE[record.levelname] + record.msg + self.STYLE['END'])
        record.levelname = (
            self.STYLE['LEVEL'] + record.levelname + self.STYLE['END'])
        return super().format(record)

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


Question: 0. Use the Matlab version for rounding numbers

static public double myRound(double x) {
    return (Math.signum(x) * Math.round(Math.abs(x)));
  }

func (r *Application) CPU(cpu float64) *Application {
	r.CPUs = cpu
	return r
}

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


Question: Add a message-type extension to the registry by descriptor.

public void add(final FieldDescriptor type, final Message defaultInstance) {
    if (type.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
      throw new IllegalArgumentException(
        "ExtensionRegistry.add() provided a default instance for a " +
        "non-message extension.");
    }
    add(new ExtensionInfo(type, defaultInstance));
  }

func NewMicrosoftOfficeAddinChangePolicyType(Description string) *MicrosoftOfficeAddinChangePolicyType {
	s := new(MicrosoftOfficeAddinChangePolicyType)
	s.Description = Description
	return s
}

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


Question: New Action(dispatcher Dispatcher) :Action

function (dispatcher) {

    if (dispatchers.isDispatcher(dispatcher)) {
      this.dispatcher = dispatcher;
    } else {
      this.dispatcher = new dispatchers.Dispatcher();
    }

    var action = this;
    var prototype = Object.getPrototypeOf(this);
    Object.keys(prototype).forEach(function (method) {
      if (method !== 'dispatch') {
        action[method] = function () {
          var ret = prototype[method].apply(action, arguments);
          if (typeof ret !== 'undefined') {
            action.dispatch(ret);
          }
        };
      }
    });
  }

public function publishNodeAction(NodeInterface $node, Workspace $selectedWorkspace)
    {
        $this->publishingService->publishNode($node);
        $this->addFlashMessage($this->translator->translateById('workspaces.selectedChangeHasBeenPublished', [], null, null, 'Modules', 'Neos.Neos'));
        $this->redirect('show', null, null, ['workspace' => $selectedWorkspace]);
    }

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


Question:
Breaks a URL up into a nice object
@method parseUrl
@for Core
@static
@param url
@returns object

function parseUrl(url) {
        if (Core.isBlank(url)) {
            return null;
        }
        var matches = url.match(httpRegex);
        if (matches === null) {
            return null;
        }
        //log.debug("matches: ", matches);
        var scheme = matches[1];
        var host = matches[3];
        var port = matches[4];
        var parts = null;
        if (!Core.isBlank(port)) {
            parts = url.split(port);
        }
        else {
            parts = url.split(host);
        }
        // make sure we use port as a number
        var portNum = Core.parseIntValue(port);
        var path = parts[1];
        if (path && _.startsWith(path, '/')) {
            path = path.slice(1, path.length);
        }
        //log.debug("parts: ", parts);
        return {
            scheme: scheme,
            host: host,
            port: portNum,
            path: path
        };
    }

def help_center_section_subscriptions(self, section_id, locale=None, **kwargs):
        ""
        api_path = "/api/v2/help_center/sections/{section_id}/subscriptions.json"
        api_path = api_path.format(section_id=section_id)
        if locale:
            api_opt_path = "/api/v2/help_center/{locale}/sections/{section_id}/subscriptions.json"
            api_path = api_opt_path.format(section_id=section_id, locale=locale)
        return self.call(api_path, **kwargs)

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


def trigger_revisions(self, trigger_id, **kwargs):
        ""
        api_path = "/api/v2/triggers/{trigger_id}/revisions.json"
        api_path = api_path.format(trigger_id=trigger_id)
        return self.call(api_path, **kwargs)

public function edit($commentId, $body)
	{
		// Build the request path.
		$path = '/gists/comments/' . (int) $commentId;

		// Build the request data.
		$data = json_encode(
			array(
				'body' => $body
			)
		);

		// Send the request.
		$response = $this->client->patch($this->fetchUrl($path), $data);

		// Validate the response code.
		if ($response->code != 200)
		{
			// Decode the error response and throw an exception.
			$error = json_decode($response->body);
			throw new \DomainException($error->message, $response->code);
		}

		return json_decode($response->body);
	}

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


Question:
Choose selected hazard x exposure combination.

        .. note:: This is an automatic Qt slot
           executed when the category selection changes.

def on_tblFunctions1_itemSelectionChanged(self):

        # Clear the selection on the 2nd matrix
        self.parent.step_fc_functions2.tblFunctions2.clearContents()
        self.parent.step_fc_functions2.lblAvailableFunctions2.clear()
        self.parent.pbnNext.setEnabled(True)

        # Put a dot to the selected cell - note there is no way
        # to center an icon without using a custom ItemDelegate
        selection = self.tblFunctions1.selectedItems()
        selItem = (len(selection) == 1) and selection[0] or None
        for row in range(self.tblFunctions1.rowCount()):
            for column in range(self.tblFunctions1.columnCount()):
                item = self.tblFunctions1.item(row, column)
                item.setText((item == selItem) and '•' or '')

public function addColor(Color $color)
    {
        if (!$this->colors->contains($color)) {
            $this->colors->add($color);
            $color->setInteractionSelection($this);
        }
    }

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


Question:
Get base keyword arguments for client for a
        specific path.

        Args:
            path (str): Absolute path or URL.

        Returns:
            dict: client args

def get_client_kwargs(self, path):

        # Remove query string from URL
        path = path.split('?', 1)[0]

        share_name, relpath = self.split_locator(path)
        kwargs = dict(share_name=share_name)

        # Directory
        if relpath and relpath[-1] == '/':
            kwargs['directory_name'] = relpath.rstrip('/')

        # File
        elif relpath:
            try:
                kwargs['directory_name'], kwargs['file_name'] = relpath.rsplit(
                    '/', 1)
            except ValueError:
                kwargs['directory_name'] = ''
                kwargs['file_name'] = relpath

        # Else, Share only
        return kwargs

def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - quiz_id
        """ID"""
        path["quiz_id"] = quiz_id

        # OPTIONAL - includes_all_versions
        """Whether to retrieve reports that consider all the submissions or only
        the most recent. Defaults to false, ignored for item_analysis reports."""
        if includes_all_versions is not None:
            params["includes_all_versions"] = includes_all_versions

        self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/reports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/reports".format(**path), data=data, params=params, all_pages=True)

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


Question:
Match request against given route

@param \Psr\Http\Message\RequestInterface $request
@param array &$route
@return int

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

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

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

        return $match;
    }

public void marshall(GetMethodRequest getMethodRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getMethodRequest.getRestApiId(), RESTAPIID_BINDING);
            protocolMarshaller.marshall(getMethodRequest.getResourceId(), RESOURCEID_BINDING);
            protocolMarshaller.marshall(getMethodRequest.getHttpMethod(), HTTPMETHOD_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Returns the name of the given import (a lower cased symbol)

def name_of(remote)
      dir_defined?(remote)
      dir = remote[:dir].dup
      dir.gsub! '/', '_'
      name = dir.downcase.to_sym
    end

public static void toLowerCase(StringValue string) {
		final char[] chars = string.getCharArray();
		final int len = string.length();

		for (int i = 0; i < len; i++) {
			chars[i] = Character.toLowerCase(chars[i]);
		}
	}

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


Question:
Get the mail representation of the notification.

@param mixed $notifiable

@return \Illuminate\Notifications\Messages\MailMessage

public function toMail($notifiable)
    {
        $content = trans('notifications.component.status_update.mail.content', [
            'name'       => $this->component->name,
            'old_status' => $this->component->human_status,
            'new_status' => trans("cachet.components.status.{$this->status}"),
        ]);

        return (new MailMessage())
            ->subject(trans('notifications.component.status_update.mail.subject'))
            ->markdown('notifications.component.update', [
                'componentName'          => $this->component->name,
                'content'                => $content,
                'unsubscribeText'        => trans('cachet.subscriber.unsubscribe'),
                'unsubscribeUrl'         => cachet_route('subscribe.unsubscribe', $notifiable->verify_code),
                'manageSubscriptionText' => trans('cachet.subscriber.manage_subscription'),
                'manageSubscriptionUrl'  => cachet_route('subscribe.manage', $notifiable->verify_code),
        ]);
    }

def _sendMsg(self, type, msg):

        if self.ALERT_STATUS and type in self.ALERT_TYPES:
            self._configMailer()
            self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)

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


Question: Run a compiled kernel instance on a device

def run_kernel(self, func, gpu_args, instance):

        logging.debug('run_kernel %s', instance.name)
        logging.debug('thread block dims (%d, %d, %d)', *instance.threads)
        logging.debug('grid dims (%d, %d, %d)', *instance.grid)

        try:
            self.dev.run_kernel(func, gpu_args, instance.threads, instance.grid)
        except Exception as e:
            if "too many resources requested for launch" in str(e) or "OUT_OF_RESOURCES" in str(e):
                logging.debug('ignoring runtime failure due to too many resources required')
                return False
            else:
                logging.debug('encountered unexpected runtime failure: ' + str(e))
                raise e
        return True

public static Writable newInstance(Class<? extends Writable> c,
      Configuration conf) {
    return newInstance(c, conf, true);
  }

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