language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def values_for(self, k): """ Each value with name `k`. """ return [getattr(frame, k) for frame in self.stack if hasattr(frame, k)]
java
public BeanComparator<T> reverse() { BeanComparator<T> bc = new BeanComparator<T>(this); bc.mOrderByName = mOrderByName; bc.mUsingComparator = mUsingComparator; bc.mFlags = mFlags ^ 0x01; return bc; }
java
public static DatatypeFactory getDTF() { DatatypeFactory dtf = threadDTF.get(); if (dtf == null) { try { dtf = DatatypeFactory.newInstance(); } catch (Exception e) { throw wrap(e); } threadDTF.set(dtf); } ret...
java
public AddressDataType getAddressDataType(ProposalPersonContract person) { AddressDataType addressType = AddressDataType.Factory.newInstance(); if (person != null) { String street1 = person.getAddressLine1(); addressType.setStreet1(street1); String street2 = person....
python
def to_tnw(orbit): """In the TNW Local Orbital Reference Frame, x is oriented along the velocity vector, z along the angular momentum, and y complete the frame. Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to TNW. >>> delta_tnw ...
java
public BranchEvent setAdType(AdType adType) { return addStandardProperty(Defines.Jsonkey.AdType.getKey(), adType.getName()); }
java
public File getFile() throws IOException { // Try the permission hack if (checkConnection()) { Permission perm = _connection.getPermission(); if (perm instanceof java.io.FilePermission) return new File(perm.getName()); } // Try...
java
private void validateXmlHeaderFragment(String receivedHeaderData, String controlHeaderData, XmlMessageValidationContext validationContext, TestContext context) { log.debug("Start XML header data validation ..."); Document received = XMLUtils.parseMessagePayload(receivedHeaderData); ...
java
private boolean verifyNodeRegistration(DatanodeRegistration nodeReg, String ipAddr) throws IOException { assert (hasWriteLock()); return inHostsList(nodeReg, ipAddr); }
java
public static callhome get(nitro_service service) throws Exception{ callhome obj = new callhome(); callhome[] response = (callhome[])obj.get_resources(service); return response[0]; }
java
public String getImageUrl() { if (thumbnailUrl != null) { return thumbnailUrl; } if (image != null) { return image.url; } return null; }
python
def toggle_class(self, csscl): """Same as jQuery's toggleClass function. It toggles the css class on this element.""" self._stable = False action = ("add", "remove")[self.has_class(csscl)] return getattr(self.attrs["klass"], action)(csscl)
java
public String pfop(String bucket, String key, String fops) throws QiniuException { return pfop(bucket, key, fops, null); }
java
public void removeFromSet (String setName, Comparable<?> key) { requestEntryRemove(setName, getSet(setName), key); }
java
public static <K, V> Func1<Iterable<Map.Entry<K, V>>, SolidMap<K, V>> toSolidMap() { return new Func1<Iterable<Map.Entry<K, V>>, SolidMap<K, V>>() { @Override public SolidMap<K, V> call(Iterable<Map.Entry<K, V>> iterable) { return new SolidMap<>(stream(iterable).map(new F...
java
public void delete(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) { if (mapping.get_id() != null) { getBulk().add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), pkVal.toString())); commitBulk(); } else { SearchResponse respon...
java
private int getPackedPosition(final int position) { if (position < getHeaderViewsCount()) { return position; } else { Pair<Integer, Integer> pair = getItemPosition(position - getHeaderViewsCount()); int groupIndex = pair.first; int childIndex = pair.second...
python
def _register_parser(cls): '''class decorator to register msg parser''' assert cls.cls_msg_type is not None assert cls.cls_msg_type not in _MSG_PARSERS _MSG_PARSERS[cls.cls_msg_type] = cls.parser return cls
python
def index(): """main functionality of webserver""" default = ["pagan", "python", "avatar", "github"] slogan = request.forms.get("slogan") if not slogan: if request.get_cookie("hist1"): slogan = request.get_cookie("hist1") else: slogan = "pagan" if not reques...
python
def hypo_list(nodes): """ :param nodes: a hypoList node with N hypocenter nodes :returns: a numpy array of shape (N, 3) with strike, dip and weight """ check_weights(nodes) data = [] for node in nodes: data.append([node['alongStrike'], node['downDip'], node['weight']]) return num...
python
def barycentric(points): '''Inverse of :func:`cartesian`.''' points = np.asanyarray(points) ndim = points.ndim if ndim == 1: points = points.reshape((1,points.size)) c = (2/np.sqrt(3.0))*points[:,1] b = (2*points[:,0] - c)/2.0 a = 1.0 - c - b out = np.vstack([a,b,c]).T if ndi...
python
def __get_document(self, content): """ Returns a `QTextDocument <http://doc.qt.nokia.com/qtextdocument.html>`_ class instance with given content. :return: Document. :rtype: QTextDocument """ document = QTextDocument(QString(content)) document.clearUndoRe...
java
public static RuntimeException codeBug(String msg) throws RuntimeException { msg = "FAILED ASSERTION: " + msg; RuntimeException ex = new IllegalStateException(msg); // Print stack trace ASAP ex.printStackTrace(System.err); throw ex; }
java
public static StatusUpdate instantiateStatusUpdate( final String typeIdentifier, final FormItemList values) throws StatusUpdateInstantiationFailedException { final StatusUpdateTemplate template = getStatusUpdateTemplate(typeIdentifier); final Class<?> templateInstantiationClass = template .getInstantiatio...
python
def update_in_hdx(self, **kwargs): # type: (Any) -> None """Check if resource exists in HDX and if so, update it Args: **kwargs: See below operation (string): Operation to perform eg. patch. Defaults to update. Returns: None """ self....
java
public void insert(final short[] argin, final int dim_x, final int dim_y) { attrval.r_dim.dim_x = dim_x; attrval.r_dim.dim_y = dim_y; DevVarShortArrayHelper.insert(attrval.value, argin); }
java
public alluxio.grpc.CompleteFilePOptions getOptions() { return options_ == null ? alluxio.grpc.CompleteFilePOptions.getDefaultInstance() : options_; }
java
public void setPicker(GVRPicker picker) { if (mPicker != null) { mPicker.setEnable(false); } mPicker = picker; }
java
public void marshall(AdminSetUserSettingsRequest adminSetUserSettingsRequest, ProtocolMarshaller protocolMarshaller) { if (adminSetUserSettingsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def GetPathFromLink(resource_link, resource_type=''): """Gets path from resource link with optional resource type :param str resource_link: :param str resource_type: :return: Path from resource link with resource type appended (if provided). :rtype: str """ resource_link = TrimBegi...
java
@Override public Long generate() { // get maximum identifier we can use (before obtaining new identifier to make sure it is in the current pool) long max = maximum.get(); // generate new identifier long identifier = atomicLong.incrementAndGet(); // check we need to obtain new...
java
private void createImageAndGraphics(int layer) { layeredImage[layer] = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB); layeredGraphics[layer] = layeredImage[layer].createGraphics(); layeredGraphics[layer].setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_AN...
java
public void setSecurityControllerMap(Map map) { for( Iterator i = map.entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry) i.next(); registerSecurityControllerAlias( (String) entry.getKey(), (SecurityController) entry.getValue() ); } }
python
def remove_step_method(self, step_method): """ Removes a step method. """ try: for s in step_method.stochastics: self.step_method_dict[s].remove(step_method) if hasattr(self, "step_methods"): self.step_methods.discard(step_method) ...
java
@Override public String getPortletOutput( IPortletWindowId portletWindowId, HttpServletRequest request, HttpServletResponse response) { final IPortletRenderExecutionWorker tracker = getRenderedPortletBodyWorker(portletWindowId, request, response); ...
java
@Override public <G> Choice6<A, B, C, D, E, G> flatMap( Function<? super F, ? extends Monad<G, Choice6<A, B, C, D, E, ?>>> fn) { return match(Choice6::a, Choice6::b, Choice6::c, Choice6::d, Choice6::e, f -> fn.apply(f).coerce()); }
java
public Vector2d normalizedPositiveX(Vector2d dir) { dir.x = m11; dir.y = -m01; return dir; }
java
private static <T> T createCustomComponent(Class<T> componentType, String componentSpec, Map<String, String> configProperties, IPluginRegistry pluginRegistry, T defaultComponent) throws Exception { if (componentSpec == null && defaultComponent == null) { throw new IllegalArgumentExceptio...
java
public DiscoverItems discoverCommands(Jid jid) throws XMPPException, SmackException, InterruptedException { return serviceDiscoveryManager.discoverItems(jid, NAMESPACE); }
python
def group_attrib(self): ''' return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member ''' group_attributes = [g.attrib for g in self.dataset.groups if self in g] if ...
python
def category(self) -> Optional[str]: '''Determine the category of existing statement''' if self.statements: if self.statements[-1][0] == ':': # a hack. ... to avoid calling isValid recursively def validDirective(): if not self.values: ...
java
static AtomTypePattern[] loadPatterns(InputStream smaIn) throws IOException { List<AtomTypePattern> matchers = new ArrayList<AtomTypePattern>(); BufferedReader br = new BufferedReader(new InputStreamReader(smaIn)); String line = null; while ((line = br.readLine()) != null) { ...
python
def addNodeLabelPrefix(self, prefix=None, copy=False): ''' Rename all nodes in the network from x to prefix_x. If no prefix is given, use the name of the graph as the prefix. The purpose of this method is to make node names unique so that composing two graphs is well-de...
python
def add_view_permissions(sender, verbosity, **kwargs): """ This post_syncdb/post_migrate hooks takes care of adding a view permission too all our content types. """ from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission for content_type ...
java
public static void setSpinnerDraggingEnabled( final JSpinner spinner, boolean enabled) { SpinnerModel spinnerModel = spinner.getModel(); if (!(spinnerModel instanceof SpinnerNumberModel)) { throw new IllegalArgumentException( "Dragging is only possi...
java
public static void add(final DMatrixD1 a , final DMatrixD1 b , final DMatrixD1 c ) { if( a.numCols != b.numCols || a.numRows != b.numRows ) { throw new MatrixDimensionException("The matrices are not all the same dimension."); } c.reshape(a.numRows,a.numCols); final int ...
java
private static boolean multiPointDisjointEnvelope_(MultiPoint multipoint_a, Envelope envelope_b, double tolerance, ProgressTracker progress_tracker) { Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D(); multipoint_a.queryEnvelope2D(env_a); envelope_b.queryEnvelope2D(env_b); if (envelopeInfCont...
java
public static Builder builder() { return new AutoValue_StackdriverStatsConfiguration.Builder() .setProjectId(DEFAULT_PROJECT_ID) .setConstantLabels(DEFAULT_CONSTANT_LABELS) .setExportInterval(DEFAULT_INTERVAL) .setMonitoredResource(DEFAULT_RESOURCE); }
java
private static String cleanPath(final Event event) throws RepositoryException { // remove any trailing data for property changes final String path = PROPERTY_TYPES.contains(event.getType()) ? event.getPath().substring(0, event.getPath().lastIndexOf("/")) : event.getPath(); // reform...
java
protected void readPersons() { try { final LoginContext login = new LoginContext( getApplicationName(), new LoginCallbackHandler(ActionCallback.Mode.ALL_PERSONS, null, null)); login.login(); for (final JAASSystem system : JAASSyste...
java
public void setXmlContentTypeManager(CmsXmlContentTypeManager manager) { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_VFS_XML_CONTENT_FINISHED_0)); } m_xmlContentTypeManager = manager; }
java
public void getGuildLogInfo(String id, String api, Callback<List<GuildLog>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildLogInfo(id, api).enqueue(callback); }
python
def make_sh_output(value, output_script, witness=False): ''' int, str -> TxOut ''' return _make_output( value=utils.i2le_padded(value, 8), output_script=make_sh_output_script(output_script, witness))
python
def loadTexture_Async(self, textureId): """Loads and returns a texture for use in the application.""" fn = self.function_table.loadTexture_Async ppTexture = POINTER(RenderModel_TextureMap_t)() result = fn(textureId, byref(ppTexture)) return result, ppTexture
java
public byte[] computeSharedSecret(Key key) throws InvalidKeyException { keyAgreement.doPhase(key, true); return keyAgreement.generateSecret(); }
java
@Override public final <T> void updateEntity( final Map<String, Object> pAddParam, final T pEntity) throws Exception { ColumnsValues columnsValues = evalColumnsValues(pAddParam, pEntity); String whereStr = evalWhereForUpdate(pEntity, columnsValues); prepareColumnValuesForUpdate(columnsValues, pE...
java
public static int getSystemProperty (String key, int defval) { String valstr = System.getProperty(key); int value = defval; if (valstr != null) { try { value = Integer.parseInt(valstr); } catch (NumberFormatException nfe) { log.warning(...
python
def _post_tags(self, fileobj): """Raises ogg.error""" page = OggPage.find_last(fileobj, self.serial, finishing=True) if page is None: raise OggVorbisHeaderError self.length = page.position / float(self.sample_rate)
java
public void bindView(final MessageCenterFragment fragment, final MessageCenterRecyclerViewAdapter adapter, final Composer composer) { title.setText(composer.title); title.setContentDescription(composer.title); closeButton.setOnClickListener(guarded(new View.OnClickListener() { public void onClick(View view) {...
java
public void useNewSOAPServiceWithOldClientAndRedirection() throws Exception { URL wsdlURL = getClass().getResource("/CustomerService.wsdl"); com.example.customerservice.CustomerServiceService service = new com.example.customerservice.CustomerServiceService(wsdlURL); com.exa...
java
public synchronized TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException { return indexSearcher.search(query, maxQueryResults); }
python
def _download_without_backoff(url, as_file=True, method='GET', **kwargs): """ Get the content of a URL and return a file-like object. """ # Make requests consistently hashable for caching. # 'headers' is handled by requests itself. # 'cookies' and 'proxies' contributes to headers. # 'files' ...
java
public void setDestinationName(final String destinationName) { if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(this, TRACE, "DestinationName", destinationName); } _destinationName = destinationName; }
python
def random_codebuch(path): """Generate a month-long codebuch and save it to a file.""" lines = [] for i in range(31): line = str(i+1) + " " # Pick rotors all_rotors = ['I', 'II', 'III', 'IV', 'V'] rotors = [random.choice(all_rotors)] while len(rotors) < 3: ...
python
def _visit_or_none(node, attr, visitor, parent, visit="visit", **kws): """If the given node has an attribute, visits the attribute, and otherwise returns None. """ value = getattr(node, attr, None) if value: return getattr(visitor, visit)(value, parent, **kws) return None
java
private static String readScript(EncodedResource resource, String commentPrefix, String separator) throws IOException { LineNumberReader lnr = new LineNumberReader(resource.getReader()); try { return readScript(lnr, commentPrefix, separator); } finally { lnr....
python
def pad(attrs, inputs, proto_obj): """ Add padding to input tensor""" new_attrs = translation_utils._fix_attribute_names(attrs, {'pads' : 'pad_width', 'value' : 'constant_value' }) n...
java
@Override public final String renderAsPhrase() { final Place place = placeRenderer.getGedObject(); return GedRenderer.escapeString(place.getString()); }
java
@Override public boolean removeAll(Collection<?> candidateElements) { boolean didRemoveAny = false; for (Object nextCandidate : candidateElements) { if (remove(nextCandidate)) { didRemoveAny = true; } } return didRemoveAny; }
java
public String getMinDateCreated() { if (m_searchParams.getMinDateCreated() == Long.MIN_VALUE) { return ""; } return Long.toString(m_searchParams.getMinDateCreated()); }
java
protected static <E extends LogRecordHandler> boolean removeHandler(Class<E> toRemove) { boolean rtn = false; Iterator<LogRecordHandler> iter = handlers.iterator(); while(iter.hasNext()){ if(iter.next().getClass().equals(toRemove)){ rtn = true; iter.remove(); } } ...
python
def get_data_range(self, name): """Gets the min/max of a scalar given its name across all blocks""" mini, maxi = np.inf, -np.inf for i in range(self.n_blocks): data = self[i] if data is None: continue # get the scalar if availble ar...
python
def printable(data): """ Replace unprintable characters with dots. @type data: str @param data: Binary data. @rtype: str @return: Printable text. """ result = '' for c in data: if 32 < ord(c) < 128: result += c ...
java
public byte getByte( String key, byte defaultValue ) throws MissingResourceException { try { return getByte( key ); } catch( MissingResourceException mre ) { return defaultValue; } }
java
public void setReferenceObject(Reference bindingObject, Class<? extends ObjectFactory> objectFactory) throws InjectionException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) T...
java
public void setForecastResultsByTime(java.util.Collection<ForecastResult> forecastResultsByTime) { if (forecastResultsByTime == null) { this.forecastResultsByTime = null; return; } this.forecastResultsByTime = new java.util.ArrayList<ForecastResult>(forecastResultsByTime...
java
private <T extends AmazonWebServiceRequest> Request<T> marshall( T awsRequest, Marshaller<Request<T>, T> marshaller, AWSRequestMetrics awsRequestMetrics) { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { return marshaller.marshall(awsRequest...
python
def _get_version_from_git_tag(path): """Return a PEP440-compliant version derived from the git status. If that fails for any reason, return the changeset hash. """ m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '') if m is None: return None version, post_commit, hash = m.groups...
java
public static void post(String path, String acceptType, Route route) { getInstance().post(path, acceptType, route); }
java
public void copyResourceToProject(CmsRequestContext context, CmsResource resource) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkManagerOfProjectRole(dbc, context.getCurrentP...
python
def call(self, op_name, query=None, **kwargs): """ Make a request to a method in this client. The response data is returned from this call as native Python data structures. This method differs from just calling the client method directly in the following ways: * It a...
python
def main(name, options): """The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str """ server = config._config_value("general", "server", o...
python
def _run_step(step_obj, step_declaration, initialized_resources): """Actually run a step.""" start_time = time.time() # Open any resources that need to be opened before we run this step for res_name in step_declaration.resources.opened: initialized_resources[res_name].open() # Create a di...
java
<T> InjectScope<T> scope(Class<? extends Annotation> scopeType) { Supplier<InjectScope<T>> scopeGen = (Supplier) _scopeMap.get(scopeType); if (scopeGen == null) { throw error("{0} is an unknown scope", scopeType.getSimpleName()); } return scopeGen.get(); }
python
def invert_map(map): """ Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceba...
java
public static QName getQualifiedName(Object obj) { return new QName(STIXSchema.getNamespaceURI(obj), STIXSchema.getName(obj)); }
java
public static ViewGroup buildStickyDrawerItemFooter(Context ctx, DrawerBuilder drawer, View.OnClickListener onClickListener) { //create the container view final LinearLayout linearLayout = new LinearLayout(ctx); linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MA...
python
def check_starts_with_this(self, function, docstring): """D404: First word of the docstring should not be `This`. Docstrings should use short, simple language. They should not begin with "This class is [..]" or "This module contains [..]". """ if docstring: first_wo...
java
private Set<JSModule> getTransitiveDeps(JSModule m) { Set<JSModule> deps = dependencyMap.computeIfAbsent(m, JSModule::getAllDependencies); return deps; }
python
def warn_on_deprecated_args(self, args): """ Print warning messages for any deprecated arguments that were passed. """ # Output warning if setup.py is present and neither --ignore-setup-py # nor --use-setup-py was specified. if getattr(args, "private", None) is not None ...
java
public static <T> TimestampedValue<T> from(StreamRecord<T> streamRecord) { if (streamRecord.hasTimestamp()) { return new TimestampedValue<>(streamRecord.getValue(), streamRecord.getTimestamp()); } else { return new TimestampedValue<>(streamRecord.getValue()); } }
python
def program_files(self, executable): """ OPTIONAL, this method is only necessary for situations when the benchmark environment needs to know all files belonging to a tool (to transport them to a cloud service, for example). Returns a list of files or directories that are necessar...
python
def attachFile(self, CorpNum, ItemCode, MgtKey, FilePath, UserID=None): """ ํŒŒ์ผ ์ฒจ๋ถ€ args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ ItemCode : ๋ช…์„ธ์„œ ์ข…๋ฅ˜ ์ฝ”๋“œ [121 - ๊ฑฐ๋ž˜๋ช…์„ธ์„œ], [122 - ์ฒญ๊ตฌ์„œ], [123 - ๊ฒฌ์ ์„œ], [124 - ๋ฐœ์ฃผ์„œ], [125 - ์ž…๊ธˆํ‘œ], [126 - ์˜์ˆ˜์ฆ] ...
python
def get_assessment_ids_by_bank(self, bank_id): """Gets the list of ``Assessment`` ``Ids`` associated with a ``Bank``. arg: bank_id (osid.id.Id): ``Id`` of the ``Bank`` return: (osid.id.IdList) - list of related assessment ``Ids`` raise: NotFound - ``bank_id`` is not found r...
python
def keybundle_from_local_file(filename, typ, usage): """ Create a KeyBundle based on the content in a local file :param filename: Name of the file :param typ: Type of content :param usage: What the key should be used for :return: The created KeyBundle """ usage = harmonize_usage(us...
python
def fire(self, args, kwargs): """ Fire this signal with the specified arguments and keyword arguments. Typically this is used by using :meth:`__call__()` on this object which is more natural as it does all the argument packing/unpacking transparently. """ for inf...
java
@Override public RequestCertificateResult requestCertificate(RequestCertificateRequest request) { request = beforeClientExecution(request); return executeRequestCertificate(request); }
python
def parse_optional_matrix(x): """Parse optional NRRD matrix from string into (M,N) :class:`numpy.ndarray` of :class:`float`. Function parses optional NRRD matrix from string into an (M,N) :class:`numpy.ndarray` of :class:`float`. This function works the same as :meth:`parse_matrix` except if a row vector i...
java
@Path("/{dsID}/content") @GET public Response getDatastream(@PathParam(RestParam.PID) String pid, @PathParam(RestParam.DSID) String dsID, @QueryParam(RestParam.AS_OF_DATE_TIME) String dateTime, @QueryParam(Rest...
java
@CheckForNull public T newInstanceFromRadioList(JSONObject config) throws FormException { if(config.isNullObject()) return null; // none was selected int idx = config.getInt("value"); return get(idx).newInstance(Stapler.getCurrentRequest(),config); }