language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void addBackground(VisualizerContext context) { // Make a background CSSClass cls = new CSSClass(this, "background"); cls.setStatement(SVGConstants.CSS_FILL_PROPERTY, context.getStyleLibrary().getBackgroundColor(StyleLibrary.PAGE)); addCSSClassOrLogError(cls); Element bg = this.svgElement(SV...
java
public static XMLBuilder create(String name, String namespaceURI) throws ParserConfigurationException, FactoryConfigurationError { return create(name, namespaceURI, false, true); }
java
public synchronized final void putThreadLocal(Object key, Object value) { if (sealed) onSealedMutation(); if (threadLocalMap == null) threadLocalMap = new HashMap<Object,Object>(); threadLocalMap.put(key, value); }
java
public void addExternalJars(File file) throws IllegalAccessException, InvocationTargetException, MalformedURLException { assert file.exists() : "Unable to find external file: " + file.getAbsolutePath(); if( file.isDirectory() ) { for( File f : file.listFiles() ) addExternalJars(f); } else if( file.get...
java
public String getPath() { StringBuffer path = new StringBuffer("/"); CmsTreeItem current = this; while (current != null) { path.insert(0, current.getId()).insert(0, "/"); current = current.getParentItem(); } String result = path.toString(); if (re...
java
public static void clearSession(final String sessionId) { if (StringUtils.isBlank(sessionId)) { return; } final App app = StructrApp.getInstance(); final PropertyKey<String[]> sessionIdKey = StructrApp.key(Principal.class, "sessionIds"); final Query<Principal> query ...
python
def multi_constructor(loader, tag_suffix, node): """ Deal with !Ref style function format """ if tag_suffix not in UNCONVERTED_SUFFIXES: tag_suffix = "{}{}".format(FN_PREFIX, tag_suffix) constructor = None if tag_suffix == "Fn::GetAtt": constructor = construct_getatt elif ...
python
def is_known_scalar(value): """ Return True if value is a type we expect in a dataframe """ def _is_datetime_or_timedelta(value): # Using pandas.Series helps catch python, numpy and pandas # versions of these types return pd.Series(value).dtype.kind in ('M', 'm') return not ...
python
def _set_loopback(self, v, load=False): """ Setter method for loopback, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/loopback (loopback-interface) If this variable is read-only (config: false) in the source YANG file, the...
java
private HttpPost createHttpPostEntity(ReviewInput reviewInput, String reviewEndpoint) { HttpPost httpPost = new HttpPost(reviewEndpoint); String asJson = GSON.toJson(reviewInput); StringEntity entity = null; try { entity = new StringEntity(asJson); } catch (Unsuppor...
java
public void setSupportedEvents(Collection<Class<? extends ApplicationEvent>> supportedEvents) { this.supportedEventsCache.clear(); if (supportedEvents == null) { this.supportedEvents = Collections.emptySet(); } else { this.supportedEvents = new LinkedH...
java
private void adaptMessageTextSize() { if (getRootView() != null) { View messageView = getRootView().findViewById(android.R.id.message); if (messageView instanceof TextView) { TextView messageTextView = (TextView) messageView; if (TextUtils.isEmpty(getDia...
java
public static CommerceShippingMethod remove(long commerceShippingMethodId) throws com.liferay.commerce.exception.NoSuchShippingMethodException { return getPersistence().remove(commerceShippingMethodId); }
java
private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { TypedArray typedArray = getContext() .obtainStyledAttributes...
python
def form_invalid(self, form): """ Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ context = self.get_context_data(form=form) #noinspection PyUnresolvedReferences return render_modal_workflow( ...
python
def get_status(self): """ Returns the Partner status. """ status = ctypes.c_int32() result = self.library.Par_GetStatus(self.pointer, ctypes.byref(status)) check_error(result, "partner") return status
python
def setStyle(self, stylename): """ Adjusts the output format of messages based on the style name provided Styles are loaded like python modules, so you can import styles from your own modules or use the ones in fastlog.styles Available styles can be found under /fastlog/styles/ ...
java
public void setupFields() { FieldInfo field = null; field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null); field.setDataClass(Integer.class); field.setHidden(true); field = new FieldInfo(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null); ...
python
def parse_function_signature(code): """ Return the name, arguments, and return type of the first function definition found in *code*. Arguments are returned as [(type, name), ...]. """ m = re.search("^\s*" + re_func_decl + "\s*{", code, re.M) if m is None: print(code) raise Excep...
java
@Nullable public static ProxyProvider findProxySupport(Bootstrap b) { ProxyProvider.DeferredProxySupport proxy = BootstrapHandlers.findConfiguration(ProxyProvider.DeferredProxySupport.class, b.config().handler()); if (proxy == null) { return null; } return proxy.proxyProvider; }
python
def waiting_member_state(self, timeout=300): """Wait for all RS members to be in an acceptable state.""" t_start = time.time() while not self.check_member_state(): if time.time() - t_start > timeout: return False time.sleep(0.1) return True
java
public static <T> T executeGroovyScript(final GroovyObject groovyObject, final Object[] args, final Class<T> clazz, final boolean failOnError) { return executeGroovyScript(groovyObject, "run", args, clazz, failOnError); ...
java
@Nullable public static String getHealthCheckedServiceName(@Nullable Map<String, ?> serviceConfig) { String healthCheckKey = "healthCheckConfig"; String serviceNameKey = "serviceName"; if (serviceConfig == null || !serviceConfig.containsKey(healthCheckKey)) { return null; } /* schema as fol...
python
def pages(self): """A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of pages. """ # Each page is an iterator of rows. But also has num_items, remaining, # and to_dat...
python
def lazy_binmap(f, xs): """ Maps a binary function over a sequence. The function is applied to each item and the item after it until the last item is reached. """ return (f(x, y) for x, y in zip(xs, xs[1:]))
java
protected String getLockToken(String tokenHash) { for (String token : tokens.keySet()) { if (tokens.get(token).equals(tokenHash)) { return token; } } return null; }
python
def save_raw_pickle(hwr_objects): """ Parameters ---------- hwr_objects : list of hwr objects """ converted_hwr = [] translate = {} translate_id = {} model_path = pkg_resources.resource_filename('hwrt', 'misc/') translation_csv = os.path.join(model_path, 'latex2writemathindex.cs...
python
def cache(self): """Cache the Zotero data.""" with open(self.cache_path, "wb") as f: cache = {self.CACHE_REFERENCE_LIST: self._references, self.CACHE_REFERENCE_TYPES: self.reference_types, self.CACHE_REFERENCE_TEMPLATES: self.reference_templates} ...
java
public static base_response apply(nitro_service client) throws Exception { nspbrs applyresource = new nspbrs(); return applyresource.perform_operation(client,"apply"); }
python
def unaccentuate(s): """ Replace accentuated chars in string by their non accentuated equivalent. """ return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))
python
def is_fornyrdhislag(text: str): """ Basic check, only the number of lines matters: 8 for fornyrðislag. >>> text1 = "Hljóðs bið ek allar\\nhelgar kindir,\\nmeiri ok minni\\nmögu Heimdallar;\\nviltu at ek, Valföðr,\\nvel fyr telja\\nforn spjöll fira,\\nþau er fremst of man." >>> text2 = ...
java
public static String getRepoPropertiesFileLocation() { String installDirPath = Utils.getInstallDir().getAbsolutePath(); String overrideLocation = System.getProperty(InstallConstants.OVERRIDE_PROPS_LOCATION_ENV_VAR); //Gets the repository properties file path from the default location if ...
java
static long parseLong(String value) { if (value.startsWith("0x")) { // Oracle JDK on OS X do not use prefix for tid - so we need to be able to read both // https://github.com/olivergondza/dumpling/issues/59 value = value.substring(2); } // Long.parseLong is f...
python
def read_local_manifest(output_path): """Return the contents of the local manifest, as a dictionary.""" local_manifest_path = get_local_manifest_path(output_path) try: with open(local_manifest_path, 'r') as f: manifest = dict(get_files_from_textfile(f)) logging.debug('Retriev...
python
def dispatch(self, inp): """Create one input Tensor for each expert. Args: inp: a list of length num_datashards `Tensor`s with shapes `[batch_size[d], <extra_input_dims>]`. Returns: a list of `num_experts` `Tensor`s with shapes `[num_examples[i], <extra_input_dims>]`. """ ...
java
public byte[] getMessage() { byte result[] = new byte[4]; result[0] = (byte)(status >> 8); result[1] = (byte)(status & 0xFF); result[2] = (byte)(events >> 8); result[3] = (byte)(events & 0xFF); return result; }
python
def anti_windup(self, xidx, xmin, xmax): """ Anti-windup limiter for state variables. Resets the limited variables and differential equations. :param xidx: state variable indices :param xmin: lower limit :param xmax: upper limit :type xidx: matrix, list ...
java
public void retrievePin( @NonNull String cardId, @NonNull String verificationId, @NonNull String userOneTimeCode, @NonNull IssuingCardPinRetrievalListener listener ) { Map<String, Object> arguments = new HashMap<>(); arguments.put(ARGUMENT_CARD_ID, ca...
python
def connect_telnet(name, ip_address=None, user='micro', password='python'): """Connect to a MicroPython board via telnet.""" if ip_address is None: try: ip_address = socket.gethostbyname(name) except socket.gaierror: ip_address = name if not QUIET: if name == ...
java
protected void updateMatrix(double[][] mat, final double[] evec, double eval) { final int size = mat.length; for(int i = 0; i < size; i++) { final double[] mati = mat[i]; final double eveci = evec[i]; for(int j = 0; j < size; j++) { mati[j] -= eval * eveci * evec[j]; } } }
java
public static Map<String,byte[]> storeDirectoryResourcesAsBytes( File directory, List<String> exclusionPatteners ) throws IOException { if( ! directory.exists()) throw new IllegalArgumentException( "The resource directory was not found. " + directory.getAbsolutePath()); if( ! directory.isDirectory()) throw...
java
private void addConnectingShadowIfNecessary(float nextShadowAngle) { if (currentShadowAngle == nextShadowAngle) { // Previously drawn shadow lines up with the next shadow, so don't draw anything. return; } float shadowSweep = (nextShadowAngle - currentShadowAngle + 360) %...
java
private final void doPadding() { if(_padContext != null && !_padContext.checkMinRepeat(_renderedItems)) { /* since padding is now running, un-set the current item so that the last item isn't accessible during any later data binding */ _currentItem...
python
def shutdown(self, callback=None): """Start the SSL shutdown sequence. Return a list of ssldata. The optional *callback* argument can be used to install a callback that will be called when the shutdown is complete. The callback will be called without arguments. """ if se...
python
def setup(self, in_name=None, out_name=None, required=None, hidden=None, multiple=None, defaults=None): """ Set the options of the block. Only the not None given options are set .. note:: a block may have multiple inputs but have only one output :param in_name: name(s) ...
python
def _build_syl(vowels, tone_numbers=False): """Builds a Pinyin syllable re pattern. Syllables can be preceded by a middle dot (tone mark). Syllables that end in a consonant are only valid if they aren't followed directly by a vowel with no apostrophe in between. The rough approach used to validate...
python
def port_get_policy(name, sel_type=None, protocol=None, port=None): ''' .. versionadded:: 2019.2.0 Returns the current entry in the SELinux policy list as a dictionary. Returns None if no exact match was found. Returned keys are: * sel_type (the selinux type) * proto (the protocol) * ...
java
public boolean getBoolean(String key, boolean defaultValue) { addToDefaults(key, Boolean.toString(defaultValue)); String value = get(key); if (value == null) { return defaultValue; } else { return Boolean.valueOf(value); } }
python
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Generic Output Location Read from File Method """ # Assign file extension attribute to file object self.fileExtension = extension # Open file and pars...
java
public com.google.api.ads.admanager.axis.v201811.WorkflowEvaluationStatus getEvaluationStatus() { return evaluationStatus; }
python
def help(route): r"""Displays help for the given route. Args: route (str): A route that resolves a member. """ help_text = getRouteHelp(route.split('/') if route else []) if help_text is None: err('Can\'t help :(') else: print '\n%s' % help_text
java
public void marshall(ElasticsearchClusterConfigStatus elasticsearchClusterConfigStatus, ProtocolMarshaller protocolMarshaller) { if (elasticsearchClusterConfigStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
java
@Override public R visitEntity(EntityTree node, P p) { return defaultAction(node, p); }
java
public static Rule conditionsRule(final Set<Condition> conditions, final Map<String, String> results) { return conditionsRule(conditions, States.state(results)); }
python
def parse_cache(self, full_df): """ Format the cached data model into a dictionary of DataFrames and a criteria map DataFrame. Parameters ---------- full_df : DataFrame result of self.get_dm_offline() Returns ---------- data_model : d...
python
def to_binary(self): """Produce a framed/packed SBP message. """ c = containerize(exclude_fields(self)) self.payload = MsgEphemerisGPSDepF._parser.build(c) return self.pack()
java
public void addSegment(Coordinate p0, Coordinate p1) { if (p0.distance(p1) < epsilon) { return; } addSegment(originalSegments, p0, p1); }
python
def setdefaults(self, from_qs): """ sets values from a QuickSettings object, only keeping values that are not already defined on the main object """ for k in from_qs.keys(): from_value = from_qs[k] fv_is_qs = isinstance(from_value, QuickSettings) ...
python
def cli(env): """List Reserved Capacity groups.""" manager = CapacityManager(env.client) result = manager.list() table = formatting.Table( ["ID", "Name", "Capacity", "Flavor", "Location", "Created"], title="Reserved Capacity" ) for r_c in result: occupied_string = "#" * i...
java
final static int compressSpaces(List<Instruction> instructionBuffer, int size) { boolean addleftspace = true; boolean addrightspace = false; boolean skipnext = false; for (int i = 0; i < size; i++) { String text = null; String newText = null; ...
java
private static Config expand(Config config, int previousTokensCount) { Config.Builder cb = Config.newBuilder().putAll(config); int tokensCount = 0; for (String key : config.getKeySet()) { Object value = config.get(key); if (value instanceof String) { String expandedValue = TokenSub.subst...
java
@Override public void put(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value)) return; if (start == this) throw Kit.codeBug(); start.put(name, start, value); }
python
def get_base_url(html: str) -> str: """ Search for login url from VK login page """ forms = BeautifulSoup(html, 'html.parser').find_all('form') if not forms: raise VVKBaseUrlException('Form for login not found') elif len(forms) > 1: raise VVKBaseUrlException('More than one login ...
python
def toggleColumnByAction( self, action ): """ Toggles whether or not the column at the inputed action's name should \ be hidden. ` :param action | <QAction> """ if ( action.text() == 'Show All' ): self.blockSignals(True) self....
python
def _draw_cursor(self, char, frame_no, x, y): """ Draw a flashing cursor for this widget. :param char: The character to use for the cursor (when not a block) :param frame_no: The current frame number. :param x: The x coordinate for the cursor. :param y: The y coordinate ...
java
public static void error(Object obj) { if (obj instanceof Throwable) { Throwable e = (Throwable) obj; error(e, e.getMessage()); } else { error("{}", obj); } }
python
def serial_udb_extra_f15_send(self, sue_ID_VEHICLE_MODEL_NAME, sue_ID_VEHICLE_REGISTRATION, force_mavlink1=False): ''' Backwards compatible version of SERIAL_UDB_EXTRA F15 and F16: format sue_ID_VEHICLE_MODEL_NAME : Serial UDB Extra Model Name Of Vehicle (uint8_t)...
java
public static Collection<Long> getTilesCoverage(final ArrayList<GeoPoint> pGeoPoints, final int pZoomLevel) { final Set<Long> result = new HashSet<>(); GeoPoint prevPoint = null; Point tile, prevTile = null; final int mapTileUpperBoun...
python
def _a_star_search_internal(graph, start, goal): """Performs an A* search, returning information about whether the goal node was reached and path cost information that can be used to reconstruct the path. """ frontier = PriorityQueue() frontier.put(start, 0) came_from = {start: None} cost_so...
java
public DirectedGraph<DirectedEdge> readDirected( File f, Indexer<String> vertexLabels) throws IOException { throw new UnsupportedOperationException(); }
java
public static Row of(final HeaderDefinition headerDefinition, final String[] values) { ArgumentChecker.notNull(headerDefinition, "headerDefinition"); ArgumentChecker.notNull(values, "values"); return new Row(headerDefinition, values); }
python
def install_program(self, extra_args): """Install the app to the virtualenv""" pip = Command(path.join(self.env, 'bin', 'pip')) args = ['install', self.raw_name, '--install-option', '--install-scripts={}' .format(self.env_bin)] + list(extra_args) print_pre...
java
protected void closeCallUnauthenticated(final ServerCall<?, ?> call, final AuthenticationException aex) { call.close(Status.UNAUTHENTICATED.withCause(aex).withDescription(UNAUTHENTICATED_DESCRIPTION), new Metadata()); }
java
public Observable<RunGetLogResultInner> getLogSasUrlAsync(String resourceGroupName, String registryName, String runId) { return getLogSasUrlWithServiceResponseAsync(resourceGroupName, registryName, runId).map(new Func1<ServiceResponse<RunGetLogResultInner>, RunGetLogResultInner>() { @Override ...
java
public static CopyMonitor create( TransferManager manager, CopyImpl transfer, ExecutorService threadPool, CopyCallable multipartCopyCallable, CopyObjectRequest copyObjectRequest, ProgressListenerChain progressListenerChain) { CopyM...
python
def setup_filter(self, ): """Create a checkbox for every reftrack type so one can filter them :returns: None :rtype: None :raises: None """ types = self.refobjinter.types.keys() for i, t in enumerate(types): cb = QtGui.QCheckBox("%s" % t) ...
python
def _construct_pillar(top_dir, follow_dir_links, keep_newline=False, render_default=None, renderer_blacklist=None, renderer_whitelist=None, template=False): ''' Construct pillar fr...
python
def replace_greek_tex(self, name): """Replace text representing greek letters with greek letters.""" name = name.replace('gamma-delta', 'gammadelta') name = name.replace('interleukin-1 beta', 'interleukin-1beta') # greek_present = False for greek_txt, tex in self.greek2tex.items(...
java
public void processContent(byte[] contentBytes, PdfDictionary resources) { this.resources.push(resources); try { PdfContentParser ps = new PdfContentParser(new PRTokeniser(contentBytes)); ArrayList operands = new ArrayList(); while (ps.parse(operands).size() > 0) { PdfLiteral operator = (PdfLiter...
python
def start_session(self, b_hold_session, sig_doc_xml=None, datafile=None): """Start a DigidocService session :return: True if session was started and session code was stored in I{session_code} """ response = self.__invoke('StartSession', { 'bHoldSession': b_hold_session, ...
java
public static <T extends MethodDescription> ElementMatcher.Junction<T> takesGenericArgument(int index, TypeDescription.Generic type) { return takesGenericArgument(index, is(type)); }
java
public static <R extends Runnable> void run(R runnable, String... args) { run(runnable, System.out, System.err, Help.Ansi.AUTO, args); }
python
def clean(decrypted: bytes) -> str: r"""Strip padding from decrypted value. Remove number indicated by padding e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14. Args: decrypted: decrypted value Returns: Decrypted stripped of junk padding """ last = decrypted[-...
java
public MimeMultipart getMimeMultipart() throws MessagingException, IOException, JAXBException { List<DataSource> bodyPartContents = createRequestBody(); return toMimeMultipart(bodyPartContents); }
java
public ExecutionContext createEvalExecutionContext(JSProgram eval, boolean direct) { // 10.4.2 (with caller) //System.err.println( "CREATE EVAL EXEC CONTEXT" ); ExecutionContext context = null; Object evalThisBinding = null; LexicalEnvironment evalLexEnv = null; LexicalE...
java
public String[] names(){ List<String> namesList = new ArrayList<>(); Enumeration names = RequestContext.getHttpRequest().getSession(true).getAttributeNames(); while (names.hasMoreElements()) { Object o = names.nextElement(); namesList.add(o.toString()); } ...
java
public float getTextRise() { Float f = (Float) getAttribute(Chunk.SUBSUPSCRIPT); if (f != null) { return f.floatValue(); } return 0.0f; }
java
@Override protected boolean putToQueueStorage(Connection conn, IQueueMessage<Long, byte[]> msg) { Long qid = msg.getId(); if (qid == null || qid.longValue() == 0) { int numRows = getJdbcHelper().execute(conn, SQL_PUT_NEW_TO_QUEUE, getQueueName(), msg.getTimestamp(), m...
java
public void writeBodyFromString(String bodyAsString, Charset charset) { message.contentEncoding(charset.name()) .contentType(Message.TEXT_PLAIN); byte[] bodyContent = bodyAsString.getBytes(charset); message.body(bodyContent); }
python
def get_application_modules(self): """ Instantiate all application modules (i.e. :class:`~admin_tools.dashboard.modules.AppList`, :class:`~fluent_dashboard.modules.AppIconList` and :class:`~fluent_dashboard.modules.CmsAppIconList`) for use in the dashboard. ""...
java
private void closeFile() throws JournalException { synchronized (JournalWriter.SYNCHRONIZER) { // check to be sure that another thread didn't close the file while // we were waiting for the lock. if (state == FILE_OPEN) { sendRequestToAllTransports(new CloseFi...
java
public static boolean delete(final File aDir) { if (aDir.exists() && aDir.listFiles() != null) { for (final File file : aDir.listFiles()) { if (file.isDirectory()) { if (!delete(file)) { LOGGER.error(MessageCodes.UTIL_012, file); ...
java
@Override public int getNbLines() { try { return Integer.parseInt(httpService.get(this.norauiWebServicesApi, scenarioName + "/nbLines")) + 1; } catch (TechnicalException | NumberFormatException | HttpServiceException e) { logger.error("getNbLines error", e); retur...
java
public static FaxClientSpi createFaxClientSpi(String type,Properties configuration) { //create fax client SPI FaxClientSpi faxClientSpi=FaxClientSpiFactory.createFaxClientSpiImpl(type,configuration,false); return faxClientSpi; }
java
@Override public final StringBuilder renderAsListItem(final StringBuilder builder, final boolean newLine, final int pad) { if (pad > 0) { return builder; } GedRenderer.renderNewLine(builder, newLine); builder.append(simpleNameRenderer.renderAsPhrase()); ...
python
def OnToggle(self, event): """Toggle button event handler""" if self.selection_toggle_button.GetValue(): self.entry_line.last_selection = self.entry_line.GetSelection() self.entry_line.last_selection_string = \ self.entry_line.GetStringSelection() sel...
python
def invert(self): """ Convert solid space to empty space and empty space to solid space. """ for poly in self.polygons: poly.flip() self.plane.flip() if self.front: self.front.invert() if self.back: self.back.invert() ...
python
def score_zernike(zf, radii, labels, indexes=None): """Score the output of construct_zernike_polynomials zf - the output of construct_zernike_polynomials which is I x J x K where K is the number of zernike polynomials computed radii - a vector of the radius of each of N labeled objects lab...
java
public Set<TZID> resolve(Locale country) { Set<TZID> ids = WinZoneProviderSPI.NAME_BASED_MAP.get(this.name).get(FormatUtils.getRegion(country)); if (ids == null) { return Collections.emptySet(); } else { return Collections.unmodifiableSet(ids); } }
java
public void setCompoundDrawablePadding (int pad){ mInputView.setCompoundDrawablePadding(pad); if(mDividerCompoundPadding) { mDivider.setPadding(mInputView.getTotalPaddingLeft(), mInputView.getTotalPaddingRight()); if(mLabelEnable) mLabelView.setPadding(mDivider.getPaddi...