file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_qtxmlpatterns.py | import pytest
from qtpy import PYSIDE2, PYSIDE6, PYQT6
@pytest.mark.skipif((PYSIDE6 or PYQT6), reason="not available with qt 6.0")
def test_qtxmlpatterns():
"""Test the qtpy.QtXmlPatterns namespace"""
from qtpy import QtXmlPatterns
assert QtXmlPatterns.QAbstractMessageHandler is not None
assert QtXmlPa... |
assert QtXmlPatterns.QSourceLocation is not None
assert QtXmlPatterns.QXmlFormatter is not None
assert QtXmlPatterns.QXmlItem is not None
assert QtXmlPatterns.QXmlName is not None
assert QtXmlPatterns.QXmlNamePool is not None
assert QtXmlPatterns.QXmlNodeModelIndex is not None
assert QtXmlP... | assert QtXmlPatterns.QSimpleXmlNodeModel is not None | conditional_block |
test_qtxmlpatterns.py | import pytest
from qtpy import PYSIDE2, PYSIDE6, PYQT6
@pytest.mark.skipif((PYSIDE6 or PYQT6), reason="not available with qt 6.0")
def | ():
"""Test the qtpy.QtXmlPatterns namespace"""
from qtpy import QtXmlPatterns
assert QtXmlPatterns.QAbstractMessageHandler is not None
assert QtXmlPatterns.QAbstractUriResolver is not None
assert QtXmlPatterns.QAbstractXmlNodeModel is not None
assert QtXmlPatterns.QAbstractXmlReceiver is not No... | test_qtxmlpatterns | identifier_name |
test_qtxmlpatterns.py | import pytest
from qtpy import PYSIDE2, PYSIDE6, PYQT6
@pytest.mark.skipif((PYSIDE6 or PYQT6), reason="not available with qt 6.0")
def test_qtxmlpatterns():
| """Test the qtpy.QtXmlPatterns namespace"""
from qtpy import QtXmlPatterns
assert QtXmlPatterns.QAbstractMessageHandler is not None
assert QtXmlPatterns.QAbstractUriResolver is not None
assert QtXmlPatterns.QAbstractXmlNodeModel is not None
assert QtXmlPatterns.QAbstractXmlReceiver is not None
i... | identifier_body | |
tvec.rs | cx, expr);
return match dest {
Ignore => write_content(bcx, &vt, expr, expr, dest),
SaveIn(lldest) => {
// lldest will have type *[T x N], but we want the type *T,
// so use GEP to convert:
let lldest = GEPi(bcx, lldest, &[0, 0]);
write_content(bcx, &... | (bcx: | get_fixed_base_and_len | identifier_name |
tvec.rs | cx, expr);
return match dest {
Ignore => write_content(bcx, &vt, expr, expr, dest),
SaveIn(lldest) => {
// lldest will have type *[T x N], but we want the type *T,
// so use GEP to convert:
let lldest = GEPi(bcx, lldest, &[0, 0]);
write_content(bcx, &... | slice_expr: &ast::Expr,
content_expr: &ast::Expr)
-> DatumBlock<'blk, 'tcx, Expr> {
let fcx = bcx.fcx;
let ccx = fcx.ccx;
let mut bcx = bcx;
debug!("trans_slice_vec(slice_expr={})",
bcx.e... |
/// &[...] allocates memory on the stack and writes the values into it, returning the vector (the
/// caller must make the reference). "..." is similar except that the memory can be statically
/// allocated and we return a reference (strings are always by-ref).
pub fn trans_slice_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx... | random_line_split |
tvec.rs | }
};
}
/// &[...] allocates memory on the stack and writes the values into it, returning the vector (the
/// caller must make the reference). "..." is similar except that the memory can be statically
/// allocated and we return a reference (strings are always by-ref).
pub fn trans_slice_vec<'blk, 'tcx>(b... | {
//!
//
// [...] allocates a fixed-size array and moves it around "by value".
// In this case, it means that the caller has already given us a location
// to store the array of the suitable size, so all we have to do is
// generate the content.
debug!("trans_fixed_vstore(expr={}, dest={})"... | identifier_body | |
loc.rs | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Loc<T, P> {
pub inner: T,
pub pos: P,
}
impl<T, P> ::std::ops::Deref for Loc<T, P> {
type Target = T;
fn deref(&self) -> &T {
&self.inner
}
}
impl<T, P> ::std::fmt::Display for Loc<T, P>
where
T: ::std::fmt::Display,
{
... | (&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.inner)
}
}
impl<T, P> ::std::fmt::Debug for Loc<T, P>
where
T: ::std::fmt::Debug,
P: ::std::fmt::Debug,
{
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "<{:?}@{:?}>", sel... | fmt | identifier_name |
loc.rs | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Loc<T, P> {
pub inner: T,
pub pos: P,
}
impl<T, P> ::std::ops::Deref for Loc<T, P> {
type Target = T;
fn deref(&self) -> &T {
&self.inner
}
}
impl<T, P> ::std::fmt::Display for Loc<T, P>
where
T: ::std::fmt::Display,
{
... | write!(f, "<{:?}@{:?}>", self.inner, self.pos)
}
} | random_line_split | |
loc.rs | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Loc<T, P> {
pub inner: T,
pub pos: P,
}
impl<T, P> ::std::ops::Deref for Loc<T, P> {
type Target = T;
fn deref(&self) -> &T {
&self.inner
}
}
impl<T, P> ::std::fmt::Display for Loc<T, P>
where
T: ::std::fmt::Display,
{
... |
}
impl<T, P> ::std::fmt::Debug for Loc<T, P>
where
T: ::std::fmt::Debug,
P: ::std::fmt::Debug,
{
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "<{:?}@{:?}>", self.inner, self.pos)
}
}
| {
write!(f, "{}", self.inner)
} | identifier_body |
test_optimizers.rs | extern crate autograd as ag;
extern crate ndarray;
use ag::prelude::*;
use ag::tensor_ops as T;
use ag::variable::NamespaceTrait;
use ag::{optimizers, VariableEnvironment};
use ndarray::array;
#[test]
fn test_adam() {
let mut env = make_env();
let opt = optimizers::Adam::default(
"my_unique_adam",
... | let mean_loss = T::reduce_mean(loss, &[0], false);
let ns = g.default_namespace();
let (vars, grads) = optimizers::grad_helper(&[mean_loss], &ns);
opt.update(&vars, &grads, g, ag::Feeder::new());
});
} | let z = T::matmul(x, w) + b;
let loss = T::sparse_softmax_cross_entropy(z, &y); | random_line_split |
test_optimizers.rs | extern crate autograd as ag;
extern crate ndarray;
use ag::prelude::*;
use ag::tensor_ops as T;
use ag::variable::NamespaceTrait;
use ag::{optimizers, VariableEnvironment};
use ndarray::array;
#[test]
fn test_adam() {
let mut env = make_env();
let opt = optimizers::Adam::default(
"my_unique_adam",
... | {
env.run(|g| {
let x = T::convert_to_tensor(array![[0.1, 0.2], [0.2, 0.1]], g).show();
let y = T::convert_to_tensor(array![1., 0.], g).show();
let w = g.variable("w");
let b = g.variable("b");
let z = T::matmul(x, w) + b;
let loss = T::sparse_softmax_cross_entropy(z,... | identifier_body | |
test_optimizers.rs | extern crate autograd as ag;
extern crate ndarray;
use ag::prelude::*;
use ag::tensor_ops as T;
use ag::variable::NamespaceTrait;
use ag::{optimizers, VariableEnvironment};
use ndarray::array;
#[test]
fn test_adam() {
let mut env = make_env();
let opt = optimizers::Adam::default(
"my_unique_adam",
... | () -> VariableEnvironment<'static, f64> {
let mut env = ag::VariableEnvironment::new();
let rng = ag::ndarray_ext::ArrayRng::<f64>::default();
env.name("w").set(rng.glorot_uniform(&[2, 2]));
env.name("b").set(ag::ndarray_ext::zeros(&[1, 2]));
env
}
fn run<O: Optimizer<f64>>(opt: O, env: VariableEnv... | make_env | identifier_name |
postmortem.py | (var)
def reflectClass(cls):
"""
Inspect class and get all the useful information for post-mortem
"""
# Reflect static variables
v_static = {}
for k,v in cls.__class__.__dict__.iteritems():
v_static[k] = dumpVariable(v)
# Reflect instance variables
v_instance = {}
for k,v in cls.__class__.__dict__.iterite... | (buf, fromBase64=True):
"""
Decode a buffer previously encoded with asBuffer
"""
# Decode buffer
if fromBase64:
buf = base64.b64decode(buf)
# Decompress buffer
buf = zlib.decompress(buf)
# Unpickle into sections
return pickle.loads(buf)
@staticmethod
def render(sections):
"""
Visualize th... | fromBuffer | identifier_name |
postmortem.py | for s in config.sections():
for o in config.options(s):
# Calculate key name
n = "%s%s.%s" % (prefix,s,o)
# Skip the ones we should skip
if n in skip:
continue
# Store on response
dat[n] = config.get(s,o)
# Handle dict instance
elif isinstance(config, dict):
for k,v in conf... | print " <%s> %s" % (formatTime(l[0]), l[1])
print ""
| random_line_split | |
postmortem.py | (var)
def reflectClass(cls):
"""
Inspect class and get all the useful information for post-mortem
"""
# Reflect static variables
v_static = {}
for k,v in cls.__class__.__dict__.iteritems():
v_static[k] = dumpVariable(v)
# Reflect instance variables
v_instance = {}
for k,v in cls.__class__.__dict__.iterite... |
class PostMortem:
"""
This class provides simple, post-mortem data collection information.
Such post-mortem can be submitted for discovering bugs in the application.
"""
GLOBAL_INFO = {}
GLOBAL_CONFIG = {}
def __init__(self):
"""
Initialize the post-mortem logging class
"""
# Flag to mark if the pos... | """
Format unix time to string
"""
# If we got none or false, return empty string
if not time:
return ""
# Format time
dt = datetime.datetime.fromtimestamp(time)
return "%i/%i/%i %i:%i:%i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) | identifier_body |
postmortem.py | v = getattr(config, k)
# Skip hidden entries
if k[0] == "_":
continue
# Check for methods
if inspect.ismethod(v) or inspect.isfunction(v):
continue
# Calculate key name
n = "%s%s" % (prefix,k)
# Store value
dat[n] = pprint.pformat(v)
# Store response
return dat
def formatTime(... | i = 0
for proc in self.activeProcesses:
res = proc['pp'].poll()
if res != None:
# Update exit code and exit time
proc['e']['exit'] = res
proc['e']['t_exit'] = time.time()
# Remove from monitoring
del self.activeProcesses[i]
i -= 1
# Update index
i += 1
time.sleep(... | conditional_block | |
git.py | # Include the offending line to simplify troubleshooting if
# this error ever occurs.
raise ValueError('unexpected show-ref line: {!r}'.format(line))
refs[ref] = sha
branch_ref = 'refs/remotes/origin/{}'.format(rev)
tag_ref = 'refs/tags/{}'.f... | update_submodules | identifier_name | |
git.py | _args(rev):
return [rev]
def is_immutable_rev_checkout(self, url, dest):
# type: (str, str) -> bool
_, rev_options = self.get_url_rev_options(hide_url(url))
if not rev_options.rev:
return False
if not self.is_commit_id_equal(dest, rev_options.rev):
# ... |
# get first 3 positions of the git version because
# on windows it is x.y.z.windows.t, and this parses as
# LegacyVersion which always smaller than a Version.
version = '.'.join(version.split('.')[:3])
return parse_version(version)
@classmethod
def get_current_branch(cl... | version = '' | conditional_block |
git.py | rev.startswith("refs/"):
# Always fetch remote refs.
return True
if not looks_like_hash(rev):
# Git fetch would fail with abbreviated commits.
return False
if cls.has_commit(dest, rev):
# Don't fetch if we have the commit locally.
... | loc = super(Git, cls).get_repository_root(location)
if loc:
return loc
try:
r = cls.run_command(
['rev-parse', '--show-toplevel'],
cwd=location,
show_stdout=False,
stdout_only=True,
on_returncode='rai... | identifier_body | |
git.py | if rev.startswith("refs/"):
# Always fetch remote refs.
return True
if not looks_like_hash(rev):
# Git fetch would fail with abbreviated commits.
return False
if cls.has_commit(dest, rev):
# Don't fetch if we have the commit locally.
... | return os.path.normpath(r.rstrip('\r\n')) | random_line_split | |
term.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> Term {
Term {
err: Box::new(io::stderr())
}
}
pub fn err(&mut self, msg: &str) {
// swallow any errors
let _ = writeln!(&mut self.err, "{}", msg);
env::set_exit_status(101);
}
}
| new | identifier_name |
term.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn err(&mut self, msg: &str) {
// swallow any errors
let _ = writeln!(&mut self.err, "{}", msg);
env::set_exit_status(101);
}
}
| {
Term {
err: Box::new(io::stderr())
}
} | identifier_body |
term.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn err(&mut self, msg: &str) {
// swallow any errors
let _ = writeln!(&mut self.err, "{}", msg);
env::set_exit_status(101);
}
} | err: Box::new(io::stderr())
}
} | random_line_split |
mod.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | use std::time::Duration;
use bincode;
use futures::{sync::mpsc, Future, Stream};
use log;
use serde::Serialize;
use tokio::net::TcpListener;
use service::ButtonService;
use shutdown::{Shutdown, ShutdownCause};
#[cfg(unix)]
fn notify_server_startup<T>(path: &Path, message: &T) -> Result<(), io::Error>
where
T: Se... | random_line_split | |
mod.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | (self, idle: Duration) {
let (tx, rx) = mpsc::channel(0);
let service = ButtonService::new(tx);
let timeout = Shutdown::new(idle, rx).map(|message| match message {
ShutdownCause::Idle(duration) => {
log::info!(
"Shutting down due to being idle fo... | run | identifier_name |
gu.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be | */
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
export default [
[['મ.રાત્રિ', 'સવારે', 'બપોરે', 'સાંજે', 'રાત્રે'], ['મધ્યરાત્રિ', 'સવારે', 'બપોરે', 'સાંજે', 'રાત્રે'], u],
[['મધ્યરાત્રિ', 'સવારે', 'બપોરે', 'સાંજે', 'રાત્રે'], u, ['મધ્યરાત્રિ', ... | * found in the LICENSE file at https://angular.io/license | random_line_split |
noConsecutiveBlankLinesRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... | extends Lint.Rules.AbstractRule {
public static DEFAULT_ALLOWED_BLANKS = 1;
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "no-consecutive-blank-lines",
description: "Disallows one or more blank lines in a row.",
hasFix: true,... | Rule | identifier_name |
noConsecutiveBlankLinesRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... | else if (consecutiveBlankLines > threshold) {
possibleFailures[possibleFailures.length - 1].end = line.end;
}
} else {
consecutiveBlankLines = 0;
}
}
if (possibleFailures.length === 0) {
return;
}
const failureString = Rule.FAILURE_STRING... | {
possibleFailures.push({
end: line.end,
pos: line.pos,
});
} | conditional_block |
noConsecutiveBlankLinesRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... | return this.applyWithFunction(sourceFile, walk, limit !== undefined ? limit : Rule.DEFAULT_ALLOWED_BLANKS);
}
}
function walk(ctx: Lint.WalkContext<number>) {
const sourceText = ctx.sourceFile.text;
const threshold = ctx.options + 1;
const possibleFailures: ts.TextRange[] = [];
let consecut... | const limit = this.ruleArguments[0] as number | undefined; | random_line_split |
noConsecutiveBlankLinesRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... | }
if (possibleFailures.length === 0) {
return;
}
const failureString = Rule.FAILURE_STRING_FACTORY(ctx.options);
const templateRanges = getTemplateRanges(ctx.sourceFile);
for (const possibleFailure of possibleFailures) {
if (!templateRanges.some((template) => template.pos < poss... | {
const sourceText = ctx.sourceFile.text;
const threshold = ctx.options + 1;
const possibleFailures: ts.TextRange[] = [];
let consecutiveBlankLines = 0;
for (const line of utils.getLineRanges(ctx.sourceFile)) {
if (line.contentLength === 0 || sourceText.substr(line.pos, line.contentLength).... | identifier_body |
kmesg_buffer.rs | extern crate errno;
extern crate libc;
#[cfg(target_os = "macos")]
use std::str;
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")] | #[cfg(target_os = "linux")]
use std::sync::mpsc;
#[cfg(target_os = "linux")]
use std::sync::mpsc::Receiver;
#[cfg(target_os = "linux")]
use std::{thread, time};
// See https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/msgbuf.h
#[cfg(target_os = "macos")]
const MAX_MSG_BSIZE: usize = 1024 * 1024;
// this e... | use std::io::{BufRead, BufReader}; | random_line_split |
kmesg_buffer.rs | extern crate errno;
extern crate libc;
#[cfg(target_os = "macos")]
use std::str;
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::io::{BufRead, BufReader};
#[cfg(target_os = "linux")]
use std::sync::mpsc;
#[cfg(target_os ... | }
}
/// Get a message (String) from the kernel message ring buffer
/// Turns out that reading to the end of an "infinite file" like "/dev/kmsg" with standard file
/// reading methods will block at the end of file, so a workaround is required. Do the blocking
/// reads on a thread that sends lines read back throug... | {
let mut message_buffer: Vec<u8> = Vec::with_capacity(MAX_MSG_BSIZE);
let buffer_ptr = message_buffer.as_mut_ptr() as *mut c_void;
let ret: i32;
unsafe {
ret = proc_kmsgbuf(buffer_ptr, message_buffer.capacity() as u32);
if ret > 0 {
message_buffer.set_len(ret as usize - 1);... | identifier_body |
kmesg_buffer.rs | extern crate errno;
extern crate libc;
#[cfg(target_os = "macos")]
use std::str;
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::io::{BufRead, BufReader};
#[cfg(target_os = "linux")]
use std::sync::mpsc;
#[cfg(target_os ... | () -> Result<String, String> {
let mut message_buffer: Vec<u8> = Vec::with_capacity(MAX_MSG_BSIZE);
let buffer_ptr = message_buffer.as_mut_ptr() as *mut c_void;
let ret: i32;
unsafe {
ret = proc_kmsgbuf(buffer_ptr, message_buffer.capacity() as u32);
if ret > 0 {
message_buff... | kmsgbuf | identifier_name |
zemanta.py | #!/usr/bin/env python
"""zemanta.py: Get suggestions from zemanta.
Last modified: Sat Jan 18, 2014 05:01PM
"""
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2013, Dilawar Singh"
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email... | gateway = 'http://api.zemanta.com/services/rest/0.0/'
args = {'method': 'zemanta.suggest',
'api_key': '{}'.format(key),
'text' : '{}'.format(text),
'return_categories': 'dmoz',
'format': 'json'}
args_enc = urllib.urlencode(args)
raw_output = urlli... | identifier_body | |
zemanta.py | #!/usr/bin/env python
"""zemanta.py: Get suggestions from zemanta.
Last modified: Sat Jan 18, 2014 05:01PM
"""
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2013, Dilawar Singh"
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email... | output = simplejson.loads(raw_output)
return output | random_line_split | |
zemanta.py | #!/usr/bin/env python
"""zemanta.py: Get suggestions from zemanta.
Last modified: Sat Jan 18, 2014 05:01PM
"""
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2013, Dilawar Singh"
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email... | (key, text):
gateway = 'http://api.zemanta.com/services/rest/0.0/'
args = {'method': 'zemanta.suggest',
'api_key': '{}'.format(key),
'text' : '{}'.format(text),
'return_categories': 'dmoz',
'format': 'json'}
args_enc = urllib.urlencode(args)
r... | getZemantaSuggestion | identifier_name |
p109.rs | //! [Problem 109](https://projecteuler.net/problem=109) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use polynomial::Polynomial;
fn | (score: u32) -> u32 {
let mut single = vec![0u32; 26];
let mut double = vec![0; 51];
let mut triple = vec![0; 61];
let mut dup = vec![0; 121];
for i in 1..21 {
single[i] = 1;
double[i * 2] = 1;
triple[i * 3] = 1;
dup[i * 2] += 1;
dup[i * 4] += 1;
dup[i... | count_way | identifier_name |
p109.rs | //! [Problem 109](https://projecteuler.net/problem=109) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use polynomial::Polynomial;
fn count_way(score: u32) -> u32 {
let mut single = vec![0u32; 26];
let mut doubl... |
}
| {
assert_eq!(11, super::count_way(6));
assert_eq!(42336, super::count_way(171));
} | identifier_body |
p109.rs | //! [Problem 109](https://projecteuler.net/problem=109) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use polynomial::Polynomial;
fn count_way(score: u32) -> u32 {
let mut single = vec![0u32; 26];
let mut doubl... | let p1 = double.clone();
let p2 = &double * &p_all;
let p3 = &double
* Polynomial::new(
(&p_all * &p_all + &dup)
.data()
.iter()
.map(|&n| n / 2)
.collect(),
);
let total = p1 + p2 + p3;
total.data().iter().t... |
let p_all = &single + &double + &triple; | random_line_split |
conftest.py | ##############
# Standard #
##############
import io
import logging
import tempfile
##############
# External #
##############
import pytest
##############
# Module #
##############
import powermate
#Enable the logging level to be set from the command line
def pytest_addoption(parser):
parser.addoption('... |
#Create basic configuration
logging.basicConfig(level=log_level, format='%(message)s')
@pytest.fixture(scope='module')
def pseudo_socket():
with tempfile.NamedTemporaryFile() as tmp:
s = powermate.event.Socket(tmp.name)
s._input = io.BytesIO()
s._output = io.BytesIO()
yie... | raise ValueError("Invalid log level : {}".format(log_level)) | conditional_block |
conftest.py | ##############
# Standard #
##############
import io
import logging
import tempfile
##############
# External #
##############
import pytest
##############
# Module #
##############
import powermate
#Enable the logging level to be set from the command line
def pytest_addoption(parser):
parser.addoption('... | ():
with tempfile.NamedTemporaryFile() as tmp:
s = powermate.event.Socket(tmp.name)
s._input = io.BytesIO()
s._output = io.BytesIO()
yield s
| pseudo_socket | identifier_name |
conftest.py | ##############
# Standard #
##############
import io
import logging
import tempfile
##############
# External #
##############
import pytest
##############
# Module #
##############
import powermate
#Enable the logging level to be set from the command line
def pytest_addoption(parser):
parser.addoption('... | with tempfile.NamedTemporaryFile() as tmp:
s = powermate.event.Socket(tmp.name)
s._input = io.BytesIO()
s._output = io.BytesIO()
yield s | identifier_body | |
conftest.py | ##############
# Standard #
############## | import io
import logging
import tempfile
##############
# External #
##############
import pytest
##############
# Module #
##############
import powermate
#Enable the logging level to be set from the command line
def pytest_addoption(parser):
parser.addoption('--log', action='store', default='INFO',
... | random_line_split | |
lib.rs | #![feature(try_from)]
#![feature(const_fn)]
#![feature(const_size_of)]
#[macro_use] extern crate log;
extern crate pest;
#[macro_use] extern crate pest_derive;
pub extern crate core;
extern crate machine;
mod var_instr;
mod property;
mod label;
use std::rc::Rc;
use std::io::Write;
use std::borrow::Cow;
use std::mem;... | match var_instr.as_instr(offset, &label_offsets) {
Ok(instr) => {
offset += instr.mem_size();
instructions.push(instr);
},
Err(LabelNotFound(label)) => return Err(Error::CustomErrorSpan {
message: "label not found".into(),
... | let mut offset = 0;
for var_instr in &var_instrs { | random_line_split |
lib.rs | #![feature(try_from)]
#![feature(const_fn)]
#![feature(const_size_of)]
#[macro_use] extern crate log;
extern crate pest;
#[macro_use] extern crate pest_derive;
pub extern crate core;
extern crate machine;
mod var_instr;
mod property;
mod label;
use std::rc::Rc;
use std::io::Write;
use std::borrow::Cow;
use std::mem;... | (name: &str, comment: &str, instrs: &[Instruction], output: &mut Vec<u8>) {
let mut header = Header {
magic: COREWAR_EXEC_MAGIC.to_be(),
prog_name: [0u8; PROG_NAME_LENGTH + 1],
prog_size: (instrs.iter().map(MemSize::mem_size).sum::<usize>() as u32).to_be(),
comment: [0u8; COMMENT_LEN... | raw_compile | identifier_name |
test_distreporter.py | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.trial.distreporter}.
"""
from cStringIO import StringIO
from twisted.trial._dist.distreporter import DistReporter
from twisted.trial.unittest import TestCase
from twisted.trial.reporter import TreeReporter
class DistRe... | (self):
"""
Calling methods of L{DistReporter} add calls to the running queue of
the test.
"""
self.distReporter.startTest(self.test)
self.distReporter.addFailure(self.test, "foo")
self.distReporter.addError(self.test, "bar")
self.distReporter.addSkip(self... | test_forwardedMethods | identifier_name |
test_distreporter.py | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
""" | Tests for L{twisted.trial.distreporter}.
"""
from cStringIO import StringIO
from twisted.trial._dist.distreporter import DistReporter
from twisted.trial.unittest import TestCase
from twisted.trial.reporter import TreeReporter
class DistReporterTestCase(TestCase):
"""
Tests for L{DistReporter}.
"""
... | random_line_split | |
test_distreporter.py | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.trial.distreporter}.
"""
from cStringIO import StringIO
from twisted.trial._dist.distreporter import DistReporter
from twisted.trial.unittest import TestCase
from twisted.trial.reporter import TreeReporter
class DistRe... | """
Calling methods of L{DistReporter} add calls to the running queue of
the test.
"""
self.distReporter.startTest(self.test)
self.distReporter.addFailure(self.test, "foo")
self.distReporter.addError(self.test, "bar")
self.distReporter.addSkip(self.test, "egg")
... | identifier_body | |
game_core.rs |
use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD};
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
... | (&mut self) {
if let Some(cmd) = self.vm.console.get_next_command() {
let (result, unblock_event) = self.command_system.execute(cmd, &mut self.vm);
if let CommandResult::NotFound = result {
writeln!(self.vm.console, "Command not recognized, type 'help' for a list of comm... | update | identifier_name |
game_core.rs | use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext; |
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
pub command_system: CommandSystem,
unblock_event: Option<UnblockEvent>,
}
impl<'a> GameCore<'a> {
pub fn new(ttf_context: &'a Sdl2TtfContext,
mut renderer: &mut Renderer,
font_file: &'a str)
... | use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD}; | random_line_split |
game_core.rs |
use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD};
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
... |
pub fn process_event(&mut self, event: &Event) {
match *event {
// Stop a blocking event
Event::KeyDown { keycode, keymod, .. }
if (keycode == Some(Keycode::C) && keymod.intersects(LCTRLMOD | RCTRLMOD) || keycode == Some(Keycode::Return)) &&
self.unblock_... | {
let cpu = Cpu::new();
let vm = VirtualMachine::new(cpu, 150, &ttf_context, &mut renderer, font_file);
GameCore {
vm: vm,
command_system: CommandSystem::new(),
unblock_event: None,
}
} | identifier_body |
game_core.rs |
use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD};
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
... |
}
self.vm.cycle();
}
}
| {
self.unblock_event = None;
} | conditional_block |
docscrape_sphinx.py | import re, inspect, textwrap, pydoc
import sphinx
from docscrape import NumpyDocString, FunctionDoc, ClassDoc
class SphinxDocString(NumpyDocString):
def __init__(self, docstring, config=None):
config = {} if config is None else config
self.use_plots = config.get('use_plots', False)
NumpyDoc... | (SphinxDocString, ClassDoc):
def __init__(self, obj, doc=None, func_doc=None, config={}):
self.use_plots = config.get('use_plots', False)
ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config)
class SphinxObjDoc(SphinxDocString):
def __init__(self, obj, doc=None, config=None):
... | SphinxClassDoc | identifier_name |
docscrape_sphinx.py | import re, inspect, textwrap, pydoc
import sphinx
from docscrape import NumpyDocString, FunctionDoc, ClassDoc
class SphinxDocString(NumpyDocString):
def __init__(self, docstring, config=None):
config = {} if config is None else config
self.use_plots = config.get('use_plots', False)
NumpyDoc... |
def __str__(self, indent=0, func_role="obj"):
out = []
out += self._str_signature()
out += self._str_index() + ['']
out += self._str_summary()
out += self._str_extended_summary()
for param_list in ('Parameters', 'Returns', 'Raises'):
out += self._str_par... | return self._str_section('Examples') | conditional_block |
docscrape_sphinx.py | import re, inspect, textwrap, pydoc
import sphinx
from docscrape import NumpyDocString, FunctionDoc, ClassDoc
class SphinxDocString(NumpyDocString):
def __init__(self, docstring, config=None):
config = {} if config is None else config
self.use_plots = config.get('use_plots', False)
NumpyDoc... |
def get_doc_object(obj, what=None, doc=None, config={}):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == '... | def __init__(self, obj, doc=None, config=None):
self._f = obj
SphinxDocString.__init__(self, doc, config=config) | identifier_body |
docscrape_sphinx.py | import re, inspect, textwrap, pydoc
import sphinx
from docscrape import NumpyDocString, FunctionDoc, ClassDoc
class SphinxDocString(NumpyDocString):
def __init__(self, docstring, config=None):
config = {} if config is None else config
self.use_plots = config.get('use_plots', False)
NumpyDoc... |
def _str_warnings(self):
out = []
if self['Warnings']:
out = ['.. warning::', '']
out += self._str_indent(self['Warnings'])
return out
def _str_index(self):
idx = self['index']
out = []
if len(idx) == 0:
return out
ou... | return out | random_line_split |
fixtures.ts | import * as moment from "moment";
import * as Faker from "faker";
import {random, shuffle, range} from "lodash";
import {Vote} from "./vote/vote.models";
import {PollOption, Poll} from "./poll/poll.models";
let lastId = 0;
function mockId(type?: string): string {
return `mock_${type || 'mockId'}_${++lastId}`;
}
c... |
let optionIds = options.map(opt => opt.id);
return {
prompt: `Who should ${Faker.lorem.sentence().toLowerCase().slice(0, -1)}?`,
id: mockId('poll'),
options: options,
status: 'open',
security: 'unverified',
created: moment(),
published: true,
expires: false,
owner: mockId('for... | {
options[ i ] = mockPollOption();
} | conditional_block |
fixtures.ts | import * as moment from "moment";
import * as Faker from "faker";
import {random, shuffle, range} from "lodash";
import {Vote} from "./vote/vote.models";
import {PollOption, Poll} from "./poll/poll.models";
let lastId = 0;
function | (type?: string): string {
return `mock_${type || 'mockId'}_${++lastId}`;
}
const COLORS = [
"#5C6BC0",
"#EF5350",
"#43A047",
"#7E57C2",
"#FF8A65",
"#8D6E63",
"#F06292",
"#FDD835",
"#3ba9c4",
"#81C784",
"#868086",
'#00796B',
'#D84315',
'#1B5E20',
'#FFE57F',
"#76FF03",
'#424242',
"... | mockId | identifier_name |
fixtures.ts | import * as moment from "moment";
import * as Faker from "faker";
import {random, shuffle, range} from "lodash";
import {Vote} from "./vote/vote.models";
import {PollOption, Poll} from "./poll/poll.models";
let lastId = 0;
function mockId(type?: string): string {
return `mock_${type || 'mockId'}_${++lastId}`;
}
c... |
export function mockVoteWithChoices(choices: string[]): Vote {
return {
id: mockId('vote'),
owner: mockId('forAny'),
choices: choices,
published: false,
cast: moment()
}
}
export function mockVote(availableChoices: string[]): Vote {
let numChoices = random(1, availableChoices.length),
s... | {
return COLORS[ ++lastColorReturned % COLORS.length ];
} | identifier_body |
fixtures.ts | import * as moment from "moment";
import * as Faker from "faker";
import {random, shuffle, range} from "lodash";
import {Vote} from "./vote/vote.models";
import {PollOption, Poll} from "./poll/poll.models";
let lastId = 0;
function mockId(type?: string): string {
return `mock_${type || 'mockId'}_${++lastId}`;
}
c... | text: name,
color: color()
};
}
export function mockPoll(): Poll {
let numOptions = random(5, 8),
options: PollOption[] = [];
for (let i = 0; i < numOptions; i++) {
options[ i ] = mockPollOption();
}
let optionIds = options.map(opt => opt.id);
return {
prompt: `Who should ${Faker.lo... | let name = `${Faker.name.firstName()} ${Faker.name.lastName()}`;
return {
id: mockId(), | random_line_split |
hash-param-read.test.js | import {
assert, html, nextFrame
} from '@open-wc/testing';
import { setupOmnitableFixture } from './helpers/utils';
import '../cosmoz-omnitable.js';
import '../cosmoz-omnitable-column-autocomplete.js';
import '../cosmoz-omnitable-column.js';
let omnitable; | group: 'group0',
name: 'Item 0'
}, {
id: 1,
group: 'group0',
name: 'Item 1'
}, {
id: 2,
group: 'group1',
name: 'Item 2'
}, {
id: 3,
group: 'group1',
name: 'Item 3'
}],
location = window.location,
instantiate = async () => {
await nextFrame();
omnitable = await setupOmnitableFixture(html`... | const data = [{
id: 0, | random_line_split |
passport-facebook-token.d.ts | // Type definitions for passport-facebook-token 0.4.0
// Project: https://github.com/drudge/passport-facebook-token
// Definitions by: Ray Martone <https://github.com/rmartone>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../passport/passport.d.ts"/>
declare module 'passport-fac... | implements passport.Strategy {
constructor(options: StrategyOptions,
verify: (accessToken: string,
refreshToken: string,
profile: Profile,
done: (err: any, user?: any) => void) => void);
name: str... | Strategy | identifier_name |
passport-facebook-token.d.ts | // Type definitions for passport-facebook-token 0.4.0
// Project: https://github.com/drudge/passport-facebook-token
// Definitions by: Ray Martone <https://github.com/rmartone>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../passport/passport.d.ts"/>
declare module 'passport-fac... | constructor(options: StrategyOptions,
verify: (accessToken: string,
refreshToken: string,
profile: Profile,
done: (err: any, user?: any) => void) => void);
name: string;
authenticate: (req:... | random_line_split | |
impl_q_string.rs | use crate::QString;
use cpp_core::CppBox;
use std::os::raw::{c_char, c_int};
/// Allows to convert Qt strings to `std` strings
impl<'a> From<&'a QString> for String {
fn from(s: &'a QString) -> String |
}
impl QString {
/// Creates Qt string from an `std` string.
///
/// `QString` makes a deep copy of the data.
pub fn from_std_str<S: AsRef<str>>(s: S) -> CppBox<QString> {
let slice = s.as_ref().as_bytes();
unsafe { QString::from_utf8_char_int(slice.as_ptr() as *mut c_char, slice.len()... | {
s.to_std_string()
} | identifier_body |
impl_q_string.rs | use crate::QString;
use cpp_core::CppBox;
use std::os::raw::{c_char, c_int};
/// Allows to convert Qt strings to `std` strings
impl<'a> From<&'a QString> for String {
fn | (s: &'a QString) -> String {
s.to_std_string()
}
}
impl QString {
/// Creates Qt string from an `std` string.
///
/// `QString` makes a deep copy of the data.
pub fn from_std_str<S: AsRef<str>>(s: S) -> CppBox<QString> {
let slice = s.as_ref().as_bytes();
unsafe { QString::f... | from | identifier_name |
impl_q_string.rs | use crate::QString;
use cpp_core::CppBox;
use std::os::raw::{c_char, c_int};
/// Allows to convert Qt strings to `std` strings
impl<'a> From<&'a QString> for String {
fn from(s: &'a QString) -> String {
s.to_std_string()
}
}
impl QString {
/// Creates Qt string from an `std` string.
///
//... | } | random_line_split | |
Dashling.d.ts | import Settings from './Settings';
import StreamController from './StreamController';
import { DashlingSessionState, DashlingRequestState } from './DashlingEnums';
export default class Dashling {
/** Exported enums for simplifying access externally. */
Event: {
sessionStateChange: string;
downlo... | getBufferRate(): number;
getPlayingQuality(streamType: string): number;
getBufferingQuality(streamType: string): number;
getMaxQuality(streamType: string): number;
private _setState(state, errorType?, errorMessage?);
private _initializeMediaSource(videoElement);
private _initializeManifest(u... | random_line_split | |
Dashling.d.ts | import Settings from './Settings';
import StreamController from './StreamController';
import { DashlingSessionState, DashlingRequestState } from './DashlingEnums';
export default class | {
/** Exported enums for simplifying access externally. */
Event: {
sessionStateChange: string;
download: string;
};
SessionState: typeof DashlingSessionState;
RequestState: typeof DashlingRequestState;
state: DashlingSessionState;
lastError: string;
lastErrorType: strin... | Dashling | identifier_name |
day23.rs | 3 => Ok(Pod::D),
_ => Err(index),
}
}
}
impl TryFrom<char> for Pod {
type Error = &'static str;
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'A' => Ok(Pod::A),
'B' => Ok(Pod::B),
'C' => Ok(Pod::C),
'D' => Ok(Pod::... | &self.hallway[(pos + 1)..new_hallway_pos]
};
if in_between.iter().any(Option::is_some) {
// Something's in the way
continue;
}
// Check if we can move into the room
if self.rooms[room]
.iter()
... |
// Check if the path is free
let in_between = if new_hallway_pos < pos {
&self.hallway[(new_hallway_pos + 1)..pos]
} else { | random_line_split |
day23.rs | 3 => Ok(Pod::D),
_ => Err(index),
}
}
}
impl TryFrom<char> for Pod {
type Error = &'static str;
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'A' => Ok(Pod::A),
'B' => Ok(Pod::B),
'C' => Ok(Pod::C),
'D' => Ok(Pod::... | (&self) -> u32 {
// A* estimate. For every entry that is not already "at rest", the cost is the cost
// required to get it to the top of its intended room.
// Cost to enter the hole for all pods that still need to
let enter_estimate: u32 = self
.rooms
.iter()
... | estimate | identifier_name |
day23.rs | 3 => Ok(Pod::D),
_ => Err(index),
}
}
}
impl TryFrom<char> for Pod {
type Error = &'static str;
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'A' => Ok(Pod::A),
'B' => Ok(Pod::B),
'C' => Ok(Pod::C),
'D' => Ok(Pod::... |
let new_cost = (base_cost + new_pos - hallway_pos) as u32 * pod.cost();
queue_new(new_pos, new_cost);
}
}
}
fn hallway_to_room(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
for (pos, pod) in self
.hallway
... | {
// Not allowed to stop here
continue;
} | conditional_block |
attributes.rs | pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint,... |
/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
if emit {
llvm::SetFunctionAttribute(val, llvm::Attribute::UWTable);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
... | {
use self::InlineAttr::*;
match inline {
Hint => llvm::SetFunctionAttribute(val, llvm::Attribute::InlineHint),
Always => llvm::SetFunctionAttribute(val, llvm::Attribute::AlwaysInline),
Never => llvm::SetFunctionAttribute(val, llvm::Attribute::NoInline),
None => {
... | identifier_body |
attributes.rs | ]
pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uin... | }
}
for &t in input_tys.iter() {
match t.sty {
_ if type_of::arg_is_indirect(ccx, t) => {
let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));
// For non-immediate arguments the callee gets its own copy of
// the val... | } | random_line_split |
attributes.rs | ]
pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uin... | (ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
use syntax::attr::*;
inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs));
// FIXME: #11906: Omitting frame pointers breaks retrieving the value of a
// parameter.
let no_fp_elim = (ccx.sess().opts.debuginfo != NoDebug... | from_fn_attrs | identifier_name |
attributes.rs | pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint,... |
}
}
for &t in input_tys.iter() {
match t.sty {
_ if type_of::arg_is_indirect(ccx, t) => {
let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));
// For non-immediate arguments the callee gets its own copy of
// the va... | {
attrs.ret(llvm::Attribute::ZExt);
} | conditional_block |
path.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | }
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(windows))]
pub fn restrict_permissions_owner(file_path: &Path) -> Result<(), i32> {
let cstr = ::std::ffi::CString::new(file_path.to_str().unwrap()).unwrap();
match unsafe { ::libc::chmod(cstr.as_ptr(), ::libc::S_IWUSR | ::libc::S_IRUSR) ... | path.push(s);
path | random_line_split |
path.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
/// Restricts the permissions of given path only to the owner.
#[cfg(windows)]
pub fn restrict_permissions_owner(_file_path: &Path) -> Result<(), i32> {
//TODO: implement me
Ok(())
}
| {
let cstr = ::std::ffi::CString::new(file_path.to_str().unwrap()).unwrap();
match unsafe { ::libc::chmod(cstr.as_ptr(), ::libc::S_IWUSR | ::libc::S_IRUSR) } {
0 => Ok(()),
x => Err(x),
}
} | identifier_body |
path.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (s: &str) -> PathBuf {
let mut path = default();
path.push("testnet");
path.push(s);
path
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(windows))]
pub fn restrict_permissions_owner(file_path: &Path) -> Result<(), i32> {
let cstr = ::std::ffi::CString::new(file_path.to_str().un... | with_testnet | identifier_name |
comparisonOperatorWithSubtypeObjectOnIndexSignature.js | //// [comparisonOperatorWithSubtypeObjectOnIndexSignature.ts]
class Base {
public a: string;
}
class Derived extends Base {
public b: string;
}
var a1: { [a: string]: string };
var b1: { [b: string]: string };
var a2: { [index: string]: Base };
var b2: { [index: string]: Derived };
var a3: { [index: number... |
return Derived;
}(Base));
var a1;
var b1;
var a2;
var b2;
var a3;
var b3;
var a4;
var b4;
// operator <
var r1a1 = a1 < b1;
var r1a1 = a2 < b2;
var r1a1 = a3 < b3;
var r1a1 = a4 < b4;
var r1b1 = b1 < a1;
var r1b1 = b2 < a2;
var r1b1 = b3 < a3;
var r1b1 = b4 < a4;
// operator >
var r2a1 = a1 > ... | {
return _super !== null && _super.apply(this, arguments) || this;
} | identifier_body |
comparisonOperatorWithSubtypeObjectOnIndexSignature.js | //// [comparisonOperatorWithSubtypeObjectOnIndexSignature.ts]
class Base {
public a: string;
}
class Derived extends Base {
public b: string;
}
var a1: { [a: string]: string };
var b1: { [b: string]: string };
var a2: { [index: string]: Base };
var b2: { [index: string]: Derived };
var a3: { [index: number... | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.cons... |
//// [comparisonOperatorWithSubtypeObjectOnIndexSignature.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
| random_line_split |
comparisonOperatorWithSubtypeObjectOnIndexSignature.js | //// [comparisonOperatorWithSubtypeObjectOnIndexSignature.ts]
class Base {
public a: string;
}
class Derived extends Base {
public b: string;
}
var a1: { [a: string]: string };
var b1: { [b: string]: string };
var a2: { [index: string]: Base };
var b2: { [index: string]: Derived };
var a3: { [index: number... | () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Base = /** @class */ (function () {
function Base() {
}
return Base;
}());
var Derived = /** @class */ (function (_super) {
__extends(Derived, _super);
... | __ | identifier_name |
popwin.js | function PopWinObject()
{
//var i = document.createElement("<iframe IsPopWin=1 name=PopWinIframe scrolling=no style='position:absolute;top:200;border:2 outset'></iframe>");
var i=document.createElement("div");
document.body.insertBefore(i);
i.outerHTML = "<iframe IsPopWin=1 id=PopWinIframe width=1 height=1 frame... | this.Object.Display = "none";
this.Object.Window.setTimeout("if(PopWinObject.Display=='none' && PopWinObject.HideWhenMouseOut) PopWinObject.Hide();",2000)
}
this.Show = function (x,y,w,h,html)
{
if(html)
this.Body.innerHTML = html;
if(h)
this.Iframe.style.posHeight = h;
if(w)
this.Iframe.style.p... | random_line_split | |
popwin.js | function | ()
{
//var i = document.createElement("<iframe IsPopWin=1 name=PopWinIframe scrolling=no style='position:absolute;top:200;border:2 outset'></iframe>");
var i=document.createElement("div");
document.body.insertBefore(i);
i.outerHTML = "<iframe IsPopWin=1 id=PopWinIframe width=1 height=1 frameborder=0 scrolling=no... | PopWinObject | identifier_name |
popwin.js | function PopWinObject()
| this.Body.style.marginBottom=0;
this.Body.style.backgroundColor="#cccccc";
this.IsAutoSize = true;
this.HideWhenMouseOut = true;
this.ClearWhenHide = false;
EventHandler.AddObject(this);
this.Iframe.onmouseover = function()
{
this.Object.Display = "block";
}
this.Iframe.onmouseout = function()
{
this.O... | {
//var i = document.createElement("<iframe IsPopWin=1 name=PopWinIframe scrolling=no style='position:absolute;top:200;border:2 outset'></iframe>");
var i=document.createElement("div");
document.body.insertBefore(i);
i.outerHTML = "<iframe IsPopWin=1 id=PopWinIframe width=1 height=1 frameborder=0 scrolling=no sty... | identifier_body |
gcalendar.rs | }
pub struct GCalendar {
/*
* Calendar object with date and time.
*/
sec: uint, /* Seconds [0-59] */
min: uint, /* Minutes [0-59] */
hour: uint, /* Hours [0-23] */
mday: uint, /* Day [0-30] */
month: uint, /* Month... |
pub fn get_day_of_month(&self) -> uint {
self.mday
}
pub fn get_month(&self) -> uint {
self.month
}
pub fn get_year(&self) -> uint {
self.year
}
pub fn get_day_of_week(&self) -> uint {
self.wday
}
pub fn get_day_of_year(&self) -> uint {
s... | {
self.hour
} | identifier_body |
gcalendar.rs | }
pub struct GCalendar {
/*
* Calendar object with date and time.
*/
sec: uint, /* Seconds [0-59] */
min: uint, /* Minutes [0-59] */
hour: uint, /* Hours [0-23] */
mday: uint, /* Day [0-30] */
month: uint, /* Month... | y -= 1;
}
let years = (year1 - year0);
let days = 365 * years + yday1 - yday0 + intervening_leap_days;
let hours = 24 * days + hour1 - hour0;
let minutes = 60 * hours + min1 - min0;
60 * minutes + sec1 - sec0
}
pub fn mktime(&self) -> uint {
... | while (y > year0) {
if is_leap_year(y) {intervening_leap_days += 1;} | random_line_split |
gcalendar.rs | }
pub struct GCalendar {
/*
* Calendar object with date and time.
*/
sec: uint, /* Seconds [0-59] */
min: uint, /* Minutes [0-59] */
hour: uint, /* Hours [0-23] */
mday: uint, /* Day [0-30] */
month: uint, /* Month... | (&self, year1: uint, yday1: uint, hour1: uint, min1: uint,
sec1: uint, year0: uint, yday0: uint, hour0: uint,
min0: uint, sec0: uint) -> uint {
/* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
* (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds.
... | ydhms_diff | identifier_name |
gcalendar.rs | /**
* Allocates a GCalendar object at epoch.
*/
pub fn new_at_epoch() -> GCalendar {
GCalendar {
sec: 0,
min: 0,
hour: 0,
mday: 0,
month: 0,
year: 0,
wday: 0,
yday: 0,
}
}
/**
* A... | {
format!("{}/{}/{}",
self.get_date('m'),
self.get_date('d'),
self.get_date('y'))
} | conditional_block | |
shared.py | from os.path import abspath
import sys
import logging
editorconfig_path = abspath('editorconfig-core-py/')
if editorconfig_path not in sys.path:
sys.path.append(editorconfig_path)
from editorconfig import get_properties, EditorConfigError
class EditorConfigPluginMixin(object):
def activate_plugin(self, win... |
def set_indentation(self, view, indent_style, indent_size, tab_width):
"""Set indentation style for given view based on given properties"""
if indent_style == 'space':
view.set_insert_spaces_instead_of_tabs(True)
if indent_size:
view.set_tab_width(indent_si... | """Set line ending style based on given end_of_line property"""
if end_of_line == "lf":
document.set_property('newline-type', 0)
elif end_of_line == "cr":
document.set_property('newline-type', 1)
elif end_of_line == "crlf":
document.set_property('newline-type'... | identifier_body |
shared.py | from os.path import abspath
import sys
import logging
editorconfig_path = abspath('editorconfig-core-py/')
if editorconfig_path not in sys.path:
sys.path.append(editorconfig_path)
from editorconfig import get_properties, EditorConfigError
class EditorConfigPluginMixin(object):
def activate_plugin(self, win... | (self, window):
"""Get EditorConfig properties for file and change settings"""
tab = window.get_active_tab()
document = tab.get_document()
view = tab.get_view()
props = self.get_document_properties(document)
self.process_properties(props)
self.set_indentation(vi... | set_config | identifier_name |
shared.py | from os.path import abspath
import sys
import logging
editorconfig_path = abspath('editorconfig-core-py/')
if editorconfig_path not in sys.path:
sys.path.append(editorconfig_path)
from editorconfig import get_properties, EditorConfigError
class EditorConfigPluginMixin(object):
def activate_plugin(self, win... | self.set_indentation(view,
props.get('indent_style'),
props.get('indent_size'),
props.get('tab_width'))
self.set_end_of_line(document, props.get('end_of_line'))
self.set_trim_trailing_whitespace(document,
... | random_line_split | |
shared.py | from os.path import abspath
import sys
import logging
editorconfig_path = abspath('editorconfig-core-py/')
if editorconfig_path not in sys.path:
sys.path.append(editorconfig_path)
from editorconfig import get_properties, EditorConfigError
class EditorConfigPluginMixin(object):
def activate_plugin(self, win... |
def set_config(self, window):
"""Get EditorConfig properties for file and change settings"""
tab = window.get_active_tab()
document = tab.get_document()
view = tab.get_view()
props = self.get_document_properties(document)
self.process_properties(props)
sel... | if getattr(document, 'editorconfig_whitespace_handler', None):
document.disconnect(document.editorconfig_whitespace_handler)
document.editorconfig_whitespace_handler = None | conditional_block |
robinhood.rs | // TODO: says premature end of input
// use chrono::{DateTime, NaiveDateTime};
// use chrono::offset::Utc;
use futures::{future, Future, Stream};
use hyper::{client::HttpConnector, Body, Client};
use hyper_tls::HttpsConnector;
use serde_derive::{Deserialize, Serialize};
use serde_json;
type HttpsClient = Client<HttpsC... | {
results: Vec<Quote>,
}
pub fn get_quotes(
client: &HttpsClient,
symbols: &Vec<String>,
) -> impl Future<Item = Quotes, Error = ()> {
let query = &symbols.join(",").to_uppercase();
let url = format!("https://api.robinhood.com/quotes/?symbols={}", query);
client
.get(url.parse().unwrap... | Quotes | identifier_name |
robinhood.rs | // TODO: says premature end of input
// use chrono::{DateTime, NaiveDateTime};
// use chrono::offset::Utc;
use futures::{future, Future, Stream};
use hyper::{client::HttpConnector, Body, Client};
use hyper_tls::HttpsConnector;
use serde_derive::{Deserialize, Serialize};
use serde_json;
type HttpsClient = Client<HttpsC... | last_extended_hours_trade_price: String,
last_trade_price: String,
last_trade_price_source: String,
previous_close: String,
previous_close_date: String,
symbol: String,
trading_halted: bool,
updated_at: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Quotes {
results: ... | // TODO: can this be a URL? needs to implement Serde's deserialize
instrument: String, | random_line_split |
feed_save.js | // Render home page and json data
exports.view = function(req, res){
// Import json data
var logData = require("../data/log.json");
// Set ateFoodGroup to numerical values
var ateGrains;
if(req.body.ateGrains == null){ateGrains = 0;}
else ateGrains = 1;
var ateFruit;
if(req.body.ateFruit == null){ateFruit ... |
"cal": parseInt(req.body.cal),
"mood": parseInt(req.body.mood),
"info": req.body.info,
"image": "public/images/food/oj.jpg",
"ateGrains": ateGrains,
"ateFruit": ateFruit,
"ateVeggies": ateVeggies,
"ateProtein": ateProtein,
"ateDairy": ateDairy
}
logData.push(newLog);
var newData = JSON.strin... | "dd": req.body.dd,
"mm": req.body.mm,
"year": req.body.yy, | random_line_split |
_strcmp95.py | redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Abydos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the impli... | (self, src: str, tar: str) -> float:
"""Return the strcmp95 similarity of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Strcmp95 ... | sim | identifier_name |
_strcmp95.py | redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Abydos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the impli... |
num_sim = n_simi / 10.0 + num_com
# Main weight computation
weight = (
num_sim / len(ying)
+ num_sim / len(yang)
+ (num_com - n_trans) / num_com
)
weight /= 3.0
# Continue to boost the weight if the strings are similar
if wei... | if yang_flag[j] == 0 and _in_range(yang[j]):
if (ying[i], yang[j]) in adjwt:
n_simi += adjwt[(ying[i], yang[j])]
yang_flag[j] = 2
break | conditional_block |
_strcmp95.py | redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Abydos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the impli... | )
weight /= 3.0
# Continue to boost the weight if the strings are similar
if weight > 0.7:
# Adjust for having up to the first 4 characters in common
j = 4 if (minv >= 4) else minv
i = 0
while (i < j) and (ying[i] == yang[i]) and (not yin... | num_sim / len(ying)
+ num_sim / len(yang)
+ (num_com - n_trans) / num_com | random_line_split |
_strcmp95.py | redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Abydos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the impli... | 0.8454999999999999
>>> cmp.sim('aluminum', 'Catalan')
0.6547619047619048
>>> cmp.sim('ATCG', 'TAGC')
0.8333333333333334
.. versionadded:: 0.1.0
.. versionchanged:: 0.3.6
Encapsulated in class
"""
def _in_range(char: str) -> bool:
... | """Return the strcmp95 similarity of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Strcmp95 similarity
Examples
--------... | identifier_body |
MultiMailViewer.ts | import m, {Component} from "mithril"
import {MailView} from "./MailView"
import {assertMainOrNode, isApp, Mode} from "../../api/common/Env"
import {ActionBar} from "../../gui/base/ActionBar"
import ColumnEmptyMessageBox from "../../gui/base/ColumnEmptyMessageBox"
import {lang} from "../../misc/LanguageViewModel"
import... | }]
: []
return [
...cancel,
attachDropdown(
{
label: "move_action",
icon: () => Icons.Folder,
},
() => this.makeMoveMailButtons(),
),
{
label: "delete_action",
click: () => {
let mails = selectedEntities()
promptAndDeleteMails(locator.mailModel, mails, () => ... | click: () => this._mailView.mailList.list.selectNone(),
icon: () => Icons.Cancel, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.