language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def printUniqueTFAM(tfam, samples, prefix):
"""Prints a new TFAM with only unique samples.
:param tfam: a representation of a TFAM file.
:param samples: the position of the samples
:param prefix: the prefix of the output file name
:type tfam: list
:type samples: dict
:type prefix: str
... |
python | def _read_csv_impl(cls,
url,
delimiter=',',
header=True,
error_bad_lines=False,
comment_char='',
escape_char='\\',
double_quote=True,
qu... |
java | static PolicyNodeImpl processPolicies(int certIndex, Set<String> initPolicies,
int explicitPolicy, int policyMapping, int inhibitAnyPolicy,
boolean rejectPolicyQualifiers, PolicyNodeImpl origRootNode,
X509CertImpl currCert, boolean finalCert)
throws CertPathValidatorException
{
... |
java | public TransactionParticipant start(PersistentTranId ptid, int flags) throws XidUnknownException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "start", new Object[]{"PersistentTranId="+ptid, xaFlagsToString(flags)});
TransactionParticipant retval = null;
... |
java | @Override
public VerifyUserAttributeResult verifyUserAttribute(VerifyUserAttributeRequest request) {
request = beforeClientExecution(request);
return executeVerifyUserAttribute(request);
} |
java | private static String convertToBeanName(final String methodName)
{
return Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
} |
java | public static synchronized boolean registerIfAbsent(final Tracer tracer) {
requireNonNull(tracer, "Cannot register GlobalTracer. Tracer is null");
return registerIfAbsent(new Callable<Tracer>() {
@Override
public Tracer call() {
return tracer;
}
... |
java | private JsonObject parse(JsonObject record, JsonSchema schema)
throws DataConversionException {
JsonObject output = new JsonObject();
for (int i = 0; i < schema.fieldsCount(); i++) {
JsonSchema schemaElement = schema.getFieldSchemaAt(i);
String columnKey = schemaElement.getColumnName()... |
python | def pickAChannelList(self, ra_deg, dec_deg):
"""Similar to pickAChannel() but takes lists as input.
This will require AstroPy to be installed.
"""
try:
from astropy.coordinates import SkyCoord
from astropy import units as u
except ImportError:
... |
python | def request(self, uri, method, *args, **kwargs):
"""
Formats the request into a dict representing the headers
and body that will be used to make the API call.
"""
if self.timeout:
kwargs["timeout"] = self.timeout
kwargs["verify"] = self.verify_ssl
kwar... |
python | def parse(
svalue, conf=None, configurable=None, ptype=None,
scope=DEFAULT_SCOPE, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT
):
"""Parser which delegates parsing to expression or format parser."""
result = None
if ptype is None:
ptype = object
compilation = REGEX_EXPR.ma... |
java | public static BigDecimal root(BigDecimal x, BigDecimal n, MathContext mathContext) {
checkMathContext(mathContext);
switch (x.signum()) {
case 0:
return ZERO;
case -1:
throw new ArithmeticException("Illegal root(x) for x < 0: x = " + x);
}
if (n.compareTo(BigDecimal.ONE) <= 0) {
MathContext mc = n... |
python | def instruction_LSL_memory(self, opcode, ea, m):
"""
Logical shift left memory location / Arithmetic shift of memory left
"""
r = self.LSL(m)
# log.debug("$%x LSL memory value $%x << 1 = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
... |
python | def display(self, format="png"):
"""
Return an object that can be used to display this sequence.
This is used for IPython Notebook.
:param format: "png" or "svg"
"""
from sebastian.core.transforms import lilypond
seq = HSeq(self) | lilypond()
lily_output... |
python | def get_trainer(name):
'''return the unique id for a trainer, determined by the md5 sum
'''
name = name.lower()
return int(hashlib.md5(name.encode('utf-8')).hexdigest(), 16) % 10**8 |
java | public void show(PeekViewActivity activity, MotionEvent motionEvent) {
PeekView peek;
if (layout == null) {
peek = new PeekView(activity, options, layoutRes, callbacks);
} else {
peek = new PeekView(activity, options, layout, callbacks);
}
peek.setOffset... |
java | private static void populateTypeMapFromParameterizedType(ParameterizedType type, Map<Type, Type> typeVariableMap) {
if (type.getRawType() instanceof Class) {
Type[] actualTypeArguments = type.getActualTypeArguments();
TypeVariable[] typeVariables = ((Class) type.getRawType()).getTypeParameters();
... |
java | String getQuery(String key)
{
String res = this.adapter.getSqlText(key);
if (res == null)
{
throw new DatabaseException("Query " + key + " does not exist");
}
return res;
} |
java | public static void delayedHideSoftKeyboard(final Context context,
final View view, int delay) {
TimerTask task = new TimerTask() {
@Override
public void run() {
hideSoftKeyboard(context, view);
}
};
Timer timer = new Timer();
timer.schedule(task, delay);
} |
python | def get_layer_timing_signal_learned_1d(channels, layer, num_layers):
"""get n-dimensional embedding as the layer (vertical) timing signal.
Adds embeddings to represent the position of the layer in the tower.
Args:
channels: dimension of the timing signal
layer: layer num
num_layers: total number of ... |
python | def _CalculateNTFSTimeHash(self, file_entry):
"""Calculates an MD5 from the date and time value of a NTFS file entry.
Args:
file_entry (dfvfs.FileEntry): file entry.
Returns:
str: hexadecimal representation of the MD5 hash value of the date and
time values of the file entry.
"""
... |
java | @Override
protected boolean shouldEncryptTokenFor(final OidcRegisteredService svc) {
if (AlgorithmIdentifiers.NONE.equalsIgnoreCase(svc.getIdTokenEncryptionAlg())) {
LOGGER.warn("ID token encryption algorithm is set to none for [{}] and ID token will not be encrypted", svc.getServiceId());
... |
java | public String label(String label) {
if (isNotInitialized()) {
return getMessage(NOT_INITIALIZED);
}
try {
return CmsJspTagLabel.wpLabelTagAction(label, getRequest());
} catch (Throwable t) {
handleException(t);
}
CmsMessageContainer ms... |
python | def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
'''draw a line on the image'''
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
clipped = cv.ClipLine((img.width, img.height), pix1, pix2)
if clipped is None:
if len(self._pix_points) == 0:
s... |
java | protected void notifyClose(ProxyQueue queue)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyClose", queue);
try
{
final short id = queue.getId();
idAllocator.releaseId(id);
//Remove the id from the map
synchronized... |
python | def ignore(mapping):
""" Use ignore to prevent a mapping from being mapped to a namedtuple. """
if isinstance(mapping, Mapping):
return AsDict(mapping)
elif isinstance(mapping, list):
return [ignore(item) for item in mapping]
return mapping |
java | @Override
public void doAuthAnswerEvent(ClientAuthSession appSession, AppRequestEvent request, AppAnswerEvent answer)
throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
logger.info("Diameter Gq AuthorizationSessionFactory :: doAuthAnswerEvent :: appSession[{}], R... |
python | def download_file(url, filename=None, show_progress=draw_pbar):
'''
Download a file and show progress
url: the URL of the file to download
filename: the filename to download it to (if not given, uses the url's filename part)
show_progress: callback function to update a progress bar
the show_pr... |
python | def fetch(self, is_dl_forced=False):
"""
:return:
"""
# create the connection details for Flybase
cxn = {
'host': 'chado.flybase.org', 'database': 'flybase', 'port': 5432,
'user': 'flybase', 'password': 'no password'}
self.dataset.setFileAccessU... |
java | protected void checkTransactionSupported(Connection conn) throws SQLException, DbRuntimeException {
if (null == isSupportTransaction) {
isSupportTransaction = conn.getMetaData().supportsTransactions();
}
if (false == isSupportTransaction) {
throw new DbRuntimeException("Transaction not supported for cu... |
java | public static byte[] copyBytesFrom(ByteBuffer bb) {
if (bb == null) {
return null;
}
if (bb.hasArray()) {
return Arrays.copyOfRange(
bb.array(),
bb.arrayOffset() + bb.position(),
bb.arrayOffset() + bb.limit());
... |
python | def setting_ctx(num_gpus):
"""
Description : set gpu module
"""
if num_gpus > 0:
ctx = [mx.gpu(i) for i in range(num_gpus)]
else:
ctx = [mx.cpu()]
return ctx |
python | def _get_primary_address(self, mac_address, node_list):
"""
Uses the _get_aggregated_node_list structure to find
the primary mac address associated to a secondary one,
if none is found returns itself.
"""
for local_addresses in node_list:
if mac_address in loc... |
java | static boolean allPositive(int[] input, int start, int length) {
for (int i = length - 1, index = start; i >= 0; i--, index++) {
if (input[index] <= 0) {
return false;
}
}
return true;
} |
python | def defer(self, func, *args, **kwargs):
"""
Arrange for `func(*args, **kwargs)` to be invoked in the context of a
service pool thread.
"""
self._ipc_latch.put(lambda: func(*args, **kwargs)) |
java | public Target getTarget(long id, TargetType type) throws WorkspaceApiException {
try {
TargetsResponse resp = targetsApi.getTarget(new BigDecimal(id), type.getValue());
Util.throwIfNotOk(resp.getStatus());
Target target = null;
if(resp.getData()... |
java | public CompoundName getFirstInChain()
{
if (tc.isEntryEnabled())
SibTr.entry(tc, "getFirstInChain");
CompoundName firstInChain = collector.getFirst();
if (tc.isEntryEnabled())
SibTr.exit(tc, "getFirstInChain", firstInChain);
return firstInChain;
} |
python | def maketabdesc(descs=[]):
"""Create a table description.
Creates a table description from a set of column descriptions. The
resulting table description can be used in the :class:`table` constructor.
For example::
scd1 = makescacoldesc("col2", "aa")
scd2 = makescacoldesc("col1", 1, "Incre... |
python | def get_submodules(mod):
"""Get all submodules of a given module"""
def catch_exceptions(module):
pass
try:
m = __import__(mod)
submodules = [mod]
submods = pkgutil.walk_packages(m.__path__, m.__name__ + '.',
catch_exceptions)
... |
python | def fit(self, X, y=None):
"""
X : data matrix, (n x d)
y : unused
"""
X = self._prepare_inputs(X, ensure_min_samples=2)
M = np.cov(X, rowvar = False)
if M.ndim == 0:
M = 1./M
else:
M = np.linalg.inv(M)
self.transformer_ = transformer_from_metric(np.atleast_2d(M))
ret... |
python | def get_go2txt(grprobj_cur, grp_go2color, grp_go2bordercolor):
"""Adds section text in all GO terms if not Misc. Adds Misc in terms of interest."""
goids_main = set(o.id for o in grprobj_cur.gosubdag.go2obj.values())
hdrobj = grprobj_cur.hdrobj
grprobj_all = Grouper("all",
... |
python | def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or ... |
python | def nonce(self, value):
"""
A bool - if the nonce extension should be used to prevent replay
attacks.
"""
if not isinstance(value, bool):
raise TypeError(_pretty_message(
'''
nonce must be a boolean, not %s
''',
... |
java | @Override
public void writeFragmentTo(MwsWriter w) {
w.write("GetServiceStatusResult", getServiceStatusResult);
w.write("ResponseMetadata", responseMetadata);
} |
python | def _create_field(self, uri , name, field_type, **kwargs):
'''Creates a field with the provided attributes.
Args:
uri base uri for the field (pipeline or box uri)
name required name string
field_type required type string [TEXT_INPUT, DATE or PERSON]
kwargs {}
return (status code, field dict)
'''
... |
java | public static void finishIfApplicable(Iterable<?> toFinish) throws IOException {
for (final Object o : toFinish) {
if (o instanceof Finishable) {
((Finishable) o).finish();
}
}
} |
python | def monitor(self, name, ip, port, quorum):
"""Add a new master to Sentinel to be monitored."""
fut = self.execute(b'MONITOR', name, ip, port, quorum)
return wait_ok(fut) |
python | def add_post(request, t_slug, t_id, p_id = False): # topic slug, topic id, post id
"""
Creates a new post and attaches it to a topic
"""
topic = get_object_or_404(Topic, id=t_id)
topic_url = '{0}page{1}/'.format(topic.get_short_url(), topic.page_count)
user = request.user
current_t... |
java | public void marshall(ExclusionPreview exclusionPreview, ProtocolMarshaller protocolMarshaller) {
if (exclusionPreview == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(exclusionPreview.getTitle(), TI... |
python | def _close_connection(self, frame_in):
"""Connection Close.
:param specification.Connection.Close frame_in: Amqp frame.
:return:
"""
self._set_connection_state(Stateful.CLOSED)
if frame_in.reply_code != 200:
reply_text = try_utf8_decode(frame_in.reply_text)
... |
python | def _central_even(f, fx, x, h):
"""Eq 9."""
n = len(x)
ee = np.diag(h)
dtype = np.result_type(fx)
hess = np.empty((n, n), dtype=dtype)
np.outer(h, h, out=hess)
for i in range(n):
hess[i, i] = (f(x + 2 * ee[i, :]) - 2 * fx + f(x - 2 * ee[i, :])) / (4. *... |
java | private boolean containsClassName(List<ClassOrInterfaceType> klassList, Set<String> simpleNames) {
for (ClassOrInterfaceType ctype : klassList) {
if (simpleNames.contains(ctype.getName())) {
return true;
}
}
return false;
} |
java | public <E extends Test> List<List<Object>> getJavaScriptConfig(final E[] tests) {
final Map<String, TestBucket> buckets = getProctorResult().getBuckets();
final List<List<Object>> groups = new ArrayList<List<Object>>(tests.length);
for (final E test : tests) {
final String testName =... |
java | public static Logger getConsoleLogger(final String name) {
return new Logger() {
@Override
public void log(String description, Object... params) {
System.out.print("[" + name + "]: " + description + "\t");
for (Object param: params)
Sys... |
java | @ResponseBody
@RequestMapping(value = "/file/{configId}", method = RequestMethod.POST)
public JsonObjectBase updateFile(@PathVariable long configId, @RequestParam("myfilerar") MultipartFile file) {
//
// 校验
//
int fileSize = 1024 * 1024 * 4;
String[] allowExtName = {".pr... |
python | def getFTPs(accessions, ftp, search, exclude, convert = False, threads = 1, attempt = 1,
max_attempts = 2):
"""
download genome info from NCBI
"""
info = wget(ftp)[0]
allMatches = []
for genome in open(info, encoding = 'utf8'):
genome = str(genome)
matches, genomeInfo... |
python | def video_to_file(self, path):
"""Write video to file.
:param path: Path to write file
"""
_LOGGER.debug("Writing video from %s to %s", self.name, path)
response = self._cached_video
if response is None:
_LOGGER.error("No saved video exist for %s.",
... |
java | public static JsonArray array(int... values) {
if (values == null) {
throw new NullPointerException(VALUES_IS_NULL);
}
JsonArray array = new JsonArray();
for (int value : values) {
array.add(value);
}
return array;
} |
python | def duration(self):
"""Duration of this series in seconds
:type: `~astropy.units.Quantity` scalar
"""
return units.Quantity(self.span[1] - self.span[0], self.xunit,
dtype=float) |
java | public People getList(String photoId) throws JinxException {
JinxUtils.validateParams(photoId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.people.getList");
params.put("photo_id", photoId);
return jinx.flickrGet(params, People.class, false);
} |
python | def libvlc_audio_set_volume(p_mi, i_volume):
'''Set current software audio volume.
@param p_mi: media player.
@param i_volume: the volume in percents (0 = mute, 100 = 0dB).
@return: 0 if the volume was set, -1 if it was out of range.
'''
f = _Cfunctions.get('libvlc_audio_set_volume', None) or \
... |
python | def clean(ctx, node=False, translations=False, all=False):
'''Cleanup all build artifacts'''
header('Clean all build artifacts')
patterns = [
'build', 'dist', 'cover', 'docs/_build',
'**/*.pyc', '*.egg-info', '.tox', 'udata/static/*'
]
if node or all:
patterns.append('node_mo... |
python | def grok_if_node(element, default_vars):
"""Properly parses a If element"""
if isinstance(element.test, jinja2.nodes.Filter) and \
element.test.name == 'default':
default_vars.append(element.test.node.name)
return default_vars + grok_vars(element) |
python | def run_via_binary_in_foreground(
self, run_command_instance=None, command=None, volumes=None,
additional_opts=None, popen_params=None, container_name=None):
"""
Create a container using this image and run it in foreground;
this method is useful to test real user scenario... |
python | def get_memory_usage(self):
"""
Get data about the virtual memory usage of the holder.
:returns: Memory usage data
:rtype: dict
Example:
>>> holder.get_memory_usage()
>>> {
>>> 'nb_arrays': 12, # The holder contains the v... |
python | def overlap(ival0, ival1):
'''
Determine if two interval tuples have overlap.
Args:
iv0 ((int,int)): An interval tuple
iv1 ((int,int)); An interval tuple
Returns:
(bool): True if the intervals overlap, otherwise False
'''
min0, max0 = ival0
min1, max1 = ival1... |
python | def add_object(self, obj):
"""Add object to local and app environment storage
:param obj: Instance of a .NET object
"""
if obj.top_level_object:
if isinstance(obj, DotNetNamespace):
self.namespaces[obj.name] = obj
self.objects[obj.id] = obj |
java | private static String generateExceptionMessage(String userId, List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("The user with id '");
sBuilder.append(userId);
sBuilder.append("' does not have one of the following permissions: ");
boole... |
python | def select_newest_project(dx_project_ids):
"""
Given a list of DNAnexus project IDs, returns the one that is newest as determined by creation date.
Args:
dx_project_ids: `list` of DNAnexus project IDs.
Returns:
`str`.
"""
if len(dx_project_ids) == 1:
return dx_proj... |
java | public static EsriFeature FeatureFromJson(JsonParser parser) throws JsonProcessingException, IOException{
parser.setCodec(jsonObjectMapper);
return parser.readValueAs(EsriFeature.class);
} |
java | public static final boolean getBooleanValue(Properties cfg, String key, boolean defaultValue) {
String propValue = cfg.getProperty(key);
if (propValue == null) {
return defaultValue;
} else {
return parseBoolean(propValue, "Property '" + key + "' needs to be either literal 'true' or ... |
python | def add_instruction (self, instr):
"""
Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables)
"""
assert(isinstance(instr, Instruction))
self.instruction_list.append(instr)
... |
java | public static ServerAddress fromString(String string) {
String tokens[] = string.split(":");
if (tokens.length == 1) {
return new ServerAddress(tokens[0], null);
}
return new ServerAddress(tokens[0], Integer.valueOf(tokens[1]));
} |
java | @Override public void onFocusChange(View v, boolean hasFocus) {
final EmailAutoCompleteTextView editText = (EmailAutoCompleteTextView) v;
if (mClearButtonEnabled) {
editText.setClearVisible((hasFocus && !TextUtils.isEmpty(editText.getText().toString())));
}
if (mOnFocusChan... |
java | static Integer parseTimeConstraint(Instance instance, String constraint,
ConnectionManager cm) throws KnowledgeSourceReadException {
Integer constraintValue = null;
if (instance != null && constraint != null) {
constraintValue = (Integer) cm.getOwnSlotValue(instance,
... |
java | public Groundy arg(String key, CharSequence value) {
mArgs.putCharSequence(key, value);
return this;
} |
java | @CheckForNull
private static File guessManifest(@Nonnull File parent) {
File file = new File(parent, "MANIFEST.MF");
if(!file.isFile()){
file = new File(parent, "META-INF/MANIFEST.MF");
}
if(!file.isFile()){
file = new File(parent, "../META-INF/MANIFEST.MF");
... |
python | def updateTraceCount(self):
"""Updates the trace count label with the data from the model"""
self.ui.ntracesLbl.setNum(self.ui.trackview.model().traceCount()) |
python | def predict(self, temp_type):
"""
Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict metho... |
java | void zApplyMinimumSpinnerButtonWidthInPixels() {
if (parent == null) {
return;
}
Dimension decreaseButtonPreferredSize = parent.getComponentDecreaseSpinnerButton().getPreferredSize();
Dimension increaseButtonPreferredSize = parent.getComponentIncreaseSpinnerButton().getPrefer... |
python | def as_command(self):
"""Return a find command document for this query.
Should be called *after* get_message.
"""
if '$explain' in self.spec:
self.name = 'explain'
return _gen_explain_command(
self.coll, self.spec, self.fields, self.ntoskip,
... |
python | def _handle_request(self, request):
""" Handle an incoming request by forwarding it to the appropriate method.
Args:
request (Request): Reference to a request object containing the
incoming request.
Raises:
RequestActionUnknown: If the act... |
python | def update_listing(self, num_iid, num, session):
'''taobao.item.update.listing 一口价商品上架
单个商品上架
输入的num_iid必须属于当前会话用户'''
request = TOPRequest('taobao.item.update.listing')
request['num_iid'] = num_iid
request['num'] = num
self.create(self.execute(request, s... |
java | public StaticResourceRequestMatcher at(Set<StaticResourceLocation> locations) {
Assert.notNull(locations, "Locations must not be null");
return new StaticResourceRequestMatcher(new LinkedHashSet<>(locations));
} |
python | def Matsumoto_1977(mp, rhop, dp, rhog, D, Vterminal=1):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ and reproduced in [2]_, [3]_, and [4]_.
First equation is used if third equation yeilds d* higher than dp.
Otherwise, use equation 2.
.. math::
\m... |
java | @Override
public void removeReaction(IReaction reaction) {
logger.debug("Removing reaction " + reaction.getID());
super.removeReaction(reaction);
} |
java | @Cmd
public String prompt(final String configKey, final String message) {
System.out.print(resolveProperty(message) + " "); //NOSONAR
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String value = StringUtils.trim(in.readLine());
config.put(configKey, value);
return value... |
python | def next_turn(self, *args):
"""Advance time by one turn, if it's not blocked.
Block time by setting ``engine.universal['block'] = True``"""
if self.tmp_block:
return
eng = self.app.engine
dial = self.dialoglayout
if eng.universal.get('block'):
Log... |
java | public String equationsToString(String prefix, NumberFormat nf) {
if((coeff == null) || (rhs == null) || (row == null) || (col == null)) {
throw new NullPointerException();
}
int[] coeffDigits = maxIntegerDigits(coeff);
int rhsDigits = maxIntegerDigits(rhs);
StringBuilder buffer = new String... |
java | private InsertStack getInsertStack()
{
Object x = _insertStack.get();
InsertStack g = null;
if (x != null)
{
g = (InsertStack) x;
g.reset();
}
else
{
g = new InsertStack(this);
x = (Object) g;
_insert... |
python | def create_integration(self, integration_info, **kwargs):
"""
Create an integration for this service.
See: https://v2.developer.pagerduty.com/v2/page/api-reference#!/
Services/post_services_id_integrations
"""
service_info = integration_info.get('service')
... |
python | def apply(model_path):
"""Run inference from a training model checkpoint. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=Model(),
input_names=['input_img'],
output_names=['prediction_img'])
pred = OfflinePredictor(pred_config)
img = cv2... |
python | def _collect_headers(self):
"""
Collect headers from the models attribute info col
"""
res = []
for prop in self.get_sorted_columns():
main_infos = self._get_prop_infos(prop)
if self._is_excluded(prop, main_infos):
continue
... |
java | public static double logGamma(final double x) {
if(Double.isNaN(x) || (x <= 0.0)) {
return Double.NaN;
}
double g = 607.0 / 128.0;
double tmp = x + g + .5;
tmp = (x + 0.5) * FastMath.log(tmp) - tmp;
double ser = LANCZOS[0];
for(int i = LANCZOS.length - 1; i > 0; --i) {
ser += LAN... |
java | public static Set<Event> compareAndGetEvents(JSONObject pre, JSONObject post, JSONObject ids) throws JSONException {
Set<Event> result = new HashSet<>();
Iterator<String> keysIterator = ids.keys();
while (keysIterator.hasNext()) {
String key = keysIterator.next();
if (pos... |
python | def add_campaign(self, name, device_filter, **kwargs):
"""Add new update campaign.
Add an update campaign with a name and device filtering. Example:
.. code-block:: python
device_api, update_api = DeviceDirectoryAPI(), UpdateAPI()
# Get a filter to use for update camp... |
java | public List<Plugin.Factory.UsingReflection.ArgumentResolver> makeArgumentResolvers() {
if (arguments == null) {
return Collections.emptyList();
} else {
List<Plugin.Factory.UsingReflection.ArgumentResolver> argumentResolvers = new ArrayList<Plugin.Factory.UsingReflection.Argument... |
java | @SuppressWarnings("unchecked")
protected <Y> Path<Y> buildPropertyPath(Root<?> root, String stringPath) {
// Si la racine est nulle
if(root == null) return null;
// Si la chaine est vide
if(stringPath == null || stringPath.trim().length() == 0) return null;
// Le Path à retournet
Path<? extends Co... |
python | def convert_from_ik_angles(self, joints):
""" Convert from IKPY internal representation to poppy representation. """
if len(joints) != len(self.motors) + 2:
raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors) + 2))
joints = [rad2deg(j) for j in jo... |
python | def _new_program(self, p):
"""New program was added to the multiprogram; update items in the
shader.
"""
for k, v in self._set_items.items():
getattr(p, self._shader)[k] = v |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.