language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static int[] getHWDFromInputType(InputType inputType) { int inH; int inW; int inDepth; // FIXME: int cast if (inputType instanceof InputType.InputTypeConvolutional) { InputType.InputTypeConvolutional conv = (InputType.InputTypeConvolutional) inputType; ...
python
def _pick_colours(self, palette_name, selected=False): """ Pick the rendering colour for a widget based on the current state. :param palette_name: The stem name for the widget - e.g. "button". :param selected: Whether this item is selected or not. :returns: A colour tuple (fg, a...
java
public ListDedicatedIpPoolsResult withDedicatedIpPools(String... dedicatedIpPools) { if (this.dedicatedIpPools == null) { setDedicatedIpPools(new java.util.ArrayList<String>(dedicatedIpPools.length)); } for (String ele : dedicatedIpPools) { this.dedicatedIpPools.add(ele);...
python
def cleanTempDirs(job): """Remove temporarly created directories.""" if job is CWLJob and job._succeeded: # Only CWLJobs have this attribute. for tempDir in job.openTempDirs: if os.path.exists(tempDir): shutil.rmtree(tempDir) job.openTempDirs = []
java
public IfcPermitTypeEnum createIfcPermitTypeEnumFromString(EDataType eDataType, String initialValue) { IfcPermitTypeEnum result = IfcPermitTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.get...
java
public Packer fillx(final double wtx) { gc.fill = GridBagConstraints.HORIZONTAL; gc.weightx = wtx; setConstraints(comp, gc); return this; }
java
public final void mSOURCE() throws RecognitionException { try { int _type = SOURCE; int _channel = DEFAULT_TOKEN_CHANNEL; // C:\\Project\\Obdalib\\obdalib-parent\\obdalib-core\\src\\main\\java\\it\\unibz\\inf\\obda\\gui\\swing\\utils\\MappingFilter.g:120:7: ( ( 'S' | 's' ) ( ...
java
public static Timestamp now() { java.sql.Timestamp date = new java.sql.Timestamp(System.currentTimeMillis()); return of(date); }
java
private static Throwable getLastArgumentIfThrowable(Object... arguments) { if (ArrayUtil.isNotEmpty(arguments) && arguments[arguments.length - 1] instanceof Throwable) { return (Throwable) arguments[arguments.length - 1]; } else { return null; } }
python
def do_search(self, string): """Search Ndrive for filenames containing the given string.""" results = self.n.doSearch(string, full_path = self.current_path) if results: for r in results: self.stdout.write("%s\n" % r['path'])
java
public final void errorf(String message, Object... args) { logf(Level.ERROR, null, message, args); }
python
def in_(self, haystack): """Perform replacement in given string. :param haystack: String to perform replacements in :return: ``haystack`` after the replacements :raise TypeError: If ``haystack`` if not a string :raise ReplacementError: If no replacement(s) have been provided y...
java
public static <T> List<T> even( Iterable<T> objects ) { return split( objects, true ); }
java
public long getPersistentTimestamp() throws ChronosException { byte[] persistentTimesampBytes = null; for (int i = 0; i <= connectRetryTimes; ++i) { try { persistentTimesampBytes = ZooKeeperUtil.getDataAndWatch(this, persistentTimestampZnode); break; } catch (KeeperException e) { ...
java
public static void main(String[] args) { FixedPrioritiesPriorityQueue<String> pq = new FixedPrioritiesPriorityQueue<String>(); System.out.println(pq); pq.add("one",1); System.out.println(pq); pq.add("three",3); System.out.println(pq); pq.add("one",1.1); System.out.println(pq); ...
java
@Override public boolean hasProtocol(final Protocol p) throws IOException { if (p == null) { return false; } try { final Packet packet = getPacket(p); return packet != null; } catch (final Exception e) { return false; } }
java
public static void appendHexString(StringBuilder buffer, byte[] bytes) { assertNotNull(buffer); if (bytes == null) { return; // do nothing (a noop) } appendHexString(buffer, bytes, 0, bytes.length); }
python
def generate_report(book_url): """ Generates the report HTML. """ with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book: accounts = [acc.fullname for acc in book.accounts] return f"""<html> <body> Hello world from python !<br> Book : ...
python
def _add_observation_to_means(self, xj, yj): """Update the means without recalculating for the addition of one observation.""" self._mean_x_in_window = ((self.window_size * self._mean_x_in_window + xj) / (self.window_size + 1.0)) self._mean_y_in_window = ((self....
python
def stripQuotes(value): """Strip single or double quotes off string; remove embedded quote pairs""" if value[:1] == '"': value = value[1:] if value[-1:] == '"': value = value[:-1] # replace "" with " value = re.sub(_re_doubleq2, '"', value) elif value[:1] == "'"...
java
XAResource reconnectRM() throws XAException { if (tc.isEntryEnabled()) Tr.entry(tc, "reconnectRM"); XAResource resource = null; XARecoveryWrapper wrapper = null; if (_recoveryData != null) { wrapper = _recoveryData.getXARecoveryWrapper(); } ...
java
public static CharPredicate range(final char a, final char b) { return new CharPredicate() { @Override public boolean isChar(char c) { return c >= a && c <= b; } @Override public String toString() { return "[" + a + '-' + b + "]"; } }; }
python
def apply_scale(self, scale): """ Apply a transformation matrix to the current path in- place Parameters ----------- scale : float or (3,) float Scale to be applied to mesh """ dimension = self.vertices.shape[1] matrix = np.eye(dimension + 1) ...
python
def clear_imgs(self) -> None: "Clear the widget's images preview pane." self._preview_header.value = self._heading self._img_pane.children = tuple()
python
def get_config_file(program, system_wide=False): '''Get the configuration file for a program. Gets the configuration file for a given program, assuming it stores it in a standard location. See also :func:`get_config_dir()`. Args: program (str): The program for which to get the configuration file. system_wi...
java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId == null) { return null; } URL url = new URL(systemId); String file = url.getFile(); if ( (file != null) && (file.indexOf('/') > -1)) { file = file.substrin...
python
def _print_pgfplot_libs_message(data): """Prints message to screen indicating the use of PGFPlots and its libraries.""" pgfplotslibs = ",".join(list(data["pgfplots libs"])) tikzlibs = ",".join(list(data["tikz libs"])) print(70 * "=") print("Please add the following lines to your LaTeX preamble:...
python
def encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: """ Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data. ...
java
public boolean isDescriptionComplete( KltFeature feature ) { for( int i = 0; i < lengthFeature; i++ ) { if( Float.isNaN(feature.desc.data[i]) ) return false; } return true; }
java
public static String getFilenameExtension(String name) { if(name == null) { return null; } int index = name.lastIndexOf('.'); return index < 0 ? null : name.substring(index + 1).toLowerCase(); }
java
public void init() throws Exception { // configure the SSLContext with a TrustManager SSLContext ctx = SSLContext.getInstance("TLS"); if (ignoreCertificates) { ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx);...
java
public DescribeLoadBalancerPolicyTypesResult withPolicyTypeDescriptions(PolicyTypeDescription... policyTypeDescriptions) { if (this.policyTypeDescriptions == null) { setPolicyTypeDescriptions(new com.amazonaws.internal.SdkInternalList<PolicyTypeDescription>(policyTypeDescriptions.length)); }...
java
private static ClassNode getParameterizedSuperClass(ClassNode classNode) { if (ClassHelper.OBJECT_TYPE.equals(classNode)) return null; ClassNode superClass = classNode.getUnresolvedSuperClass(); if (superClass==null) { return ClassHelper.OBJECT_TYPE; } if (!classNode....
java
public static Type toType(Class<?> clazz) { Type t = SQL_MAP_ABLE_TYPES.get(clazz); if (t == null) return Type.OTHER; else return t; }
java
public static Srp withDeviceDescription(final int descriptionType, final int... additionalDescriptionTypes) { final ByteBuffer buffer = ByteBuffer.allocate(additionalDescriptionTypes.length + 1); for (final int dt : additionalDescriptionTypes) buffer.put((byte) dt); buffer.put((byte) descriptionType); retur...
java
public static String createVMJson( String hostIpPort, String id, String template, String title, String summary, String userData, String user, String password, Map<String,String> config, boolean waitForActive ) throws TargetException { // Count VM creations (+ make title unique, it is u...
java
public com.google.api.ads.adwords.axis.v201809.cm.Money getTargetCpa() { return targetCpa; }
java
@Override public PluginDefinition fetch(String id) { List<String> tmpl = broker.callRPCList("RGCWFPAR GETTMPL", null, id); PluginDefinition def = new PluginDefinition(); def.setId(id); String entity = null; for (String s : tmpl) { String[] pcs = StrUtil.s...
java
public void insertAsParent( AstNode newParent ) { if (newParent == null) { return; } newParent.removeFromParent(); if (this.parent != null) { this.parent.replaceChild(this, newParent); } newParent.addLastChild(this); }
java
private void loadTemplates() throws CDKException { try (InputStream gin = getClass().getResourceAsStream(TEMPLATE_PATH); InputStream in = new GZIPInputStream(gin); IteratingSDFReader sdfr = new IteratingSDFReader(in, builder)) { while (sdfr.hasNext()) { fina...
python
def highlight_null(self, null_color='red'): """ Shade the background ``null_color`` for missing values. Parameters ---------- null_color : str Returns ------- self : Styler """ self.applymap(self._highlight_null, null_color=null_color) ...
java
@Override public Response recipients(Iterable<String> usernames) { this.usernames.addAll(Sets.newHashSet(usernames)); return this; }
python
def set_table(genome, table, table_name, connection_string, metadata): """ alter the table to work between different dialects """ table = Table(table_name, genome._metadata, autoload=True, autoload_with=genome.bind, extend_existing=True) #print "\t".join([c.name for c in tab...
java
private List<E> getFilteredList(Class<E> enumeration, E... excludedValues) { List<E> filteredValues = new ArrayList<>(); Collections.addAll(filteredValues, enumeration.getEnumConstants()); if (excludedValues != null) { for (E element : excludedValues) { filteredValues...
python
def is_connected(self, use_cached=True): """Return True if the device is currrently connect and False if not""" device_json = self.get_device_json(use_cached) return int(device_json.get("dpConnectionStatus")) > 0
python
def _create_sending_stream(self, pub_addr): """ Create a `ZMQStream` for sending responses back to Mongrel2. """ sock = self._zmq_context.socket(zmq.PUB) sock.setsockopt(zmq.IDENTITY, self.sender_id) sock.connect(pub_addr) stream = ZMQStream(sock, io_loop=self.io_...
python
def refresh(self): """ Refresh session on 401. This is called automatically if your existing session times out and resends the operation/s which returned the error. :raises SMCConnectionError: Problem re-authenticating using existing api credentials """ ...
java
public void init(Email annotation, PropertyMetadata propertyMetadata) { m_propertyMetadata = propertyMetadata; m_pattern = java.util.regex.Pattern.compile("^" + ATOM + "+(\\." + ATOM + "+)*@" + DOMAIN + "|" + IP_DOMAIN + ")$", j...
python
def check_ensembl_api_version(self): """ check the ensembl api version matches a currently working version This function is included so when the api version changes, we notice the change, and we can manually check the responses for the new version. """ self.atte...
python
def U(self): "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)" if getattr(self.data, 'tzinfo', None): return int(calendar.timegm(self.data.utctimetuple())) else: return int(time.mktime(self.data.timetuple()))
java
public URI build() { try { return new URI((isView ? VIEW_SCHEME : DATASET_SCHEME) + ":" + pattern.construct(options).toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not build URI", e); } }
python
def complete_abstract_value( self, return_type: GraphQLAbstractType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: """Complete an abstract value. Complete a value of an abstract ty...
python
def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]: """ Private method which return the cartesian product of the states of the genes in the model. It represents all the possible state for a given model. Examples -------- The model cont...
python
def _kshape(x, k): """ >>> from numpy.random import seed; seed(0) >>> _kshape(np.array([[1,2,3,4], [0,1,2,3], [-1,1,-1,1], [1,2,2,3]]), 2) (array([0, 0, 1, 0]), array([[-1.2244258 , -0.35015476, 0.52411628, 1.05046429], [-0.8660254 , 0.8660254 , -0.8660254 , 0.8660254 ]])) """ m =...
python
def _indent(self, textstr, indent_level=4): """ Indent a string. Textwrap's indent method only exists for 3.3 or above. In 2.7 we have to fake it. Parameters ---------- textstring : str String to be indented. indent_level : str N...
python
def register_arguments(func, args=None): """add given arguments to local args is a list that may contains nested lists (i.e. def func(a, (b, c, d)): ...) """ if args is None: args = func.args.args if func.args.vararg: func.set_local(func.args.vararg, func.args) i...
java
protected Options getOptions() throws MojoExecutionException { File persistence = ensurePersistenceXml(); Options opts = new Options(); if (toolProperties != null) { opts.putAll(toolProperties); } opts.put(OPTION_PROPERTIES_FILE, persistence.getAbsolutePath()); ...
java
public static String validateRevisionHistory(final Document doc, final String[] dateFormats) { final List<String> invalidRevNumbers = new ArrayList<String>(); // Find each <revnumber> element and make sure it matches the publican regex final NodeList revisions = doc.getElementsByTagName("revisi...
java
@SuppressWarnings("unchecked") public T queue(final String name, Function... funcs) { for (final Function f : funcs) { for (Element e : elements()) { queue(e, name, f); } } return (T) this; }
python
def start(self): """ Starts this QEMU VM. """ with (yield from self._execute_lock): if self.is_running(): # resume the VM if it is paused yield from self.resume() return if self._manager.config.get_section_config("...
python
def calculateLocalElasticity(self, bp, frames=None, helical=False, unit='kT'): r"""Calculate local elastic matrix or stiffness matrix for local DNA segment .. note:: Here local DNA segment referred to less than 5 base-pair long. In case of :ref:`base-step-image`: Shift (:math:`Dx`), Slide (:ma...
python
def umount(self, source): """ Unmount partion :param source: Full partition path like /dev/sda1 """ args = { 'source': source, } self._umount_chk.check(args) response = self._client.raw('disk.umount', args) result = response.get() ...
java
public int compareTo(Object o) { if (!(o instanceof UrlMapping)) { throw new IllegalArgumentException("Cannot compare with Object [" + o + "]. It is not an instance of UrlMapping!"); } if (equals(o)) return 0; UrlMapping other = (UrlMapping) o; // this wild card co...
java
public EventCategoriesMap withEvents(EventInfoMap... events) { if (this.events == null) { setEvents(new com.amazonaws.internal.SdkInternalList<EventInfoMap>(events.length)); } for (EventInfoMap ele : events) { this.events.add(ele); } return this; }
java
@SuppressWarnings("PointlessArithmeticExpression") @Override protected void onStartLine(byte[] line, int limit) throws ParseException { switchPool(server.poolReadWrite); HttpMethod method = getHttpMethod(line); if (method == null) { throw new UnknownFormatException(HttpServerConnection.class, "Unknown ...
java
public OvhOrder email_exchange_organizationName_service_exchangeService_accountUpgrade_duration_GET(String organizationName, String exchangeService, String duration, OvhAccountQuotaEnum newQuota, String primaryEmailAddress) throws IOException { String qPath = "/order/email/exchange/{organizationName}/service/{exchang...
java
public Link andAffordances(List<Affordance> affordances) { List<Affordance> newAffordances = new ArrayList<>(); newAffordances.addAll(this.affordances); newAffordances.addAll(affordances); return withAffordances(newAffordances); }
java
@Override public String getString(int index) { synchronized (lock) { final Object obj = getMValue(internalArray, index).asNative(internalArray); return obj instanceof String ? (String) obj : null; } }
java
public Observable<ServiceEndpointPolicyDefinitionInner> getAsync(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName) { return getWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName).map(new Func1<ServiceRe...
python
def state_check_collisions( state_engine, nameop, history_id_key, block_id, checked_ops, collision_checker ): """ See that there are no state-creating or state-preordering collisions at this block, for this history ID. Return True if collided; False if not """ # verify no collisions against already...
java
protected boolean reclaim () { if (_source != null && _source.isStopped()) { _source.setBuffer(null); _buffer.sourceUnbound(); _source = null; return true; } return false; }
python
def isClientCert(self, name): ''' Checks if a user client certificate (PKCS12) exists. Args: name (str): The name of the user keypair. Examples: Check if the client certificate "myuser" exists: exists = cdir.isClientCert('myuser') Retur...
python
def _pop_translated_data(self): """ Separate data of translated fields from other data. """ translated_data = {} for meta in self.Meta.model._parler_meta: translations = self.validated_data.pop(meta.rel_name, {}) if translations: translated...
java
private static Drawable getRippleMask(int color, int radius) { float[] outerRadius = new float[8]; Arrays.fill(outerRadius, radius); RoundRectShape r = new RoundRectShape(outerRadius, null, null); ShapeDrawable shapeDrawable = new ShapeDrawable(r); shapeDrawable.getPaint().setCol...
java
public static ns_doc_image[] get_filtered(nitro_service service, String filter) throws Exception { ns_doc_image obj = new ns_doc_image(); options option = new options(); option.set_filter(filter); ns_doc_image[] response = (ns_doc_image[]) obj.getfiltered(service, option); return response; }
python
def ndef(ctx, slot, prefix): """ Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if not dev.config.nfc_supported: ctx.fail('NFC interface not available.') if not co...
java
public void blur() { String cantFocus = "Unable to focus on "; String action = "Focusing, then unfocusing (blurring) on " + prettyOutput(); String expected = prettyOutputStart() + " is present, displayed, and enabled to be blurred"; try { if (isNotPresentDisplayedEnabledInput...
python
def delete_files_in_folder(fldr): """ delete all files in folder 'fldr' """ fl = glob.glob(fldr + os.sep + '*.*') for f in fl: delete_file(f, True)
java
public static ServerLock createServerLock(BootstrapConfig bootProps) { String serverName = bootProps.getProcessName(); File serverDir = bootProps.getConfigFile(null); File serverOutputDir = bootProps.getOutputFile(null); File serverWorkArea = bootProps.getWorkareaFile(null); Ser...
python
def get_formatted(self, key): """Return formatted value for context[key]. If context[key] is a type string, will just format and return the string. If context[key] is a special literal type, like a py string or sic string, will run the formatting implemented by the custom tag ...
python
def query_one(cls, *args, **kwargs): """ Same as collection.find_one, but return Document then dict """ doc = cls._coll.find_one(*args, **kwargs) if doc: return cls.from_storage(doc)
python
def _draw_button(self, overlay, text, location): """Draws a button on the won and lost overlays, and return its hitbox.""" label = self.button_font.render(text, True, (119, 110, 101)) w, h = label.get_size() # Let the callback calculate the location based on # the width and heigh...
python
def _hasher_first_run(self, preimage): ''' Invoke the backend on-demand, and check an expected hash result, then replace this first run with the new hasher method. This is a bit of a hacky way to minimize overhead on hash calls after this first one. ''' new_hasher = self....
java
public void setupKeys() { KeyAreaInfo keyArea = null; keyArea = new KeyAreaInfo(this, Constants.UNIQUE, ID_KEY); keyArea.addKeyField(ID, Constants.ASCENDING); keyArea = new KeyAreaInfo(this, Constants.SECONDARY_KEY, CODE_KEY); keyArea.addKeyField(CODE, Constants.ASCENDING); ...
python
def is_fp_arg(self, arg): """ This should take a SimFunctionArgument instance and return whether or not that argument is a floating-point argument. Returns True for MUST be a floating point arg, False for MUST NOT be a floating point arg, None for when it...
java
private SearchRequest createRequest(final SearchFilter filter) { final SearchRequest request = new SearchRequest(); request.setBaseDn(this.baseDN); request.setSearchFilter(filter); /** LDAP attributes to fetch from search results. */ if (getResultAttributeMapping() != null && !g...
java
public Observable<PacketCaptureResultInner> beginCreateAsync(String resourceGroupName, String networkWatcherName, String packetCaptureName, PacketCaptureInner parameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).map(new Func1<ServiceRespo...
python
def register_logger(self, logger): """ Register a new logger. """ handler = CommandHandler(self) handler.setFormatter(CommandFormatter()) logger.handlers = [handler] logger.propagate = False output = self.output level = logging.WARNING if ...
python
def _compute_frequencies(self, word_sent): """ Compute the frequency of each of word. Input: word_sent, a list of sentences already tokenized. Output: freq, a dictionary where freq[w] is the frequency of w. """ freq = defaultdict(int) for s in word_sent: for word...
python
def track_retrack(image_list, initial_points, max_retrack_distance=0.5, keep_bad=False): """Track-retracks points in image list Using track-retrack can help in only getting point tracks of high quality. The point is tracked forward, and then backwards in the image sequence. Points that end...
java
@Deprecated public void weakAddWatcher(File file, Watcher watcher) { weakAddWatcher(file.toPath(), watcher); }
python
def is_legal_subject(self, c: OntologyClass) -> bool: """ is_legal_subject(c) = true if - c in included_domains(self) or - super_classes_closure(c) intersection included_domains(self) is not empty There is no need to check the included_domains(super_properties_closure(self)) bec...
python
def main(args=sys.argv[1:]): """Extract text from a file. Commands: extract - extract text from path check - make sure all deps are installed Usage: fulltext extract [-v] [-f] <path>... fulltext check [-t] Options: -f, --file Open file first. ...
java
public static SkippableIterator flatand(SkippableIterator... bitmap) { if (bitmap.length == 0) throw new RuntimeException("nothing to process"); SkippableIterator answer = bitmap[0]; for (int k = 1; k < bitmap.length; ++k) { answer = and2by2(answer, bitmap[k]); } return answer; }
java
private static DescriptorProtoPOJO getDescritorProtoPOJO(FileDescriptorProtoPOJO fileDescriptorProto, MessageElement typeElement, Set<String> messageSet, Set<String> enumSet) { DescriptorProtoPOJO ret = new DescriptorProtoPOJO(); ret.name = typeElement.name(); ret.fields = new ...
python
def ffill(self, dim, limit=None): '''Fill NaN values by propogating values forward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None ...
python
def autocorrelation( data, name, maxlags=100, format='png', reflected=False, suffix='-acf', path='./', fontmap=None, new=True, last=True, rows=1, columns=1, num=1, verbose=1): """ Generate bar plot of the autocorrelation function for a series (usually an MCMC trace). :Arguments: data: P...
java
public long getLong(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number) o).longValue() : (long) getDouble(key); }
java
public ParallelTaskBuilder setTargetHostsFromLineByLineText( String sourcePath, HostsSourceType sourceType) throws TargetHostsLoadException { this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath, sourceType); return this; }
java
public static double JensenShannonDivergence(double[] p, double[] q) { double[] m = new double[p.length]; for (int i = 0; i < m.length; i++) { m[i] = (p[i] + q[i]) / 2; } return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2; }