language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _setbin_safe(self, binstring): """Reset the bitstring to the value given in binstring.""" binstring = tidy_input_string(binstring) # remove any 0b if present binstring = binstring.replace('0b', '') self._setbin_unsafe(binstring)
python
def retryable(a_func, retry_options, **kwargs): """Creates a function equivalent to a_func, but that retries on certain exceptions. Args: a_func (callable): A callable. retry_options (RetryOptions): Configures the exceptions upon which the callable should retry, and the parameters to th...
python
def write_to_cache(self, data, filename=''): ''' Writes data to file as JSON. Returns True. ''' if not filename: filename = self.cache_path_cache json_data = json.dumps(data) with open(filename, 'w') as cache: cache.write(json_data) return True
java
public synchronized void start() { // ggf. laufenden Thread beenden stop(); this.thread = new Thread("Flicker Update-Thread") { public void run() { // Wir fangen beim ersten Halbbyte an. halfbyteid = 0; // Die Clock, die immer hin und...
python
def train(self, data, label, batch_size): """ Description : training for LipNet """ # pylint: disable=no-member sum_losses = 0 len_losses = 0 with autograd.record(): losses = [self.loss_fn(self.net(X), Y) for X, Y in zip(data, label)] for loss ...
java
public static XslTransformer getTransformer(File xslFile) throws TransformerConfigurationException { if (xslFile == null) { throw new IllegalArgumentException("xslFile is null"); } return getTransformer(new StreamSource(xslFile)); }
java
public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException { addRoute(new Route(urlPattern, true), actorClass); }
java
public int deleteByMetadata(long fileId) throws SQLException { DeleteBuilder<MetadataReference, Void> db = deleteBuilder(); db.where().eq(MetadataReference.COLUMN_FILE_ID, fileId); int deleted = db.delete(); return deleted; }
java
public static List<String> readLines(File targetFile, String charsetName) { return readLines(targetFile.toPath(), charsetName); }
python
def get_by_id(self, id): """Find user by his id and return user model.""" user = super(ExtendedUsersService, self).get_by_id(id) user.first_name = 'John' + str(id) user.last_name = 'Smith' + str(id) user.gender = 'male' return user
java
public static Version from(int major, int minor, int patch, String build) { return new Version(major, minor, patch, build); }
python
def geocode(self, query, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be ...
python
def vspec_magic(data): """ Takes average vector of replicate measurements """ vdata, Dirdata, step_meth = [], [], "" if len(data) == 0: return vdata treat_init = ["treatment_temp", "treatment_temp_decay_rate", "treatment_temp_dc_on", "treatment_temp_dc_off", "treatment_ac_field", "treatm...
java
static Interval removeIntervalFromEnd(Interval largeInterval, Interval smallInterval) { Preconditions.checkArgument( largeInterval.getEnd().equals(smallInterval.getEnd()), "end should be same. largeInterval[%s] smallInterval[%s]", largeInterval, smallInterval ); return new ...
java
public void setNotificationProject(String notificationProject) { m_notificationProject = notificationProject; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key(Messages.INIT_NOTIFICATION_PROJECT_1, m_notificationProject)); } }
python
def __parse_direct_mention(self, message_text): """ Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention, returns None """ matches = re.search(MENTION_REGEX, message_text) ...
python
def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size): """Gather top beams from nested structure.""" _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size) return _gather_beams(nested, topk_indexes, batch_size, beam_size)
python
def _handle_message_flow(self, app_message): """ Handle protocol flow for incoming and outgoing messages, depending on service level and according to MQTT spec. paragraph 4.3-Quality of Service levels and protocol flows :param app_message: PublishMessage to handle :return: nothin...
java
public EClass getGCFLT() { if (gcfltEClass == null) { gcfltEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(450); } return gcfltEClass; }
python
def graph(data): """Draws graph of rating vs episode number""" title = data['name'] + ' (' + data['rating'] + ') ' plt.title(title) plt.xlabel('Episode Number') plt.ylabel('Ratings') rf,ef=graphdata(data) col=['red', 'green' , 'orange'] for i in range(len(rf)): x,y=ef[i],rf[i] ...
java
public void setInstanceStates(java.util.Collection<String> instanceStates) { if (instanceStates == null) { this.instanceStates = null; return; } this.instanceStates = new com.amazonaws.internal.SdkInternalList<String>(instanceStates); }
java
public void end () { Texture tex = (Texture)tile(); Image image = canvas.image; // if our texture is already the right size, just update it if (tex != null && tex.pixelWidth == image.pixelWidth() && tex.pixelHeight == image.pixelHeight()) tex.update(image); // otherwise we need to create a n...
java
public OvhContact contact_POST(String city, String country, String email, String firstname, String lastname, String phone, String province, String street, String title, String zip) throws IOException { String qPath = "/store/contact"; StringBuilder sb = path(qPath); HashMap<String, Object>o = new HashMap<String, ...
java
public Attribute getTypeAttribute() { final Attribute ret; if (this.typeAttributeName == null && getParentType() != null) { ret = getParentType().getTypeAttribute(); } else { ret = this.attributes.get(this.typeAttributeName); } return ret; }
java
public static byte[] serialize(Object value) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); serialize(value, out); return out.toByteArray(); }
java
public Pair<List<Group>> getSurfaceResidues(double minAsaForSurface) { List<Group> surf1 = new ArrayList<Group>(); List<Group> surf2 = new ArrayList<Group>(); for (GroupAsa groupAsa:groupAsas1.values()) { if (groupAsa.getAsaU()>minAsaForSurface) { surf1.add(groupAsa.getGroup()); } } for (GroupAsa ...
java
public void disposeAndValidate() throws ObjectNotFoundException, ComposedException { List<NlsObject> errorList = this.duplicateIdErrors; this.duplicateIdErrors = null; for (Resolver resolver : this.id2callableMap.values()) { if (!resolver.resolved) { errorList.add(this.bundle.errorObjectNotFo...
java
private final byte getFlags() { if (!gotFlags) { flags = ((Byte)jmo.getField(ControlAccess.FLAGS)).byteValue(); gotFlags = true; } return flags; }
python
def sub_list(self, from_index, to_index): """ Returns a sublist from this list, whose range is specified with from_index(inclusive) and to_index(exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa...
java
public void marshall(SnsAction snsAction, ProtocolMarshaller protocolMarshaller) { if (snsAction == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(snsAction.getTargetArn(), TARGETARN_BINDING); ...
python
def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs): """k-modes algorithm""" random_state = check_random_state(random_state) if sparse.issparse(X): raise TypeError("k-modes does not support sparse data.") X = check_array(X, dtype=None) # Convert the ca...
python
def get_snapshot(nexus_url, repository, group_id, artifact_id, packaging, version, snapshot_version=None, target_dir='/tmp', target_file=None, classifier=None, username=None, password=None): ''' Gets snapshot of the desired version of the artifact nexus_url URL of nexus instance rep...
java
final synchronized public boolean[] readCoils(int serverAddress, int startAddress, int quantity) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadCoils(serverAddress, startAddress, quantity); ReadCo...
python
def new(self, tag_ident, tag_serial=0): # type: (int, int) -> None ''' A method to create a new UDF Descriptor Tag. Parameters: tag_ident - The tag identifier number for this tag. tag_serial - The tag serial number for this tag. Returns: Nothing ...
java
String getIndexRoots() { String roots = StringUtil.getList(getIndexRootsArray(), " ", ""); StringBuffer s = new StringBuffer(roots); /* s.append(' '); s.append(identitySequence.peek()); */ return s.toString(); }
java
protected CmsContainerElementBean getParentElement(CmsContainerElementBean element) { if (m_elementInstances == null) { initPageData(); } CmsContainerElementBean parent = null; CmsContainerBean cont = m_parentContainers.get(element.getInstanceId()); if ((cont != null...
python
def determine_result(self, returncode, returnsignal, output, isTimeout): """ Parse the output of the tool and extract the verification result. This method always needs to be overridden. If the tool gave a result, this method needs to return one of the benchexec.result.RESULT_* st...
python
def start_client(self, host, port=5001, protocol='TCP', timeout=5, parallel=None, bandwidth=None): """iperf -D -c host -t 60 """ cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)] if not (protocol, 'UDP'): cmd.append('-u') if parall...
python
def _chart_support(self, name, data, caller, **kwargs): "template chart support function" id = 'chart-%s' % next(self.id) name = self._chart_class_name(name) options = dict(self.environment.options) options.update(name=name, id=id) # jinja2 prepends 'l_' or 'l_{{ n }}'(v...
python
def go_to(self, url_or_text): """Go to page *address*""" if is_text_string(url_or_text): url = QUrl(url_or_text) else: url = url_or_text self.webview.load(url)
python
def compose_matrix(scale=None, shear=None, angles=None, translate=None, perspective=None): """Return transformation matrix from sequence of transformations. This is the inverse of the decompose_matrix function. Sequence of transformations: scale : vector of 3 scaling factors ...
java
void checkPermissions(MultiplePermissionsListener listener, Collection<String> permissions, Thread thread) { checkMultiplePermissions(listener, permissions, thread); }
python
def copy(self): "Return a clone of this hash object." other = _ChainedHashAlgorithm(self._algorithms) other._hobj = deepcopy(self._hobj) other._fobj = deepcopy(self._fobj) return other
python
def loadNelderMeadData(name): ''' Reads the progress of a parallel Nelder-Mead search from a text file, as created by saveNelderMeadData(). Parameters ---------- name : string Name of the txt file from which to read search progress. Returns ------- simplex : np.array ...
java
public boolean verifyDrawable(Drawable who) { for (int i = 0; i < mHolders.size(); ++i) { if (who == get(i).getTopLevelDrawable()) { return true; } } return false; }
java
private void onPublicKeysGroupAdded(int uid, ApiEncryptionKeyGroup keyGroup) { UserKeys userKeys = getCachedUserKeys(uid); if (userKeys == null) { return; } UserKeysGroup validatedKeysGroup = validateUserKeysGroup(uid, keyGroup); if (validatedKeysGroup != null) { ...
python
def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data)
python
def read_wv_master_file(wv_master_file, lines='brightest', debugplot=0): """read arc line wavelengths from external file. Parameters ---------- wv_master_file : string File name of txt file containing the wavelength database. lines : string Indicates which lines to read. For files w...
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WSubordinateControl subordinate = (WSubordinateControl) component; XmlStringBuilder xml = renderContext.getWriter(); if (!subordinate.getRules().isEmpty()) { int seq = 0; for (Rule rule : subordinate.get...
java
public String getPoolName() { if (CmsStringUtil.isEmpty(m_poolName)) { // use default pool as pool name m_poolName = OpenCms.getSqlManager().getDefaultDbPoolName(); } return m_poolName; }
java
public EEnum getGCBIMGFORMAT() { if (gcbimgformatEEnum == null) { gcbimgformatEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(136); } return gcbimgformatEEnum; }
java
@SuppressWarnings("unused") public void setMaxDate(Calendar calendar) { mDefaultLimiter.setMaxDate(calendar); if (mDayPickerView != null) { mDayPickerView.onChange(); } }
python
def json_pretty_print(s): '''pretty print JSON''' s = json.loads(s) return json.dumps(s, sort_keys=True, indent=4, separators=(',', ': '))
python
def resize(im, short, max_size): """ only resize input image to target size and return scale :param im: BGR image input by opencv :param short: one dimensional size (the short side) :param max_size: one dimensional max size (the long side) :return: resized image (NDArray) and scale (float) "...
python
def confirm(self, msg, _timeout=-1): ''' Send a confirm prompt to the GUI Arguments: msg (string): The message to display to the user. _timeout (int): The optional amount of time for which the prompt should be displayed to...
python
def set_def_xml_acl(self, acl_str, key_name='', headers=None): """sets or changes a bucket's default object""" return self.set_xml_acl(acl_str, key_name, headers, query_args=DEF_OBJ_ACL)
python
def run_info(template): """ Print information about a specific template. """ template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example proje...
python
def build_index_from_labels(df, indices, remove_prefix=None, types=None, axis=1): """ Build a MultiIndex from a list of labels and matching regex Supply with a dictionary of Hierarchy levels and matching regex to extract this level from the sample label :param df: :param indices: Tuples of ind...
python
def partial_results(self): '''The results that the RPC has received *so far* This may also be the complete results if :attr:`complete` is ``True``. ''' results = [] for r in self._results: if isinstance(r, Exception): results.append(type(r)(*deepcopy(...
java
public static void createWordNetCaches(String componentKey, Properties properties) throws SMatchException { properties = getComponentProperties(makeComponentPrefix(componentKey, InMemoryWordNetBinaryArray.class.getSimpleName()), properties); if (properties.containsKey(JWNL_PROPERTIES_PATH_KEY)) { ...
java
protected void removeNormalization( TrifocalTensor solution ) { DMatrixRMaj N2_inv = N2.matrixInv(); DMatrixRMaj N3_inv = N3.matrixInv(); DMatrixRMaj N1 = this.N1.matrix(); for( int i = 0; i < 3; i++ ) { DMatrixRMaj T = solution.getT(i); for( int j = 0; j < 3; j++ ) { for( int k = 0; k < 3; k++ ) { ...
python
def pipe_substr(context=None, _INPUT=None, conf=None, **kwargs): """A string module that returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, ...
python
def start_with(self, request): """Start the crawler using the given request. Args: request (:class:`nyawc.http.Request`): The startpoint for the crawler. """ HTTPRequestHelper.patch_with_options(request, self.__options) self.queue.add_request(request) self...
java
public synchronized void close() throws IOException { // // Kill running tasks. Do this in a 2nd vector, called 'tasksToClose', // because calling jobHasFinished() may result in an edit to 'tasks'. // TreeMap<TaskAttemptID, TaskInProgress> tasksToClose = new TreeMap<TaskAttemptID, TaskInProgr...
java
void readInnerClasses(ClassSymbol c) { int n = nextChar(); for (int i = 0; i < n; i++) { nextChar(); // skip inner class symbol ClassSymbol outer = readClassSymbol(nextChar()); Name name = readName(nextChar()); if (name == null) name = names.empty; ...
java
public synchronized void releasePreservingBuffers() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "releasePreservingBuffers"); released = true; valid = false; if (receivedData != null) { receivedData.release(); receivedData ...
java
public static <V> CompletionHandler<V, Void> createAsyncHandler(final Consumer<V> success, final Consumer<Throwable> fail) { return new CompletionHandler<V, Void>() { @Override public void completed(V result, Void attachment) { if (success != null) success.accept(resu...
python
def _termination_callback(self, process_name, returncode): """ Called when the process has stopped. :param returncode: Process returncode """ self._terminate_process_iou() if returncode != 0: if returncode == -11: message = 'IOU VM "{}" proce...
python
def create(container, portal_type, *args, **kwargs): """Creates an object in Bika LIMS This code uses most of the parts from the TypesTool see: `Products.CMFCore.TypesTool._constructInstance` :param container: container :type container: ATContentType/DexterityContentType/CatalogBrain :param po...
java
public void setMaxPayloadSize(int max) { addField(ConfigureNodeFields.max_payload_size, FormField.Type.text_single); setAnswer(ConfigureNodeFields.max_payload_size.getFieldName(), max); }
python
def destination_uri_file_counts(self): """Return file counts from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.extract.destinationUriFileCounts Returns: a list of integer counts, each representing the number of fi...
java
@Override public LoginConfiguration getLoginConfig() { LoginConfiguration loginConfig = securityMetadata != null ? securityMetadata.getLoginConfiguration() : null; return loginConfig; }
java
protected Validator createValidator(FaceletContext ctx) { if (this.validatorId == null) { throw new TagException( this.tag, "Default behavior invoked of requiring a validator-id passed in the " ...
java
public static TaxNumberMapSharedConstants create() { if (taxNumberMapConstants == null) { // NOPMD it's thread save! synchronized (TaxNumberMapConstantsImpl.class) { if (taxNumberMapConstants == null) { taxNumberMapConstants = new TaxNumberMapConstantsImpl( readMapFromPropertie...
python
def plot_rh(self, rh, plot_range=None): """ Required input: RH: Relative humidity (%) Optional Input: plot_range: Data range for making figure (list of (min,max,step)) """ # PLOT RELATIVE HUMIDITY if not plot_range: plot_range = [0, 100...
java
public String updateIndiceMapping(String action,String indexMapping) throws ElasticSearchException { try { return this.client.executeHttp(action, indexMapping, ClientUtil.HTTP_POST); } catch(ElasticSearchException e){ return ResultUtil.hand404HttpRuntimeException(e,String.class,ResultUtil.OPERTYPE_updateI...
python
def remove_son(self, son): """ Remove the son node. Do nothing if the node is not a son Args: fathers: list of fathers to add """ self._sons = [x for x in self._sons if x.node_id != son.node_id]
java
public void delete(long oid) throws SQLException { FastpathArg[] args = new FastpathArg[1]; args[0] = Fastpath.createOIDArg(oid); fp.fastpath("lo_unlink", args); }
java
public Duration newDurationDayTime( final boolean isPositive, final int day, final int hour, final int minute, final int second) { return newDuration(isPositive, DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, ...
java
public void setPlacementGroups(java.util.Collection<PlacementGroup> placementGroups) { if (placementGroups == null) { this.placementGroups = null; return; } this.placementGroups = new com.amazonaws.internal.SdkInternalList<PlacementGroup>(placementGroups); }
python
def differences(self, n): """ Returns a TimeSeriesRDD where each time series is differenced with the given order. The new RDD will be missing the first n date-times. Parameters ---------- n : int The order of differencing to perform. ...
java
public void initServer() { if (m_initialized) { return; } try { m_registry = LocateRegistry.createRegistry(m_port); m_provider = new CmsRemoteShellProvider(m_port); I_CmsRemoteShellProvider providerStub = (I_CmsRemoteShellProvider)(UnicastRemoteOb...
java
@Override public CommerceTierPriceEntry removeByC_ERC(long companyId, String externalReferenceCode) throws NoSuchTierPriceEntryException { CommerceTierPriceEntry commerceTierPriceEntry = findByC_ERC(companyId, externalReferenceCode); return remove(commerceTierPriceEntry); }
java
@Override public void encodeTo(FLEncoder enc) { final Encoder encoder = new Encoder(enc); internalArray.encodeTo(encoder); encoder.release(); }
java
public void createPool(String poolId, String virtualMachineSize, CloudServiceConfiguration cloudServiceConfiguration, int targetDedicatedNodes) throws BatchErrorException, IOException { createPool(poolId, virtualMachineSize, cloudServiceConfiguration, targetDedicatedNodes,...
python
def unmapped(sam, mates): """ get unmapped reads """ for read in sam: if read.startswith('@') is True: continue read = read.strip().split() if read[2] == '*' and read[6] == '*': yield read elif mates is True: if read[2] == '*' or re...
python
async def get_response(self, message=None, *, timeout=None): """ Returns a coroutine that will resolve once a response arrives. Args: message (`Message <telethon.tl.custom.message.Message>` | `int`, optional): The message (or the message ID) for which a response ...
python
def x(self, d): """ Allows to configure the X of the grid with one method call. Keys for the dictionary: property, min, max, step, base, expression Types: property=str, min=float, max=float, step=float, base=float, expression=str :param d: the dictionary with the parameters ...
java
private CompletableFuture<SegmentProperties> mergeInStorage(SegmentMetadata transactionMetadata, MergeSegmentOperation mergeOp, TimeoutTimer timer) { return this.storage .getStreamSegmentInfo(transactionMetadata.getName(), timer.getRemaining()) .thenAcceptAsync(transProperties ->...
python
def knot_insertion(degree, knotvector, ctrlpts, u, **kwargs): """ Computes the control points of the rational/non-rational spline after knot insertion. Part of Algorithm A5.1 of The NURBS Book by Piegl & Tiller, 2nd Edition. Keyword Arguments: * ``num``: number of knot insertions. *Default: 1* ...
python
async def disconnect(self): """ Disconnect from target. """ if not self.connected: return self.writer.close() self.reader = None self.writer = None
java
@Override public BSONObject create(boolean array, List<String> pathParts) { if (rootClass == null) { return array ? new BasicDBList() : new BasicDBObject(); } if (pathParts == null) { try { return (DBObject) rootClass.newInstance(); } catc...
python
async def stop(self): """ Irreversibly stop the receiver. """ if self.__started: self.__transport._unregister_rtp_receiver(self) self.__stop_decoder() self.__rtcp_task.cancel() await self.__rtcp_exited.wait()
python
def subscribe(self, topic, callback, qos): """Subscribe to an MQTT topic.""" if topic in self.topics: return def _message_callback(mqttc, userdata, msg): """Callback added to callback list for received message.""" callback(msg.topic, msg.payload.decode('utf-8...
python
def _log_control(self, s): """Write control characters to the appropriate log files""" if self.encoding is not None: s = s.decode(self.encoding, 'replace') self._log(s, 'send')
python
def synteny_scan(points, xdist, ydist, N): """ This is the core single linkage algorithm which behaves in O(n): iterate through the pairs, foreach pair we look back on the adjacent pairs to find links """ clusters = Grouper() n = len(points) points.sort() for i in range(n): f...
java
public static InetAddress findLocalAddressViaNetworkInterface() { Enumeration<NetworkInterface> networkInterfaces; try { networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { return null; } while (networkInterfaces.has...
python
def open_session(self): """ Open a new session to modify this server. You can either call this fnc directly, or turn on autosession which will open/commit sessions for you transparently. """ if self.session is not None: msg = "session already open; commit it ...
java
public void marshall(SignalExternalWorkflowExecutionFailedEventAttributes signalExternalWorkflowExecutionFailedEventAttributes, ProtocolMarshaller protocolMarshaller) { if (signalExternalWorkflowExecutionFailedEventAttributes == null) { throw new SdkClientException("Invalid argument pas...
java
private void setContentTypeHeader(final HttpResponse response, final URLConnection connection) { response.headers().set(CONTENT_TYPE, mimeTypesMap.getContentType(connection.getURL().getPath())); }