language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def help_center_article_translation_create(self, article_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/translations#create-translation" api_path = "/api/v2/help_center/articles/{article_id}/translations.json" api_path = api_path.format(article_id=article_id) ...
java
public static ContextualLogger getLogger(Class clazz, LoggerContext context) { return new ContextualLogger(LoggerFactory.getLogger(clazz), context); }
python
def on_down(self, host): """ Called by the parent Cluster instance when a node is marked down. Only intended for internal use. """ future = self.remove_pool(host) if future: future.add_done_callback(lambda f: self.update_created_pools())
python
def get_device_info(self) -> Mapping[str, str]: ''' Queries Temp-Deck for it's build version, model, and serial number returns: dict Where keys are the strings 'version', 'model', and 'serial', and each value is a string identifier { 'serial'...
java
public ApiResponse<Void> deleteCharactersCharacterIdContactsWithHttpInfo(Integer characterId, List<Integer> contactIds, String datasource, String token) throws ApiException { com.squareup.okhttp.Call call = deleteCharactersCharacterIdContactsValidateBeforeCall(characterId, contactIds, ...
java
@Override public DescribeLoadBalancerTargetGroupsResult describeLoadBalancerTargetGroups(DescribeLoadBalancerTargetGroupsRequest request) { request = beforeClientExecution(request); return executeDescribeLoadBalancerTargetGroups(request); }
java
public Object evaluate(Object pContext, VariableResolver pResolver, Map functions, String defaultPrefix, Logger pLogger) throws ELException { Object ret = mPrefix.evaluate(pContext, pResolver,...
python
def hide_routemap_holder_route_map_content_set_origin_origin_igp(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy") route_map = ET.SubElemen...
python
def generate(self, tree): ''' generates code based on templates and gen functions defined in the <x> lang generator ''' for middleware in DEFAULT_MIDDLEWARES + self.middlewares: tree = middleware.process(tree) # changed in place!! original = self._generate_nod...
java
public ExecutionEnvironment.ExecutionState getExecutionState(String topologyName) { return awaitResult(delegate.getExecutionState(null, topologyName)); }
java
public String getVolumeLabel() { final StringBuilder sb = new StringBuilder(); for (int i=0; i < MAX_VOLUME_LABEL_LENGTH; i++) { final char c = (char) get8(VOLUME_LABEL_OFFSET + i); if (c != 0) { sb.append(c); } else { break; ...
python
def file_to_url(self, file_rel_path): """Convert a relative file path to a file URL.""" _abs_path = os.path.abspath(file_rel_path) return urlparse.urlparse(_abs_path, scheme='file').geturl()
java
private FileStatusEntry createPathEntry(final FileStatusEntry parent, final Path childPath) throws IOException { final FileStatusEntry entry = parent.newChildInstance(childPath); entry.refresh(childPath); final FileStatusEntry[] children = doListPathsEntry(childPath, entry); entry.setChildren(chil...
java
public void writeHeader(List<? extends AttributeProvider> providers) throws IOException, AttributeException { if (this.columns == null) { this.columns = extractColumns(providers); writeDescriptionHeader(providers.size()); writeColumns(); } }
python
def to_json(self, indent=None): """Serialize this workflow to JSON""" inputs = ParameterCollection(self.inputs) d = { 'meta': { 'name': self.name, 'description': self.description }, 'inputs': [], 'workflow': [], ...
python
def get_printer(colors: bool = True, width_limit: bool = True, disabled: bool = False) -> Printer: """ Returns an already initialized instance of the printer. :param colors: If False, no colors will be printed. :param width_limit: If True, printing width will be limited by console width. :param dis...
python
def _ConvertDictToObject(self, json_dict): """Converts a JSON dict into a path specification object. The dictionary of the JSON serialized objects consists of: { '__type__': 'PathSpec' 'type_indicator': 'OS' 'parent': { ... } ... } Here '__type__' indicates the obje...
java
private static void parseWelcomeFiles(final WelcomeFileListType welcomeFileList, final WebApp webApp) { if (welcomeFileList != null && welcomeFileList.getWelcomeFile() != null && !welcomeFileList.getWelcomeFile().isEmpty()) { welcomeFileList.getWelcomeFile().forEach(webApp::addWelcomeFile); } }
python
def get_nfc_chars(self): """ Returns the set of IPA symbols that are precomposed (decomposable) chars. These should not be decomposed during string normalisation, because they will not be recognised otherwise. In IPA 2015 there is only one precomposed character: ç, the voiceless palatal fricative. """ ...
python
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer h...
python
def get_display_list(brains_or_objects=None, none_item=False): """ Returns a DisplayList with the items sorted by Title :param brains_or_objects: list of brains or objects :param none_item: adds an item with empty uid and text "Select.." in pos 0 :return: DisplayList (uid, title) sorted by title asc...
python
def stemmed(text): """ Returns a list of simplified and stemmed down terms for the inputted text. This will remove common terms and words from the search and return only the important root terms. This is useful in searching algorithms. :param text | <str> :return [<str>,...
python
def get_metadata(self, key) -> str: """ Get the value of a metadata. Returns None if metadata does not exist. Args: key (str): name of the metadata Returns: str: the value of the metadata (or None) """ return self.metadata[key] if key in self.metada...
python
def get_git_file_path(filename): """ Get relative path for filename in git root. :param filename: File name :return: relative path or None """ git_root = get_git_root(filename) return relpath(filename, git_root).replace("\\", "/") if git_root else ''
java
@SuppressWarnings("unchecked") public EList<IfcRelSequence> getIsSuccessorFrom() { return (EList<IfcRelSequence>) eGet(Ifc2x3tc1Package.Literals.IFC_PROCESS__IS_SUCCESSOR_FROM, true); }
java
public void applyConfiguration(Configuration configuration) { if (plugins != null) { plugins.stream() .filter(pluginDefinition -> pluginDefinition.isConfigurationSupported(configuration)) .forEach(pluginDefinition -> project.getDependencies().add(configuration...
python
def render(self, **kwargs): """Renders the HTML representation of the element.""" if isinstance(self._parent, GeoJson): keys = tuple(self._parent.data['features'][0]['properties'].keys()) self.warn_for_geometry_collections() elif isinstance(self._parent, TopoJson): ...
python
async def workerTypeHealth(self, *args, **kwargs): """ Look up the resource health for a workerType Return a view of the health of a given worker type This method gives output: ``v1/health.json#`` This method is ``experimental`` """ return await self._makeApiC...
java
public void setEditable(String editable) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(editable)) { m_editable = Boolean.valueOf(editable).booleanValue(); } }
java
@Override protected void initGraphics() { super.initGraphics(); titleText = new Text(); titleText.setFill(tile.getTitleColor()); Helper.enableNode(titleText, !tile.getTitle().isEmpty()); text = new Text(tile.getText()); text.setFill(tile.getUnitColor()); Helper....
python
def encode (self): """Encodes this SeqDelay to a binary bytearray.""" delay_s = int( math.floor(self.delay) ) delay_ms = int( (self.delay - delay_s) * 255.0 ) return struct.pack('>H', delay_s) + struct.pack('B', delay_ms)
python
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: RoomContext for this RoomInstance :rtype: twilio.rest.video.v1.room.RoomContext """ ...
java
public Replication queryParams(Map<String, Object> queryParams) { this.replication = replication.queryParams(queryParams); return this; }
python
def first_phase(invec, outvec, N1, N2): """ This implements the first phase of the FFT decomposition, using the standard FFT many plans. Parameters ----------- invec : array The input array. outvec : array The output array. N1 : int Number of rows. N2 : int ...
python
def transform_audio(self, y): '''Compute the HCQT Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape = (n_frames, n_bins, n_harmonics) The CQT magnitude ...
python
def websocket(self, uri, *args, **kwargs): """Create a websocket route from a decorated function :param uri: endpoint at which the socket endpoint will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :pa...
python
def fetch_result_sets(cls, db, datasource_type): """Returns a list of tables [schema1.table1, schema2.table2, ...] Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>. """ res...
python
def watch_dir(path: str) -> None: """Add ``path`` to watch for autoreload.""" _compile_exclude_patterns() if config.autoreload or config.debug: # Add files to watch for autoreload p = pathlib.Path(path) p.resolve() _add_watch_path(p)
java
private File findManifestFileThrowing() throws IOException, URISyntaxException { JavaFileObject dummySourceFile = filer.createSourceFile("dummy" + System.currentTimeMillis()); String dummySourceFilePath = dummySourceFile.toUri().toString(); if (dummySourceFilePath.startsWith("file:")) { ...
python
def lookup(domain): """Find the virNetwork object associated to the domain. If the domain has more than one network interface, the first one is returned. None is returned if the domain is not attached to any network. """ xml = domain.XMLDesc(0) element = etree.fromstring(xml) subelm = ...
java
public static void setReferences(IReferences references, Iterable<Object> components) throws ReferenceException, ConfigException { for (Object component : components) setReferencesForOne(references, component); } /** * Unsets references in specific component. * * To unset references components must i...
java
public OvhOperation serviceName_output_graylog_dashboard_POST(String serviceName, Boolean autoSelectOption, String description, String optionId, String title) throws IOException { String qPath = "/dbaas/logs/{serviceName}/output/graylog/dashboard"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Obje...
python
def _check_index_in_compilations(context: BaseContext, index: str): """Store compilation flag at specified index in context's shared data.""" compilations = 'compilations' if compilations not in context.shared_data: return False return index in context.shared_data[compilations]
python
def get_json(self): """Create JSON for CNA port. :returns: JSON for CNA port as follows: { "@PortIdx":1, "PortEnable":{ }, "Functions":{ } } """ port = self.get_basic_json() p...
python
def get_java_remote_console_url(self, ip=None): """ Generates a Single Sign-On (SSO) session for the iLO Java Applet console and returns the URL to launch it. If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the iLO Java Applet will prompt for cr...
java
public java.util.List<String> getClassicLinkVPCSecurityGroups() { if (classicLinkVPCSecurityGroups == null) { classicLinkVPCSecurityGroups = new com.amazonaws.internal.SdkInternalList<String>(); } return classicLinkVPCSecurityGroups; }
java
@Override public int compareTo(final Outcome other) { return Data.getTotalComparator().compare(this.invocationID, other.invocationID); }
python
def flg(self, name, help, abbrev=None): """Describe a flag""" abbrev = abbrev or '-' + name[0] longname = '--' + name.replace('_', '-') self._add(name, abbrev, longname, action='store_true', help=help)
java
public CertificateListDescriptionInner listByIotHub(String resourceGroupName, String resourceName) { return listByIotHubWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); }
java
public static Vector<Object> toXmlRpcReferencesParameters(Collection<Reference> references) { Vector<Object> referencesParams = new Vector<Object>(); for(Reference reference : references) { referencesParams.add(reference.marshallize()); } return ...
python
def log_params(params, name="params"): """Dumps the params with `logging.error`.""" for i, param in enumerate(params): if not param: # Empty tuple. continue if not isinstance(param, (list, tuple)): logging.error( "%s[%d] : (%s) = [%s]", name, i, param.shape, onp.array(param)) ...
python
def verify_gmt_integrity(gmt): """ Make sure that set ids are unique. Args: gmt (GMT object): list of dicts Returns: None """ # Verify that set ids are unique set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt] assert len(set(set_ids)) == len(set_ids), ( "Set identif...
java
@CheckReturnValue public RoleData newRole() { final RoleData role = new RoleData(roles.size()); this.roles.add(role); return role; }
python
def supports_tagging(obj): """ :param obj: a class or instance """ if isinstance(obj, type): return issubclass(obj, SupportTagging) if not isinstance(obj, SupportTagging): return False if obj.id is None: return False return True
java
public static Iterable<Function<Object[], Object[]>> getTransformers(Constructor<?> constructor) { Iterable<ArgumentTransformer> transformers = Lists.newArrayList( new PrimitiveAwareVarArgsTransformer(constructor), new PrimitiveTransformer(constructor), new VarArg...
java
public final int[] getVariableSizes() { int[] sizes = new int[size()]; for (int i = 0; i < vars.length; i++) { sizes[i] = ((DiscreteVariable) vars[i]).numValues(); } return sizes; }
python
def editContactItem(self, contactType, contactItem, contactInfo): """ Edit the given contact item with the given contact type. Broadcast the edit to all L{IOrganizerPlugin} powerups. @type contactType: L{IContactType} @param contactType: The contact type which will be used to e...
java
public int addElement(int element, int treap) { int treap_; if (treap == -1) { if (m_defaultTreap == nullNode()) m_defaultTreap = createTreap(-1); treap_ = m_defaultTreap; } else { treap_ = treap; } return addElement_(element, 0, treap_); }
python
def _add_slice(seq, slc): """ Our textwrap routine deals in slices. This function will concat contiguous slices as an optimization so lookup performance is faster. It expects a sequence (probably a list) to add slice to or will extend the last slice of the sequence if it ends where the new slice begins...
python
def parse_toplevel_config(self, config): """Parse @config to setup @self state.""" if not Formatter.initialized: html_theme = config.get('html_theme', 'default') if html_theme != 'default': uri = urllib.parse.urlparse(html_theme) if not uri.scheme...
java
public T findById(ID id) { T retVal = (T) getEntityManager().find(getEntityClass(), id); return retVal; }
python
def down(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press down key n times. **中文文档** 按下方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.down_key, n, interval) self.delay(post_dl)
java
private void writeModelDetails() throws IOException { ModelSchemaV3 modelSchema = (ModelSchemaV3) SchemaServer.schema(3, model).fillFromImpl(model); startWritingTextFile("experimental/modelDetails.json"); writeln(modelSchema.toJsonString()); finishWritingTextFile(); }
java
private void obtainPadding(@StyleRes final int themeResourceId) { TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(themeResourceId, new int[]{R.attr.materialDialogPaddingLeft, R.attr.materialDialogPaddingTop, R.attr.materialDialogPaddingRight, R.attr...
python
def read_document(fnm): """Read a document that is stored in a text file as JSON. Parameters ---------- fnm: str The path of the document. Returns ------- Text """ with codecs.open(fnm, 'rb', 'ascii') as f: return Text(json.loads(f.read()))
python
def _calc(cls, **kwargs): """ Calculate sunrise or sunset based on: Parameters: jd: Julian Day lat: latitude lon: longitude stage: sunrise or sunset """ zenith = 90.833333 # offical value jd = kwargs.get("jd", None) ...
python
def register(**criteria): """ class decorator to add :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index: .. testcode:: import cqparts from cqparts.params import * # Created Part or Assembly @cqparts.search.register( ...
python
def get_special_scen_code(regions, emissions): """ Get special code for MAGICC6 SCEN files. At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions data is being provided for. The second digit, the 'sce...
python
def traverse(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM): ''' Traverse a dict or list using a colon-delimited (or otherwise delimited, using the ``delimiter`` param) target string. The target ``foo:bar:0`` will return ``data['foo']['bar'][0]`` if this value exists, and will otherwise re...
python
def _expand_wildcard_action(action): """ :param action: 'autoscaling:*' :return: A list of all autoscaling permissions matching the wildcard """ if isinstance(action, list): expanded_actions = [] for item in action: expanded_actions.extend(_expand_wildcard_action(item)) ...
python
def destroy_s3(app='', env='dev', **_): """Destroy S3 Resources for _app_ in _env_. Args: app (str): Application name env (str): Deployment environment/account name Returns: boolean: True if destroyed sucessfully """ session = boto3.Session(profile_name=env) client = se...
python
def plot_fft(f, S, dt): '''Plot fft Args ---- f: ndarray Array of frequencies produced with PSD S: ndarray Array of powers produced with PSD dt: ndarray Sampling rate of sensor ''' import numpy xf = numpy.linspace(0.0, 1/(2.0*dt), N/2) plt.plot(xf, 2.0/N...
java
public Collection<Logger> getParentLoggers() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); List<Logger> loggers = new ArrayList<>(ctx.getLoggers()); Map<String, Logger> parentMap = new HashMap<>(); try { for (Logger logger : loggers) { if (null != logger.getParent() && parentM...
java
protected void set(PofValue target, Object value) { navigator.navigate(target).setValue(value); }
java
public static Encoding getEncodingFromString(String encodingString){ if(encodingString == null || encodingString.isEmpty() || encodingString.equalsIgnoreCase("Plain")){ return Encoding.Plain; } else if(encodingString.equalsIgnoreCase("gzip")){ return Encoding.Gzip; } else...
python
def sync_month_metric(self, unique_identifier, metric, start_date, end_date): """ Uses the count for each day in the date range to recalculate the counters for the months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_d...
java
public boolean dumpTo(File outFile) throws IOException { if (exists()) { dump(getOffset(), outFile); return true; } else { return false; } }
java
protected String getArgumentValue(String arg, String[] args, ConsoleWrapper stdin, PrintStream stdout) { for (int i = 1; i < args.length; i++) { String key = args[i].split("=")[0]; if (key.equals(arg)) { return getValue(args[i]); } } return nul...
java
public WithCache.CacheState getCacheState() { return new WithCache.CacheState(size(), _max, _get, _hit, _rep); }
java
List<String> split(String value) { if (value == null) { return Collections.emptyList(); } String[] parts = value.split(",", -1); return Arrays.asList(parts); }
python
def _render_full_resource(self, instance, include, fields): """ Generate a representation of a full resource to match JSON API spec. :param instance: The instance to serialize :param include: Dictionary of relationships to include :param fields: Dictionary of fields to filter ...
java
public String getText() { //convert textable to map of text Object key = null; try { //read bindTemplate String bindTemplate = getTemplate(); Map<Object,String> textMap = new Hashtable<Object,String>(); for(Map.Entry<String, Textable> en...
python
def plot_seebeck_mu(self, temp=600, output='eig', xlim=None): """ Plot the seebeck coefficient in function of Fermi level Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, and band gap) Returns: ...
python
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target...
python
def uma_rp_get_rpt(self, ticket, claim_token=None, claim_token_format=None, pct=None, rpt=None, scope=None, state=None): """Function to be used by a UMA Requesting Party to get RPT token. Parameters: * **ticket (str, REQUIRED):** ticket * **claim_token (st...
java
protected void initialize(String pFileName, boolean parse) { this.fileName = pFileName; Path path = null; try { path = getPath(pFileName); List<String> lines = Files.readAllLines(path, Charset.defaultCharset()); int i = 1; for (String line : lines) { processLine(line, i, pars...
python
def annotated_dataset_path(cls, project, dataset, annotated_dataset): """Return a fully-qualified annotated_dataset string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}", project=project, ...
python
def replacebranch(idf, loop, branch, listofcomponents, fluid=None, debugsave=False, testing=None): """It will replace the components in the branch with components in listofcomponents""" if fluid is None: fluid = '' # -------- testing --------...
java
public static FacesMessage getMessage(String messageId, String... params) { String summary = null; String detail = null; ResourceBundle bundle; String bundleName; FacesContext context = FacesContext.getCurrentInstance(); Locale locale = context.getViewRoot().getLocale(); // see if we have a user-provided...
python
def purge_docs(cls, app, env, docname): # pragma: no cover """Handler for Sphinx's env-purge-doc event. This event is emitted when all traces of a source file should be cleaned from the environment (that is, if the source file is removed, or before it is freshly read). This is for exte...
python
def setActiveModule(Module): r"""Helps with collecting the members of the imported modules. """ module_name = Module.__name__ if module_name not in ModuleMembers: ModuleMembers[module_name] = [] ModulesQ.append(module_name) Group(Module, {}) # brand the module with __ec_member__ state....
python
def ping(host, timeout=False, return_boolean=False): ''' Performs a ping to a host CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2016.11.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.pin...
java
public void reset(String name){ if (name.equals(Names.MAIN_BRUSH.toString())) mainBrushWorkTime = 0; if (name.equals(Names.SENSOR.toString())) sensorTimeSinceCleaning = 0; if (name.equals(Names.SIDE_BRUSH.toString())) sideBrushWorkTime = 0; if (name.equals(Names.FILTER.toString())) filte...
java
private Set<String> findResourceNamesFromFileSystem(String classPathRootOnDisk, String scanRootLocation, File folder) { LOGGER.debug("Scanning for resources in path: {} ({})", folder.getPath(), scanRootLocation); File[] files = folder.listFiles(); if (files == null) { return emptySe...
java
public static void assertJsonEquals(Object expected, Object actual, Configuration configuration) { assertJsonPartEquals(expected, actual, ROOT, configuration); }
java
public synchronized boolean consolidate() throws IOException { if (isTainted()) { // proceed with consolidation XSequentialEventBuffer nBuffer = new XSequentialEventBuffer(buffer .getProvider(), this.attributeMapSerializer); int overflowIndex = 0; int fileBufferIndex = 0; for (int i = 0; i < size;...
java
public static List<Map<String, Object>> readExcelToMapList(File file, Integer scale) throws ReadExcelException { return XLSReader.readExcel(file, scale).getDatas(); }
java
@Pure @SuppressWarnings("checkstyle:npathcomplexity") public static URL replaceExtension(URL filename, String extension) { if (filename == null) { return null; } if (extension == null) { return filename; } String path = filename.getPath().replaceFirst(Pattern.quote(URL_PATH_SEPARATOR) + "+$", "");...
java
public static boolean isBindable(Class<?> subClass) { return !subClass.isInterface() && !Modifier.isAbstract( subClass.getModifiers()) && subClass.getTypeParameters().length == 0; }
python
def apply_injectables(self, targets): """Given an iterable of `Target` instances, apply their transitive injectables.""" target_types = {type(t) for t in targets} target_subsystem_deps = {s for s in itertools.chain(*(t.subsystems() for t in target_types))} for subsystem in target_subsystem_deps: #...