language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _is_excluded(filename, exclusions): """Return true if filename matches any of exclusions.""" for exclusion in exclusions: if fnmatch(filename, exclusion): return True return False
java
public static IndianCalendar of( int iyear, IndianMonth imonth, int idom ) { return IndianCalendar.of(iyear, imonth.getValue(), idom); }
java
private void search(final long pMapTileIndex) { for (final MapTileModuleProviderBase provider : mProviders) { try { if (provider instanceof MapTileDownloader) { final ITileSource tileSource = ((MapTileDownloader) provider).getTileSource(); if (...
java
private static String getPomText(ReleaseId releaseId, ReleaseId... dependencies) { String pom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schema...
python
def estimate_supercell_matrix(spglib_dataset, max_num_atoms=120): """Estimate supercell matrix from conventional cell Diagonal supercell matrix is estimated from basis vector lengths and maximum number of atoms to be accepted. Supercell is assumed to be made from the stand...
java
public <T> T getPrototypeBean(final Function<BeanAccessor, T> creator) { final PrototypeProvider provider = new PrototypeProvider(name, creator); return provider.getBean(this, dryRun); }
python
def blackbody_wn_rad2temp(wavenumber, radiance): """Derive brightness temperatures from radiance using the Planck function. Wavenumber space""" if np.isscalar(radiance): rad = np.array([radiance, ], dtype='float64') else: rad = np.array(radiance, dtype='float64') if np.isscalar(wav...
python
def luhn(base, num_only=False, allow_lower_case=False): """Return the Luhn check digit for the given string. Args: base(str): string for which to calculate the check digit num_only(bool): allow only digits in `base` (default: False) allow_lower_case(bool): allow lower case letters in `b...
python
def get_links(self, request=None): """ Return a dictionary containing all the links that should be included in the API schema. """ links = LinkNode() # Generate (path, method, view) given (path, method, callback). paths = [] view_endpoints = [] fo...
java
public static synchronized void destroyManagedConnectionPool(String poolName, Object mcp) { log.tracef("%s", new TraceEvent(poolName, Integer.toHexString(System.identityHashCode(mcp)), TraceEvent.MANAGED_CONNECTION_POOL_DESTROY, ...
java
public static WidgetLib init(GVRContext gvrContext, String customPropertiesAsset) throws InterruptedException, JSONException, NoSuchMethodException { if (mInstance == null) { // Constructor sets mInstance to ensure the initialization order new WidgetLib(gvrContext, customProp...
python
def _encode_dbref(name, value, check_keys, opts): """Encode bson.dbref.DBRef.""" buf = bytearray(b"\x03" + name + b"\x00\x00\x00\x00") begin = len(buf) - 4 buf += _name_value_to_bson(b"$ref\x00", value.collection, check_keys, opts) buf += _name_value_to_bson(b"$id\x00...
python
def from_out_edges(cls, vertices, edge_mapper): """ Create a DirectedGraph from a collection of vertices and a mapping giving the vertices that each vertex is connected to. """ vertices = set(vertices) edges = set() heads = {} tails = {} # Number...
java
@Override @Trivial public Enumeration<URL> getResources(String name) throws IOException { /* * The default implementation of getResources never calls getResources on its parent, instead it just calls findResources on all of the loaders parents. We know that our * parent will be a gatew...
java
@Override public Object invoke(final MethodInvocation invocation) throws Throwable { final Method method = invocation.getMethod(); final Transactional annotation = method.getAnnotation(Transactional.class); Object result; if (null == annotation) { result = invocation.proceed(); } else { ...
java
private CloseableHttpClient buildClient(boolean trustSelfSigned) { try { // if required, define custom SSL context allowing self-signed certs SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault() : SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); ...
java
static SettingsCommand get(Map<String, String[]> clArgs) { for (Command cmd : Command.values()) { if (cmd.category == null) continue; for (String name : cmd.names) { final String[] params = clArgs.remove(name); if (...
python
def finalize(self, **kwargs): """ Finalize the plot with ticks, labels, and title Parameters ---------- kwargs: dict generic keyword arguments. """ # NOTE: not deduping here, so this is total, not unique self.set_title( "PosTag plo...
python
def define_ppo_epoch(memory, hparams, action_space, batch_size): """PPO epoch.""" observation, reward, done, action, old_pdf, value = memory # This is to avoid propagating gradients through simulated environment. observation = tf.stop_gradient(observation) action = tf.stop_gradient(action) reward = tf.stop...
python
def restore_cmd(argv): """Try to restore a broken virtualenv by reinstalling the same python version on top of it""" if len(argv) < 1: sys.exit('You must provide a valid virtualenv to target') env = argv[0] path = workon_home / env py = path / env_bin_dir / ('python.exe' if windows else 'p...
python
def do_OP_RIGHT(vm): """ >>> s = [b'abcdef', b'\\3'] >>> do_OP_RIGHT(s, require_minimal=True) >>> print(s==[b'def']) True >>> s = [b'abcdef', b'\\0'] >>> do_OP_RIGHT(s, require_minimal=False) >>> print(s==[b'']) True """ pos = vm.pop_nonnegative() if pos > 0: vm.a...
java
public static Document parse(File file) throws IOException, SAXException, IllegalArgumentException { return parse(file, true); }
java
@Override public ThreadContext createDefaultThreadContext(Map<String, String> execProps) { return new SecurityContextImpl(false, null); }
java
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) { if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } Class<?> proxyClass = null; /* collect interfac...
java
public static <T extends Number> WindowOver<T> stddevSamp(Expression<T> expr) { return new WindowOver<T>(expr.getType(), SQLOps.STDDEVSAMP, expr); }
java
public List<FileInfo> listAllFileInfoForPrefix(URI prefix) throws IOException { logger.atFine().log("listAllFileInfoForPrefixPage(%s)", prefix); StorageResourceId prefixId = getPrefixId(prefix); List<GoogleCloudStorageItemInfo> itemInfos = gcs.listObjectInfo( prefixId.getBucketName(), pr...
java
@Order @Bean ArmeriaServerConfigurator corsConfigurator( @Value("${zipkin.query.allowed-origins:*}") String allowedOrigins) { CorsServiceBuilder corsBuilder = CorsServiceBuilder.forOrigins(allowedOrigins.split(",")) // NOTE: The property says query, and the UI does not use POST, but we allow POST? /...
java
protected Response buildPost(final WebApplicationService service, final Map<String, String> parameters) { return DefaultResponse.getPostResponse(service.getOriginalUrl(), parameters); }
java
public <T> List<List<T>> queryTypedResults(String sql, String[] args) { return db.queryTypedResults(sql, args); }
java
@Override public <U> CollectionX<U> unitIterable(final Iterable<U> u) { return ListX.fromIterable(u); }
java
public static DataResource fromName(String name) { String[] parts = StringUtils.split(name, '/'); if (!parts[0].equals(ROOT_NAME) || parts.length > 3) throw new IllegalArgumentException(String.format("%s is not a valid data resource name", name)); if (parts.length == 1) ...
python
def train( self, X_train, Y_train, n_epochs=25, lr=0.01, batch_size=256, shuffle=True, X_dev=None, Y_dev=None, print_freq=5, dev_ckpt=True, dev_ckpt_delay=0.75, b=0.5, pos_label=1, seed=1234, ...
java
private void actionProduced() { for (final ProducerListener listener : listeners) { listener.notifyProduced(currentObject); } for (final ProducibleListener listener : current.getFeature(Producible.class).getListeners()) { listener.notifyProduct...
java
private List<Bucket> lookup(Record record) { List<Bucket> buckets = new ArrayList(); for (Property p : config.getLookupProperties()) { String propname = p.getName(); Collection<String> values = record.getValues(propname); if (values == null) continue; for (String value : values)...
java
protected void _generate(SarlSkill skill, IExtraLanguageGeneratorContext context) { final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(skill); final PyAppendable appendable = createAppendable(jvmType, context); List<JvmTypeReference> superTypes = getSuperTypes(skill.getExtends(), skill.get...
java
public void marshall(LoggingOptionsPayload loggingOptionsPayload, ProtocolMarshaller protocolMarshaller) { if (loggingOptionsPayload == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(loggingOptionsPa...
python
def describe(self): """ describes a Symbol, returns a string """ lines = [] lines.append("Symbol = {}".format(self.name)) if len(self.tags): tgs = ", ".join(x.tag for x in self.tags) lines.append(" tagged = {}".format(tgs)) if len(self.aliases): ...
java
public static String getText(final Node root) { if (root == null) { return ""; } else { final StringBuilder result = new StringBuilder(1024); if (root.hasChildNodes()) { final NodeList list = root.getChildNodes(); for (int i = 0; i < li...
java
public PathImpl lookupImpl(String userPath, Map<String,Object> newAttributes, boolean isAllowRoot) { if (userPath == null) { return lookupImpl(getPath(), newAttributes, isAllowRoot); } if (! isAllowRoot) { return schemeWalk(userPath, newAttrib...
java
protected void addOccupantInfo (BodyObject body, OccupantInfo info) { // clone the canonical copy and insert it into the DSet _plobj.addToOccupantInfo(info); // add the body oid to our place object's occupant list _plobj.addToOccupants(body.getOid()); }
java
public Set<T> outEdges(int vertex) { // REMINDER: this is probably best wrapped with yet another // decorator class to avoid the O(n) penality of iteration over all // the edges Set<T> edges = getAdjacencyList(vertex); if (edges.isEmpty()) return Collections.<T>emptyS...
python
def get_ref_favorites(self, project, repository_id=None, identity_id=None): """GetRefFavorites. [Preview API] Gets the refs favorites for a repo and an identity. :param str project: Project ID or project name :param str repository_id: The id of the repository. :param str identity...
python
def html_table_from_query(rows: Iterable[Iterable[Optional[str]]], descriptions: Iterable[Optional[str]]) -> str: """ Converts rows from an SQL query result to an HTML table. Suitable for processing output from the defunct function ``rnc_db.fetchall_with_fieldnames(sql)``. ...
java
private static Map<State, StateStrategy> createStrategyMap() { final Map<State, StateStrategy> map = new EnumMap<>(State.class); map.put(State.CLOSED, new StateStrategyClosed()); map.put(State.OPEN, new StateStrategyOpen()); return map; }
python
def preferred_format(incomplete_format, preferred_formats): """Return the preferred format for the given extension""" incomplete_format = long_form_one_format(incomplete_format) if 'format_name' in incomplete_format: return incomplete_format for fmt in long_form_multiple_formats(preferred_forma...
python
def get_string_offset(edge): """return the offset (int) of a string""" onset_label = edge.find('labels[@name="SEND"]') onset_str = onset_label.xpath('@valueString')[0] return int(onset_str)
java
public void setSecurityPolicy(com.google.api.ads.admanager.axis.v201805.SecurityPolicySettings securityPolicy) { this.securityPolicy = securityPolicy; }
java
private void _RemoveValidator( Row item, int column ) { // already clean ? if( m_currentEditedItem == null && m_currentEditedColumn < 0 ) return; // touch the table if( m_callback != null ) m_callback.onTouchCellContent( item, column ); if( m_currentEditor != null ) m_currentEditor.removeFromParen...
java
@Nullable public static String getFromFirstExcl (@Nullable final String sStr, @Nullable final String sSearch) { return _getFromFirst (sStr, sSearch, false); }
java
public static boolean isEmpty(File file) { if (null == file) { return true; } if (file.isDirectory()) { String[] subFiles = file.list(); if (ArrayUtil.isEmpty(subFiles)) { return true; } } else if (file.isFile()) { return file.length() <= 0; } return false; }
python
def conditional_probability_alive_matrix(self, max_frequency=None, max_recency=None): """ Compute the probability alive matrix. Parameters ---------- max_frequency: float, optional the maximum frequency to plot. Default is max observed frequency. max_recency:...
python
def on_IOError(self, e): """ Handle an IOError exception. """ sys.stderr.write("Error: %s: \"%s\"\n" % (e.strerror, e.filename))
java
public void addSummaryLinkComment(AbstractMemberWriter mw, ProgramElementDoc member, Tag[] firstSentenceTags, Content tdSummary) { addIndexComment(member, firstSentenceTags, tdSummary); }
java
public RestRequestInformation asRestRequestInformation() { try { return new RestRequestInformationImpl( api, new URL(endpoint.getFullUrl(urlParameters)), queryParameters, headers, body); } catch (MalformedURLException e) { throw new AssertionError(e); ...
python
def wherein(self, fieldname, collection, negate=False): """ .wherein(fieldname, collection, negate=False) Returns a new DataTable with rows only where the value at `fieldname` is contained within `collection`. """ if negate: return self.mask([elem not in coll...
python
def _interpolate(self, kind='linear'): """Apply scipy.interpolate.interp1d along resampling dimension.""" # drop any existing non-dimension coordinates along the resampling # dimension dummy = self._obj.copy() for k, v in self._obj.coords.items(): if k != self._dim an...
python
def run(command, options, args): """Run the requested command. args is either a list of descriptions or a list of strings to filter by""" if command == "backend": subprocess.call(("sqlite3", db_path)) if command == "add": dp = pdt.Calendar() due = mktime(dp.parse(options.due)[0]) i...
java
private void assignInstancesToContainers(PackingPlanBuilder planBuilder, Map<String, Integer> parallelismMap, PolicyType policyType) throws ConstraintViolationException { for (String componentName : parallelismMap.keySet()) ...
python
def load_x509_cert(url, httpc, spec2key, **get_args): """ Get and transform a X509 cert into a key. :param url: Where the X509 cert can be found :param httpc: HTTP client to use for fetching :param spec2key: A dictionary over keys already seen :param get_args: Extra key word arguments to the HT...
java
public String mailbox(ImapRequestLineReader request) throws ProtocolException { String mailbox = astring(request); if (mailbox.equalsIgnoreCase(ImapConstants.INBOX_NAME)) { return ImapConstants.INBOX_NAME; } else { return BASE64MailboxDecoder.decode(mailbox); } ...
python
def Append(self, item): """Add an item to the list. Args: item (object): item. """ if self._index >= self._size: self._index = self._index % self._size try: self._list[self._index] = item except IndexError: self._list.append(item) self._index += 1
java
public com.google.api.ads.admanager.axis.v201808.ProgressStep[] getSteps() { return steps; }
python
def set_window_geometry(geometry): """Set window geometry. Parameters ========== geometry : tuple (4 integers) or None x, y, dx, dy values employed to set the Qt backend geometry. """ if geometry is not None: x_geom, y_geom, dx_geom, dy_geom = geometry mngr = plt.get_c...
java
public ActivityImpl parseSubProcess(Element subProcessElement, ScopeImpl scope) { ActivityImpl subProcessActivity = createActivityOnScope(subProcessElement, scope); subProcessActivity.setSubProcessScope(true); parseAsynchronousContinuationForActivity(subProcessElement, subProcessActivity); Boolean isT...
python
def _set_pim(self, v, load=False): """ Setter method for pim, mapped from YANG variable /rbridge_id/router/hide_pim_holder/pim (container) If this variable is read-only (config: false) in the source YANG file, then _set_pim is considered as a private method. Backends looking to populate this variabl...
java
public void setMaxNumberOfThreadsPerTask(Integer maxNumberOfThreadsPerTask) { if(maxNumberOfThreadsPerTask<0) { throw new IllegalArgumentException("The max number of threads can not be negative."); } else if(maxNumberOfThreadsPerTask==0) { this.maxNumberOfThreadsPerTask =...
python
def block_signals(self): """Prevent the combos and dock listening for event changes.""" self.disconnect_layer_listener() self.aggregation_layer_combo.blockSignals(True) self.exposure_layer_combo.blockSignals(True) self.hazard_layer_combo.blockSignals(True)
java
public R fetchQuery(String properties) { ((TQRootBean) _root).query().fetchQuery(_name, properties); return _root; }
python
def render_and_write(template_dir, path, context): """Renders the specified template into the file. :param template_dir: the directory to load the template from :param path: the path to write the templated contents to :param context: the parameters to pass to the rendering engine """ env = Envi...
python
def _set_add_options(cls, checked_codes, options): """Set `checked_codes` by the `add_ignore` or `add_select` options.""" checked_codes |= cls._expand_error_codes(options.add_select) checked_codes -= cls._expand_error_codes(options.add_ignore)
python
def longest_lines(shape): """ Creates lines from shape :param shape: :return: list of dictionaries with col,row,len fields """ lines = [] for level in set(shape): count = 0 for i in range(len(shape)): if shape[i] <= level: count += 1 el...
java
public Collection<Tag> getListUser(String userId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_LIST_USER); parameters.put("user_id", userId); Response response = transportAPI.get(transportAPI.getPath(), pa...
java
public Set<HttpMethod> allAllowedMethods() { if (anyMethodRouter.size() > 0) { Set<HttpMethod> ret = new HashSet<HttpMethod>(9); ret.add(HttpMethod.CONNECT); ret.add(HttpMethod.DELETE); ret.add(HttpMethod.GET); ret.add(HttpMethod.HEAD); ret.add(HttpMethod.OPTIONS); ret.add(HttpMethod.PATCH); r...
java
static void splitHeaders(ClassList classes) { Set<String> ctVersions = new HashSet<>(); for (ClassDescription cd : classes) { for (ClassHeaderDescription header : cd.header) { for (char c : header.versions.toCharArray()) { ctVersions.add("" + c); ...
python
def frange(x, y, jump=1): """ range for floats """ precision = get_sig_digits(jump) while x < y: yield round(x, precision) x += jump
java
public void jump(int index) { if (index >= byteBuffer.capacity()) { throw new IllegalArgumentException("cannot jump past " + "end of input"); } byteBuffer.position(index); byteBuffer.limit(byteBuffer.capacity()); }
java
private void serverHello(ServerHello mesg) throws IOException { serverKeyExchangeReceived = false; if (debug != null && Debug.isOn("handshake")) { mesg.print(System.out); } // check if the server selected protocol version is OK for us ProtocolVersion mesgVersion = me...
java
@Override public Request<DescribePlacementGroupsRequest> getDryRunRequest() { Request<DescribePlacementGroupsRequest> request = new DescribePlacementGroupsRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def set_world(self, grd, start_y_x, y_x): """ tell the agent to move to location y,x Why is there another grd object in the agent? Because this is NOT the main grid, rather a copy for the agent to overwrite with planning routes, etc. The real grid is initialised in Worl...
java
public Class parseClass(File file) throws CompilationFailedException, IOException { return parseClass(new GroovyCodeSource(file, config.getSourceEncoding())); }
python
def compress(self): """Main function of compression.""" for ast_token in self.ast_tokens: if type(ast_token) in self.dispatcher: # pylint: disable=unidiomatic-typecheck self.dispatcher[type(ast_token)](ast_token) else: self.dispatcher['default'](a...
python
def find_source_files_from_list(self, file_names): """ Finds all source files that actually exists from a list of file names. :param list[str] file_names: The list of file names. """ for file_name in file_names: if os.path.exists(file_name): routine_n...
python
def call_fn_name(token): """Customize CALL_FUNCTION to add the number of positional arguments""" if token.attr is not None: return '%s_%i' % (token.kind, token.attr) else: return '%s_0' % (token.kind)
python
def complete(self, table_name, key): """ Log a completed job. When a job is completed, its reservation entry is deleted. :param table_name: `database`.`table_name` :param key: the dict of the job's primary key """ job_key = dict(table_name=table_name, key_hash=key_hash(k...
java
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if(getOrientation() == HORIZONTAL) { int N = getChildCount(); for (int i = 0; i < N; i++) { View child = getChildAt(i); int ...
python
def set_auto_discard_for_device(self, name, controller_port, device, discard): """Sets a flag in the device information which indicates that the medium supports discarding unused blocks (called trimming for SATA or unmap for SCSI devices) .This may or may not be supported by a particular drive, ...
java
public INDArray loadSingleSentence(String sentence) { List<String> tokens = tokenizeSentence(sentence); if(format == Format.CNN1D || format == Format.RNN){ int[] featuresShape = new int[] {1, wordVectorSize, Math.min(maxSentenceLength, tokens.size())}; INDArray features = Nd4j.cr...
java
@Nonnull public Process exec() throws IOException { List<String> commandWords = toCommandWords(); ProcessBuilder builder = new ProcessBuilder(commandWords); // TODO: Use Redirect to send the I/O somewhere useful. QEmuCommandLineUtils.redirectIO(builder); return builder.start(...
python
def main(): """Main ShutIt function. Handles the configured actions: - skeleton - create skeleton module - list_configs - output computed configuration - depgraph - output digraph of module dependencies """ # Create base shutit object. shutit = shutit_global.shutit_global_object.shutit_objects[0] ...
python
def shared_otuids(groups): """ Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on group combination and their shared OTUIDs as values. """ for g in sorted(groups): ...
python
def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None): """Prepares section for PDF output. """ import pylatex as pl if case == 'sectionmain': if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage')) with doc.create(pl.Section(s...
python
def _validate_lattice_vectors(self, lattice_vectors): """Ensure that the lattice_vectors are reasonable inputs. """ dataType = np.float64 if lattice_vectors is None: lattice_vectors = np.identity(self.dimension, dtype=dataType) else: lattice_vectors =...
python
def parse_union_type_extension(lexer: Lexer) -> UnionTypeExtensionNode: """UnionTypeExtension""" start = lexer.token expect_keyword(lexer, "extend") expect_keyword(lexer, "union") name = parse_name(lexer) directives = parse_directives(lexer, True) types = parse_union_member_types(lexer) ...
python
def to_array(self): """ Serializes this GameMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(GameMessage, self).to_array() array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type...
python
def remove(self, child): '''Remove a ``child`` from the list of :attr:`children`.''' try: self.children.remove(child) if isinstance(child, String): child._parent = None except ValueError: pass
python
def get_vars(n): """ extract variables from expression node defined by tuple-pair: (_var_, [variable name]) """ op = n[0] if op.startswith('_') and op.endswith('_'): op = op.strip('_') if op == 'var': return [n[1]] return [] else: ret = [] ...
java
public static INDArray conv2d(INDArray input, INDArray kernel, Type type) { return Nd4j.getConvolution().conv2d(input, kernel, type); }
python
def fire_failed_msisdn_lookup(self, to_identity): """ Fires a webhook in the event of a None to_addr. """ payload = {"to_identity": to_identity} hooks = Hook.objects.filter(event="identity.no_address") for hook in hooks: hook.deliver_hook( None...
python
def _update_model(self, normalization_type='stats'): """ Updates the model (when more than one observation is available) and saves the parameters (if available). """ if self.num_acquisitions % self.model_update_interval == 0: # input that goes into the model (is unziped in c...
python
def scatter(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d scatter plot, and returns the resulting Plot object. The function supports SArrays of dtypes: int, float. Parameters -------...