language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void addPoint(float x, float y) { if (hasVertex(x,y) && (!allowDups)) { return; } ArrayList tempPoints = new ArrayList(); for(int i=0;i<points.length;i++) { tempPoints.add(new Float(points[i])); } tempPoints.add(new Float(x)); te...
java
protected final JSType getRestrictedWithoutNull(JSType type) { return type == null ? null : type.visit(restrictNullVisitor); }
java
public void config(Config config) throws ConfigException, HibernateException { log.trace("config(Config)"); // Hibernate configuration class is the session factory builder Configuration configuration = null; // Hibernate configuration resource is not null if config parameter is null - for zer...
python
def create_version(self, project_id_or_key, version_name, extra_request_params={}): """ client = BacklogClient("your_space_name", "your_api_key") client.create_version("YOUR_PROJECT", "VERSION_NAME", {"description": "version descriptio...
python
def upsert(self, document, cond): """ Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a lis...
java
public static Map<String,String> objectToMap(Object object,String... ignore){ Map<String,String> tempMap = new LinkedHashMap<String, String>(); for(Field f : getAllFields(object.getClass())){ if(!f.isAccessible()){ f.setAccessible(true); } boolean ig = false; if(ignore!=null&&ignore.length>0)...
python
def setup_pathing(self): """Format pathing for S3 deployments.""" self.s3_version_uri = self._path_formatter(self.version) self.s3_latest_uri = self._path_formatter("LATEST") self.s3_canary_uri = self._path_formatter("CANARY") self.s3_alpha_uri = self._path_formatter("ALPHA") ...
python
def remove_hooks(target, **hooks): """ Remove the given hooks from the given target. :param target: The object from which to remove hooks. If all hooks are removed from a given method, the HookedMethod object will be removed and replaced with the original function. ...
java
public static Condition startsWithUri(final String uri) { return new Condition(input -> input.getUri().startsWith(uri)); }
python
def k_nearest(self, vec, k): """Get the k nearest neighbors of a vector (in terms of highest inner products). :param (np.array) vec: query vector :param (int) k: number of top neighbors to return :return (list[tuple[str, float]]): a list of (word, score) pairs, in descending order ...
java
public static <T> Subscription includeWhen( Collection<T> collection, T element, ObservableValue<Boolean> condition) { return subscribe(condition, new Consumer<Boolean>() { private boolean included = false; @Override public void accept(Boo...
python
def matches(self, filter_props): """Check if the filter matches the supplied properties.""" if filter_props is None: return False found_one = False for key, value in filter_props.items(): if key in self.properties and value != self.properties[key]: ...
java
@Override public T call() throws Exception { String contextualMethods = threadContextDescriptor.getExecutionProperties().get(WSContextService.CONTEXTUAL_METHODS); boolean applyContext = contextualMethods == null || Arrays.asList(contextualMethods.split(",")).contains("call"); T result; ...
java
public static MavenCoord fromGAVPC(String coordGavpc) { Matcher mat = REGEX_GAVCP.matcher(coordGavpc); if (!mat.matches()) throw new IllegalArgumentException("Wrong Maven coordinates format, must be G:A:V[:P[:C]] . " + coordGavpc); return new MavenCoord() .setGroupId(mat...
python
def write(self, buf): """Write bytes to the stream.""" underflow = self._audio_stream.write(buf) if underflow: logging.warning('SoundDeviceStream write underflow (size: %d)', len(buf)) return len(buf)
python
def making_blockstr(varblock,count,colorline,element,zoomblock,filename,sidebarstring,colorkeyfields): # starting wrapper that comes before html table code ''' if not colorkeyfields == False: start = """\n\tfunction addDataToMap%s(data, map) {\t\tvar skillsSelect = document.getElementById("mapStyle");\n\t\tvar sel...
java
private void serializeAliasedDiscoveryConfig( JsonObject object, String tag, AliasedDiscoveryConfig config) { if (config != null) { object.add(tag, new AliasedDiscoveryConfigDTO(config).toJson()); } }
java
@Override public void start() throws Exception { try { reRegisterServices(); } catch ( KeeperException e ) { log.error("Could not register instances - will try again later", e); } client.getConnectionStateListenable().addListener(co...
java
@Override public String getAuthType() { String type = null; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "getAuthType: " + type); } return type; }
java
public static GatewayTimeout of(int errorCode, Throwable cause) { if (_localizedErrorMsg()) { return of(errorCode, cause, defaultMessage(GATEWAY_TIMEOUT)); } else { touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; } }
java
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Override public String getMessageToClient(@FormParam(Constants.Message.MFC) String json) { HttpSession httpSession = getHttpSession(); setContext(httpSession); MessageFromClient message = MessageFromClient.createFrom...
python
def bp_commands(self, frame, breakpoint_hits): """Call every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called, False otherwise.""" # Handle multiple breakpoints on the same line (issue 14789) effective_bp_lis...
java
private void init() { setLayout(new BorderLayout()); initToolBar(); contentPane = new JPanel(); contentPane.setLayout(new GridLayout(0, 1, 0, 0)); contentPane.setBackground(Color.WHITE); add(contentPane, BorderLayout.CENTER); }
java
private <L extends UriBaseListener> void analyzeInternal(final String input, L listener) { pathSegmentIndex = -1; walker.walk(listener, prepareUri(input).value0); }
java
public final Tuple7<T10, T11, T12, T13, T14, T15, T16> skip9() { return new Tuple7<>(v10, v11, v12, v13, v14, v15, v16); }
java
public long guessNextBCFRecordStart(long beg, long end) throws IOException { // Buffer what we need to go through. byte[] arr = new byte[ bgzf ? BGZF_MAX_BYTES_READ : UNCOMPRESSED_BYTES_NEEDED]; this.inFile.seek(beg); int totalRead = 0; for (int left = Math.min((int)(end - beg), arr.length); left > 0;...
java
@Override public CommerceNotificationAttachment create( long commerceNotificationAttachmentId) { CommerceNotificationAttachment commerceNotificationAttachment = new CommerceNotificationAttachmentImpl(); commerceNotificationAttachment.setNew(true); commerceNotificationAttachment.setPrimaryKey(commerceNotificat...
java
public static ProbeSender createMulticastProbeSender(String niName) throws TransportConfigException { Transport mcastTransport = new MulticastTransport(niName); ProbeSender gen = new ProbeSender(mcastTransport); return gen; }
java
public boolean isDefault() { return (valueAsString != null && valueAsString.equals(defaultValueAsString)) || (valueAsString == null && defaultValueAsString == null); }
java
private void commitEntries() { raft.checkThread(); // Sort the list of replicas, order by the last index that was replicated // to the replica. This will allow us to determine the median index // for all known replicated entries across all cluster members. List<RaftMemberContext> members = raft.get...
java
public static DefaultFileSet.Builder with(BaseFolder baseFolder, AnnotatedFile manifest, String manifestPath) { return new Builder(baseFolder, manifest, manifestPath); }
java
public static <T> Set<T> getRandomSubset(Set<T> set, int count) { Set<T> result = new HashSet<>(); HashList<T> opSet = new HashList<>(set); while (result.size() < count) { int next = rand.nextInt(opSet.size()); if (!result.contains(opSet.get(next))) { result.add(opSet.get(next)); } } ret...
python
def populate_local_cache(self): """Populate the local cache from DB. Read the entries from FW DB and Calls routines to populate the cache. """ fw_dict = self.get_all_fw_db() for fw_id in fw_dict: LOG.info("Populating cache for FW %s", fw_id) fw_data = fw_...
java
private List<Integer> getSplitPositions(String text) { ArrayList<Integer> splitPositions = new ArrayList<>(); int position; int currentPosition = 0; while (true) { int indexOfMaru = text.indexOf("。", currentPosition); int indexOfTen = text.indexOf("、", currentPos...
python
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is ...
java
@Deprecated public void addSslListener(InetSocketAddress addr, String keystore, String storPass, String keyPass) throws IOException { if (webServer.isStarted()) { throw new IOException("Failed to add ssl listener"); } SslSocketConnector sslListener = new SslSocketConnector(); sslListener.s...
java
@Override protected boolean validateSettings() throws IllegalArgumentException { // Validate values which do not require user input first to avoid unnecesary // work on the user part. // dates Date startDate = getStartDate(); Date stopDate = getStopDate(); if (startD...
python
def _reset(self): ''' _reset - reset this object. Assigned to .reset after __init__ call. ''' HTMLParser.reset(self) self.root = None self.doctype = None self._inTag = []
java
public <T> T doWithoutTransaction(final SpecificTxAction<T, C> action) { checkNotx(); return template.doInTransaction(new TxConfig(OTransaction.TXTYPE.NOTX), action); }
python
def patches(self, basemap, simplify=None, predicate=None, args_f=None, **kwargs): """ Return geodata as a list of Matplotlib patches :param basemap: A mpl_toolkits.basemap.Basemap :param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry. ...
java
public boolean pushAll(V firstValue, V... moreValues) { check(); context.getValueStack().pushAll(firstValue, moreValues); return true; }
java
public final void mLIKE() throws RecognitionException { try { int _type = LIKE; int _channel = DEFAULT_TOKEN_CHANNEL; // hql.g:42:6: ( 'like' ) // hql.g:42:8: 'like' { match("like"); if (state.failed) return; } state.type = _type; state.channel = _channel; } finally { // do for sur...
java
public static CmsResource convertRawResource(CmsObject cms, Object input) throws CmsException { CmsResource result; if (input instanceof CmsResource) { // input is already a resource result = (CmsResource)input; } else if (input instanceof String) { if (CmsUU...
python
def mk_getkw(kw, defaults,prefer_passed=False): ''' a helper for generating a function for reading keywords in interface functions with a dictionary with defaults expects the defaults dictionary to have keywords you request. example: defaults = dict(a='a',b=3); def bigfunc(**kw): g...
java
private static String encode(String pathElement) { try { return URLEncoder.encode(pathElement, Charsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw Throwables.propagate(e); // Should never happen } }
python
def get_speaker_info(self, refresh=False, timeout=None): """Get information about the Sonos speaker. Arguments: refresh(bool): Refresh the speaker info cache. timeout: How long to wait for the server to send data before giving up, as a float, or a ...
python
def get_aws_secrets_from_file(credentials_file): # type: (str) -> Set[str] """Extract AWS secrets from configuration files. Read an ini-style configuration file and return a set with all found AWS secret access keys. """ aws_credentials_file_path = os.path.expanduser(credentials_file) if not o...
java
@Override public void setParameters(Object[] params) throws CDKException { if (params.length != 1) { throw new CDKException("AromaticBondsCountDescriptor expects one parameter"); } if (!(params[0] instanceof Boolean)) { throw new CDKException("The first parameter must...
python
def _combine_to_jointcaller(processed): """Add joint calling information to variants, while collapsing independent regions. """ by_vrn_file = collections.OrderedDict() for data in (x[0] for x in processed): key = (tz.get_in(("config", "algorithm", "jointcaller"), data), data["vrn_file"]) ...
java
public Observable<ServiceResponse<UUID>> createPatternAnyEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, CreatePatternAnyEntityRoleOptionalParameter createPatternAnyEntityRoleOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException...
java
private String buildGoogMsgVarNameHelper(MsgNode msgNode) { // NOTE: MSG_UNNAMED/MSG_EXTERNAL are a special tokens recognized by the jscompiler. MSG_UNNAMED // disables the default logic that requires all messages to be uniquely named. // and MSG_EXTERNAL causes the jscompiler to not extract these messages....
python
def set_fig_title(self, title, **kwargs): """Set overall figure title. Set title for overall figure. This is not for a specific plot. It will place the title at the top of the figure with a call to ``fig.suptitle``. Args: title (str): Figure title. Keywork Argument...
python
def read_xdg_config_dirs(name, extension): """ Read from files found in XDG-specified system-wide configuration paths, defaulting to ``/etc/xdg``. Depends on ``XDG_CONFIG_DIRS`` environment variable. :param name: application or configuration set name :param extension: file extension to look for...
java
public String getTreeSite(String type) { String result = m_treeSite.get(type); return result; }
python
def os_workload_status(configs, required_interfaces, charm_func=None): """ Decorator to set workload status based on complete contexts """ def wrap(f): @wraps(f) def wrapped_f(*args, **kwargs): # Run the original function first f(*args, **kwargs) # Set...
python
def remove_securitygroup_rules(self, group_id, rules): """Remove rules from a security group. :param int group_id: The ID of the security group :param list rules: The list of IDs to remove """ return self.security_group.removeRules(rules, id=group_id)
python
def correct(self, temp, we_t): """ Compute weC from weT """ if not PIDTempComp.in_range(temp): return None n_t = self.cf_t(temp) if n_t is None: return None we_c = we_t * n_t return we_c
java
@Override public List<SimulatorEvent> accept(SimulatorEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Accepted event " + event); } if (event instanceof HeartbeatEvent) { return processHeartbeatEvent((HeartbeatEvent)event); } else if (event instanceof TaskAttemptCompletionEvent) { ...
python
def get_default_session(self): """ The default session is nothing more than the first session added into the session handler pool. This will likely change in the future but for now each session identifies the domain and also manages domain switching within a single session. ...
java
public static <T> Stream<T> reject(Stream<T> source, Predicate<? super T> predicate) { return source.filter(predicate.negate()); }
java
public void printUsage(PrintWriter pw, int width, String cmdLineSyntax) { int argPos = cmdLineSyntax.indexOf(' ') + 1; printWrapped(pw, width, getSyntaxPrefix().length() + argPos, getSyntaxPrefix() + cmdLineSyntax); }
java
public Observable<Void> syncVirtualNetworkInfoAsync(String resourceGroupName, String name) { return syncVirtualNetworkInfoWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { ...
java
private static String driverVersion() { // "Session" is arbitrary - the only thing that matters is that the class we use here is in the // 'org.neo4j.driver' package, because that is where the jar manifest specifies the version. // This is done as part of the build, adding a MANIFEST.MF file...
java
public void registerService(Object service) { this.setService(service); String serviceClass = getInterfaceClassName(); if (service != null) serviceRegistration = context.registerService(serviceClass, this.service, properties); }
python
def _apply_search_backrefs(pattern, flags=0): """Apply the search backrefs to the search pattern.""" if isinstance(pattern, (str, bytes)): re_verbose = bool(VERBOSE & flags) re_unicode = None if bool((ASCII | LOCALE) & flags): re_unicode = False elif bool(UNICODE & f...
python
def get_object_cache_keys(instance): """ Return the cache keys associated with an object. """ if not instance.pk or instance._state.adding: return [] keys = [] for language in _get_available_languages(instance): keys.append(get_urlfield_cache_key(instance.__class__, instance.pk,...
java
private CmsResource getResourceToEdit(CmsObject cms) { CmsResource resource = null; if (m_uuid != null) { try { CmsUUID uuid = new CmsUUID(m_uuid); resource = cms.readResource(uuid, CmsResourceFilter.ignoreExpirationOffline(cms)); } catch (Number...
python
def ProcessIterator(pids, process_regex_string, ignore_grr_process, error_list): """Yields all (psutil-) processes that match certain criteria. Args: pids: A list of pids. If given, only the processes with those pids are returned. process_regex_string: If given, only processes whose name matches the ...
java
public void setWp(A_CmsListDialog wp) { m_wp = wp; Iterator<I_CmsListDirectAction> itActs = getDirectActions().iterator(); while (itActs.hasNext()) { I_CmsListDirectAction action = itActs.next(); action.setWp(wp); } Iterator<CmsListDefaultAction> itDefAct...
java
private static void createRestorerInstance() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createRestorerInstance"); try { Class cls = Class.forName(SI_MESSAGE_HANDLE_RESTORER_CLASS); instance = (SIMessageHandleRestorer) cls.newInstance(); } catch (Excep...
java
public void setText(int index, String value) { set(selectField(AssignmentFieldLists.CUSTOM_TEXT, index), value); }
python
def _filter_path(self, path): """ 筛选出 path 目录下所有的视频文件 """ if self._is_videofile(path): return [path, ] if os.path.isdir(path): result = [] for root, dirs, files in os.walk(path): result.extend(filter(self._is_videofile, map( ...
java
public static int read(ReadableByteChannel ch, ByteBuffer bb) throws IOException { if (ch instanceof SelectableChannel) { SelectableChannel sc = (SelectableChannel)ch; synchronized (sc.blockingLock()) { boolean bm = sc.isBlocking(); if (!bm) ...
python
def _create_marks(fig, marks=[bq.Mark], options={}, params={}): """ Initializes and returns marks for a figure as a list. Each mark is passed in as a class. The plot options should be passed into options. Any additional parameters to initialize plot components are passed into params as a dict of { ...
java
public void setQuery(final String metric, final Map<String, String> tags) { this.metric = metric; this.tags = tags; metric_uid = tsdb.getUID(UniqueIdType.METRIC, metric); tag_uids = Tags.resolveAll(tsdb, tags); }
python
def _from_dict(cls, _dict): """Initialize a TableReturn object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = DocInfo._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'mo...
java
static void createSynthesizedExternVar(AbstractCompiler compiler, String varName) { Node nameNode = IR.name(varName); // Mark the variable as constant if it matches the coding convention // for constant vars. // NOTE(nicksantos): honestly, I'm not sure how much this matters. // AFAIK, all people wh...
java
@SuppressWarnings("unchecked") public Query limit(int limit) { if (limit < 0) { throw new IllegalArgumentException(format("Limit of %d is negative.", limit)); } if (limit > MAX_LIMIT) { throw new IllegalArgumentException( format("Limit of %d is greater than %d.", limit, MAX_LIMIT) ...
python
def mount_volume(volume, device='/dev/xvdf', mountpoint='/mnt/data', fstype='ext4'): ''' Mount an EBS volume Args: volume (str): EBS volume ID device (str): default /dev/xvdf mountpoint (str): default /mnt/data fstype (str): default ext4 ''' _ec2().attach_volume(volu...
java
public void removeTextSearchParameter(String key) { try { ParamType type = ParamType.valueOf(key); switch (type) { case language: m_searchObject.setLocale(getStartLocale()); break; case text: m_s...
java
public Observable<InputInner> updateAsync(String resourceGroupName, String jobName, String inputName, InputInner input) { return updateWithServiceResponseAsync(resourceGroupName, jobName, inputName, input).map(new Func1<ServiceResponseWithHeaders<InputInner, InputsUpdateHeaders>, InputInner>() { @Ov...
python
def open_file(self) : """If this FSNode is a file, open it for reading and return the file handle""" if self.isdir() : raise Exception("FSQuery tried to open a directory as a file : %s" % self.abs) return open(self.abs)
java
@Nullable public static String removeSpacesAndHyphens(@Nullable String cardNumberWithSpaces) { if (isBlank(cardNumberWithSpaces)) { return null; } return cardNumberWithSpaces.replaceAll("\\s|-", ""); }
python
def get_section_header(self, section): """ Get a specific section header by index or name. Args: section(int or str): The index or name of the section header to return. Returns: :class:`~ELF.SectionHeader`: The section header. Raises: KeyErr...
python
def ensure_index(self, key, unique=False): """Wrapper for pymongo.Collection.ensure_index """ return self.collection.ensure_index(key, unique=unique)
java
@Override protected void addNavDetailLink(boolean link, Content liNav) { if (link) { liNav.addContent(writer.getHyperLink( SectionName.PROPERTY_DETAIL, contents.navProperty)); } else { liNav.addContent(contents.navProperty); } ...
java
public com.google.api.ads.admanager.axis.v201808.ColumnType[] getColumnTypes() { return columnTypes; }
java
public <V, T extends Enum & Option> OptionsMapper env(final String name, final T option, final Function<String, V> converter) { register("env: " + name, option, System.getenv(name), converter); return this; }
python
def find_executable(cls, name, check_syspaths=False): """Find an executable. Args: name (str): Program name. check_syspaths (bool): If True, check the standard system paths as well, if program was not found on current $PATH. Returns: str: Ful...
java
public static <T> List<Number> findIndexValues(Iterator<T> self, Number startIndex, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) { List<Number> result = new ArrayList<Number>(); long count = 0; long startCount = startIndex.longValue(); BooleanClosureWrapper bcw = ...
python
def findbeam_Guinier(data, orig_initial, mask, rmin, rmax, maxiter=100, extent=10, callback=None): """Find the beam by minimizing the width of a Gaussian centered at the origin (i.e. maximizing the radius of gyration in a Guinier scattering). Inputs: data: scattering matrix ...
java
public boolean isLockLive(String nodeId) throws LockException { try { return isLockLive.run(nodeId); } catch (LockException e) { if (LOG.isTraceEnabled()) { LOG.trace("An exception occurred: " + e.getMessage()); } } return fals...
java
static ClassInfoList getAllStandardClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) { return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.STANDARD_CLASS), /* sortByName = */ true); }
java
public static Method getRequiredMethod(Class type, String name, Class... argumentTypes) { try { return type.getDeclaredMethod(name, argumentTypes); } catch (NoSuchMethodException e) { return findMethod(type, name, argumentTypes) .orElseThrow(() -> newNoSuchMethodE...
python
def exclude_time(self, start, end, days): """Added an excluded time by start, end times and the days. ``start`` and ``end`` are in military integer times (e.g. - 1200 1430). ``days`` is a collection of integers or strings of fully-spelt, lowercased days of the week. """...
java
@Override protected void initTableInfoUniqueKeys(final Connection _con, final String _sql, final Map<String, TableInformation> _cache4Name) throws SQLException { final String sqlStmt = new StringBuilder() ...
python
def _UserUpdateIgnoredDirs(self, origIgnoredDirs = []): """ Add ignored directories to database table. Always called if the database table is empty. User can build a list of entries to add to the database table (one entry at a time). Once finished they select the finish option and all entries w...
python
def from_lasio(cls, l, remap=None, funcs=None, data=True, req=None, alias=None, fname=None): """ Constructor. If you already have the lasio object, then this makes a well object from it. Args: l (lasio object): a lasio object. remap (dict): Optional. A dict of 'o...
python
def _pkcs1imify(self, data): """ turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. """ size = len(util.deflate_long(self.n, 0)) filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) -...
java
public int[] findLongest(CharSequence query, int start) { if ((query == null) || (start >= query.length())) { return new int[]{0, -1}; } int state = 1; int maxLength = 0; int lastVal = -1; for (int i = start; i < query.length(); i++) { ...