language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void startTMasterChecker() { final int checkIntervalSec = TypeUtils.getInteger(sinkConfig.get(KEY_TMASTER_LOCATION_CHECK_INTERVAL_SEC)); Runnable runnable = new Runnable() { @Override public void run() { TopologyMaster.TMasterLocation location = (TopologyMaster.T...
python
def set_widgets(self): """Set widgets on the Exposure Layer From Canvas tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_lay...
python
def _get_grouper(obj, key=None, axis=0, level=None, sort=True, observed=False, mutated=False, validate=True): """ create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. This may be composed of multiple Grouping objects, indicating multip...
python
def stop(self): """ Stop this server so that the calling process can exit """ # unsetup_fuse() self.fuse_process.teardown() for uuid in self.processes: self.processes[uuid].terminate()
java
public long getCount(final Query query, final Map parameters) { final String ordering = ((JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.executeWithMap(parameters); query.setOrdering(orderi...
python
def relpath(self, path): """ Get path relative to storage. args: path (str): Absolute path or URL. Returns: str: relative path. """ for root in self.roots: # Root is regex, convert to matching root string if isinstance(roo...
java
public static void createZipFile(Logger log, File sourceDir, File outputZipFile) throws IOException { FileFilter filter = null; createZipFile(log, sourceDir, outputZipFile, filter); }
java
@Override public List<CPDefinition> getCPDefinitionsByUuidAndCompanyId(String uuid, long companyId) { return cpDefinitionPersistence.findByUuid_C(uuid, companyId); }
java
protected synchronized void releaseBroker(PersistenceBroker broker) { /* arminw: only close the broker instance if we get it from the PBF, do nothing if we obtain it from PBThreadMapping */ if (broker != null && _needsClose) { _ne...
java
@Override public DateOfBirthType buildObject(String namespaceURI, String localName, String namespacePrefix) { return new DateOfBirthTypeImpl(namespaceURI, localName, namespacePrefix); }
java
protected static String getTargetText(Target target) { if (target != null) { if (target.getStartNode() != null) { return getNodeText(target.getStartNode()); } else if (target.getContext() != null) { return Constant.messages.getString("context.prefixName", target.getContext().getName()); } else if (ta...
python
def list_keys(user=None, gnupghome=None): ''' List keys in GPG keychain user Which user's keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. gnupghome Specify the location...
java
public static JsonUtil getInstance() { if (instance == null) { synchronized (JsonUtilImpl.class) { if (instance == null) { JsonUtilImpl impl = new JsonUtilImpl(); impl.initialize(); } } } return instance; }
python
def create_router(name, ext_network=None, admin_state_up=True, profile=None): ''' Creates a new router CLI Example: .. code-block:: bash salt '*' neutron.create_router new-router-name :param name: Name of router to create (must be first) :param ext_network: ID or na...
java
@Override public void sessionClosed(IoSession session) throws Exception { log.debug("Session closed"); String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID); if (sessionId != null) { log.trace("Session id: {}", sessionId); RTMPMinaConn...
python
def _heuristic_bin_width(obs): """Optimal histogram bin width based on the Freedman-Diaconis rule""" IQR = sp.percentile(obs, 75) - sp.percentile(obs, 25) N = len(obs) return 2*IQR*N**(-1/3)
java
@Nullable private TaskSlot getTaskSlot(AllocationID allocationId) { Preconditions.checkNotNull(allocationId); return allocationIDTaskSlotMap.get(allocationId); }
java
public void addExportable(String name, BtrpOperand e, Set<String> scopes) { this.exported.put(name, e); this.exportScopes.put(name, scopes); }
python
def city(self): """ :example 고양시 """ pattern = self.random_element(self.cities) return self.generator.parse(pattern)
java
public RolloutGroupConditionBuilder successAction(final RolloutGroupSuccessAction action, final String expression) { conditions.setSuccessAction(action); conditions.setSuccessActionExp(expression); return this; }
python
def delimit(x: str, delims: Tuple[str, str]) -> str: """Delimits x, using delims[0] (left) and delims[1] (right).""" return delims[0] + x + delims[1]
java
public static <A, B> Map<A, B> getMapUnsafe(final List list, final Integer... path) { return getUnsafe(list, Map.class, path); }
java
@Override public Money subtract(MonetaryAmount subtrahend) { MoneyUtils.checkAmountParameter(subtrahend, this.currency); if (subtrahend.isZero()) { return this; } return new Money(this.number.subtract(subtrahend.getNumber().numberValue(BigDecimal.class)), getCurrency()); ...
java
public static Map.Entry<String,String> parseVariableName( String variableName ) { String componentOrFacetName = "", simpleName = variableName; int index = variableName.indexOf( '.' ); if( index >= 0 ) { componentOrFacetName = variableName.substring( 0, index ).trim(); simpleName = variableName.substring( i...
python
def _stick_device(self): """ Discovers the filename of the evdev device that represents the Sense HAT's joystick. """ for evdev in glob.glob('/sys/class/input/event*'): try: with io.open(os.path.join(evdev, 'device', 'name'), 'r') as f: ...
java
public MediaState getSeasonAccountState(int tvID, String sessionID) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); parameters.add(Param.SESSION_ID, sessionID); URL url = new ApiUrl(apiKey, MethodBase.SEASON).subMethod(MethodSu...
java
public Integer queryInt(String paramName, Integer defaultValue) { return this.request.queryInt(paramName, defaultValue); }
python
def send_command(self, command): '''Send a command to a device''' data = {"command": command, "device_id": self.device_id} try: response = self.api_iface._api_post("/api/v2/commands", data) return Command(response, self) except APIError as e: print("AP...
python
def _propagate_options(self, change): "Set the values and labels, and select the first option if we aren't initializing" options = self._options_full self.set_trait('_options_labels', tuple(i[0] for i in options)) self._options_values = tuple(i[1] for i in options) if self._initi...
java
protected void regenerateMetrics() { if (isInstrumentationEnabled()) { this.recordsInMeter = Optional.of(this.metricContext.meter(MetricNames.DataWriterMetrics.RECORDS_IN_METER)); this.successfulWritesMeter = Optional.of(this.metricContext.meter(MetricNames.DataWriterMetrics.SUCCESSFUL_WRITES_...
python
def submit(self, *items): """Return job ids assigned to the submitted items.""" with self.lock: if self.closed: raise BrokenPipe('Job submission has been closed.') id = self.jobcount self._status += ['SUBMITTED'] * len(items) self.jobcount += len(items) for item in items: self.waitqueue.put((...
java
private void setMapForKeyGroup(int keyGroupId, Map<N, Map<K, S>> map) { try { state[indexToOffset(keyGroupId)] = map; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Key group index " + keyGroupId + " is out of range of key group " + "range [" + keyGroupOffset + ", " + (ke...
java
public List<Path> download(List<URI> srcs) { try { return paths.getAll(srcs).values().asList(); } catch (ExecutionException e) { throw new RuntimeException(e); } }
java
@Override public CommerceUserSegmentEntry removeByG_K(long groupId, String key) throws NoSuchUserSegmentEntryException { CommerceUserSegmentEntry commerceUserSegmentEntry = findByG_K(groupId, key); return remove(commerceUserSegmentEntry); }
java
public Observable<WorkItemConfigurationInner> getDefaultAsync(String resourceGroupName, String resourceName) { return getDefaultWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<WorkItemConfigurationInner>, WorkItemConfigurationInner>() { @Override p...
java
public void getAllPvPSeasonID(Callback<List<String>> callback) throws NullPointerException { gw2API.getAllPvPSeasonIDs().enqueue(callback); }
java
public void set( CameraUniversalOmni original ) { super.set(original); this.mirrorOffset = original.mirrorOffset; if( radial.length != original.radial.length ) radial = new double[ original.radial.length ]; System.arraycopy(original.radial,0,radial,0,radial.length); this.t1 = original.t1; this.t2 = or...
python
def init_auth(username, password): """Initializes the auth settings for accessing MyAnimeList through its official API from a given username and password. :param username Your MyAnimeList account username. :param password Your MyAnimeList account password. :return A tuple containing your credentials...
python
def build_github_url( repo, branch=None, path='requirements.txt', token=None ): """ Builds a URL to a file inside a Github repository. """ repo = re.sub(r"^http(s)?://github.com/", "", repo).strip('/') # args come is as 'None' instead of not being provided if not path: ...
java
public static void show(@NonNull final Snackbar snackbar, @NonNull final ViewGroup parent, final boolean usePhoneLayout) { MAIN_THREAD.post(new Runnable() { @Override public void run() { Snackbar currentSnackbar = getCurrentSnackbar(); ...
java
protected LrsActor getActor(PortalEvent event) { String username = event.getUserName(); return actorService.getLrsActor(username); }
java
private static IJavaType findTypeFromJre(Class c) { IJavaType type = (IJavaType) TypeSystem.get(c, TypeSystem.getExecutionEnvironment().getJreModule()); IExecutionEnvironment execEnv = type.getTypeLoader().getModule().getExecutionEnvironment(); if (execEnv.getProject().isDisposed()) { throw new Illega...
python
def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, ...
python
def make_slider_range(self, cursor_pos): """Make slider range QRect""" # The slider range indicator position follows the mouse vertical # position while its height corresponds to the part of the file that # is currently visible on screen. vsb = self.editor.verticalScrollBar() ...
python
def submit_sms_conversion(self, message_id, delivered=True, timestamp=None): """ Notify Nexmo that an SMS was successfully received. :param message_id: The `message-id` str returned by the send_message call. :param delivered: A `bool` indicating that the message was or was not successfu...
java
public void releaseService(BeanContextChild child, Object requestor, Object service) { if (!contains(child)) { throw new IllegalArgumentException(child + "is not a child of this context!"); } // todo: for multithreaded usage this block needs to be synchronized Class service...
java
public void transform(Source xmlSource, Result outputTarget, boolean shouldRelease) throws TransformerException { synchronized (m_reentryGuard) { SerializationHandler xoh = createSerializationHandler(outputTarget); this.setSerializationHandler(xoh); m_outputTarget = outpu...
python
def synthesize( self, text_file, audio_file_path, quit_after=None, backwards=False ): """ Synthesize the text contained in the given fragment list into a ``wav`` file. Return a tuple ``(anchors, total_time, num_chars)``. ...
python
def group_hydra_breakends(end_iter): """Group together hydra breakends with overlapping ends. This provides a way to identify inversions, translocations and insertions present in hydra break point ends. We cluster together the endpoints and return together any items with closely oriented pairs. Thi...
java
public void setDispatchMode(int[] dispatchModeInts) { //convert to DispatcherType dispatchMode = new DispatcherType [dispatchModeInts.length]; for (int i=0;i<dispatchModeInts.length;i++){ int dispatchModeCur=dispatchModeInts[i]; switch (dispatchModeCur) { case 0: dispatchMode[i]=DispatcherType.RE...
java
@TargetApi(Build.VERSION_CODES.FROYO) public static boolean hasGpsLocationFeature(PackageManager manager) { return manager.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS); }
python
def from_df(cls, df:DataFrame, cat_names:OptStrList=None, cont_names:OptStrList=None, procs=None, **kwargs)->'ItemList': "Get the list of inputs in the `col` of `path/csv_name`." return cls(items=range(len(df)), cat_names=cat_names, cont_names=cont_names, procs=procs, inner_df=df.copy(), **kwargs)
python
def report_spans(self): """ Periodically report the queued spans """ logger.debug("Span reporting thread is now alive") def span_work(): queue_size = self.queue.qsize() if queue_size > 0 and instana.singletons.agent.can_send(): response = instana.singleto...
python
def build_relational_field(self, field_name, relation_info): """ Create fields for forward and reverse relationships. """ field_class = self.serializer_related_field field_kwargs = get_relation_kwargs(field_name, relation_info) to_field = field_kwargs.pop('to_field', Non...
python
def get_context(self): """Return an SSL.Context from self attributes.""" # See https://code.activestate.com/recipes/442473/ c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_c...
python
def save_session_to_file(self, sessionfile): """Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.""" pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)
java
public Script instantiate(Class<? extends Script> clazz, Context cx) throws EvaluatorException { try { GeneratedClassLoader loader = SecurityController.createLoader( cx.getApplicationClassLoader(), securityDomain); loader.linkClass(clazz); if (!Script.class.isAssignableFrom(clazz)) { throw Context.r...
java
public Matrix4x3d identity() { if ((properties & PROPERTY_IDENTITY) != 0) return this; m00 = 1.0; m01 = 0.0; m02 = 0.0; m10 = 0.0; m11 = 1.0; m12 = 0.0; m20 = 0.0; m21 = 0.0; m22 = 1.0; m30 = 0.0; m31 = 0.0; ...
java
public boolean fillIfLive(long timeout) throws IOException { StreamImpl source = _source; byte []readBuffer = _readBuffer; if (readBuffer == null || source == null) { _readOffset = 0; _readLength = 0; return false; } if (_readOffset > 0) { System.arraycopy(readBuffer,...
java
@Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { final MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); return enabled ? new PropertyMethodReferenceWrapper(mv, access, name, d...
java
private int findBitRate(int bitrateIndex, int version, int layer) { int ind = -1; if (version == MPEG_V_1) { if (layer == MPEG_L_1) { ind = 0; } else if (layer == MPEG_L_2) { ind = 1; } else if (layer == MPEG_L_3) { ind = 2; } } else if ((version == MPEG_V_2) || (versi...
java
public Task removeDatastoreEx_Task(Datastore[] datastore) throws HostConfigFault, RuntimeFault, RemoteException { ManagedObjectReference taskMor = getVimService().removeDatastoreEx_Task(getMOR(), MorUtil.createMORs(datastore)); return new Task(getServerConnection(), taskMor); }
java
public static <T> TypeSerializerSnapshot<T> snapshotBackwardsCompatible(TypeSerializer<T> originatingSerializer) { return configureForBackwardsCompatibility(originatingSerializer.snapshotConfiguration(), originatingSerializer); }
java
public InputStream toInputStream() { byte[] encoded = toXML().toString().getBytes(Charset.forName("UTF-8")); return new ByteArrayInputStream(encoded); }
python
def is_offsetlike(arr_or_obj): """ Check if obj or all elements of list-like is DateOffset Parameters ---------- arr_or_obj : object Returns ------- boolean Whether the object is a DateOffset or listlike of DatetOffsets Examples -------- >>> is_offsetlike(pd.DateOf...
java
@Bean(name = AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME) ApplicationEventMulticaster applicationEventMulticaster(@Qualifier("asyncExecutor") final Executor executor, final TenantAware tenantAware) { final SimpleApplicationEventMulticaster simpleApplicationEventMulticaster...
python
def parse_map_Ka(self): """Ambient map""" Kd = os.path.join(self.dir, " ".join(self.values[1:])) self.this_material.set_texture_ambient(Kd)
java
public final EObject ruleGroup() throws RecognitionException { EObject current = null; EObject this_AbstractToken_0 = null; EObject lv_elements_2_0 = null; enterRule(); try { // InternalXtext.g:1192:2: ( (this_AbstractToken_0= ruleAbstractToken ( () ( (lv_eleme...
java
public void clearTemplateCacheFor(final String templateName) { Validate.notNull(templateName, "Template name cannot be null"); if (!this.initialized) { initialize(); } this.configuration.getTemplateManager().clearCachesFor(templateName); }
java
public Reference runReference(String projectName, String sutName, String requirementRepositoryId, String requirementName, String locale) throws GreenPepperServerException { return runReference(projectName, sutName, requirementRepositoryId, requirementName, null, null, locale); }
java
public static List<IntDependency> treeToDependencyList(Tree tree, Index<String> wordIndex, Index<String> tagIndex) { List<IntDependency> depList = new ArrayList<IntDependency>(); treeToDependencyHelper(tree, depList, 0, wordIndex, tagIndex); if (DEBUG) { System.out.println("-----------------------...
java
private MoneyFormatterBuilder appendInternal(MoneyPrinter printer, MoneyParser parser) { printers.add(printer); parsers.add(parser); return this; }
python
def save(keystorerc=None, keystore=None, files=[], verbose=False): '''create a keystore, compress and encrypt to file''' config = None if keystorerc: config = config_reader.read(keystorerc) if not config: print('No configuration found.', file=sys.stderr) sys.exit(-1) elif keystore and len(f...
python
def stderr_handle(): """Generate debug-level appropriate stderr context for executing things through subprocess. Normally stderr gets sent to dev/null but when debugging it is sent to stdout.""" gpg_stderr = None handle = None if LOGGER.getEffectiveLevel() > logging.DEBUG: handle = open(...
java
public ParallelTaskBuilder setSshPassword(String password) { this.sshMeta.setPassword(password); this.sshMeta.setSshLoginType(SshLoginType.PASSWORD); return this; }
python
def _load_paths(self, paths, depth=0): ''' Goes recursevly through the given list of paths in order to find and pass all preset files to ```_load_preset()``` ''' if depth > self.MAX_DEPTH: return for path in paths: try: # avoid em...
java
public GrpcServerLimiterBuilder partitionByAttribute(Attributes.Key<String> attribute) { return partitionResolver(context -> context.getCall().getAttributes().get(attribute)); }
python
def TotalFees(self): """ Get the total transaction fees in the block. Returns: Fixed8: """ amount = Fixed8.Zero() for tx in self.Transactions: amount += tx.SystemFee() return amount
python
def route_election(self, election): """ Legislative or executive office? """ if ( election.election_type.slug == ElectionType.GENERAL or ElectionType.GENERAL_RUNOFF ): self.bootstrap_general_election(election) elif election.race.special...
python
def apply(self, func, *extras): """ >> a = AccumDict({'a': 1, 'b': 2}) >> a.apply(lambda x, y: 2 * x + y, 1) {'a': 3, 'b': 5} """ return self.__class__({key: func(value, *extras) for key, value in self.items()})
python
def set_created_date(self, created_date): """Sets the created date. arg: created_date (osid.calendaring.DateTime): the new created date raise: InvalidArgument - ``created_date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullA...
java
public static ArrayList<ValidationMessage> shiftAndRemoveFeature( Entry entry, int deletedBeginNs) { List<Location> locationsList = null; ArrayList<Feature> gapFeatures = new ArrayList(); ArrayList<ValidationMessage> validationMessages = new ArrayList(); long featureNewBeginLocation = 0; long featureNewEnd...
java
public FastAdapterBottomSheetDialog<Item> add(int position, Item item) { mItemAdapter.add(position, item); return this; }
java
public static int today() { java.time.LocalDate today = java.time.LocalDate.now(); return today.getYear() * 10000 + today.getMonthValue() * 100 + today.getDayOfMonth(); }
python
def _do_layout(self): """Set sizers""" sizer_dialog = wx.FlexGridSizer(3, 1, 0, 0) # Sub sizers sizer_buttons = wx.FlexGridSizer(1, 3, 5, 5) # Adding buttons to sizer_buttons for button in [self.button_cancel, self.button_apply, self.button_ok]: sizer_butto...
java
public static synchronized void putChannel(WonderPushChannel channel) { try { if (_putChannel(channel)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while putting channel " + channel, ex); } }
python
def get_stats(self): """Given XML version, parse create XMLAbstract object and sets xml_stats attribute.""" self.gather_xml() self.xml_version = self.bs_xml.find('statistics')['version'] if self.xml_version is None: raise XmlError("Unable to determine XML version via 'statis...
java
private void manageService(Entity rawEntity){ CloudFoundryService cloudFoundryService; if (rawEntity instanceof CloudFoundryService){ cloudFoundryService = (CloudFoundryService) rawEntity; String serviceName = cloudFoundryService .getConfig(CloudFou...
python
def get_default_config(self): """ Returns the default collector settings """ config = super(CPUCollector, self).get_default_config() config.update({ 'path': 'cpu', 'percore': 'True', 'xenfix': None, 'simple': 'False', ...
java
@Override public String getName() { StringBuilder result = new StringBuilder(); String prefix = ""; for (IPOContext ctxt : this) { String name = ctxt.getName(); if (name.length() > 0) { result.append(prefix); result.append(name); prefix = ", "; } } return result.toString(); }
java
@Override public void startElement(String uri, String localName, String qName, Attributes a) throws SAXException { // null out any existing content buffer. // This will start a fresh buffer for every element enco...
python
def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be eith...
java
public void restoreMainRecord(Record record, boolean altMatchesToNull) { Iterator<BaseTable> iterator = this.getTables(); while (iterator.hasNext()) { BaseTable table = iterator.next(); if ((table != null) && (table != this.getNextTable())) { ...
java
protected boolean clearSpecial(DatabaseConnection connection, Logger logger) { NestedConnection currentSaved = specialConnection.get(); boolean cleared = false; if (connection == null) { // ignored } else if (currentSaved == null) { logger.error("no connection has been saved when clear() called"); } els...
java
public static void copyBranch(String base, String branch, long revision, String baseUrl) throws IOException { log.info("Copying branch " + base + AT_REVISION + revision + " to branch " + branch); CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument("cp"); addDefaultArgume...
python
def add_bridge(self, bridge): """ Add bridge groups. :param bridge: Add groups from this bridge. """ for group in bridge.groups: self._groups[group.name] = group
python
def alias_delete(indices, aliases, hosts=None, body=None, profile=None, source=None): ''' Delete an alias of an index indices Single or multiple indices separated by comma, use _all to perform the operation on all indices. aliases Alias names separated by comma CLI example:: ...
java
public void run() { synchronized (ivCancelLock) { //d601399 if (ivIsCanceled) { //d583637 //if this instance has been canceled, we do no more processing. // this also guarantees that a future alarm is not created. return; } ...
java
public static <K, V> KeyValueSink<K, V> asMapSink(ImmutableMap.Builder<K, V> mapB) { return new ImmutableMapBuilderSink<>(mapB); }
java
private boolean updateWastedAllocationTracker(long wastedBytes) { // Early check for huge allocation that exceeds the limit if (wastedBytes < EXCESS_WASTE_BYTES) { // We round up to ensure work < granularity are still accounted for int wastedAllocation = ((int) (wastedByt...