language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static IOException createIOException(List<IOException> exceptions) { if (exceptions == null || exceptions.isEmpty()) { return null; } if (exceptions.size() == 1) { return exceptions.get(0); } return new MultipleIOException(exceptions); }
python
def encode_basestring(s, _PY3=PY3, _q=u('"')): """Return a JSON representation of a Python string """ if _PY3: if isinstance(s, binary_type): s = s.decode('utf-8') else: if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def repla...
java
public void marshall(BatchDetectDominantLanguageRequest batchDetectDominantLanguageRequest, ProtocolMarshaller protocolMarshaller) { if (batchDetectDominantLanguageRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
python
def max_size_max_distance_subset(items, min_thresh=0, Kstart=2, verbose=False): r""" Args: items (?): min_thresh (int): (default = 0) Kstart (int): (default = 2) Returns: ?: prev_subset_idx CommandLine: python -m utool.util_alg --exec-max_size_max_distance_subse...
python
def on_linecolor(self, *args): """If I don't yet have the instructions for drawing the selection box in my canvas, put them there. In any case, set the :class:`Color` instruction to match my current ``linecolor``. """ if hasattr(self, 'color'): self.color.rgba = self...
java
public long calculateDuration() { if (!nodes.isEmpty()) { long endTime = 0; for (int i = 0; i < getNodes().size(); i++) { Node node = getNodes().get(i); long nodeEndTime = node.overallEndTime(); if (nodeEndTime > endTime) { ...
java
@Override public GetUrlTaskResult getHlsUrl(String spaceId, String contentId) throws ContentStoreException { final GetHlsUrlTaskParameters params = new GetHlsUrlTaskParameters(); params.setSpaceId(spaceId); params.setContentId(contentId); return GetUrlTaskResult.deserialize( ...
python
def round_off(idnad: Tuple[List[float], List[float]], dp: int = 2): """ Round off an ideal/nadir estimate e.g. so that it's looks nicer when plotted. This function is careful to round so only ever move the values away from the contained range. """ ideal, nadir = idnad mult = np.power(10, dp)...
java
public Configuration getConfiguration(String name) { Configuration[] values = getConfigurations(name); if (values == null) { return null; } return values[0]; }
python
def _set_network_adapter_mapping(domain, gateway, ip_addr, subnet_mask, mac): ''' Returns a vim.vm.customization.AdapterMapping object containing the IP properties of a network adapter card domain Domain of the host gateway Gateway address ip_addr IP address subne...
java
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { ManagedConnection result = null; Iterator it = connectionSet.iterator(); while (result == ...
python
def mbar( ttrajs, dtrajs, bias, maxiter=100000, maxerr=1.0E-15, save_convergence_info=0, dt_traj='1 step', direct_space=False): r""" Multi-state Bennet acceptance ratio Parameters ---------- ttrajs : numpy.ndarray(T) of int, or list of numpy.ndarray(T_i) of int A single discrete...
python
def send_confirmation_instructions(user): """Sends the confirmation instructions email for the specified user. :param user: The user to send the instructions to """ confirmation_link, token = generate_confirmation_link(user) _security.send_mail(config_value('EMAIL_SUBJECT_CONFIRM'), user.email, ...
java
public static <T> Iterator<T> concat( final Iterator<? extends Iterator<? extends T>> inputs) { checkNotNull(inputs); return new Iterator<T>() { Iterator<? extends T> current = emptyIterator(); Iterator<? extends T> removeFrom; @Override public boolean hasNext() { // http:...
python
def add_block(self, name): """ Adds a new block to the AST. `name` Block name. * Raises a ``ValueError`` exception if `name` is invalid or an existing block name matches value provided for `name`. """ if not self.RE_NAME.match(name): ...
python
def sql_post(self, owner, id, query, **kwargs): """ SQL query This endpoint executes SQL queries against a dataset. SQL results are available in a variety of formats. By default, `application/json` will be returned. Set the `Accept` header to one of the following values in accordance with your ...
python
def isnumeric(obj): ''' Return true if obj is a numeric value ''' from decimal import Decimal if type(obj) == Decimal: return True else: try: float(obj) except: return False return True
python
def debugging(): """This one I use for debugging...""" print("In debugging") json_file = r"C:\Scripting\Processing\Cell" \ r"data\outdata\SiBEC\cellpy_batch_bec_exp02.json" b = init(default_log_level="DEBUG") b.load_info_df(json_file) print(b.info_df.head()) # setting some ...
java
public static void clearEvidence(Network bn, String nodeName) throws ShanksException { int node = bn.getNode(nodeName); if (bn.isEvidence(node)) { bn.clearEvidence(nodeName); bn.updateBeliefs(); } }
java
public ContextMenuItem addItem(String caption) { ContextMenuItemState itemState = getState().addChild(caption, getNextId()); ContextMenuItem item = new ContextMenuItem(null, itemState); m_items.put(itemState.getId(), item); return item; }
java
public void disableICE() { if (this.ice) { this.ice = false; this.iceAuthenticator.reset(); // Disable ICE on RTP channels this.rtpChannel.disableIce(); if(!rtcpMux) { this.rtcpChannel.disableIce(); } ...
python
def get_contact(self, msisdn): """ Returns the WhatsApp ID for the given MSISDN """ response = self.session.post( urllib_parse.urljoin(self.api_url, "/v1/contacts"), json={"blocking": "wait", "contacts": [msisdn]}, ) response.raise_for_status() ...
python
def write_passes(self, outfile, rows, packed=False): """ Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear ...
python
def find_next_character(code, position, char): """Find next char and return its first and last positions""" end = LineCol(code, *position) while not end.eof and end.char() in WHITESPACE: end.inc() if not end.eof and end.char() == char: return end.tuple(), inc_tuple(end.tuple()) retu...
java
public DatabaseInfo getDatabaseInfo(Connection connection) throws SQLException { PreparedStatement statement = connection.prepareStatement("select @@servername, db_name()"); ResultSet results = null; DatabaseInfo info = null; try { results = statement.exe...
java
@Override public void onTriggerChange(Operation operation, String tenantId, String triggerId) { log.debugf("Executing: %s tenantId: %s triggerId: %s", operation, tenantId, triggerId); switch (operation) { case ADD: case UPDATE: Trigger reloadTrigger = new Trig...
java
public void writeTo(String zoneID, OutputStream out) throws IOException { if (out instanceof DataOutput) { writeTo(zoneID, (DataOutput)out); } else { DataOutputStream dout = new DataOutputStream(out); writeTo(zoneID, (DataOutput)dout); dout.flush(); ...
java
public static Callable<?> getTaskFromExtras(final Intent intent) { if (!intent.hasExtra(EXTRA_TASK) && !intent.hasExtra(EXTRA_TASK_BUNDLE)) { return null; } Parcelable taskArg = intent.getParcelableExtra(EXTRA_TASK); if (taskArg == null) { Bundle bundle = intent.getBundleExtra(EXTRA_TASK_BU...
python
def save_model(self, request, obj, form, change): """ Save model for every language so that field auto-population is done for every each of it. """ super(DisplayableAdmin, self).save_model(request, obj, form, change) if settings.USE_MODELTRANSLATION: lang = ge...
java
public void addLockInformation(Object key, boolean contention, boolean failLock) { if (!isEnabled()) { return; } syncOffer(Stat.MOST_LOCKED_KEYS, key); if (contention) { syncOffer(Stat.MOST_CONTENDED_KEYS, key); } if (failLock) { syncOffer(Stat.MOST_FAILE...
java
public static void cut(Image srcImage, OutputStream out, Rectangle rectangle) throws IORuntimeException { cut(srcImage, getImageOutputStream(out), rectangle); }
python
def show_list_translations(context, item): """ Return the widget to select the translations we want to order or delete from the item it's being edited :param context: :param item: :return: """ if not item: return manager = Manager() manager.set_master(item) ct_item...
python
def _exec_ipmitool(driver_info, command): """Execute the ipmitool command. This uses the lanplus interface to communicate with the BMC device driver. :param driver_info: the ipmitool parameters for accessing a node. :param command: the ipmitool command to be executed. """ ipmi_cmd = ("ipmitoo...
python
def _get_token( request=None, allowed_auth_schemes=('OAuth', 'Bearer'), allowed_query_keys=('bearer_token', 'access_token')): """Get the auth token for this request. Auth token may be specified in either the Authorization header or as a query param (either access_token or bearer_token). We'll check in ...
java
public AnnotationHeader parseAnnotation(String resourceLocation, File annotationFile) throws IOException, BELDataMissingPropertyException, BELDataConversionException, BELDataInvalidPropertyException { if (annotationFile == null) { throw new InvalidArgument("annota...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case TypesPackage.JVM_STRING_ANNOTATION_VALUE__VALUES: return values != null && !values.isEmpty(); } return super.eIsSet(featureID); }
python
def _plot_line( self, start, end, data ): """ plot line from start = (x0, y0) to end = (x1, y1) """ clipped_line = self.canvas._clip_line(start, end) if clipped_line is None: return False start, end = clipped_line ...
python
def handle_challenge(self,data): """ Executed when the server requests additional authentication """ # Send challenge response self.send_message(AUTHENTICATE( signature = self.password, extra = {} ))
java
public void eachRow(String sql, Map map, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException { eachRow(sql, singletonList(map), metaClosure, offset, maxRows, rowClosure); }
python
def do_i_raise_dependency(self, status, inherit_parents, hosts, services, timeperiods): # pylint: disable=too-many-locals """Check if this object or one of its dependency state (chk dependencies) match the status :param status: state list where dependency matters (notification failure criteria)...
java
public synchronized void checkState(State... requiredStates) throws IllegalStateException { for (State requiredState : requiredStates) { if (requiredState.equals(currentState)) { return; } } throw new IllegalStateException(String.format(Locale.US, ...
python
def AgregarFardo(self, cod_trazabilidad, clase_tabaco, peso, **kwargs): "Agrego un fardo al último romaneo agregado a la liq." fardo = dict(codTrazabilidad=cod_trazabilidad, claseTabaco=clase_tabaco, peso=peso) self.solicitud['romaneo'][-1]['fardo'].append(fardo) return True
python
def subprocess(self, argv): """ Execute subprocess commands with proper ouput. This is no longer used in landsat-util :param argv: A list of subprocess arguments :type argv: List :returns: void """ if self.verbose: ...
python
def object_present( name, source=None, hash_type=None, extra_args=None, extra_args_from_pillar='boto_s3_object_extra_args', region=None, key=None, keyid=None, profile=None, ): ''' Ensure object exists in S3. name The name of the state definition. This wil...
python
def _get_file_size(self): """ Fetches file size by reading the Content-Length header for the resource. :return: File size. """ file_size = retry(self._retry_count)(_get_content_length)( self._session, self.url, self._timeout ) file_size = int(f...
java
public OpenAPI downloadModel() throws Exception { String download = download(); if (download != null) { try { SwaggerParseResult parseResult = new OpenAPIParser().readContents(download, null, null, null); if (parseResult != null) { return p...
python
def collect(self): """ Perform the bulk of the work of collectstatic. Split off from handle_noargs() to facilitate testing. """ if self.symlink: if sys.platform == 'win32': raise CommandError("Symlinking is not supported by this " ...
java
@Override public GetDocumentPathResult getDocumentPath(GetDocumentPathRequest request) { request = beforeClientExecution(request); return executeGetDocumentPath(request); }
java
public void marshall(UpdateApplicationRequest updateApplicationRequest, ProtocolMarshaller protocolMarshaller) { if (updateApplicationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateA...
java
boolean isParityFile(Path p, Codec c) { return isParityFile(p.toUri().getPath(), c); }
java
public static void e(String tag, String message, Object... args) { sLogger.e(tag, message, args); }
python
def _is_orphan(scc, graph): """ Return False iff the given scc is reachable from elsewhere. """ return all(p in scc for v in scc for p in graph.parents(v))
java
protected List<Field> getSingleLevelOfFields(Class<?> clazz) { List<Field> fields = new ArrayList<Field>(); for (Field field : clazz.getDeclaredFields()) { if (!field.isAnnotationPresent(Inject.class)) { continue; } fields.add(field); } ...
java
public void onClick(ClickEvent clickEvent) { List<Feature> features = new ArrayList<Feature>(); for (VectorLayer layer : mapWidget.getMapModel().getVectorLayers()) { features.addAll(layer.getSelectedFeatureValues()); } // only zoom when there where really some items selected if (features.size() > 0) { ...
java
private static double abramowitzStegunFormula26p5p22(final double a, final double b, final double yp) { final double b2m1 = (2.0 * b) - 1.0; final double a2m1 = (2.0 * a) - 1.0; final double lambda = ((yp * yp) - 3.0) / 6.0; final double htmp = (1.0 / a2m1) + (1.0 / b2m1); final double h = 2.0...
python
def _parse_opts(self, data): """ Given a tag string, this function will parse any options out of it and return a tuple of (tag_name, options_dict). Options may be quoted in order to preserve spaces, and free-standing options are allowed. The tag name itself may also serve as an o...
java
private void populateDatastructuresForAnalysisTraversal(ReferenceMap referenceMap) { // Merge the prop and name references into a single multimap since only the name matters. ArrayListMultimap<String, Node> referencesByName = ArrayListMultimap.create(); for (Map.Entry<String, ? extends List<Node>> entry : r...
python
def parse_instruction(string, location, tokens): """Parse instruction. """ mnemonic_str = ReilMnemonic.from_string(tokens["mnemonic"]) oprnd1 = tokens["fst_operand"][0] oprnd2 = tokens["snd_operand"][0] oprnd3 = tokens["trd_operand"][0] ins_builder = ReilBuilder() return ins_builder.b...
java
private void processExternalTasks(List<Task> externalTasks) { // // Sort the list of tasks into ID order // Collections.sort(externalTasks); // // Find any external tasks which don't have a sub project // object, and set this attribute using the most recent // value. ...
java
public Integer getIdFromName(String profileName) { PreparedStatement query = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { query = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_PROFILE + ...
java
public void setUTCDiffM(Integer newUTCDiffM) { Integer oldUTCDiffM = utcDiffM; utcDiffM = newUTCDiffM; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.UNIVERSAL_DATE_AND_TIME_STAMP__UTC_DIFF_M, oldUTCDiffM, utcDiffM)); }
python
def constrain_secdepth(self, thresh): """ Constrain the observed secondary depth to be less than a given value :param thresh: Maximum allowed fractional depth for diluted secondary eclipse depth """ self.apply_constraint(UpperLimit(self.secondary_depth, ...
python
def _run_script(self, session, file_path): """ Runs the given script file :param session: Current shell session :param file_path: Path to the file to execute :return: True if a file has been execute """ if file_path: # The 'run' command returns False ...
java
public void doActivities(Object seedData) { // retrieve injected by Spring List<Activity> activities = getActivities(); if (seedData != null) { context.setSeedData(seedData); } for (Activity activity : activities) { try { context = activity.execute(context); } catch (Throwable th) { Workflo...
java
public final <C> Callable<C> withSpan(Span span, final Callable<C> callable) { return CurrentSpanUtils.withSpan(span, /* endSpan= */ false, callable); }
java
public LongStreamEx prepend(LongStream other) { return new LongStreamEx(LongStream.concat(other, stream()), context.combine(other)); }
java
public static UpdateDeploymentRequest createUpdateDeploymentRequest(String applicationName, String deploymentName, String commitId) { UpdateDeploymentRequest updateDeploymentRequest = new UpdateDeploymentRequest(); updateDeploymentRequest.setApplicationName(applicationName); updateDeploymentRequest.setDeploymentN...
python
def fix_parameters(self): """Helper function that fixes all parameters""" for W, b in zip(self.W_list, self.b_list): W.fix() b.fix()
python
def plothist(self,fig=None,**kwargs): """Plots a histogram of samples using provided bins. Parameters ---------- fig : None or int Parameter passed to `setfig`. kwargs Keyword arguments passed to `plt.hist`. """ setfig(fig) ...
java
public void marshall(StartMonitoringMembersRequest startMonitoringMembersRequest, ProtocolMarshaller protocolMarshaller) { if (startMonitoringMembersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.m...
python
def get_tabs(self, request, **kwargs): """Returns the initialized tab group for this view.""" if self._tab_group is None: self._tab_group = self.tab_group_class(request, **kwargs) return self._tab_group
java
void recoverSegments(SyncTask task) throws IOException { // obtain the list of segments that are valid if (!prepareRecovery(task)) { return; } // iterate through all nodes for (InetSocketAddress jn : journalNodes) { if (isLocalIpAddress(jn.getAddress()) && jn.getPort() == jour...
java
@Override public int compareTo(ADStarNodeImpl<A, S, C> o) { return this.key.compareTo(o.key); }
python
def list_dfu_devices(*args, **kwargs): """Prints a lits of devices detected in DFU mode.""" devices = get_dfu_devices(*args, **kwargs) if not devices: print("No DFU capable devices found") return for device in devices: print("Bus {} Device {:03d}: ID {:04x}:{:04x}" ...
python
def deal_caps(x:Collection[str]) -> Collection[str]: "Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before." res = [] for t in x: if t == '': continue if t[0].isupper() and len(t) > 1 and t[1:].islower(): res.append(TK_MAJ) res.append(t.lower()) re...
java
public static IntegerVector addUnmodified(IntegerVector vector1, IntegerVector vector2) { if (vector2.length() != vector1.length()) throw new IllegalArgumentException( "Vectors of different sizes cannot be added"); IntegerVect...
java
public void addTerm(final IndexTerm term) { int i = 0; final int termNum = termList.size(); for (; i < termNum; i++) { final IndexTerm indexTerm = termList.get(i); if (indexTerm.equals(term)) { return; } // Add targets when same t...
python
def remover(self, id_script_type): """Remove Script Type from by the identifier. :param id_script_type: Identifier of the Script Type. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Script Type is null and invalid. :raise Tip...
java
private boolean compareTypesOld(Type parmType, Type argType) { // XXX equality not implemented for GenericObjectType // if (parmType.equals(argType)) return true; // Compare type signatures instead if (GenericUtilities.getString(parmType).equals(GenericUtilities.getString(argType))) { ...
python
def get_certificate(self, filename): """ Return a X.509 certificate object by giving the name in the apk file :param filename: filename of the signature file in the APK :returns: a :class:`Certificate` certificate """ cert = self.get_certificate_der(filename) cer...
python
def clear_start_timestamp(self): """stub""" if (self.get_start_timestamp_metadata().is_read_only() or self.get_start_timestamp_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['startTimestamp'] = \ self.get_start_timestamp_metad...
java
private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) { EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget(); EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR); WSAEndpointReferenceUtils.se...
java
public com.google.api.ads.adwords.axis.v201809.cm.AdGroupExtensionSetting getAdGroupExtensionSetting() { return adGroupExtensionSetting; }
java
public boolean isEnabled(String featurePath) { checkArgument(!Strings.isNullOrEmpty(featurePath)); return config.getConfig(featurePath).getBoolean("enabled"); }
python
def get_rmq_cluster_running_nodes(self, sentry_unit): """Parse rabbitmqctl cluster_status output string, return list of running rabbitmq cluster nodes. :param unit: sentry unit :returns: List containing node names of running nodes """ # NOTE(beisner): rabbitmqctl cluster...
python
def _make_request(self, conf, post_params={}): """Make a request to the API and return data in a pythonic object""" endpoint, requires_auth = conf # setup the url and the request objects url = '%s%s.php' % (self.api_url, endpoint) log.debug('Setting url to %s' % url) req...
java
public static boolean shouldProxy(Properties props) { String shouldProxy = props.getProperty(HadoopSecurityManager.ENABLE_PROXYING); return shouldProxy != null && shouldProxy.equals("true"); }
java
public void start(final SyncOptimizeManagerResultCallBack callback) { if (isRunning()) { throw new IllegalStateException( "The start() method cannot be called when the sync optimize process is running."); } running = true; new Thread(new Runnable() { ...
python
def _keyword_to_row(self, keyword, value, wrap_slash=False): """Helper to make a message row from a keyword. .. versionadded:: 3.2 Use this when constructing a table from keywords to display as part of a message object. :param keyword: The keyword to be rendered. :type...
python
def add_my_api_key_to_groups(self, body, **kwargs): # noqa: E501 """Add API key to a list of groups. # noqa: E501 An endpoint for adding API key to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586...
java
private void initDefinition(NodeData parent) throws RepositoryException, ConstraintViolationException { if (this.isRoot()) { // root - no parent this.definition = new NodeDefinitionData(null, null, true, true, OnParentVersionAction.ABORT, true, new InternalQNa...
python
def recursive_insert(self, node, coord, data, start, end): """Recursively inserts id data into nodes""" if node[0] != -1: left = (start, node[0]) right = (node[0], end) #if left is totally within coord if self.is_within(left, coord): node[...
python
def get_error_details(self): # type: () -> Optional[Dict[str, Any]] """ Get more information about the latest X server error. """ details = {} # type: Dict[str, Any] if ERROR.details: details = {"xerror_details": ERROR.details} ERROR.details = None ...
python
def _get_collection(self, collection_uri, request_headers=None): """Generator function that returns collection members.""" # get the collection status, headers, thecollection = self._rest_get(collection_uri) if status != 200: msg = self._get_extended_error(thecollection) ...
java
public String convertTileSetColorCSPACEToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
@Override public void write(JsonWriterImpl out, ZonedDateTime value) { out.write(value.format(_formatter)); }
java
public static Collection<Named> sortByName(Collection<Named> aNamedVOs) { List<Named> list = null; if (aNamedVOs instanceof List) list = (List<Named>) aNamedVOs; else list = new ArrayList<Named>(aNamedVOs); Collections.sort(list); return list; ...
python
def _rename_file(self, line=""): """Rename an ontology 2016-04-11: not a direct command anymore """ if not self.all_ontologies: self._help_nofiles() else: out = [] for each in self.all_ontologies: if line in each: ...
python
def callback(self, event): """ Callback function to spawn a mini-browser when a feature is clicked. """ artist = event.artist ind = artist.ind limit = 5 browser = True if len(event.ind) > limit: print "more than %s genes selected; not spawning ...
python
def zrevrangebyscore(self, name, max, min, start=None, num=None, withscores=False, score_cast_func=float): """ Return a range of values from the sorted set ``name`` with scores between ``min`` and ``max`` in descending order. If ``start`` and ``num`` are specifi...