language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @GET
@Path(WEBUI_WORKERS)
@ReturnType("alluxio.wire.MasterWebUIWorkers")
public Response getWebUIWorkers() {
return RestUtils.call(() -> {
MasterWebUIWorkers response = new MasterWebUIWorkers();
response.setDebug(ServerConfiguration.getBoolean(PropertyKey.DEBUG));
List<WorkerInfo> workerIn... |
python | def echo_to_output_stream(self, email_messages):
""" Write all messages to the stream in a thread-safe way. """
if not email_messages:
return
with self._lock:
try:
stream_created = self.open()
for message in email_messages:
... |
java | public synchronized void clear(ApplicationDefinition appDef) {
String appName = appDef.getAppName();
for (TableDefinition tableDef : appDef.getTableDefinitions().values()) {
m_cacheMap.remove(appName + "/" + tableDef.getTableName()); // might have no entry
}
m_appShardMa... |
java | private static void processItems(Map<DisconfKey, List<IDisconfUpdate>> inverseMap,
DisconfUpdateService disconfUpdateService, IDisconfUpdate iDisconfUpdate) {
List<String> itemKeys = Arrays.asList(disconfUpdateService.itemKeys());
// 反索引
for (String key : i... |
python | def _elementtree_to_dict(self, element):
"""Convert XML elementtree to dictionary.
Converts the actual response from the ILO for an API
to the dictionary.
"""
node = {}
text = getattr(element, 'text')
if text is not None:
text = text.strip()
... |
java | public MessagePacker packString(String s)
throws IOException
{
if (s.length() <= 0) {
packRawStringHeader(0);
return this;
}
else if (CORRUPTED_CHARSET_ENCODER || s.length() < smallStringOptimizationThreshold) {
// Using String.getBytes is gene... |
python | def edit(self, name=None, description=None, start_date=None, due_date=None, assignees=None, assignees_ids=None,
status=None):
"""Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (opti... |
java | public JsonResponse cancelBlast(Integer blastId) throws IOException {
Blast blast = new Blast();
Date d = null;
blast
.setBlastId(blastId)
.setScheduleTime(d);
return apiPost(blast);
} |
java | protected void updateAddedCount() {
SpiderScan sc = this.getSelectedScanner();
if (sc != null) {
this.getAddedCountValueLabel().setText(Integer.toString(sc.getNumberOfNodesAdded()));
} else {
this.getAddedCountValueLabel().setText(ZERO_REQUESTS_LABEL_TEXT);
}
} |
python | def create_without_data(cls, id_):
"""
根据 objectId 创建一个 leancloud.Object,代表一个服务器上已经存在的对象。可以调用 fetch 方法来获取服务器上的数据
:param id_: 对象的 objectId
:type id_: string_types
:return: 没有数据的对象
:rtype: Object
"""
if cls is Object:
raise RuntimeError('can not... |
java | public <R> R forEach(def<R> func, int index) {
return forThose($.alwaysTrue(), func, index);
} |
python | def remove(self, key, glob=False):
"""Remove key value pair in a local or global namespace."""
ns = self.namespace(key, glob)
try:
self.keyring.delete_password(ns, key)
except PasswordDeleteError: # OSX and gnome have no delete method
self.set(key, '', glob) |
python | def add_basemap(ax, zoom=12):
"""
Adds map to a plot.
"""
url = ctx.sources.ST_TONER_LITE
xmin, xmax, ymin, ymax = ax.axis()
basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax,
zoom=zoom, url=url)
ax.imshow(basemap, extent=extent, interpolati... |
python | def euclidean3d(v1, v2):
"""Faster implementation of euclidean distance for the 3D case."""
if not len(v1) == 3 and len(v2) == 3:
print("Vectors are not in 3D space. Returning None.")
return None
return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2) |
python | def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = self.lex_pattern.match(text)
if not m:
raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt))
try:
... |
java | public static boolean isWorkplaceUri(URI uri) {
return (uri != null) && uri.getPath().startsWith(OpenCms.getSystemInfo().getWorkplaceContext());
} |
java | public final Collection<State> acceptStates() {
if(acceptStates == null) {
final Collection<State> states = this.states();
acceptStates =
DSUtil.filterColl(_acceptStates(),
new Predicate<State>() {
public boolean check(State state) {
return states.contains(state);
}
... |
python | def delete_stream(stream_name, region=None, key=None, keyid=None, profile=None):
'''
Delete the stream with name stream_name. This cannot be undone! All data will be lost!!
CLI example::
salt myminion boto_kinesis.delete_stream my_stream region=us-east-1
'''
conn = _get_conn(region=region,... |
python | def add_object(self, obj):
"""
Adds a RiakObject to the inputs.
:param obj: the object to add
:type obj: RiakObject
:rtype: :class:`RiakMapReduce`
"""
return self.add_bucket_key_data(obj._bucket._name, obj._key, None) |
java | @Deprecated
public StreamReadsRequest getStreamReadsRequest(String readGroupSetId) {
return StreamReadsRequest.newBuilder()
.setReadGroupSetId(readGroupSetId)
.setReferenceName(referenceName)
.setStart(start)
.setEnd(end)
.build();
} |
python | def _evaluate(self,z,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential
INPUT:
z
t
OUTPUT:
Pot(z,t;R)
HISTORY:
2010-07-13 - Written - Bovy (NYU)
"""
return self._Pot(self._R,z,phi=sel... |
python | def delete(self):
"""Delete this column family.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_delete_column_family]
:end-before: [END bigtable_delete_column_family]
"""
modification = table_admin_v2_pb2.ModifyColumnFam... |
java | private void setResourceInformation() {
String sitePath = m_cms.getSitePath(m_resource);
int pathEnd = sitePath.lastIndexOf('/') + 1;
String baseName = sitePath.substring(pathEnd);
m_sitepath = sitePath.substring(0, pathEnd);
switch (CmsMessageBundleEditorTypes.BundleType.toBund... |
java | static List<String> getExecutableNames() {
List<String> executableNames = new ArrayList<>();
if (Platform.getCurrent().is(Platform.WINDOWS)) {
Collections.addAll(executableNames, ProcessNames.PHANTOMJS.getWindowsImageName(),
ProcessNames.CHROMEDRIVER.getWindowsImageName()... |
java | protected void setSuccessMessageInCookie(final HttpServletResponse response,
final String message) {
final Cookie cookie = new Cookie(AZKABAN_SUCCESS_MESSAGE, message);
cookie.setPath("/");
response.addCookie(cookie);
} |
java | static void encodeInteger(ByteBuffer source, int value, int n) {
int twoNminus1 = PREFIX_TABLE[n];
int pos = source.position() - 1;
if (value < twoNminus1) {
source.put(pos, (byte) (source.get(pos) | value));
} else {
source.put(pos, (byte) (source.get(pos) | twoN... |
java | public static double conditionP(DMatrixRMaj A , double p )
{
if( p == 2 ) {
return conditionP2(A);
} else if( A.numRows == A.numCols ){
// square matrices are the typical case
DMatrixRMaj A_inv = new DMatrixRMaj(A.numRows,A.numCols);
if( !CommonOps_D... |
python | def bootstrap_modulator(self, protocol: ProtocolAnalyzer):
"""
Set initial parameters for default modulator if it was not edited by user previously
:return:
"""
if len(self.modulators) != 1 or len(self.table_model.protocol.messages) == 0:
return
modulator = s... |
java | public static SessionProvider createAnonimProvider()
{
Identity id = new Identity(IdentityConstants.ANONIM, new HashSet<MembershipEntry>());
return new SessionProvider(new ConversationState(id));
} |
java | public static Field[] getFields(Class<?> clazz, String... fieldNames) {
return WhiteboxImpl.getFields(clazz, fieldNames);
} |
java | protected void handleUndefinedMode(CliOptionContainer option) {
CliStyle style = this.cliState.getCliStyle();
CliStyleHandling handling = style.modeUndefined();
if (handling != CliStyleHandling.OK) {
ObjectNotFoundException exception = new ObjectNotFoundException(CliMode.class, option.getOption().mod... |
python | def unpack_value(self, tup_tree):
"""
Find VALUE or VALUE.ARRAY under tup_tree and convert to a Python value.
Looks at the TYPE of the node to work out how to decode it.
Handles nodes with no value (e.g. when representing NULL by omitting
VALUE)
"""
valtype = at... |
java | public static double[] minusEquals(final double[] v1, final double[] v2) {
assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
for(int i = 0; i < v1.length; i++) {
v1[i] -= v2[i];
}
return v1;
} |
java | public void parse(DefaultHandler dh, File f) throws SAXException, ParserConfigurationException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(dh);
xr.parse(new InputS... |
python | def time_seconds(tc_array, year):
"""Return the time object from the timecodes
"""
tc_array = np.array(tc_array, copy=True)
word = tc_array[:, 0]
day = word >> 1
word = tc_array[:, 1].astype(np.uint64)
msecs = ((127) & word) * 1024
word = tc_array[:, 2]
msecs += word & 1023
msecs... |
python | def first(self, default=None, as_dict=False, as_ordereddict=False):
"""Returns a single record for the RecordCollection, or `default`. If
`default` is an instance or subclass of Exception, then raise it
instead of returning it."""
# Try to get a record, or return/raise default.
... |
python | def _load_json_module():
"""Try to load a valid json module.
There are more than one json modules that might be installed. They are
mostly compatible with one another but some versions may be different.
This function attempts to load various json modules in a preferred order.
It does a basic check... |
python | def set_sort_cb(self, w, index):
"""This callback is invoked when the user selects a new sort order
from the preferences pane."""
name = self.sort_options[index]
self.t_.set(sort_order=name) |
java | public Observable<Void> beginStopAsync(String groupName, String serviceName) {
return beginStopWithServiceResponseAsync(groupName, serviceName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body... |
python | def _set_main_widget(self, widget, redraw):
"""
add provided widget to widget list and display it
:param widget:
:return:
"""
self.set_body(widget)
self.reload_footer()
if redraw:
logger.debug("redraw main widget")
self.refresh() |
java | public void arcTo(double x1, double y1, double x2, double y2, double radius) {
this.gc.arcTo(
doc2fxX(x1), doc2fxY(y1),
doc2fxX(x2), doc2fxY(y2),
doc2fxSize(radius));
} |
java | public static List<String> getTextfileFromUrl(String _url, Charset _charset) {
return getTextfileFromUrl(_url, _charset, false);
} |
python | def partition_query(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... |
python | def receive_nack(self, msg):
'''
Returns a new Prepare message if the number of Nacks received reaches
a quorum.
'''
self.observe_proposal(msg.promised_proposal_id)
if msg.proposal_id == self.proposal_id and self.nacks_received is not None:
self.nacks_receive... |
java | public static String getSubstitutedProperty( String value,
PropertyAccessor propertyAccessor ) {
if (value == null || value.trim().length() == 0) return value;
StringBuilder sb = new StringBuilder(value);
// Get the index of the first constant,... |
java | @NullSafe
public static boolean isWhole(Number value) {
return (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long
|| value instanceof BigInteger);
} |
java | public static String getResponseHeadersOutput(Response response) {
if (response == null) {
return "";
}
StringBuilder responseHeaders = new StringBuilder();
String uuid = getUUID();
responseHeaders.append(ONCLICK_TOGGLE).append(uuid).append("\")'>Toggle Headers</a> ")... |
python | def install_cmd(argv):
'''Use Pythonz to download and build the specified Python version'''
installer = InstallCommand()
options, versions = installer.parser.parse_args(argv)
if len(versions) != 1:
installer.parser.print_help()
sys.exit(1)
else:
try:
actual_instal... |
java | public String readLongUTF() throws IOException {
int length = readCompressedInt();
StringBuilder SB = new StringBuilder(length);
for(int position = 0; position<length; position+=20480) {
int expectedLen = length - position;
if(expectedLen>20480) expectedLen = 20480;
String block = readUTF();
if(block.... |
python | def upload_gallery_photo(self, gallery_id, source_amigo_id, file_obj,
chunk_size=CHUNK_SIZE, force_chunked=False,
metadata=None):
"""
Upload a photo to a dataset's gallery.
"""
simple_upload_url = 'related_tables/%s/upload' % gal... |
java | ServerHeartbeat createServer(String serverId)
{
int p = serverId.indexOf(':');
String address = serverId.substring(0, p);
int port = Integer.parseInt(serverId.substring(p + 1));
boolean isSSL = false;
return _heartbeatService.createServer(address, port, isSSL);
} |
python | def fill_empty_slots(self, items):
"""Append dicts to the items passed in for those slots that don't have
any analysis assigned but the row needs to be rendered still.
:param items: dictionary with the items to be rendered in the list
"""
for pos in self.get_empty_slots():
... |
python | def sequence_to_graph(G, seq, color='black'):
"""
Automatically construct graph given a sequence of characters.
"""
for x in seq:
if x.endswith("_1"): # Mutation
G.node(x, color=color, width="0.1", shape="circle", label="")
else:
G.node(x, color=color)
for a,... |
java | public void setErrorTime(com.google.api.ads.admanager.axis.v201805.DateTime errorTime) {
this.errorTime = errorTime;
} |
java | public static void showErrorDialog(Throwable t, Runnable onClose) {
showErrorDialog(t.getLocalizedMessage(), t, onClose);
} |
java | public Observable<ManagementLockObjectInner> getAtResourceLevelAsync(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String lockName) {
return getAtResourceLevelWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace,... |
java | public Collection<Monitor> list(String name, String type, int offset, int limit)
{
List<Monitor> ret = new ArrayList<Monitor>();
Collection<Monitor> monitors = list(offset, limit);
for(Monitor monitor : monitors)
{
if((name == null || monitor.getName().toLowerCase().index... |
python | def _parse_udf_vol_descs(self, extent, length, descs):
# type: (int, int, PyCdlib._UDFDescriptors) -> None
'''
An internal method to parse a set of UDF Volume Descriptors.
Parameters:
extent - The extent at which to start parsing.
length - The number of bytes to read f... |
python | def find_favorite_videos_by_username(self, user_name,
orderby='favorite-time',
page=1, count=20):
"""doc: http://open.youku.com/docs/doc?id=54
"""
url = 'https://openapi.youku.com/v2/videos/favorite/by_user.json'
... |
java | public static Matrix zero(int rows, int columns) {
long size = (long) rows * columns;
return size > 1000 ? SparseMatrix.zero(rows, columns) : DenseMatrix.zero(rows, columns);
} |
java | protected static void assertion(boolean b, String msg)
{
if(!b)
{
throw new RuntimeException(XSLMessages.createMessage(XSLTErrorResources.ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR, new Object[]{msg}));
// "Programmer's assertion in RundundentExprEliminator: "+msg);
}
} |
java | public synchronized EventScope<T> register(final Class<? extends T> eventClass, final Object receiver,
final Pattern namePattern) {
final Method method = this.detectReceiverMethod(receiver, eventClass, namePattern);
this.registerInternal(receiver, method, eventClass);
return this;
} |
java | public void sendWithBulkProcessor(Map<String, ?> source, String index,
String type, String id) {
sendWithBulkProcessor(
buildIndexRequest(index, type, id).source(source));
} |
python | def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this... |
java | protected void open(int remoteid, long remotewindow, int remotepacket)
throws IOException {
this.remoteid = remoteid;
this.remotewindow = new DataWindow(remotewindow, remotepacket);
this.state = CHANNEL_OPEN;
synchronized (listeners) {
for (Enumeration<ChannelEventListener> e = listeners.elements(); e
... |
python | def equalizer(self, frequency, q=1.0, db=-3.0):
"""equalizer takes three parameters: filter center frequency in Hz, "q"
or band-width (default=1.0), and a signed number for gain or
attenuation in dB.
Beware of clipping when using positive gain.
"""
self.command.append('e... |
python | def _concat_compat(to_concat, axis=0):
"""
provide concatenation of an array of arrays each of which is a single
'normalized' dtypes (in that for example, if it's object, then it is a
non-datetimelike and provide a combined dtype for the resulting array that
preserves the overall dtype if possible)
... |
python | def current_task(self, args):
"""Name of current action for progress-bar output.
The specific task string is depends on the configuration via `args`.
Returns
-------
ctask : str
String representation of this task.
"""
ctask = self.nice_name if self.n... |
python | def tryCComment(self, block):
"""C comment checking. If the previous line begins with a "/*" or a "* ", then
return its leading white spaces + ' *' + the white spaces after the *
return: filler string or null, if not in a C comment
"""
indentation = None
prevNonEmptyBloc... |
python | def laser_hook(self, hook_type: str) -> Callable:
"""Registers the annotated function with register_laser_hooks
:param hook_type:
:return: hook decorator
"""
def hook_decorator(func: Callable):
""" Hook decorator generated by laser_hook
:param func: Dec... |
java | static ConnectionInfo newForwardedConnectionInfo(HttpRequest request, Channel channel) {
if (request.headers().contains(FORWARDED_HEADER)) {
return parseForwardedInfo(request, (SocketChannel)channel);
}
else {
return parseXForwardedInfo(request, (SocketChannel)channel);
}
} |
python | def _make_random_string(length):
"""Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate.
"""
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
return ''.join(random.choice(chars) for x in range(length)) |
java | public void createAgent(String agent_name, String path) {
IComponentIdentifier agent = cmsService.createComponent(agent_name,
path, null, null).get(new ThreadSuspendable());
createdAgents.put(agent_name, agent);
} |
python | def bind(self):
"""Attempts to bind to the LDAP server using the credentials of the
service account.
:return: Bound LDAP connection object if successful or ``None`` if
unsuccessful.
"""
conn = self.initialize
try:
conn.simple_bind_s(
... |
python | def get_facet_serializer_class(self):
"""
Return the class to use for serializing facets.
Defaults to using ``self.facet_serializer_class``.
"""
if self.facet_serializer_class is None:
raise AttributeError(
"%(cls)s should either include a `facet_seria... |
java | public ContinueUpdateRollbackRequest withResourcesToSkip(String... resourcesToSkip) {
if (this.resourcesToSkip == null) {
setResourcesToSkip(new com.amazonaws.internal.SdkInternalList<String>(resourcesToSkip.length));
}
for (String ele : resourcesToSkip) {
this.resourcesT... |
python | def get_colours(color_group, color_name, reverse=False):
color_group = color_group.lower()
cmap = get_map(color_group, color_name, reverse=reverse)
return cmap.hex_colors
"""
if not reverse:
return cmap.hex_colors
else:
return cmap.hex_colors[::-1]
""" |
python | def upvotes(self, option):
"""
Set whether to filter by a user's upvoted list. Options available are
user.ONLY, user.NOT, and None; default is None.
"""
params = join_params(self.parameters, {"upvotes": option})
return self.__class__(**params) |
python | def as_yaml(self):
"""
Render the YAML node and subnodes as string.
"""
dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True)
return dumped if sys.version_info[0] == 3 else dumped.decode("utf8") |
python | def crude_search_scicrunch_via_label(self, label:str) -> dict:
""" Server returns anything that is simlar in any catagory """
url = self.base_url + 'term/search/{term}?key={api_key}'.format(
term = label,
api_key = self.api_key,
)
return self.get(url) |
java | protected JRDesignChart createChart(DJChart djChart) {
JRDesignGroup jrGroupChart = getJRGroupFromDJGroup(djChart.getColumnsGroup());
JRDesignChart chart = new JRDesignChart(new JRDesignStyle().getDefaultStyleProvider(), djChart.getType());
JRDesignGroup parentGroup = getParent(jrGroupChart);
... |
python | def _get_location_descriptor(self, location):
"""
Get corresponding :class:`LocationDescriptor` object from a string or a :class:`LocationDescriptor` itself.
Args:
location: a string or a :class:`LocationDescriptor`.
Returns:
A corresponding :cla... |
java | public static boolean isGroundTerm(Term term) {
if (term instanceof Function) {
return ((Function)term).getVariables().isEmpty();
}
return term instanceof Constant;
} |
python | def make_diffuse_comp_info(self, merged_name, galkey):
""" Make the information about a single merged component
Parameters
----------
merged_name : str
The name of the merged component
galkey : str
A short key identifying the galprop parameters
... |
python | def from_frames(self, path):
"""
Read from frames
"""
frames_path = sorted([os.path.join(path, x) for x in os.listdir(path)])
frames = [ndimage.imread(frame_path) for frame_path in frames_path]
self.handle_type(frames)
return self |
python | def find_pareto_front(population):
"""Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals
"""
pareto_front = set(range(len(population)))
for i in range(len(population)):
... |
python | def merge_inner(clsdict):
"""
Merge the inner class(es) of a class:
e.g class A { ... } class A$foo{ ... } class A$bar{ ... }
==> class A { class foo{...} class bar{...} ... }
"""
samelist = False
done = {}
while not samelist:
samelist = True
classlist = list(clsdict.keys... |
python | def _set_char(self, char, type):
'''
Sets the currently active character, e.g. ト. We save some information
about the character as well. active_char_info contains the full
tuple of rōmaji info, and active_ro_vowel contains e.g. 'o' for ト.
We also set the character type: either a ... |
java | @Override
public Token retrieveToken() {
log.debug("DefaultTokenProvider retrieveToken()");
try {
SSLContext sslContext;
/*
* If SSL cert checking for endpoints has been explicitly disabled,
* register a new scheme for HTTPS that won't cause self-signed
* certs to error out.
*/
if (SDKG... |
java | public DescribeEndpointsResult withEndpoints(Endpoint... endpoints) {
if (this.endpoints == null) {
setEndpoints(new java.util.ArrayList<Endpoint>(endpoints.length));
}
for (Endpoint ele : endpoints) {
this.endpoints.add(ele);
}
return this;
} |
java | public double[] getBasisVector( int which ) {
if( which < 0 || which >= numComponents )
throw new IllegalArgumentException("Invalid component");
DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);
CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);
return v.data;
} |
java | private boolean shouldGwtDotCreate(TypeLiteral<?> typeLiteral) throws BindingCreationException {
Class<?> rawType = typeLiteral.getRawType();
if (rawType.isInterface()) {
// Check whether we can GWT.create() the interface.
// Remote service proxies don't have rebind rules; we handle them
// s... |
java | public static void runExample(
AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId)
throws RemoteException {
// Get the campaign criterion service.
CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(session,
CampaignCriterionService... |
python | def _start_of_century(self):
"""
Reset the date to the first day of the century.
:rtype: Date
"""
year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + 1
return self.set(year, 1, 1) |
java | @Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case AfplibPackage.PAGE_OVERLAY_CONDITIONAL_PROCESSING__PG_OV_TYPE:
setPgOvType((Integer)newValue);
return;
case AfplibPackage.PAGE_OVERLAY_CONDITIONAL_PROCESSING__LEVEL:
setLevel((Integer)newValue);
return;
}
... |
java | private String getCDCQueryJson(CDCQuery cdcQuery) throws SerializationException {
ObjectMapper mapper = getObjectMapper();
String json = null;
try {
json = mapper.writeValueAsString(cdcQuery);
} catch (Exception e) {
throw new SerializationException(e);
}
return json;
} |
java | private HandlerAdapter getHandlerAdapter(HttpRequest request) {
for (HandlerAdapter ha : mAdapterList) {
if (ha.intercept(request)) return ha;
}
return null;
} |
java | private void setTranslationChain() {
for (final Converter<String, String> t : minimalTranslationChain) {
forward = forward.andThen(t);
}
for (final Converter<String, String> t : Lists.reverse(minimalTranslationChain)) {
reverse = reverse.andThen(t.reverse());
}
... |
java | public void addChar(char nextCh)
throws IOException
{
int ch;
while ((ch = readChar()) >= 0) {
outputChar((char) ch);
}
outputChar(nextCh);
} |
python | def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Optional
for key in iterkeys(self.stats):
self.views[key]['optional'] = True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.