function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def get_next_by_order(self, **kwargs):
"""
Retrieves next object by order.
"""
return self._get_next_or_previous_by_order(True, **kwargs) | cccs-web/mezzanine | [
2,
1,
2,
1,
1404268714
] |
def is_editable(self, request):
"""
Restrict in-line editing to the objects's owner and superusers.
"""
return request.user.is_superuser or request.user.id == self.user_id | cccs-web/mezzanine | [
2,
1,
2,
1,
1404268714
] |
def create_site_permission(sender, **kw):
sender_name = "%s.%s" % (sender._meta.app_label, sender._meta.object_name)
if sender_name.lower() != user_model_name.lower():
return
user = kw["instance"]
if user.is_staff and not user.is_superuser:
perm, created = SitePermission.objects.get_or_c... | cccs-web/mezzanine | [
2,
1,
2,
1,
1404268714
] |
def load_(self, h): return 1 | albertz/music-player | [
483,
61,
483,
16,
1345772141
] |
def testMethods(self):
self.assertResultIsBOOL(TestCIPluginInterfaceHelper.load_) | albertz/music-player | [
483,
61,
483,
16,
1345772141
] |
def findIndex(grid,charElem):
for i in range(len(grid)):
for j in range(len(grid[i])):
if(grid[i][j] == charElem):
return [i,j]
return [-1,-1] | tejasnikumbh/Algorithms | [
6,
5,
6,
1,
1417624809
] |
def genSurr(grid,i,j):
validIndices = []
surrIndices = [ (1,0) , (-1,0) , (0,1) , (0,-1) ]
if(len(grid) == 0): return -1
else:
# Number of rows and columns in grid
ROWS = len(grid)
COLS = len(grid[0])
for (a,b) in surrIndices:
xIndex = i + a
yIndex... | tejasnikumbh/Algorithms | [
6,
5,
6,
1,
1417624809
] |
def genValidSurr(grid,surr,validChars,visitedSet):
validSet = []
for point in surr:
indexI = point[0]
indexJ = point[1]
gridPoint = grid[indexI][indexJ]
if((gridPoint in validChars) and not(point in visitedSet)):
validSet.append(point)
return validSet | tejasnikumbh/Algorithms | [
6,
5,
6,
1,
1417624809
] |
def dfsPathSearch(grid,
startIndex,
goalIndex,
pathSoFar,
visitedNodes):
# Marking the current node as explored
visitedNodes.add(startIndex)
# Base case of recursion in case we want to stop
# after certain condition
if(startInd... | tejasnikumbh/Algorithms | [
6,
5,
6,
1,
1417624809
] |
def parseGrid(stream,r,c):
grid = [[] for x in range(r)]
for i in range(r):
grid[i] = list(stream.readline().rstrip())
return grid | tejasnikumbh/Algorithms | [
6,
5,
6,
1,
1417624809
] |
def get_installed_pypackages():
return {p.project_name.lower(): p for p in pkg_resources.working_set} | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def warning(message, **kwargs):
kwargs["fg"] = kwargs.get("fg", "red")
click.secho(u"warning: {}".format(message), **kwargs) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def fatal(message, **kwargs):
error(message, level="fatal", **kwargs) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def get(url, session=None, silent=not debug, **kwargs):
"""Retrieve a given URL and log response.
:param session: a :class:`requests.Session` object.
:param silent: if **True**, response status and URL will not be printed.
"""
session = session or requests
kwargs["verify"] = kwargs.get("verify"... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def get_dir_from_zipfile(zip_file, fallback=None):
"""Return the name of the root folder in a zip file.
:param zip_file: a :class:`zipfile.ZipFile` instance.
:param fallback: if `None`, the name of the zip file is used. This is
returned if the zip file contains more than one top-level directory,
... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def on_cleanup_error(function, path, excinfo):
click.secho("warning: failed to remove file or directory: {}\n"
"please delete it manually.".format(path),
fg="red") | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __init__(self, package, version):
"""Construct a new requirement.
:param package: the package name.
:param version: a semver compatible version specification.
"""
self.package = package
self.version = version
if self.version and not re.match(r"[<=>~]", versio... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def coerce(cls, string):
"""Create a :class:`Requirement` object from a given package spec."""
match = re.match(cls.spec_regex, string)
if not match:
raise InvalidRequirementSpecError("could not parse requirement")
package = match.group(1)
if all(match.group(2, 3)):
... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __eq__(self, other):
return (isinstance(other, self.__class__) and
other.package == self.package) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __str__(self):
return "".join([self.package, self.version or ""]) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __init__(self, filename=None):
self.filename = None
if filename:
self.load(filename) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def load(self, requirements_file=None):
"""Load or reload requirements from a requirements.txt file.
:param requirements_file: if not given, the filename used from
initialization will be read again.
"""
if requirements_file is None:
requirements_file = self.filen... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def remove(self, elem):
"""Remove a requirement.
:param elem: a string or :class:`Requirement` instance.
"""
if isinstance(elem, text_type):
for requirement in self:
if requirement.package == elem:
return super(Requirements, self).remove(r... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __repr__(self):
return "<Requirements({})>".format(self.filename.name or "") | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __init__(self, name, filename=None):
self.name = name
super(NamedRequirements, self).__init__(filename=filename) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __init__(self, groups=None):
super(GroupedRequirements, self).__init__(NamedRequirements)
self.groups = groups or self.default_groups
self.filename = None
self.create_default_groups() | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def create_default_groups(self):
for group in self.groups:
group = group.replace(" ", "_").lower()
self[group] = NamedRequirements(group) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def load(self, filename, create_if_missing=True):
filename = Path(filename)
if not filename.exists() and create_if_missing:
self.load_pip_requirements()
with filename.open("w") as f:
f.write(yaml.dump(self.serialized, default_flow_style=False,
... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def serialized(self):
to_ret = {}
for group, requirements in self.items():
to_ret[group] = [str(requirement) for requirement in requirements]
return to_ret | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def yaml(self):
return yaml.dump(self.serialized, default_flow_style=False,
encoding=None) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def get_package_url(cls, package, session=None, silent=False):
response = get("{}/packages/{}".format(cls.bower_base_uri, package))
return response.json().get("url", None) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def clean_semver(cls, version_spec):
return re.sub(r"([<>=~])\s+?v?", "\\1", version_spec, re.IGNORECASE) | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def __init__(self, assets_dir=None, requirements_file="requirements.yml"):
self.assets_dir = assets_dir or Path(".") / "assets"
self.requirements = GroupedRequirements()
self.requirements.load(requirements_file)
self.temp_dir = mkdtemp() | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def get_bower_package(self, url, dest=None, version=None,
process_deps=True):
dest = dest or Path(".") / "assets"
parsed_url = urlparse(url)
if parsed_url.scheme == "git" or parsed_url.path.endswith(".git"):
if parsed_url.netloc == "github.com":
... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def install_pip(self, package, save=True, save_dev=False):
"""Installs a pip package.
:param save: if `True`, pins the package to the Hydrogen requirements
YAML file.
:param save_dev: if `True`, pins the package as a development
dependency to the Hydrogen requirements YA... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def main(ctx):
which = "where" if sys.platform == "win32" else "which"
if envoy.run(which + " git").status_code != 0:
click.secho("fatal: git not found in PATH", fg="red")
sys.exit(1)
ctx.obj = Hydrogen() | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def freeze(h, output_yaml, resolve, groups):
"""Output installed packages."""
if not groups:
groups = filter(lambda group: not group.lower().startswith("bower"),
h.requirements.keys())
else:
groups = [text_type.strip(group) for group in groups.split(",")]
if outp... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def install(h, pip, groups, save, save_dev, packages):
"""Install a pip or bower package."""
if groups:
groups = [text_type.strip(group) for group in groups.split(",")]
else:
groups = h.requirements.keys()
if not packages:
for group in groups:
if group not in h.requi... | darvid/hydrogen | [
3,
1,
3,
1,
1415991326
] |
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read() | ntucker/django-aloha-edit | [
21,
5,
21,
1,
1367876699
] |
def __str__(self):
return "%s: %s" % (self.get_type_display(), self.value) | Kniyl/mezzanine | [
1,
2,
1,
1,
1398427594
] |
def __str__(self):
return "%s: %s" % (self.user_name, self.text) | Kniyl/mezzanine | [
1,
2,
1,
1,
1398427594
] |
def is_holiday(date1, holidays = getattr(settings, 'SCHOOL_HOLIDAYS', [])):
for date_start, date_end in holidays:
if isinstance(date_end, str):
if date1.date() == date_start.date():
return True
elif date1.date() >= date_start.date() and date1.date() <= date_end.date():
... | unicefuganda/edtrac | [
7,
3,
7,
3,
1324013652
] |
def previous_calendar_week(t=None):
"""
To education monitoring, a week runs between Thursdays,
Thursday marks the beginning of a new week of data submission
Data for a new week is accepted until Wednesday evening of the following week
"""
d = t or datetime.datetime.now()
if not d.weekday() ... | unicefuganda/edtrac | [
7,
3,
7,
3,
1324013652
] |
def get_polls(**kwargs):
script_polls = ScriptStep.objects.values_list('poll', flat=True).exclude(poll=None)
return Poll.objects.exclude(pk__in=script_polls).annotate(Count('responses')) | unicefuganda/edtrac | [
7,
3,
7,
3,
1324013652
] |
def list_poll_responses(poll, **kwargs):
"""
pass a poll queryset and you get yourself a dict with locations vs responses (quite handy for the charts)
dependecies: Contact and Location must be in your module; this lists all Poll responses by district
"""
#forceful import
from poll.models import ... | unicefuganda/edtrac | [
7,
3,
7,
3,
1324013652
] |
def __init__(self, sample=[], population=False):
"""Statistics class initializer method."""
# Raise an exception if the data set is empty.
if (not sample):
raise StatisticsException, "Empty data set!: %s" % sample
# The data set (a list).
self.sample = sample
... | unicefuganda/edtrac | [
7,
3,
7,
3,
1324013652
] |
def __getVariance(self):
"""Determine the measure of the spread of the data set about the mean.
Sample variance is determined by default; population variance can be
determined by setting population attribute to True.
"""
x = 0 # Summation variable.
# Subtract the mean f... | unicefuganda/edtrac | [
7,
3,
7,
3,
1324013652
] |
def extract_key_count(list, key=None):
"""
A utility function written to count the number of times a `key` would appear in, for example, a categorized poll.
Examples:
>>> extract_key_count('yes',
"""
if list and key:
# go through a list of dictionaries
for dict in list:
... | unicefuganda/edtrac | [
7,
3,
7,
3,
1324013652
] |
def main(app):
target_dir = os.path.join(app.builder.srcdir, 'book_figures')
source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples')
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
if n... | cigroup-ol/metaopt | [
21,
3,
21,
11,
1382447731
] |
def __init__(self, name, code, url_namespace='anysign', **kwargs):
"""Configure backend."""
#: Human-readable name.
self.name = name
#: Machine-readable name. Should be lowercase alphanumeric only, i.e.
#: PEP-8 compliant.
self.code = code
#: Namespace for URL r... | novafloss/django-anysign | [
22,
9,
22,
9,
1402504862
] |
def get_signer_url(self, signer):
"""Return URL where signer signs document.
Raise ``NotImplementedError`` in case the backend does not support
"signer view" feature.
Default implementation reverses :meth:`get_signer_url_name` with
``signer.pk`` as argument.
"""
... | novafloss/django-anysign | [
22,
9,
22,
9,
1402504862
] |
def get_signer_return_url(self, signer):
"""Return absolute URL where signer is redirected after signing.
The URL must be **absolute** because it is typically used by external
signature service: the signer uses external web UI to sign the
document(s) and then the signature service redir... | novafloss/django-anysign | [
22,
9,
22,
9,
1402504862
] |
def get_signature_callback_url(self, signature):
"""Return URL where backend can post signature notifications.
Raise ``NotImplementedError`` in case the backend does not support
"signature callback url" feature.
Default implementation reverses :meth:`get_signature_callback_url_name`
... | novafloss/django-anysign | [
22,
9,
22,
9,
1402504862
] |
def _ValidateFileReplicationRule(rule):
"""Raises an error if a FileReplicationRule is invalid.
For example, checks that if REPLICATION_TYPE_FILTER, destination_fields
are specified.
Args:
rule: (FileReplicationRule) The rule to validate.
"""
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:... | endlessm/chromium-browser | [
21,
16,
21,
3,
1435959644
] |
def __init__(self, *args, **kwargs):
super().__init__(os.path.join('languages', 'java'), install=True,
*args, **kwargs) | jimporter/bfg9000 | [
68,
20,
68,
13,
1424839632
] |
def test_install(self):
self.build('install')
self.assertDirectory(self.installdir, [
os.path.join(self.libdir, 'program.jar'),
])
os.chdir(self.srcdir)
cleandir(self.builddir)
self.assertOutput(
['java', '-jar', os.path.join(self.libdir, 'progra... | jimporter/bfg9000 | [
68,
20,
68,
13,
1424839632
] |
def __init__(self, *args, **kwargs):
super().__init__(os.path.join('languages', 'java'),
extra_env={'JAVAC': os.getenv('GCJ', 'gcj')},
*args, **kwargs) | jimporter/bfg9000 | [
68,
20,
68,
13,
1424839632
] |
def __init__(self, *args, **kwargs):
super().__init__(os.path.join('languages', 'java_library'),
install=True, *args, **kwargs) | jimporter/bfg9000 | [
68,
20,
68,
13,
1424839632
] |
def test_install(self):
self.build('install')
self.assertDirectory(self.installdir, [
os.path.join(self.libdir, 'lib.jar'),
os.path.join(self.libdir, 'program.jar'),
])
os.chdir(self.srcdir)
cleandir(self.builddir)
self.assertOutput(
... | jimporter/bfg9000 | [
68,
20,
68,
13,
1424839632
] |
def dict_diff(a, b):
diff = dict()
for k in a:
if k in b:
if b[k] != a[k]:
diff[k] = (a[k],b[k])
return diff | cmand/scamper | [
19,
15,
19,
1,
1427748624
] |
def __init__(self, wartsfile, verbose=False):
super(WartsTraceBoxReader, self).__init__(wartsfile, verbose) | cmand/scamper | [
19,
15,
19,
1,
1427748624
] |
def next_object(self):
# read warts object header
self.header = self.fd.read(8)
# sanity check
if len(self.header) != 8:
return None
(magic, typ, length) = struct.unpack('!HHI', self.header)
if self.verbose:
print "Magic: %02X Obj: %02X Len: %02x" % (magic, typ, length)
assert(ma... | cmand/scamper | [
19,
15,
19,
1,
1427748624
] |
def __init__(self, data, verbose=False):
super(WartsTraceBox, self).__init__(TRACEBOXTYPE, verbose)
self.data = data
self.flagdata = data
self.pkts = []
self.flag_defines = [
('listid', unpack_uint32_t),
('cycleid', unpack_uint32_t),
('userid', unpack_uint32_t),
('srcaddr', self.... | cmand/scamper | [
19,
15,
19,
1,
1427748624
] |
def __init__(self, data, refs, verbose=False):
super(WartsTraceBoxPkt, self).__init__(TRACEBOXTYPE, verbose)
self.update_ref(refs)
self.flagdata = data
self.flag_defines = [
('dir', unpack_uint8_t),
('time', read_timeval),
('len', unpack_uint16_t),
('data', self.read_pass),
]
... | cmand/scamper | [
19,
15,
19,
1,
1427748624
] |
def read_tracebox_pkt(self, data):
fields = dict()
ip = dpkt.ip.IP(data)
fields['hop'] = socket.inet_ntoa(ip.src)
if ip.p == dpkt.ip.IP_PROTO_ICMP:
# This is a reply from a hop
fields['hop'] = socket.inet_ntoa(ip.src)
icmp = ip.data
#print "ICMP quote:", icmp.type, icmp.code, "LE... | cmand/scamper | [
19,
15,
19,
1,
1427748624
] |
def test_unicode_title():
get_beyonce = GetCurrentContent("Beyoncé Knowles")
assert get_beyonce() | mahmoud/wapiti | [
36,
11,
36,
6,
1358639129
] |
def test_web_request():
url = 'http://upload.wikimedia.org/wikipedia/commons/d/d2/Mcgregor.jpg'
get_photo = base.WebRequestOperation(url)
res = get_photo()
text = res[0]
assert len(text) == 16408 | mahmoud/wapiti | [
36,
11,
36,
6,
1358639129
] |
def test_missing_revisions():
get_revs = GetPageRevisionInfos('Coffee_lololololol')
rev_list = get_revs()
'''
Should return 'missing' and negative pageid
'''
assert len(rev_list) == 0 | mahmoud/wapiti | [
36,
11,
36,
6,
1358639129
] |
def calculate_distance_boundary(r, mu, r_inner, r_outer):
"""
Calculate distance to shell boundary in cm.
Parameters
----------
r : float
radial coordinate of the RPacket
mu : float
cosine of the direction of movement
r_inner : float
inner radius of current shell
r_... | tardis-sn/tardis | [
173,
342,
173,
166,
1323325219
] |
def calculate_distance_line(
r_packet, comov_nu, is_last_line, nu_line, time_explosion | tardis-sn/tardis | [
173,
342,
173,
166,
1323325219
] |
def calculate_distance_line_full_relativity(
nu_line, nu, time_explosion, r_packet | tardis-sn/tardis | [
173,
342,
173,
166,
1323325219
] |
def select_numeric(df):
return df.select_dtypes(exclude=['object']) | Featuretools/featuretools | [
6538,
841,
6538,
165,
1504908917
] |
def es():
es = load_mock_customer(n_customers=15,
n_products=15,
n_sessions=75,
n_transactions=1000,
random_seed=0,
return_entityset=True)
return es | Featuretools/featuretools | [
6538,
841,
6538,
165,
1504908917
] |
def df(es):
df = es['customers'].df
df['target'] = np.random.randint(1, 3, df.shape[0]) # 1 or 2 values
return df | Featuretools/featuretools | [
6538,
841,
6538,
165,
1504908917
] |
def pipeline(es):
pipeline = Pipeline(steps=[
('ft', DFSTransformer(entityset=es,
target_entity="customers",
max_features=20)),
("numeric", FunctionTransformer(select_numeric, validate=False)),
('imp', SimpleImputer()),
('et... | Featuretools/featuretools | [
6538,
841,
6538,
165,
1504908917
] |
def test_sklearn_estimator(df, pipeline):
# Using with estimator
pipeline.fit(df['customer_id'].values, y=df.target.values) \
.predict(df['customer_id'].values)
result = pipeline.score(df['customer_id'].values, df.target.values)
assert isinstance(result, (float))
# Pickling / Unpicklin... | Featuretools/featuretools | [
6538,
841,
6538,
165,
1504908917
] |
def test_sklearn_gridsearchcv(df, pipeline):
# Using with GridSearchCV
params = {
'et__max_depth': [5, 10]
}
grid = GridSearchCV(estimator=pipeline,
param_grid=params,
cv=3)
grid.fit(df['customer_id'].values, df.target.values)
assert len(g... | Featuretools/featuretools | [
6538,
841,
6538,
165,
1504908917
] |
def {% if function_name is defined %}{{ function_name | lower() }}{% else %}main{% endif %}(): | ReconCell/smacha | [
15,
2,
15,
1,
1501314993
] |
def time_func(func, data, iterations):
start = time.time()
while iterations:
iterations -= 1
func(data)
return time.time() - start | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def test_json_serialization(name, serialize, deserialize, benchmark):
ser_data, des_data = benchmark(run_client_test, name, serialize, deserialize)
msg = "\n%-11s serialize: %0.3f deserialize: %0.3f total: %0.3f" % (
name, ser_data, des_data, ser_data + des_data
)
print(msg) | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def test_json_unicode_strings(name, serialize, deserialize, benchmark):
print("\nArray with 256 unicode strings:")
ser_data, des_data = benchmark(run_client_test,
name, serialize, deserialize,
data=unicode_strings,
... | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def test_json_scii_strings(name, serialize, deserialize, benchmark):
print("\nArray with 256 ascii strings:")
ser_data, des_data = benchmark(run_client_test,
name, serialize, deserialize,
data=strings,
)
... | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def test_json_booleans(name, serialize, deserialize, benchmark):
print("\nArray with 256 True's:")
ser_data, des_data = benchmark(run_client_test,
name, serialize, deserialize,
data=booleans,
)
msg = "%-... | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def test_json_list_of_dictionaries(name, serialize, deserialize, benchmark):
print("\nArray of 100 dictionaries:")
ser_data, des_data = benchmark(run_client_test,
name, serialize, deserialize,
data=list_dicts,
... | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def test_json_dictionary_of_lists(name, serialize, deserialize, benchmark):
print("\nDictionary of 100 Arrays:")
ser_data, des_data = benchmark(run_client_test,
name, serialize, deserialize,
data=dict_lists,
... | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def test_json_medium_complex_objects(name, serialize, deserialize, benchmark):
print("\n256 Medium Complex objects:")
ser_data, des_data = benchmark(run_client_test,
name, serialize, deserialize,
data=medium_complex,
... | thedrow/cyrapidjson | [
7,
3,
7,
5,
1451993583
] |
def finalize_options(self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
__builtins__.__NUMPY_SETUP__ = False
import numpy
self.include_dirs.append(numpy.get_include()) | visualfabriq/bqueryd | [
5,
1,
5,
5,
1480679165
] |
def read(*parts):
"""
Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
return f.read() | visualfabriq/bqueryd | [
5,
1,
5,
5,
1480679165
] |
def view(self, dtype=None, typ=None):
return self | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def adata():
adata = ad.AnnData(np.zeros((100, 100)))
adata.obsm["o"] = np.zeros((100, 50))
adata.varm["o"] = np.zeros((100, 50))
return adata | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def adata_parameterized(request):
return gen_adata(shape=(200, 300), X_type=request.param) | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def matrix_type(request):
return request.param | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def mapping_name(request):
return request.param | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def test_views():
X = np.array(X_list)
adata = ad.AnnData(X, obs=obs_dict, var=var_dict, uns=uns_dict, dtype="int32")
assert adata[:, 0].is_view
assert adata[:, 0].X.tolist() == np.reshape([1, 4, 7], (3, 1)).tolist()
adata[:2, 0].X = [0, 0]
assert adata[:, 0].X.tolist() == np.reshape([0, 0, 7... | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def test_set_obsm_key(adata):
init_hash = joblib.hash(adata)
orig_obsm_val = adata.obsm["o"].copy()
subset_obsm = adata[:50]
assert subset_obsm.is_view
subset_obsm.obsm["o"] = np.ones((50, 20))
assert not subset_obsm.is_view
assert np.all(adata.obsm["o"] == orig_obsm_val)
assert init_h... | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def test_set_obs(adata, subset_func):
init_hash = joblib.hash(adata)
subset = adata[subset_func(adata.obs_names), :]
new_obs = pd.DataFrame(
dict(a=np.ones(subset.n_obs), b=np.ones(subset.n_obs)),
index=subset.obs_names,
)
assert subset.is_view
subset.obs = new_obs
assert ... | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def test_drop_obs_column():
adata = ad.AnnData(np.array(X_list), obs=obs_dict, dtype="int32")
subset = adata[:2]
assert subset.is_view
# returns a copy of obs
assert subset.obs.drop(columns=["oanno1"]).columns.tolist() == ["oanno2", "oanno3"]
assert subset.is_view
# would modify obs, so it ... | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def test_set_varm(adata):
init_hash = joblib.hash(adata)
dim0_size = np.random.randint(2, adata.shape[1] - 1)
dim1_size = np.random.randint(1, 99)
orig_varm_val = adata.varm["o"].copy()
subset_idx = np.random.choice(adata.var_names, dim0_size, replace=False)
subset = adata[:, subset_idx]
a... | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def test_not_set_subset_X(matrix_type, subset_func):
adata = ad.AnnData(matrix_type(asarray(sparse.random(20, 20))))
init_hash = joblib.hash(adata)
orig_X_val = adata.X.copy()
while True:
subset_idx = slice_subset(adata.obs_names)
if len(adata[subset_idx, :]) > 2:
break
s... | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
def test_set_subset_obsm(adata, subset_func):
init_hash = joblib.hash(adata)
orig_obsm_val = adata.obsm["o"].copy()
while True:
subset_idx = slice_subset(adata.obs_names)
if len(adata[subset_idx, :]) > 2:
break
subset = adata[subset_idx, :]
internal_idx = _normalize_ind... | theislab/anndata | [
355,
126,
355,
257,
1502460606
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.