language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void evaluateConstraints(DoubleSolution solution) { double[] constraint = new double[this.getNumberOfConstraints()]; double x1,x2,x3,x4,x5,x6,x7; x1 = solution.getVariableValue(0); x2 = solution.getVariableValue(1); x3 = solution.getVariableValue(2); x4 = solution.getVariableValue(3); ...
python
def add(self, rule, method, target, name=None, static=False): ''' Add a new route or replace the target for an existing route. ''' if static: depr("Use a backslash to escape ':' in routes.") # 0.9 rule = rule.replace(':','\\:') if rule in self.routes: self.ro...
java
private AbstractNode findFirstNodeByName(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException { final String name = PathHelper.getName(path); if (!name.isEmpty()) { logger.debug("Requested name: {}", name); final Query query ...
java
public synchronized void createWorkspace(String workspaceName) throws RepositoryException { SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION); final WorkspaceContainer wsContainer = repositoryContainer.getWorkspaceContainer(workspaceName); if (ws...
java
public Object getMCWFromMctoMCWMap(Object mc) { Object mcw = null; mcToMCWMapRead.lock(); try { mcw = mcToMCWMap.get(mc); } finally { mcToMCWMapRead.unlock(); } return mcw; }
python
def resolve_one(self, correlation_id, key): """ Resolves a single connection parameters by its key. :param correlation_id: (optional) transaction id to trace execution through call chain. :param key: a key to uniquely identify the connection. :return: a resolved connection. ...
java
public static long extractMaximumFramesize(Configuration configuration) { String maxFrameSizeStr = configuration.getString(AkkaOptions.FRAMESIZE); String akkaConfigStr = String.format(SIMPLE_AKKA_CONFIG_TEMPLATE, maxFrameSizeStr); Config akkaConfig = ConfigFactory.parseString(akkaConfigStr); return akkaConfig.g...
python
def _load_all(self): ''' Load all of them ''' with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True
python
def print_format_output(dataframe): """Prints output of given dataframe to fit into terminal. Returns: table (pd.DataFrame): Final outputted dataframe. dropped_cols (list): Columns dropped due to terminal size. empty_cols (list): Empty columns (dropped on default). """ print_df ...
java
public static String getDBQualifiedName(String clusterName, String dbName) { return String.format("%s@%s", dbName.toLowerCase(), clusterName); }
java
public void process(RootDoc root) throws IOException { // out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<XMI xmi.version=\"1.1\" >"); out.println(" <XMI.header>"); out.println(" <XMI.metamodel href=\"/vol/acfiles7/egonw/SourceForge/CDK/cdk/reports/javadoc/test...
python
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
java
static synchronized <T extends Model> void putEntity(T entity) { if (entity.id != null) { sCache.put(getEntityIdentifier(entity.getClass(), entity.id), entity); } }
python
def find_obj(self, env, modname, classname, name, type_name, searchmode=0): """Find a Chapel object for "name", possibly with module or class/record name. Returns a list of (name, object entry) tuples. :arg int searchmode: If 1, search more specific names first. Otherwise, search bu...
java
public EClass getIfcBuilding() { if (ifcBuildingEClass == null) { ifcBuildingEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(54); } return ifcBuildingEClass; }
java
protected PType typeCheckLet(INode node, LinkedList<PDefinition> localDefs, INode body, TypeCheckInfo question) throws AnalysisException { // Each local definition is in scope for later local definitions... Environment local = question.env; for (PDefinition d : localDefs) { if (d instanceof AExplicitFun...
java
private CompositeExpression parseComparisonRange() { Token token = tokens.lookahead(); CompositeExpression expr; switch (token.type) { case EQUAL: tokens.consume(); expr = eq(parseVersion()); break; case NOT_EQUAL: ...
java
private V get(K key, int hash) { if (hash == this.hash && key.equals(this.key)) { return this.value; } int bucket = bucket(hash); int bucketMask = 1 << bucket; return (mask & bucketMask) != 0 ? children[index(bucketMask)].get(key, shift(hash)) : null; }
python
def user_filter(config, message, fasnick=None, *args, **kw): """ A particular user Use this rule to include messages that are associated with a specific user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fmn.rules.utils.msg2usernames(message, **config)
python
def section(request): """ Determines the current site section from resolved view pattern and adds it to context['section']. Section defaults to the first specified section. """ # If SECTIONS setting is not specified, don't do anything. try: sections = settings.SECTIONS except Attribu...
python
def transpose(surf, **kwargs): """ Transposes the input surface(s) by swapping u and v parametric directions. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param surf: input surface(s) :type surf: abstract.Surface, multi.SurfaceContain...
java
private static List<String> tokeniseOnLowercaseToUppercase( String name ) { List<String> splits = new ArrayList<>(); // the following stores data in pairs (start, finish, start, ...) ArrayList<Integer> candidateBoundaries = new ArrayList<>(); // now process the array looking for boundar...
java
private static int put(byte[] block, int offset, byte[] b, int off, int len) { System.arraycopy(b, off, block, offset, len); return len; }
java
@BetaApi public final Operation deleteSignedUrlKeyBackendService(String backendService, String keyName) { DeleteSignedUrlKeyBackendServiceHttpRequest request = DeleteSignedUrlKeyBackendServiceHttpRequest.newBuilder() .setBackendService(backendService) .setKeyName(keyName) ...
java
public List<Object> fromThriftRow(Class<?> clazz, EntityMetadata m, List<String> relationNames, boolean isWrapReq, ConsistencyLevel consistencyLevel, Object... rowIds) throws Exception { List<Object> entities = new ArrayList<Object>(); if (rowIds != null) { for (Objec...
java
@Override public List<Object> collectMilestoningOverlaps() { List<Object> duplicateData = FastList.newList(); for (SemiUniqueEntry obj : nonDatedTable) { collectMilestoningOverlaps(duplicateData, obj); } return duplicateData; }
java
public static QrcodeTicket qrcodeCreateFinal(String access_token,int scene_id){ String json = String.format("{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\":%d}}}", scene_id); return qrcodeCreate(access_token,json); }
java
public static PartialMerkleTree buildFromLeaves(NetworkParameters params, byte[] includeBits, List<Sha256Hash> allLeafHashes) { // Calculate height of the tree. int height = 0; while (getTreeWidth(allLeafHashes.size(), height) > 1) height++; List<Boolean> bitList = new ArrayL...
java
@Override public void removeByCommerceCountryId(long commerceCountryId) { for (CommerceAddress commerceAddress : findByCommerceCountryId( commerceCountryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceAddress); } }
java
public DB2ESImportBuilder addFieldValue(String fieldName, Object value){ addFieldValue( fieldValues, fieldName, value); return this; }
java
private static Bitmap loadBitmapOptimized(ImageSource source, int limit) throws ImageLoadException { int scale = getScaleFactor(source.getImageMetadata(), limit); return loadBitmap(source, scale); }
java
protected String resolveNamespace(String namespace, String name) { return resolveNamespace(namespace, name, null); }
python
def remote(self, action): """ Function specific for MMI, not BMI. action is one of: "play", "stop", "pause", "rewind", "quit" """ method = "remote" A = None metadata = {method: action} send_array(self.socket, A, metadata) A, metadata = recv_array...
python
def energy(self, spins, break_aux_symmetry=True): """A formula for the exact energy of Theta with spins fixed. Args: spins (dict): Spin values for a subset of the variables in Theta. break_aux_symmetry (bool, optional): Default True. If True, break the aux variab...
python
def position_target_global_int_encode(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This ...
java
@RequestMapping(value = "/findByUsername", method = RequestMethod.GET) public @ResponseBody ResponseAccount findByUsername( @RequestParam(value = "username", required = true) String username) { logger.debug("Received request to get account by username"); ResponseAccount acconut = accountService.getAccountByUs...
java
public MethodInfo addMethod(Method method) { Modifiers modifiers = new Modifiers(method.getModifiers()); modifiers.setAbstract(this.getModifiers().isInterface()); TypeVariableDesc[] typeParams = lookupTypeVariables(method); TypeDesc ret = TypeDesc.forClass(method.getReturnType(), ...
java
@Override protected void defineWidgets() { // initialize the project object to use for the dialog initMessageObject(); setKeyPrefix(KEY_PREFIX); addWidget(new CmsWidgetDialogParameter(m_msgInfo, "from", PAGES[0], new CmsDisplayWidget())); addWidget(new CmsWidgetDialogParam...
java
public static policydataset get(nitro_service service, String name) throws Exception{ policydataset obj = new policydataset(); obj.set_name(name); policydataset response = (policydataset) obj.get_resource(service); return response; }
java
public Command findCommand(String name) { for (Command candidate : this.commands) { String candidateName = candidate.getName(); if (candidateName.equals(name) || (isOptionCommand(candidate) && ("--" + candidateName).equals(name))) { return candidate; } } return null; }
python
def logging_on(level=logging.WARNING): """Turn logging on. """ global _is_logging_on if not _is_logging_on: console = logging.StreamHandler() console.setFormatter(logging.Formatter("[%(levelname)s: %(asctime)s :" " %(name)s] %(message)s", ...
python
def get_objective_query_session(self, proxy): """Gets the ``OsidSession`` associated with the objective query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveQuerySession`` :rtype: ``osid.learning.ObjectiveQuerySession`` :raise: ``...
python
def makeLinearxFunc(self,mLvl,pLvl,MedShk,xLvl): ''' Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of linear interpolations over market resources. Parameters -...
python
def show(self): """ Display the information (with a pretty print) about the method """ self.show_info() self.show_notes() if self.code != None: self.each_params_by_register(self.code.get_registers_size(), self.get_d...
python
def extent(self): """Helper for matplotlib imshow""" return ( self.intervals[1].pix1 - 0.5, self.intervals[1].pix2 - 0.5, self.intervals[0].pix1 - 0.5, self.intervals[0].pix2 - 0.5, )
python
def has_free_moves(self): """Returns whether a move is possible, when there are no free cells.""" return any(self._can_cell_be_merged(x, y) for x in range(self.COUNT_X) for y in range(self.COUNT_Y))
python
def rebin2x2(a): """ Wrapper around rebin that actually rebins 2 by 2 """ inshape = np.array(a.shape) if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even raise RuntimeError, "I want even image shapes !" return rebin(a, inshape/2)
java
public int convertPointToAbsolutePosition(int relativePosition) { if (relativePosition < 0 || relativePosition >= length()) throw new IllegalArgumentException("Relative position outside this range (" + relativePosition + ")."); if (reversed) return upper - 1 - relativePosition; ...
java
public static List<Polygon> createSimpleDirectionArrow( Geometry... geometries ) { List<Polygon> polygons = new ArrayList<>(); for( Geometry geometry : geometries ) { for( int i = 0; i < geometry.getNumGeometries(); i++ ) { Geometry geometryN = geometry.getGeometryN(i); ...
python
def _resolved_objects(pdf, xobject): """Retrieve rotatation info.""" return [pdf.getPage(i).get(xobject) for i in range(pdf.getNumPages())][0]
java
@Override public T getPluginOrDefaultFor(S delimiter, Supplier<T> defaultSupplier) { Assert.notNull(delimiter, "Delimiter must not be null!"); Assert.notNull(defaultSupplier, "Default supplier must not be null!"); return getPluginFor(delimiter).orElseGet(defaultSupplier); }
python
def _replace_placeholder(self, string, custom_id): """ Replace the prefix placeholder :class:`~aeneas.globalconstants.PPV_OS_TASK_PREFIX` with ``custom_id`` and return the resulting string. :rtype: string """ if string is None: return None sel...
python
def _get_bios_hash_password(self, bios_password): """Get the hashed BIOS password.""" request_headers = {} if bios_password: bios_password_hash = hashlib.sha256((bios_password.encode()). hexdigest().upper()) request_headers[...
python
def format_ubuntu_dialog(df): """ Print statements paired with replies, formatted for easy review """ s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] # <1> reply = list(split_turns(record.Utterance))[-1] # <2> s += 'Statement: {}\n'.format(s...
python
def Rz_to_coshucosv(R,z,delta=1.,oblate=False): """ NAME: Rz_to_coshucosv PURPOSE: calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta INPUT: R - radius z - height delta= focus oblate= (False) if True, compute oblate confocal co...
java
@Help(help = "Generate a new Key in the NFVO") public String generateKey(String name) throws SDKException { return (String) requestPost("generate", name); }
java
public static ZonedDateTime updateDateTime(ZonedDateTime value, float range) { range = range != 0 ? range : 10; if (range < 0) return value; float days = RandomFloat.nextFloat(-range, range); return value.plusDays((int) days); }
java
private static String removeStringDelimiters(String key) { String k = key.trim(); if (CmsStringUtil.isNotEmpty(k)) { if (k.charAt(0) == TEXT_DELIMITER) { k = k.substring(1); } if (k.charAt(k.length() - 1) == TEXT_DELIMITER) { k = k.sub...
java
public PoolPatchOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; } else { this.ocpDate = new DateTimeRfc1123(ocpDate); } return this; }
java
@Override public void release(Throwable cause) { if (STATE_UPDATER.compareAndSet(this, State.ALIVE, State.RELEASING)) { signalPayloadRelease(cause); } markReleased(); releaseFuture.complete(null); }
java
@CodingStyleguideUnaware public static <T extends Iterable <?>> T notEmpty (final T aValue, final String sName) { if (isEnabled ()) return notEmpty (aValue, () -> sName); return aValue; }
java
protected OutputStream createFileOutputStream(File file) { try { return new FileOutputStream(file); } catch (FileNotFoundException e) { throw new GenException(Message.DOMAGEN9001, e, e); } }
python
def read_pascal_string(fp, encoding='macroman', padding=2): """ Reads pascal string (length + bytes). :param fp: file-like object :param encoding: string encoding :param padding: padding size :return: str """ start_pos = fp.tell() # read_length_block doesn't work for a byte. len...
python
def transformer_base_vq_ada_32ex_packed(): """Set of hyperparameters for lm1b packed following tpu params.""" hparams = transformer_base_v2() expert_utils.update_hparams_for_vq_gating(hparams) hparams.moe_num_experts = 32 hparams.gating_type = "vq" # this gives us a batch size of 16 because each seq is len ...
python
def run_transaction(self, command_list, do_commit=True): '''This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur if the e...
java
public synchronized void update(double sample) { long now = System.currentTimeMillis(); if (lastMillis == 0) { // first sample average = sample; lastMillis = now; return; } long deltaTime = now - lastMillis; double coeff = Math.exp(-1.0 * (...
java
@SneakyThrows protected String getBackupMetadataFilenamePrefix(final AbstractResource metadataResource, final SamlRegisteredService service) { val mdFileName = metadataResource.getFilename(); if (StringUtils.isBlank(mdFileName)) { throw new FileNotFoundException("Unable to determine file...
java
public void readBytes(OutputStream out, int length) throws IOException { slice.getBytes(position, out, length); position += length; }
java
private HeaderElement findHeader(HeaderKeys key, int instance) { final int ord = key.getOrdinal(); if (!storage.containsKey(ord) && ord <= HttpHeaderKeys.ORD_MAX) { return null; } HeaderElement elem = null; //If the ordinal created for this key is larger than 1024,...
java
public List<Display> getDisplays() { return new EnumParameterList<Display>(DISPLAY) { @Override protected Display _asObject(String value) { return Display.get(value); } }; }
python
def _visit_te_shape(self, shape: ShExJ.shapeExpr, visit_center: _VisitorCenter) -> None: """ Visit a shape expression that was reached through a triple expression. This, in turn, is used to visit additional triple expressions that are referenced by the Shape :param shape: Shape reached...
python
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: dict generic keyword arguments """ # Set the title self.set_...
python
def send_venue(chat_id, latitude, longitude, title, address, foursquare_id=None, reply_to_message_id=None, reply_markup=None, disable_notification=False, **kwargs): """ Use this method to send information about a venue. :param chat_id: Unique identifier for the target chat or ...
python
def get_request(self, url): """ Wraps the URL to retrieve to protects against "creative" interpretation of the RFC: http://bugs.python.org/issue8732 """ if isinstance(url, string_types): url = urllib2.Request(url, headers={'Accept-encoding': 'identity'}) retur...
python
def servers(self, server='api.telldus.com', port=http.HTTPS_PORT): """Fetch list of servers that can be connected to. :return: list of (address, port) tuples """ logging.debug("Fetching server list from %s:%d", server, port) conn = http.HTTPSConnection(server, port, context=sel...
python
def bayesian_hmm(observations, estimated_hmm, nsample=100, reversible=True, stationary=False, p0_prior='mixed', transition_matrix_prior='mixed', store_hidden=False, call_back=None): r""" Bayesian HMM based on sampling the posterior Generic maximum-likelihood estimation of HMMs Parameters ...
java
@Override public void reset(final long mNodeKey) { super.reset(mNodeKey); if (mBindingSeq != null) { mBindingSeq.reset(mNodeKey); } }
java
public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) { Expression method = methodCall.getMethod(); // !important: performance enhancement boolean IS_NAME_MATCH = false; if (method instanceof ConstantExpression) { ...
python
def ask(question, default_answer=False, default_answer_str="no"): """ Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The...
python
async def import_wallet(self, indy_config: dict, path: str, access: str = None) -> None: """ Import a VON anchor wallet. Raise BadAccess on bad access credential value. :param indy_config: indy wallet configuration to use, with: - 'id' - 'storage_type' (optional) ...
python
def diff_objects(self, latest_commit_sha): """ Push all changes to origin, based on objects, not on commits. Important: Call this push after every new commit, or we lose commits. """ base = ['git', '--bare', '--git-dir', self.git_path] object_shas...
java
public boolean isEqualBasedOn(BiPredicate<? super E, ? super A> compareFunc) { return equals(expectedDef, expectedRoot, actualDef, actualRoot, compareFunc); }
java
public Response filenameHeader(String filename) { if (filename != null && !filename.isEmpty()) { header(HttpConstants.Header.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); } else { header(HttpConstants.Header.CONTENT_DISPOSITION, "attachment; filename=\"\""); ...
python
def _override_options(options, **overrides): """Override options.""" for opt, val in overrides.items(): passed_value = getattr(options, opt, _Default()) if opt in ('ignore', 'select') and passed_value: value = process_value(opt, passed_value.value) value += process_value(...
python
def _generate_identifier_name(self, columns, prefix="", max_size=30): """ Generates an identifier from a list of column names obeying a certain string length. """ hash = "" for column in columns: hash += "%x" % binascii.crc32(encode(str(column))) return (pref...
python
def fix_local_scheme(home_dir, symlink=True): """ Platforms that use the "posix_local" install scheme (like Ubuntu with Python 2.7) need to be given an additional "local" location, sigh. """ try: import sysconfig except ImportError: pass else: if sysconfig._get_defaul...
python
def _readvalue(sock, buf, size): """Read specified amount of bytes from the socket. Read size bytes, followed by the "\r\n" characters, from the socket, and return those bytes and any trailing bytes read after the "\r\n". Args: sock: Socket object, should be connected. buf: String, zer...
java
public static Integer getIntValue(@NonNull byte[] value, @IntFormatType int formatType, @IntRange(from = 0) int offset) { if ((offset + getTypeLen(formatType)) > value.length) { RxBleLog.w( "Int formatType (0x%x) is longer than remaining bytes (%d) - returning null", formatType, ...
python
def mini(description, **kwargs): """Single notification function Simple notification function in one line. Has only one required parameter and attempts to use reasonable defaults for everything else :param string description: Notification message """ kwargs['notifierFactory'] = GrowlNotifier gntp.notifier.mini(...
java
@Indexable(type = IndexableType.DELETE) @Override public CPDisplayLayout deleteCPDisplayLayout( CPDisplayLayout cpDisplayLayout) { return cpDisplayLayoutPersistence.remove(cpDisplayLayout); }
python
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Set html field with correct iframe. """ if self.url: iframe_html = '<iframe src="{}" frameborder="0" title="{}" allowfullscreen></iframe>' self.html = iframe_html.format( s...
python
def _init_math_handler(self): """ Parse math configuration and set up math handler. """ fields = self.settings.math_output.split(None, 1) name = fields[0].lower() option = fields[1] if len(fields) > 1 else None if name == 'html': option = self.settings...
python
def equation_of_time_spencer71(dayofyear): """ Equation of time from Duffie & Beckman and attributed to Spencer (1971) and Iqbal (1983). The coefficients correspond to the online copy of the `Fourier paper`_ [1]_ in the Sundial Mailing list that was posted in 1998 by Mac Oglesby from his corres...
python
def add(self, *matches, **kw): # kw=default=None, boolean=False '''Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous,...
java
public static void write(Path self, String text) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(Files.newOutputStream(self), Charset.defaultCharset()); writer.write(text); writer.flush(); Writer temp = writer; ...
python
def construct_schema_validators(schema, context): """ Given a schema object, construct a dictionary of validators needed to validate a response matching the given schema. Special Cases: - $ref: These validators need to be Lazily evaluating so that circular validation dep...
java
public void visitApply(JCMethodInvocation tree) { setTypeAnnotationPositions(tree.pos); // Generate code for method. Item m = genExpr(tree.meth, methodType); // Generate code for all arguments, where the expected types are // the parameters of the method's external type (that is,...
python
def OneHot(*xs, simplify=True, conj=True): """ Return an expression that means "exactly one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] ...
java
public <I extends Request, O extends Response> LoggingClient<I, O> build(Client<I, O> delegate) { return new LoggingClient<>(delegate, requestLogLevel(), successfulResponseLogLevel(), failedResponseLogLevel(...
java
public <E> Predicate<E> toEntityPredicate(EntityAccessor<E> accessor) { return entityPredicate(constraints, schema, accessor, strategy); }