language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void setTrueValue(String trueValue) { this.trueValue = trueValue; this.trueValueChars = trueValue.toCharArray(); this.trueValueBytes = toBytes(trueValue, trueValue); }
java
public Method findAnnotatedMethod(Class<?> clazz, Class<? extends Annotation> anno) { for (Method meth : clazz.getMethods()) { if (meth.isAnnotationPresent(anno)) { return meth; } } return null; }
java
protected final QB generateQuery(final Map<String, List<Object>> query) { QB queryBuilder = null; if (this.queryAttributeMapping != null) { for (final Map.Entry<String, Set<String>> queryAttrEntry : this.queryAttributeMapping.entrySet()) { final String queryAttr = queryAttrE...
python
def BROKER_TYPE(self): """Custom setting allowing switch between rabbitmq, redis""" broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE) if broker_type not in SUPPORTED_BROKER_TYPES: log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format( br...
python
def load(self, host, exact_host_match=False): """ Load a config for a hostname or url. This method calls :func:`ftr_get_config` and :meth`append` internally. Refer to their docs for details on parameters. """ # Can raise a SiteConfigNotFound, intentionally bubbled. conf...
java
public BidiRun getLogicalRun(int logicalPosition) { verifyValidParaOrLine(); verifyRange(logicalPosition, 0, length); return BidiLine.getLogicalRun(this, logicalPosition); }
python
def as_dict(config): """ Converts a ConfigParser object into a dictionary. The resulting dictionary has sections as keys which point to a dict of the sections options as key => value pairs. """ settings = defaultdict(lambda: {}) for section in config.sections(): for key, val in conf...
java
private void fireUserInputChange() { if (!internallySettingText && (this.listeners != null)) { for (Iterator it = this.listeners.iterator(); it.hasNext();) { UserInputListener userInputListener = (UserInputListener) it.next(); userInputListener.update(this); } } }
python
def get_pose_error(target_pose, current_pose): """ Computes the error corresponding to target pose - current pose as a 6-dim vector. The first 3 components correspond to translational error while the last 3 components correspond to the rotational error. Args: target_pose: a 4x4 homogenous m...
python
def path(self, value): """ Setter for **self.__path** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("path", value) self._...
python
def populate_tree(self, parentItem, children_list): """Recursive method to create each item (and associated data) in the tree.""" for child_key in children_list: self.item_depth += 1 (filename, line_number, function_name, file_and_line, node_type ) = self.functi...
java
@SuppressWarnings("rawtypes") @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.setInvocationCount(StringUtils.countMatches(getBrowser(), ",") + 1); }
java
public void dispatchEvent(final ManagerEvent event) { if (logger.isDebugEnabled()) { logger.debug("dispatch=" + event.toString()); //$NON-NLS-1$ } // take a copy of the listeners so they can be modified whilst we // iterate over them // The iteration may ...
python
def dead_links(self): """Generate the coordinates of all dead links leaving working chips. Any link leading to a dead chip will also be included in the list of dead links. In non-torroidal SpiNNaker sysmtes (e.g. single SpiNN-5 boards), links on the periphery of the system will be marke...
java
public String getFirst(String name, String defaultValue) { String value = getFirst(name); if (value == null) { value = defaultValue; } return value; }
python
def _parse_binary(v, header_d): """ Parses binary string. Note: <str> for py2 and <binary> for py3. """ # This is often a no-op, but it ocassionally converts numbers into strings v = nullify(v) if v is None: return None if six.PY2: try: return six.bi...
java
public boolean isEquivalent(CompilationUnit other) { if (!destination.getAbsoluteFile().equals(other.destination.getAbsoluteFile())) return false; if (encoding != null ? !encoding.equals(other.encoding) : other.encoding != null) return false; if (resourceReader != null ? !resourceReader.equals(o...
java
private void getExecutionIdsHelper(final List<Integer> allIds, final Collection<Pair<ExecutionReference, ExecutableFlow>> collection) { collection.stream().forEach(ref -> allIds.add(ref.getSecond().getExecutionId())); Collections.sort(allIds); }
python
def circuit_to_pdf_using_qcircuit_via_tex(circuit: circuits.Circuit, filepath: str, pdf_kwargs=None, qcircuit_kwargs=None, clean_ext=('dvi', 'ps'), ...
java
public com.google.api.ads.adwords.axis.v201809.cm.AssetLink getMandatoryAdText() { return mandatoryAdText; }
python
def _import_next_layer(self, proto, length): """Import next layer extractor. Positional arguments: * proto -- str, next layer protocol name * length -- int, valid (not padding) length Returns: * bool -- flag if extraction of next layer succeeded ...
java
@Requires({ "kind != null", "kind.isOld()", "list != null" }) protected void invokeOldValues(ContractKind kind, List<Integer> list) { List<MethodContractHandle> olds = contracts.getMethodHandles(kind, methodName, methodDesc, 0); if (olds.isEmpty()) { return; } for (MethodC...
python
def _flush(self): """ Decorator for flushing handlers with an lock, catching exceptions """ if not self.enabled: return try: try: self.lock.acquire() self.flush() except Exception: self.log.error(...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.GBOX__RES: return RES_EDEFAULT == null ? res != null : !RES_EDEFAULT.equals(res); case AfplibPackage.GBOX__XPOS0: return XPOS0_EDEFAULT == null ? xpos0 != null : !XPOS0_EDEFAULT.equals(xpos0); case AfplibPackage...
java
private static SqlInfo buildNewSqlInfo(String nameSpace, Node node, Object paramObj) { return buildSqlInfo(nameSpace, SqlInfo.newInstance(), node, paramObj); }
java
public static void main(String[] args) throws Exception { String datapath = "../data"; String allfile = datapath + "/FNLPDATA/all.seg"; String testfile = datapath + "/FNLPDATA/test.seg"; String trainfile = datapath + "/FNLPDATA/train.seg"; MyFiles.delete(testfile); MyFiles.delete(trainfile); MyFi...
java
public static void close(@Nullable Connection con) throws SQLException { if (con != null && !con.isClosed()) { if (!con.getAutoCommit()) { con.rollback(); con.setAutoCommit(true); } con.close(); } }
java
public OvhUserWithPassword serviceName_user_userId_changePassword_POST(String serviceName, String userId) throws IOException { String qPath = "/dbaas/queue/{serviceName}/user/{userId}/changePassword"; StringBuilder sb = path(qPath, serviceName, userId); String resp = exec(qPath, "POST", sb.toString(), null); re...
python
def W(self): "ISO-8601 week number of year, weeks starting on Monday" # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt week_number = None jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1 weekday = self.data.weekday() + 1 day_of_year = self.z() if day_of_year <...
java
public void start(String name) { GVRAnimator anim = findAnimation(name); if (name.equals(anim.getName())) { start(anim); return; } }
python
def getActorLimits(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ generators = [g for g in self.env.case.online_generators if g.bus.type != REFERENCE] limits =...
java
public void marshall(DevEndpoint devEndpoint, ProtocolMarshaller protocolMarshaller) { if (devEndpoint == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(devEndpoint.getEndpointName(), ENDPOINTNAME_BI...
java
public static <T, E extends Exception> ShortList mapToShort(final T[] a, final int fromIndex, final int toIndex, final Try.ToShortFunction<? super T, E> func) throws E { checkFromToIndex(fromIndex, toIndex, len(a)); N.checkArgNotNull(func); if (N.isNullOrEmpty(a)) { ...
java
protected static Attributes buildAttributes(final Map attributes) { final AttributesImpl attr = new AttributesImpl(); for (Object o : attributes.entrySet()) { final Map.Entry entry = (Map.Entry) o; final String attributeName = (String) entry.getKey(); final String att...
java
private boolean isInteger(String columnOrConstant, List<String> tableNames, boolean debugPrint) { return isIntegerConstant(columnOrConstant) || isIntegerColumn(columnOrConstant, tableNames, debugPrint); }
python
def robot_wireless(max_iters=100, kernel=None, optimize=True, plot=True): """Predict the location of a robot given wirelss signal strength readings.""" try:import pods except ImportError: print('pods unavailable, see https://github.com/sods/ods for example datasets') return data = pods.d...
python
def ccid_xfr_block(self, data, timeout=0.1): """Encapsulate host command *data* into an PC/SC Escape command to send to the device and extract the chip response if received within *timeout* seconds. """ frame = struct.pack("<BI5B", 0x6F, len(data), 0, 0, 0, 0, 0) + data ...
java
public void setParamTabEdButtonStyle(String value) { try { m_userSettings.setEditorButtonStyle(Integer.parseInt(value)); } catch (Throwable t) { // should usually never happen } }
python
def items(cls): """ All values for this enum :return: list of str """ return [ cls.GREEN, cls.BLACK_AND_WHITE, cls.CONTRAST_SHIFTED, cls.CONTRAST_CONTINUOUS ]
java
public static <T> SerializedCheckpointData[] fromDeque( ArrayDeque<Tuple2<Long, Set<T>>> checkpoints, TypeSerializer<T> serializer, DataOutputSerializer outputBuffer) throws IOException { SerializedCheckpointData[] serializedCheckpoints = new SerializedCheckpointData[checkpoints.size()]; int pos = 0; f...
java
public static final void debug(TraceComponent tc, String msg, Object... objs) { TrConfigurator.getDelegate().debug(tc, msg, objs); }
java
public final DateList getDates(final Date seed, final Period period, final Value value) { return getDates(seed, period.getStart(), period.getEnd(), value, -1); }
python
def getNextEyeLocation(self, currentEyeLoc): """ Generate next eye location based on current eye location. @param currentEyeLoc (numpy.array) Current coordinate describing the eye location in the world. @return (tuple) Contains: nextEyeLoc (numpy.array) Coordinate ...
python
def get_tiles(self): """Get all TileCoordinates contained in the region""" for x, y in griditer(self.root_tile.x, self.root_tile.y, ncol=self.tiles_per_row): yield TileCoordinate(self.root_tile.zoom, x, y)
java
final Expression then(final Expression expression) { return new Expression(expression.resultType(), expression.features()) { @Override protected void doGen(CodeBuilder adapter) { Statement.this.gen(adapter); expression.gen(adapter); } }; }
python
def verify_images(path:PathOrStr, delete:bool=True, max_workers:int=4, max_size:Union[int]=None, recurse:bool=False, dest:PathOrStr='.', n_channels:int=3, interp=PIL.Image.BILINEAR, ext:str=None, img_format:str=None, resume:bool=None, **kwargs): "Check if the images in `path` are...
java
public Optional<ZonedDateTime> nextExecution(final ZonedDateTime date) { Preconditions.checkNotNull(date); try { ZonedDateTime nextMatch = nextClosestMatch(date); if (nextMatch.equals(date)) { nextMatch = nextClosestMatch(date.plusSeconds(1)); } ...
python
def follow(self): """ Follow a user." """ data = json.dumps({"action": "follow"}) r = requests.post( "https://kippt.com/api/users/%s/relationship" % (self.id), headers=self.kippt.header, data=data ) return (r.json())
python
def validate(self, instance, value): """Check shape and dtype of vector and scales it to given length""" value = super(BaseVector, self).validate(instance, value) if self.length is not None: try: value.length = self._length_array(value) except ZeroDivisi...
java
public static boolean isNegative(ZMatrixD1 a, ZMatrixD1 b, double tol) { if( a.numRows != b.numRows || a.numCols != b.numCols ) throw new IllegalArgumentException("Matrix dimensions must match"); int length = a.getNumElements()*2; for( int i = 0; i < length; i++ ) { if(...
python
def delete(self, path_list, **kwargs): """ 删除文件或文件夹 :param path_list: 待删除的文件或文件夹列表,每一项为服务器路径 :type path_list: list """ data = { 'filelist': json.dumps([path for path in path_list]) } url = 'http://{0}/api/filemanager?opera=delete'.format(BAI...
java
public OvhOrder dedicatedCloud_serviceName_vdi_POST(String serviceName, Long datacenterId, String firstPublicIpAddress, String secondPublicIpAddress) throws IOException { String qPath = "/order/dedicatedCloud/{serviceName}/vdi"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<S...
python
def obfn_g1(self, Y1): r"""Compute :math:`g_1(\mathbf{y_1})` component of ADMM objective function. """ return np.linalg.norm((self.wl1 * Y1).ravel(), 1)
java
public FireableEventType getEventId(EventLookupFacility eventLookupFacility, Request request, boolean inDialogActivity) { final String requestMethod = request.getMethod(); // Cancel is always the same. if (requestMethod.equals(Request.CANCEL)) inDialogActivity = false; FireableEventType eventID = nul...
python
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
java
public void updateThroughput(long currentTime) { synchronized (throughputCalculationLock) { int interval = (int) (currentTime - lastThroughputCalculationTime); long minInterval = getThroughputCalculationIntervalInMillis(); if (minInterval == 0 || interval < minInterval) { ...
java
static Shape shapeOf(List<Point2D> points) { Path2D path = new Path2D.Double(); if (!points.isEmpty()) { path.moveTo(points.get(0).getX(), points.get(0).getY()); for (Point2D point : points) path.lineTo(point.getX(), point.getY()); path.closePath(); ...
java
private boolean isSupported(Class<?> t) { if (Boolean.class.equals(t) || boolean.class.equals(t) || Byte.class.equals(t) || byte.class.equals(t) || Short.class.equals(t) || short.class.equals(t) || Integer.class.equals(t) || int.class.equals(t) || Long.class.equals(t) ||...
java
public void clean() throws BackupException { File storageDir = new File(PrivilegedSystemHelper.getProperty("java.io.tmpdir")); WorkspaceQuotaRestore wqr = new WorkspaceQuotaRestore(this, storageDir); wqr.clean(); }
java
private void addShardStart(TableDefinition tableDef, int shardNumber, Date shardDate) { SpiderTransaction spiderTran = new SpiderTransaction(); spiderTran.addShardStart(tableDef, shardNumber, shardDate); Tenant tenant = Tenant.getTenant(tableDef); DBTransaction dbTran = DBService.ins...
java
public float[] getFieldPositions(String name) { Item item = getFieldItem(name); if (item == null) return null; float ret[] = new float[item.size() * 5]; int ptr = 0; for (int k = 0; k < item.size(); ++k) { try { PdfDictionary wd = item.getW...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.PTD__XPBASE: setXPBASE(XPBASE_EDEFAULT); return; case AfplibPackage.PTD__YPBASE: setYPBASE(YPBASE_EDEFAULT); return; case AfplibPackage.PTD__XPUNITVL: setXPUNITVL(XPUNITVL_EDEFAULT); return; case...
java
@Override // defined by AbstractDoclet protected void generateClassFiles(SortedSet<TypeElement> arr, ClassTree classtree) throws DocletException { List<TypeElement> list = new ArrayList<>(arr); ListIterator<TypeElement> iterator = list.listIterator(); TypeElement klass = null; ...
python
def poly_curve(x, *a): """ Arbitrary dimension polynomial. """ output = 0.0 for n in range(0, len(a)): output += a[n]*x**n return output
java
public Observable<ProjectInner> getAsync(String groupName, String serviceName, String projectName) { return getWithServiceResponseAsync(groupName, serviceName, projectName).map(new Func1<ServiceResponse<ProjectInner>, ProjectInner>() { @Override public ProjectInner call(ServiceResponse<P...
java
public final void listenInline(AsyncWorkListener<T,TError> listener) { synchronized (this) { if (!unblocked || listenersInline != null) { if (listenersInline == null) listenersInline = new ArrayList<>(5); listenersInline.add(listener); return; } } if (error != null) listener.error(error)...
python
def _dist_obs_oracle(oracle, query, trn_list): """A helper function calculating distances between a feature and frames in oracle.""" a = np.subtract(query, [oracle.f_array[t] for t in trn_list]) return (a * a).sum(axis=1)
python
def write_fits(self, filename, moctool=''): """ Write a fits file representing the MOC of this region. Parameters ---------- filename : str File to write moctool : str String to be written to fits header with key "MOCTOOL". Default = ...
python
def __sum(self, line): """Return the IRQ sum number. IRQ line samples: 1: 44487 341 44 72 IO-APIC 1-edge i8042 LOC: 33549868 22394684 32474570 21855077 Local timer interrupts FIQ: usb_fiq """ splitted_line = line.sp...
python
def unlike(self, id, reblog_key): """ Unlike the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response """ url = "/v2/user/unlike" ...
python
def dbmax_mean(self, value=None): """ Corresponds to IDD Field `dbmax_mean` Mean of extreme annual maximum dry-bulb temperature Args: value (float): value for IDD Field `dbmax_mean` Unit: C if `value` is None it will not be checked against the ...
java
public TableBuilder addInnerBorder(BorderStyle style) { this.addBorder(0, 0, model.getRowCount(), model.getColumnCount(), INNER, style); return this; }
python
def split_datetime(self, column_name_prefix = "X", limit=None, timezone=False): """ Splits an SArray of datetime type to multiple columns, return a new SFrame that contains expanded columns. A SArray of datetime will be split by default into an SFrame of 6 columns, one for each y...
java
public static <T,K,V> List<T> collect(Map<K,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> transform) { return (List<T>) collect(self, new ArrayList<T>(self.size()), transform); }
java
@SuppressWarnings("unchecked") @Override public void publishEvent(ApplicationEvent event) { if (event instanceof MappingContextEvent) { this.schmeaCreator .onApplicationEvent((MappingContextEvent<SolrPersistentEntity<?>, SolrPersistentProperty>) event); } }
java
public static boolean recoverWeight(ProviderInfo providerInfo, int weight) { providerInfo.setStatus(ProviderStatus.RECOVERING); providerInfo.setWeight(weight); return true; }
java
@Override public Identifier toPhysicalColumnName(Identifier columnIdentifier, JdbcEnvironment context) { return convertToLimitedLowerCase(context, columnIdentifier, null); }
java
private static Object castObject( Class<?> toType, Class<?> fromType, Object fromValue, int operation, boolean checkOnly ) throws UtilEvalError { /* Lots of preconditions checked here... Once things are running smoothly we might comment these out (...
python
def parse(self, text): """Do the parsing.""" text = tounicode(text, encoding="utf-8") result, i = self._parse(text, 0) if text[i:].strip(): self._fail("Unexpected trailing content", text, i) return result
python
def get(self): """ Get current user info. Returns :class:`User` object. :Example: user = client.user.get() """ response, instance = self.request("GET", self.uri) return self.load_instance(instance)
python
def ghostedDistArrayFactory(BaseClass): """ Returns a ghosted distributed array class that derives from BaseClass @param BaseClass base class, e.g. DistArray or MaskedDistArray @return ghosted dist array class """ class GhostedDistArrayAny(BaseClass): """ Ghosted distributed arr...
java
public CMAArray<CMAContentType> fetchAll( String spaceId, String environmentId, Map<String, String> query) { assertNotNull(spaceId, "spaceId"); DefaultQueryParameter.putIfNotSet(query, DefaultQueryParameter.FETCH); return service.fetchAll(spaceId, environmentId, query).blockingFirst(); }
python
def _ensure_folders(self, *paths): """ Ensure that paths to folder(s) exist. Some command-line tools will not attempt to create folder(s) needed for output path to exist. They instead assume that they already are present and will fail if that assumption does not hold. :...
java
public SDVariable eq(SDVariable x, SDVariable y) { return eq(null, x, y); }
python
def load(fileobj): """Load the submission from a file-like object :param fileobj: File-like object :return: the loaded submission """ with gzip.GzipFile(fileobj=fileobj, mode='r') as z: submission = Submission(metadata=json.loads(z.readline())) for line ...
java
public static List<Fodselsnummer> getManyDNumberFodselsnummerForDate(Date date) { if (date == null) { throw new IllegalArgumentException(); } DateFormat df = new SimpleDateFormat("ddMMyy"); String centuryString = getCentury(date); String dateString = df.format(date); dateString = new StringBuilder() ...
java
public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { if (table == null) { throw Util.nullArgument("table"); } String scopeIn; switch (scope) { case bestRowTemporary : ...
java
public Map<String,String> parse(final char[] chars, char separator) { if (chars == null) { return new HashMap<String,String>(); } return parse(chars, 0, chars.length, separator); }
java
public void createWithDepth(int allowableDepth, TreeGP manager, TGPInitializationStrategy initializationStrategy){ final int constantCount = manager.getConstants().size(); for(int i=0; i < constantCount; ++i){ constantSet.add(new Terminal("c" + i, manager.constant(i), manager.constantText(i), true...
java
public boolean validateCVC() { if (StripeTextUtils.isBlank(cvc)) { return false; } String cvcValue = cvc.trim(); String updatedType = getBrand(); boolean validLength = (updatedType == null && cvcValue.length() >= 3 && cvcValue.length() <= 4) ...
java
public SubscribeData subscribe(Collection<Statistic> statistics) throws WorkspaceApiException { try { StatisticsSubscribeData subscribeData = new StatisticsSubscribeData(); StatisticsSubscribeDataData data = new StatisticsSubscribeDataData(); data.setStatistics(new ArrayL...
python
def get_poll_option_formset(self, formset_class): """ Returns an instance of the poll option formset to be used in the view. """ if self.request.forum_permission_handler.can_create_polls( self.get_forum(), self.request.user, ): return formset_class(**self.get_poll_option_...
python
def meta_get(self, key, metafield, default=None): ''' Return the value of a meta field for a key. ''' return self._meta.get(key, {}).get(metafield, default)
java
private Integer listCorruptFileBlocks(String dir, int limit, String baseUrl) throws IOException { int errCode = -1; int numCorrupt = 0; int cookie = 0; String lastBlock = null; final String noCorruptLine = "has no CORRUPT files"; final String noMoreCorruptLine = "has no more CORRUPT files"; ...
java
private List<Pair<String, StandardCredentials>> getGitClientCredentials() { List<Pair<String, StandardCredentials>> credentialsList = new ArrayList<>(); GitSCM gitScm = getJenkinsScm(); for (UserRemoteConfig uc : gitScm.getUserRemoteConfigs()) { String url = uc.getUrl(); ...
python
def parse_member( cls, obj: dict, collection: "DtsCollection", direction: str, **additional_parameters) -> List["DtsCollection"]: """ Parse the member value of a Collection response and returns the list of object while setting the graph ...
java
public void refresh(String vaultName, String resourceGroupName, String fabricName, String filter) { refreshWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, filter).toBlocking().single().body(); }
python
def _create_fw_fab_dev(self, tenant_id, drvr_name, fw_dict): """This routine calls the Tenant Edge routine if FW Type is TE. """ if fw_dict.get('fw_type') == fw_constants.FW_TENANT_EDGE: self._create_fw_fab_dev_te(tenant_id, drvr_name, fw_dict)
python
def iter_emails(self, number=-1, etag=None): """Iterate over email addresses for the authenticated user. :param int number: (optional), number of email addresses to return. Default: -1 returns all available email addresses :param str etag: (optional), ETag from a previous request to...
java
protected <OBJ> OBJ filterIfSimpleText(OBJ value, FormMappingOption option, String propertyName, Class<?> propertyType) { if (value == null) { return null; } if (value instanceof String) { final String str = (String) value; if (option.getSimpleTextParameterFil...