language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def _build_comments(self, soup):
"""
For the story, builds and returns a list of Comment objects.
"""
comments = []
current_page = 1
while True:
# Get the table holding all comments:
if current_page == 1:
table = soup.f... |
python | def uninstall_handler(self, event_type, handler, user_handle=None):
"""Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handl... |
java | protected int binarySearch (int x)
{
// copied from java.util.Arrays which I wouldn't have to have done had the provided a
// means by which to binarySearch in a subset of an array. alas.
int low = 0;
int high = _size-1;
while (low <= high) {
int mid = (low + hig... |
python | def write_fits(self, fitsfile):
"""Write the ROI model to a FITS file."""
tab = self.create_table()
hdu_data = fits.table_to_hdu(tab)
hdus = [fits.PrimaryHDU(), hdu_data]
fits_utils.write_hdus(hdus, fitsfile) |
python | async def discover_slave(self, service, timeout, **kwargs):
"""Perform Slave discovery for specified service."""
# TODO: use kwargs to change how slaves are picked up
# (eg: round-robin, priority, random, etc)
idle_timeout = timeout
pools = self._pools[:]
for sentinel i... |
java | private ResultPoint[] detectSolid2(ResultPoint[] points) {
// A..D
// : :
// B--C
ResultPoint pointA = points[0];
ResultPoint pointB = points[1];
ResultPoint pointC = points[2];
ResultPoint pointD = points[3];
// Transition detection on the edge is not stable.
// To safely detect, ... |
java | public void clear() {
boolean done = false;
while (!done) {
ReceiveMessageBatchTask currentBatch = null;
synchronized (finishedTasks) {
currentBatch = finishedTasks.poll();
}
if (currentBatch != null) {
currentBatch.clear()... |
python | def _load_feed(path: str, view: View, config: nx.DiGraph) -> Feed:
"""Multi-file feed filtering"""
config_ = remove_node_attributes(config, ["converters", "transformations"])
feed_ = Feed(path, view={}, config=config_)
for filename, column_filters in view.items():
config_ = reroot_graph(config_,... |
java | protected Charset setContentType(MediaType mediaType, MultivaluedMap<String, Object> httpHeaders) {
String charset = mediaType.getParameters().get("charset");
Charset encoding;
MediaType finalMediaType;
if (charset == null) {
encoding = this.getEncoding();
HashMap... |
java | public static void copy(InputStream is, File file) throws IOException {
Asserts.notNullParameter("is", is);
Asserts.notNullParameter("file", file);
FileOutputStream os = null;
os = new FileOutputStream(file);
copy(is, os);
} |
java | public static void invoke(Class<?> type, String methodName, Object... arguments) {
invoke(type, methodName, getArgumentTypes(arguments), arguments, Void.class);
} |
python | def put(self, udid):
''' finish task '''
data = tornado.escape.json_decode(self.request.body)
id = data['id']
result = data['result']
if self.results.get(id) is None:
self.results[id] = result
else:
that = self.results[id]
that.write(js... |
java | public Query queryEntityConnectionsWithinLocation(
String connectingEntityType, String connectingEntityId,
String connectionType, float distance, float lattitude,
float longitude, String ql) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("ql"... |
python | def load_library(self):
"loads configuration options"
try:
filename = self.environment.get_template('chartkick.json').filename
except TemplateNotFound:
return {}
else:
options = Options()
options.load(filename)
return options |
python | def p_union_patch(self, p):
"""union_patch : PATCH uniont ID NL INDENT field_list examples DEDENT"""
p[0] = AstUnionPatch(
path=self.path,
lineno=p[2][1],
lexpos=p[2][2],
name=p[3],
fields=p[6],
examples=p[7],
closed=p[2... |
java | public PropertyRequest addProperty(ElementDescriptor<?> property)
{
if (mProp == null)
{
mProp = new HashMap<ElementDescriptor<?>, Object>(16);
}
mProp.put(property, null);
return this;
} |
java | public boolean photos_addTag(Long photoId, Integer taggedUserId, Double xPct, Double yPct)
throws FacebookException, IOException {
return photos_addTag(photoId, xPct, yPct, taggedUserId, null);
} |
python | def PrintField(self, field, value):
"""Print a single field name/value pair."""
out = self.out
out.write(' ' * self.indent)
if self.use_field_number:
out.write(str(field.number))
else:
if field.is_extension:
out.write('[')
if (field.containing_type.GetOptions().message_se... |
python | def get_document_field_display(self, field_name, field):
""" Render a link to a document """
document = getattr(self.instance, field_name)
if document:
return mark_safe(
'<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % (
document.url,
... |
java | private void copyJarDependencies (State state) throws IOException {
if (this.tmpJobDir == null) {
throw new RuntimeException("Job directory is not created");
}
if (!state.contains(ConfigurationKeys.JOB_JAR_FILES_KEY)) {
return;
}
// create sub-dir to save jar files
LocalFileSystem ... |
java | public Date getFirstDateInCalendar(Date dateTarget)
{
// Now get the first box on the calendar
int iFirstDayOfWeek = calendar.getFirstDayOfWeek();
calendar.setTime(dateTarget);
int iTargetDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int iOffset = -Math.abs(iTargetDayOfWeek... |
java | @Override
public void debug(Object object) {
if (level <= DEBUG) {
if (object instanceof Throwable) {
debugThrowable((Throwable) object);
} else {
debugString("" + object);
}
}
} |
python | def do_default(value, default_value=u'', boolean=False):
"""If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if th... |
java | public List<IndustryFacilitiesResponse> getIndustryFacilities(String datasource, String ifNoneMatch)
throws ApiException {
ApiResponse<List<IndustryFacilitiesResponse>> resp = getIndustryFacilitiesWithHttpInfo(datasource, ifNoneMatch);
return resp.getData();
} |
java | public synchronized void write(DataOutput out) throws IOException {
jobid.write(out);
out.writeFloat(setupProgress);
out.writeFloat(mapProgress);
out.writeFloat(reduceProgress);
out.writeFloat(cleanupProgress);
out.writeInt(runState);
out.writeLong(startTime);
Text.writeString(out, user)... |
python | def add_thellier_gui_criteria(self):
'''criteria used only in thellier gui
these criteria are not written to pmag_criteria.txt
'''
category = "thellier_gui"
for crit in ['sample_int_n_outlier_check', 'site_int_n_outlier_check']:
self.acceptance_criteria[crit] = {}
... |
java | public final String aggFunc() throws RecognitionException {
String name = null;
try {
// druidG.g:470:2: ( LONG_SUM | DOUBLE_SUM | UNIQUE | HYPER_UNIQUE | MIN | MAX | JAVASCRIPT )
int alt199=7;
switch ( input.LA(1) ) {
case LONG_SUM:
{
alt199=1;
}
break;
case DOUBLE_SUM:
{
a... |
java | public void marshall(TrialMinutes trialMinutes, ProtocolMarshaller protocolMarshaller) {
if (trialMinutes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(trialMinutes.getTotal(), TOTAL_BINDING);
... |
python | def read_manifest(self, encrypted=None):
"""
Read an existing manifest.
"""
with open(self.manifest_path, 'r') as input_file:
self.manifest = yaml.safe_load(input_file)
if 'env' not in self.manifest:
self.manifest['env'] = {}
if 'servic... |
python | def _get_bounds(self, ib, dimension):
"""ib == 0/1 means lower/upper bound, return a vector of length
`dimension` """
sign_ = 2 * ib - 1
assert sign_**2 == 1
if self.bounds is None or self.bounds[ib] is None:
return array(dimension * [sign_ * np.Inf])
res = []... |
python | def recursive_children(self):
"""
Generator returning all recursive children elements.
"""
for child in self.children:
yield child
for recursive_child in child.recursive_children:
yield recursive_child |
java | @Override
public UpdateProjectResult updateProject(UpdateProjectRequest request) {
request = beforeClientExecution(request);
return executeUpdateProject(request);
} |
java | public ConfigRenderOptions setComments(boolean value) {
if (value == comments)
return this;
else
return new ConfigRenderOptions(originComments, value, formatted, json);
} |
java | @Override
protected void processRecord(Tuple2<Boolean, Row> change) {
synchronized (resultLock) {
// insert
if (change.f0) {
processInsert(change.f1);
}
// delete
else {
processDelete(change.f1);
}
}
} |
python | def _update_zone_tracker(self, message):
"""
Trigger an update of the :py:class:`~alarmdecoder.messages.Zonetracker`.
:param message: message to update the zonetracker with
:type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py... |
java | @SuppressWarnings ({ "rawtypes", "unchecked" })
private final void processQueue () {
SoftValue<V> softValue;
while ((softValue = (SoftValue) queue.poll()) != null) {
internalMap.remove(softValue.key);
}
} |
python | def make_reply(msgname, types, arguments, major):
"""Helper method for constructing a reply message from a list or tuple.
Parameters
----------
msgname : str
Name of the reply message.
types : list of kattypes
The types of the reply message parameters (in order).
arguments : lis... |
python | def translate_command(val):
'''
Input should either be a single string, or a list of strings. This is used
for the two args that deal with commands ("command" and "entrypoint").
'''
if isinstance(val, six.string_types):
return val
elif isinstance(val, list):
for idx in range(len(... |
python | def crps(self):
"""
Calculates the continuous ranked probability score.
"""
return np.sum(self.errors["F_2"].values - self.errors["F_O"].values * 2.0 + self.errors["O_2"].values) / \
(self.thresholds.size * self.num_forecasts) |
java | public static boolean argEquals(LDblToByteFuncMemento the, Object that) {
return Null.<LDblToByteFuncMemento> equals(the, that, (one, two) -> {
if (one.getClass() != two.getClass()) {
return false;
}
LDblToByteFuncMemento other = (LDblToByteFuncMemento) two;
return LObjBytePair.argEquals(one.functio... |
java | @SuppressWarnings("unchecked")
private boolean trySetValue(List<?> datas, Object pojo, CustomPropertyDescriptor field,
Class<? extends Collection> clazz) {
log.debug("要赋值的fieldName为{}", field.getName());
Collection collection = tryBuildCollection(clazz);
if (... |
python | def process_fastq_plain(fastq, **kwargs):
"""Combine metrics extracted from a fastq file."""
logging.info("Nanoget: Starting to collect statistics from plain fastq file.")
inputfastq = handle_compressed_input(fastq)
return ut.reduce_memory_usage(pd.DataFrame(
data=[res for res in extract_from_fa... |
python | def write(self, filename, format='tar', write_detection_catalog=True,
catalog_format="QUAKEML", debug=0):
"""
Write Family out, select output format.
:type format: str
:param format:
One of either 'tar', 'csv', or any obspy supported
catalog output.... |
java | void sendHeaderAndCounterNameAndRead(Channel channel) {
ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, 0);
channel.writeAndFlush(buf);
} |
java | public void setAddress(final String address) {
this.address = address == null ? null : URI.create(address);
} |
java | protected ValidationListener registerMessageReceiver(String propertyName, Messagable messageReceiver) {
MessagableValidationListener messagableValidationListener = new MessagableValidationListener(propertyName,
messageReceiver);
validationResults.addValidationListener(propertyName, messagableValidationListener)... |
java | public Observable<Tag> createTagAsync(UUID projectId, String name, CreateTagOptionalParameter createTagOptionalParameter) {
return createTagWithServiceResponseAsync(projectId, name, createTagOptionalParameter).map(new Func1<ServiceResponse<Tag>, Tag>() {
@Override
public Tag call(Service... |
java | public void onHttpClientUpgrade() throws Http2Exception {
if (connection().isServer()) {
throw connectionError(PROTOCOL_ERROR, "Client-side HTTP upgrade requested for a server");
}
if (!prefaceSent()) {
// If the preface was not sent yet it most likely means the handler w... |
python | def create_session(self, alias, url, headers={}, cookies={},
auth=None, timeout=None, proxies=None,
verify=False, debug=0, max_retries=3, backoff_factor=0.10, disable_warnings=0):
""" Create Session: create a HTTP session to a server
``url`` Base url of the... |
python | def inferThalamus(t, l6Input, ffInput):
"""
Compute the effect of this feed forward input given the specific L6 input.
:param t: instance of Thalamus
:param l6Input:
:param ffInput: a numpy array of 0's and 1's
:return:
"""
print("\n-----------")
t.reset()
t.deInactivateCells(l6Input)
ffOutput = ... |
python | def from_string(html_str, url=None):
"Creates a new CourseCatalog instance from an string containing xml."
return CourseCatalog(BeautifulSoup(_remove_divs(html_str),
convertEntities=BeautifulSoup.HTML_ENTITIES
), url) |
python | def cycles(self):
"""
Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ... |
python | def parse(self):
"""Parse the metadata.rb into a dict."""
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
depends = {}
for line in data:
if not len(line) == 2:
continue
... |
java | public void init(RecordOwner recordOwner)
{
m_dbEditMode = Constants.EDIT_NONE;
m_listener = null;
m_bDisplayOption = true;
m_depScreens = null; // List of all Dependent screens (doesn't include m_recordOwner)
m_recordOwner = recordOwner;
this.getTable(); /... |
java | public void setUseChartDataTextColor(final boolean USE) {
if (null == useChartDataTextColor) {
_useChartDataTextColor = USE;
redraw();
} else {
useChartDataTextColor.set(USE);
}
} |
java | public TokenSyncDate getTokenSyncDate(Integer subscriptionId) {
EntityManager entityManager = getEntityManager();
try {
List<TokenSyncDate> list = entityManager
.createQuery("SELECT syncDate FROM TokenSyncDate AS syncDate WHERE subscriptionId = :subscriptionId", TokenSyncDate.class).setMaxResult... |
java | public static Config getConfig()
{
final Configuration systemConfig = new SystemConfiguration();
final String configName = systemConfig.getString(CONFIG_PROPERTY_NAME);
final String configLocation = systemConfig.getString(CONFIG_LOCATION_PROPERTY_NAME);
Preconditions.checkState(confi... |
java | protected String getString(byte[] data, int offset) {
if (offset < 0) {
return "";
}
int i = offset;
while (data[i++] != 0x00) {
;
}
return getString(data, offset, i - offset - 1);
} |
python | def distance_to_point_on_equator(lng_rad, lat_rad, lng_rad_p1):
"""
uses the simplified haversine formula for this special case (lat_p1 = 0)
:param lng_rad: the longitude of the point in radians
:param lat_rad: the latitude of the point
:param lng_rad_p1: the latitude of the point1 on the equator (l... |
java | @Override
public ListTemplatesResult listTemplates(ListTemplatesRequest request) {
request = beforeClientExecution(request);
return executeListTemplates(request);
} |
java | private BrowserUsageData getMSIEUsageData() {
BrowserUsageData data = new BrowserUsageData();
data
.setBrowserName("MSIE");
data
.setMarketShare(55.11f);
ColorReference ieColor = new HighchartsColor(0);
data
.setColor(ieColor);
data
.getVersionUsageData()
... |
python | def _run_paired(paired):
"""Run somatic variant calling pipeline.
"""
from bcbio.structural import titancna
work_dir = _sv_workdir(paired.tumor_data)
seg_files = model_segments(tz.get_in(["depth", "bins", "normalized"], paired.tumor_data),
work_dir, paired)
call_fi... |
java | private RestrictionLevel getRestrictionLevel(String input) {
// Section 5.2 step 1:
if (!fAllowedCharsSet.containsAll(input)) {
return RestrictionLevel.UNRESTRICTIVE;
}
// Section 5.2 step 2:
if (ASCII.containsAll(input)) {
return RestrictionLevel.ASCII;
... |
python | def _get_cpu_info_internal():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns {} if nothing is found.
'''
# Get the CPU arch and bits
arch, bits = _parse_arch(DataSource.arch_string_raw)
friendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(sys.maxsize) or 'unkn... |
python | def tuple2dict(mytuple, constructor=dict):
"""
Turn a tuple as returned by dict2tuple back
into a dictionary structure. The optional
parameter "constructor" governs, what class
is used to create the dictionary: by default,
the standard dict class is used, but in DINGO
we mostly use the Dingo... |
python | def set_missing_host_key_policy(self, policy):
"""
Set policy to use when connecting to servers without a known host key.
Specifically:
* A **policy** is a "policy class" (or instance thereof), namely some
subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the
... |
python | def validate_meta(meta):
"""
Validates Linguist Meta attribute.
"""
if not isinstance(meta, (dict,)):
raise TypeError('Model Meta "linguist" must be a dict')
required_keys = ("identifier", "fields")
for key in required_keys:
if key not in meta:
raise KeyError('Model... |
java | @Nonnegative
public static int getCharacterCount (final int nValue)
{
// index is always one character less than the real size; that's why nPrefix
// is 1 more!
final int nPrefix = nValue < 0 ? 2 : 1;
final int nRealValue = MathHelper.abs (nValue);
for (int nIndex = 0;; nIndex++)
if (nRea... |
python | def kxtrct(keywd, terms, nterms, instring, termlen=_default_len_out, stringlen=_default_len_out, substrlen=_default_len_out):
"""
Locate a keyword in a string and extract the substring from
the beginning of the first word following the keyword to the
beginning of the first subsequent recognized terminat... |
java | public static void setAppThisVersionCodeLaunchCount(Context context, long appThisVersionCodeLaunchCount) {
SharedPreferences prefs = getSharedPreferences(context);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putLong(PREF_KEY_APP_LAUNCH_COUNT, appThisVersionCodeLaunchCount);... |
java | public OvhOrder hosting_web_serviceName_bandwidth_duration_GET(String serviceName, String duration, OvhBandwidthOfferEnum traffic) throws IOException {
String qPath = "/order/hosting/web/{serviceName}/bandwidth/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
query(sb, "traffic", traffic);
St... |
java | private void applyFullPagerState(float position, boolean isLeaving) {
views.fullBackground.setVisibility(position == 0f ? View.INVISIBLE : View.VISIBLE);
views.fullBackground.setAlpha(position);
views.pagerToolbar.setVisibility(position == 0f ? View.INVISIBLE : View.VISIBLE);
views.page... |
java | private boolean resizeAndSaveImage(int maxWidth, int maxHeight) throws IOException {
// Decode image file, compress and re-save it
boolean saved = false;
File targetFile = configuration.diskCache.get(uri);
if (targetFile != null && targetFile.exists()) {
ImageSize targetImageSize = new ImageSize(maxWidth, ma... |
python | def get_poes(self, sctx, rctx, dctx, imt, imls, truncation_level):
"""
Adapts the original `get_poes()` from the :class:
openquake.hazardlib.gsim.base.GMPE to call a function that take the
weighted sum of the PoEs from the epistemic uncertainty adjustment
"""
return get_w... |
java | public void onClick(MenuItemClickEvent event) {
FeatureTransaction ft = mapWidget.getMapModel().getFeatureEditor().getFeatureTransaction();
if (ft != null && index != null) {
mapWidget.render(ft, RenderGroup.VECTOR, RenderStatus.DELETE);
RemoveCoordinateOp op = new RemoveCoordinateOp(index);
ft.execute(op)... |
python | def expire(app, sandbox, exit=True):
"""Expire hits for an experiment id."""
success = []
failures = []
service = _mturk_service_from_config(sandbox)
hits = _current_hits(service, app)
for hit in hits:
hit_id = hit["id"]
try:
service.expire_hit(hit_id)
suc... |
java | public static ScheduledExecutorService newScheduledThreadPool(int size, String poolName) {
// Caller runs only occurs after shutdown, as queue size is unbounded.
ScheduledThreadPoolExecutor result = new ScheduledThreadPoolExecutor(size, getThreadFactory(poolName), new CallerRuns());
// Do not e... |
python | def proc_df(df, y_fld=None, skip_flds=None, ignore_flds=None, do_scale=False, na_dict=None,
preproc_fn=None, max_n_cat=None, subset=None, mapper=None):
""" proc_df takes a data frame df and splits off the response variable, and
changes the df into an entirely numeric dataframe. For each column of df... |
python | def getPeersByName(self, name):
'''
getPeersByName - Gets peers (elements on same level) with a given name
@param name - Name to match
@return - None if no parent element (error condition), otherwise a TagCollection of peers that matched.
'''
peers = self.pe... |
python | def register(self, user_dict):
"""Send an user_dict to NApps server using POST request.
Args:
user_dict(dict): Dictionary with user attributes.
Returns:
result(string): Return the response of Napps server.
"""
endpoint = os.path.join(self._config.get('n... |
java | void notifyNewClientConnected(Socket socket)
{
try
{
int secure = 0;
while (clients.containsKey(Byte.valueOf(lastId)))
{
lastId++;
secure++;
final int max = 127;
if (secure > max)
{
... |
java | public static CmsInlineEntityWidget createWidgetForEntity(
Element element,
I_CmsInlineFormParent formParent,
CmsEntity parentEntity,
CmsAttributeHandler attributeHandler,
int attributeIndex,
I_CmsInlineHtmlUpdateHandler htmlUpdateHandler,
I_CmsWidgetService widge... |
java | public void sort(Sorter sorter) {
if (!(mWrappedRunner instanceof Sortable)) {
return;
}
Sortable sortable = (Sortable) mWrappedRunner;
sortable.sort(sorter);
} |
java | @Generated(value={"com.threerings.presents.tools.GenDObjectTask"})
public void setLocks (DSet<NodeObject.Lock> value)
{
requestAttributeChange(LOCKS, value, this.locks);
DSet<NodeObject.Lock> clone = (value == null) ? null : value.clone();
this.locks = clone;
} |
java | public static <T1, T2, T3> TriPredicate<T1, T2, T3> and(TriPredicate<T1, T2, T3> first, TriPredicate<T1, T2, T3> second) {
dbc.precondition(first != null, "first predicate is null");
dbc.precondition(second != null, "second predicate is null");
return Logic.Ternary.and(Iterations.iterable(first,... |
java | public static int searchDescending(long[] longArray, long value) {
int start = 0;
int end = longArray.length - 1;
int middle = 0;
while(start <= end) {
middle = (start + end) >> 1;
if(value == longArray[middle]) {
return middle;
... |
python | def load_file(filename,
file_type='json',
klazz=YapconfError,
open_kwargs=None,
load_kwargs=None):
"""Load a file with the given file type.
Args:
filename (str): The filename to load.
file_type (str, optional): Defaults to 'json'. The file... |
python | def _build(self, inputs, is_training):
"""Connects the module to some inputs.
Args:
inputs: Tensor, final dimension must be equal to embedding_dim. All other
leading dimensions will be flattened and treated as a large batch.
is_training: boolean, whether this connection is to training data.... |
java | public static boolean isParentWindowFocused(Component component) {
Window window = SwingUtilities.getWindowAncestor(component);
return window != null && window.isFocused();
} |
java | protected void readContributor(Revision rev, String str) throws IOException, ArticleReaderException
{
char[] contrChars = str.toCharArray();
int size;
StringBuilder buffer = null;
this.keywords.reset();
for(char curChar:contrChars){
if (buffer != null) {
buffer.append(curChar);
}
if (this.ke... |
python | def _add_to_download_queue(self, lpath, rfile):
# type: (Downloader, pathlib.Path,
# blobxfer.models.azure.StorageEntity) -> None
"""Add remote file to download queue
:param Downloader self: this
:param pathlib.Path lpath: local path
:param blobxfer.models.azure.St... |
java | public static byte[] encodeDN(Codec codec, String distinguishedName) throws Exception {
X500Principal issuer = new X500Principal(distinguishedName);
X509CertSelector certSelector = new X509CertSelector();
certSelector.setIssuer(issuer);
byte[] asnX501DN = certSelector.getIssuerAsBytes();... |
python | def unshorten_url(short_url):
"""Unshortens the short_url or returns None if not possible."""
short_url = short_url.strip()
if not short_url.startswith('http'):
short_url = 'http://{0}'.format(short_url)
try:
cached_url = UnshortenURL.objects.get(short_url=short_url)
except Unshorte... |
java | @Override
public DEBBuilder setPostUnInstallation(String script, String interpreter)
{
setMaintainerScript("postrm", script, interpreter);
return this;
} |
python | def get_folding_model_data(
nstep, rvec0=np.zeros((5)), nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0, rcut=3.0):
r"""wrapper for the folding model generator"""
fm = FoldingModel(dt, kT, mass=mass, damping=damping, rcut=rcut)
return fm.sample(rvec0, nstep, nskip=nskip) |
python | def _process_cidr_file(self, file):
""" Iterate over ip info and extract useful data """
data = {'cidr': list(), 'countries': set(), 'city_country_mapping': dict()}
allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
for cidr_info in self._line_to_dict(file, field_names=settings.IPG... |
java | public PagedList<BlobContainerInner> listStorageContainers(final String resourceGroupName, final String accountName, final String storageAccountName) {
ServiceResponse<Page<BlobContainerInner>> response = listStorageContainersSinglePageAsync(resourceGroupName, accountName, storageAccountName).toBlocking().singl... |
java | public boolean matchesAny(String... seq) {
for (String s : seq) {
if (matches(s))
return true;
}
return false;
} |
python | def is_active(self, node):
"""Checks whether a statement is active.
An assignment is active when its right hand side contains active
variables.
Args:
node: an instance of gast.Assign
Returns:
Whether the statement is active.
"""
# Special case: If the right hand side is a pop ... |
python | def diff_halfMatch(self, text1, text2):
"""Do the two texts share a substring which is at least half the length of
the longer text?
This speedup can produce non-minimal diffs.
Args:
text1: First string.
text2: Second string.
Returns:
Five element Array, containing the prefix of t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.