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 |
|---|---|---|---|---|
testcases.py | from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""... |
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = 'testuser@buymore.com'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.us... | perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm) | random_line_split |
testcases.py | from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""... | """
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username... | is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = 'testuser@buymore.com'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
... | identifier_body |
testcases.py | from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""... |
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom asserti... | kwargs['username'] = username | conditional_block |
testcases.py | from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""... | (self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirects... | assertIsRedirect | identifier_name |
parser.rs | TreeMap,
sync::{Arc, Mutex},
};
use syntect::{
highlighting::{Color, ThemeSet},
html::highlighted_html_for_string,
parsing::SyntaxSet,
};
use thiserror::Error;
use typed_arena::Arena;
use url_path::UrlPath;
#[derive(Error, Debug)]
pub enum ParseError {
#[error("Utf8Error: `{0}`")]
Utf8Error(#[f... | else {
format!("/#{}", url5)
};
log::info!("url6: {}", url6);
let mut new_nodelink = nodelink.clone();
new_nodelink.url = url6.into_bytes();
NodeValue::Link(new_no... | {
// leave as it
url5
} | conditional_block |
parser.rs | , Mutex},
};
use syntect::{
highlighting::{Color, ThemeSet},
html::highlighted_html_for_string,
parsing::SyntaxSet,
};
use thiserror::Error;
use typed_arena::Arena;
use url_path::UrlPath;
#[derive(Error, Debug)]
pub enum ParseError {
#[error("Utf8Error: `{0}`")]
Utf8Error(#[from] FromUtf8Error),
... | format_source_code | identifier_name | |
parser.rs | TreeMap,
sync::{Arc, Mutex},
};
use syntect::{
highlighting::{Color, ThemeSet},
html::highlighted_html_for_string,
parsing::SyntaxSet,
};
use thiserror::Error;
use typed_arena::Arena;
use url_path::UrlPath;
#[derive(Error, Debug)]
pub enum ParseError {
#[error("Utf8Error: `{0}`")]
Utf8Error(#[f... | } else {
None
}
} else {
None
};
Ok(Html {
title,
content: render_html,
})
} else {
Err(ParseError::MdParseError)
| if let Some(ref got) = *got {
Some(got.to_string()) | random_line_split |
parser.rs | Map,
sync::{Arc, Mutex},
};
use syntect::{
highlighting::{Color, ThemeSet},
html::highlighted_html_for_string,
parsing::SyntaxSet,
};
use thiserror::Error;
use typed_arena::Arena;
use url_path::UrlPath;
#[derive(Error, Debug)]
pub enum ParseError {
#[error("Utf8Error: `{0}`")]
Utf8Error(#[from]... |
}
pub fn parse(arg: &str) -> Result<Html, ParseError> {
let referred_files = pre_parse_get_embedded_files(arg);
let embed_files = if let Ok(referred_files) = referred_files {
let file_contents = plugins::fetch_file_contents(referred_files);
Some(file_contents)
} else {
None
};
... | {
Settings { base_dir: None }
} | identifier_body |
test_crs.py |
from fiona import crs
def test_proj_keys():
assert len(crs.all_proj_keys) == 85
assert 'proj' in crs.all_proj_keys
assert 'no_mayo' in crs.all_proj_keys
def test_from_string():
# A PROJ.4 string with extra whitespace.
val = crs.from_string(
" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_d... |
def test_to_string_utm():
# Make a string from a mapping with a few bogus items
val = {
'proj': 'utm', 'ellps': 'WGS84', 'zone': 13,
'no_defs': True, 'foo': True, 'axis': False, 'belgium': [1,2] }
assert crs.to_string(
val) == "+ellps=WGS84 +no_defs +proj=utm +zone=13"
def test_f... | val = {
'proj': 'longlat', 'ellps': 'WGS84', 'datum': 'WGS84',
'no_defs': True, 'foo': True, 'axis': False, 'belgium': [1,2] }
assert crs.to_string(
val) == "+datum=WGS84 +ellps=WGS84 +no_defs +proj=longlat" | identifier_body |
test_crs.py |
from fiona import crs
def test_proj_keys():
assert len(crs.all_proj_keys) == 85
assert 'proj' in crs.all_proj_keys
assert 'no_mayo' in crs.all_proj_keys
def test_from_string():
# A PROJ.4 string with extra whitespace.
val = crs.from_string(
" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_d... | ():
val = crs.from_epsg(4326)
assert val['init'] == "epsg:4326"
assert val['no_defs'] == True
| test_from_epsg | identifier_name |
test_crs.py | from fiona import crs
def test_proj_keys():
assert len(crs.all_proj_keys) == 85
assert 'proj' in crs.all_proj_keys
assert 'no_mayo' in crs.all_proj_keys
def test_from_string():
# A PROJ.4 string with extra whitespace.
val = crs.from_string(
" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_de... | assert val['no_defs'] == True | val) == "+ellps=WGS84 +no_defs +proj=utm +zone=13"
def test_from_epsg():
val = crs.from_epsg(4326)
assert val['init'] == "epsg:4326" | random_line_split |
utils.rs | use rustc_serialize::{Encodable, Encoder};
use url::Url;
use git2::{self, ObjectType};
use core::GitReference;
use util::{CargoResult, ChainError, human, ToUrl, internal};
#[derive(PartialEq, Clone, Debug)]
pub struct GitRevision(git2::Oid);
impl fmt::Display for GitRevision {
fn fmt(&self, f: &mut fmt::Formatte... | use std::fs::{self, File};
| random_line_split | |
utils.rs | no revision for that reference was found.
pub struct GitCheckout<'a> {
database: &'a GitDatabase,
location: PathBuf,
revision: GitRevision,
repo: git2::Repository,
}
#[derive(RustcEncodable)]
pub struct EncodableGitCheckout {
database: EncodableGitDatabase,
location: String,
revision: Stri... | (&self) -> CargoResult<()> {
// If we're interrupted while performing this reset (e.g. we die because
// of a signal) Cargo needs to be sure to try to check out this repo
// again on the next go-round.
//
// To enable this we have a dummy file in our checkout, .cargo-ok, which
... | reset | identifier_name |
utils.rs | GitCheckout<'a> {
database: &'a GitDatabase,
location: PathBuf,
revision: GitRevision,
repo: git2::Repository,
}
#[derive(RustcEncodable)]
pub struct EncodableGitCheckout {
database: EncodableGitDatabase,
location: String,
revision: String,
}
impl<'a> Encodable for GitCheckout<'a> {
f... | {
info!("update submodules for: {:?}", repo.workdir().unwrap());
for mut child in try!(repo.submodules()).into_iter() {
try!(child.init(false));
let url = try!(child.url().chain_error(|| {
internal("non-utf8 url for submodule")
... | identifier_body | |
conf.py | values have a default; values that are commented out
# serve to show the default.
from dodotable import __version__, __version_info__
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relativ... | # A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML outp... | pygments_style = 'sphinx'
| random_line_split |
find.py | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Find files on the client."""
import stat
from grr.client.client_actions import searching as searching_actions
from grr.lib import aff4
from grr.lib import flow
from grr.lib.aff4_objects import aff4_grr
from grr.lib.aff4_objects import standard
... |
for response in responses:
# Create the file in the VFS
vfs_urn = aff4_grr.VFSGRRClient.PathspecToURN(response.hit.pathspec,
self.client_id)
response.hit.aff4path = vfs_urn
# TODO(user): This ends up being fairly expensive.
if sta... | raise IOError(responses.status) | conditional_block |
find.py | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Find files on the client."""
import stat
from grr.client.client_actions import searching as searching_actions
from grr.lib import aff4
from grr.lib import flow
from grr.lib.aff4_objects import aff4_grr
from grr.lib.aff4_objects import standard
... |
class FindFiles(flow.GRRFlow):
r"""Find files on the client.
The logic is:
- Find files under "Path"
- Filter for files with os.path.basename matching "Path Regular Expression"
- Filter for files with sizes between min and max limits
- Filter for files that contain "Data Regular Expression" in t... | random_line_split | |
find.py | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Find files on the client."""
import stat
from grr.client.client_actions import searching as searching_actions
from grr.lib import aff4
from grr.lib import flow
from grr.lib.aff4_objects import aff4_grr
from grr.lib.aff4_objects import standard
... | (self):
"""Ensure that the request is sane."""
self.findspec.Validate()
class FindFiles(flow.GRRFlow):
r"""Find files on the client.
The logic is:
- Find files under "Path"
- Filter for files with os.path.basename matching "Path Regular Expression"
- Filter for files with sizes between min ... | Validate | identifier_name |
find.py | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Find files on the client."""
import stat
from grr.client.client_actions import searching as searching_actions
from grr.lib import aff4
from grr.lib import flow
from grr.lib.aff4_objects import aff4_grr
from grr.lib.aff4_objects import standard
... |
class FindFiles(flow.GRRFlow):
r"""Find files on the client.
The logic is:
- Find files under "Path"
- Filter for files with os.path.basename matching "Path Regular Expression"
- Filter for files with sizes between min and max limits
- Filter for files that contain "Data Regular Expression" in... | """Ensure that the request is sane."""
self.findspec.Validate() | identifier_body |
yandexmusic.py |
from ..compat import compat_str
from ..utils import (
ExtractorError,
int_or_none,
float_or_none,
sanitized_Request,
urlencode_postdata,
)
class YandexMusicBaseIE(InfoExtractor):
@staticmethod
def _handle_error(response):
error = response.get('error')
if error:
... | dexMusicPlaylistBaseIE):
IE_NAME = 'yandexmusic:playlist'
IE_DESC = 'Яндекс.Музыка - Плейлист'
_VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/users/[^/]+/playlists/(?P<id>\d+)'
_TESTS = [{
'url': 'http://music.yandex.ru/users/music.partners/playlists/1245',
'info_dict': {
... | album = self._download_json(
'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id,
album_id, 'Downloading album JSON')
entries = self._build_playlist(album['volumes'][0])
title = '%s - %s' % (album['artists'][0]['name'], album['title'])
year = album.get... | identifier_body |
yandexmusic.py |
from ..compat import compat_str
from ..utils import (
ExtractorError,
int_or_none,
float_or_none,
sanitized_Request,
urlencode_postdata,
)
class YandexMusicBaseIE(InfoExtractor):
@staticmethod
def _handle_error(response):
error = response.get('error')
if error:
... | title = track['title']
track_info = {
'id': track['id'],
'ext': 'mp3',
'url': self._get_track_url(track['storageDir'], track['id']),
'filesize': int_or_none(track.get('fileSize')),
'duration': float_or_none(track.get('durationMs'), 1000),
'... | p://' + thumbnail
track_ | conditional_block |
yandexmusic.py |
from ..compat import compat_str
from ..utils import (
ExtractorError,
int_or_none,
float_or_none,
sanitized_Request,
urlencode_postdata,
)
class YandexMusicBaseIE(InfoExtractor):
@staticmethod
def _handle_error(response):
error = response.get('error')
if error:
... | album_id = self._match_id(url)
album = self._download_json(
'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id,
album_id, 'Downloading album JSON')
entries = self._build_playlist(album['volumes'][0])
title = '%s - %s' % (album['artists'][0]['name']... | def _real_extract(self, url): | random_line_split |
yandexmusic.py |
from ..compat import compat_str
from ..utils import (
ExtractorError,
int_or_none,
float_or_none,
sanitized_Request,
urlencode_postdata,
)
class YandexMusicBaseIE(InfoExtractor):
@staticmethod
def _handle_error(response):
error = response.get('error')
if error:
... | mobj = re.match(self._VALID_URL, url)
album_id, track_id = mobj.group('album_id'), mobj.group('id')
track = self._download_json(
'http://music.yandex.ru/handlers/track.jsx?track=%s:%s' % (track_id, album_id),
track_id, 'Downloading track JSON')['track']
return self... | lf, url):
| identifier_name |
HighlighterManager.spec.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* 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 appl... |
it('should create the HeatmapHighlighter', () => {
expect(highlighterManager.highlighters[0]).to.be.an.instanceof(HeatmapHighlighter);
});
it('should implement getCellBackground method', () => {
expect(highlighterManager).to.have.property('getCellBackground');
});
it('should return proper backgroun... | random_line_split | |
fixtures.py | from datetime import date, time, timedelta
from decimal import Decimal
import itertools
from django.utils import timezone
from six.moves import xrange
from .models import Person
def get_fixtures(n=None):
"""
Returns `n` dictionaries of `Person` objects.
If `n` is not specified it defaults to 6.
"... | n = n or len(fixtures)
fixtures = itertools.cycle(fixtures)
for _ in xrange(n):
yield next(fixtures)
def create_fixtures(n=None):
"""
Wrapper for Person.bulk_create which creates `n` fixtures
"""
Person.objects.bulk_create(Person(**person)
for perso... | ] | random_line_split |
fixtures.py | from datetime import date, time, timedelta
from decimal import Decimal
import itertools
from django.utils import timezone
from six.moves import xrange
from .models import Person
def get_fixtures(n=None):
| },
{
'big_age': 245999992349999, 'comma_separated_age': '6,2,9',
'age': 25, 'positive_age': 49999, 'positive_small_age': 315,
'small_age': 5409, 'certified': False, 'null_certified': True,
'name': 'Pete', 'email': 'petekweetookniet@mailinator.com',
... | """
Returns `n` dictionaries of `Person` objects.
If `n` is not specified it defaults to 6.
"""
_now = timezone.now().replace(microsecond=0) # mysql doesn't do microseconds. # NOQA
_date = date(2015, 3, 28)
_time = time(13, 0)
fixtures = [
{
'big_age': 59999999999999... | identifier_body |
fixtures.py | from datetime import date, time, timedelta
from decimal import Decimal
import itertools
from django.utils import timezone
from six.moves import xrange
from .models import Person
def get_fixtures(n=None):
"""
Returns `n` dictionaries of `Person` objects.
If `n` is not specified it defaults to 6.
"... | (n=None):
"""
Wrapper for Person.bulk_create which creates `n` fixtures
"""
Person.objects.bulk_create(Person(**person)
for person in get_fixtures(n))
| create_fixtures | identifier_name |
fixtures.py | from datetime import date, time, timedelta
from decimal import Decimal
import itertools
from django.utils import timezone
from six.moves import xrange
from .models import Person
def get_fixtures(n=None):
"""
Returns `n` dictionaries of `Person` objects.
If `n` is not specified it defaults to 6.
"... |
def create_fixtures(n=None):
"""
Wrapper for Person.bulk_create which creates `n` fixtures
"""
Person.objects.bulk_create(Person(**person)
for person in get_fixtures(n))
| yield next(fixtures) | conditional_block |
test_topi_qnn.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | test_simulated_quantize()
test_simulated_dequantize() | conditional_block | |
test_topi_qnn.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | s_np = np.random.uniform(low=1e-4, high=0.1, size=channels).astype("float32")
z_np = np.random.uniform(low=-10, high=10, size=channels).astype("int32")
dq_np = np.zeros(shape=data_shape, dtype="float32")
def check_target(target, dev):
# Wrap the numpy arrays in nd arrays.
a = tvm.nd.arr... | # Create random numpy values to assign to inputs.
a_np = np.random.uniform(low=-128, high=127, size=data_shape).astype(in_dtype)
a_np_f = a_np.astype("float32")
d_np = np.int32(topi.nn.SQNN_DTYPE_TO_CODE[in_dtype]) | random_line_split |
test_topi_qnn.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | (data_shape, in_dtype, channels, axis):
# Create placeholder variables for all qnn inputs.
A = te.placeholder(data_shape, name="value", dtype="float32")
D = te.placeholder([], name="dtype", dtype="int32")
S = te.placeholder([te.size_var("scale_dim")], name="scale", dtype="float32")
Z = te.placeholde... | verify_simulated_dequantize | identifier_name |
test_topi_qnn.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | m = graph_executor.GraphModule(lib["default"](dev))
m.set_input("a", a_np)
m.run()
real_q_out = m.get_output(0)
# Compile the simulated quantize function.
with tvm.target.Target(target):
sched = tvm.topi.testing.get_injective_schedule(target)(SIM_Q)
... | a = tvm.nd.array(a_np, dev)
d = tvm.nd.array(d_np, dev)
s = tvm.nd.array(s_np, dev)
z = tvm.nd.array(z_np, dev)
q = tvm.nd.array(q_np, dev)
# Construct equivalent relay graph.
per_channel = channels[0] != 1
a_var = relay.var("a", shape=data_shape, dtype="float32"... | identifier_body |
Tile.ts | ///<reference path="../references.ts" />
module Hexes {
export enum TileType {
Blank,
Empty,
Full
}
export enum TileState {
Covered,
Exposed
}
export interface ITile {
coordinate: ICoordinate;
type: TileType;
state: TileState;
}
... | (game: Phaser.Game, coordinate: ICoordinate, type: TileType = TileType.Blank, state: TileState = TileState.Covered) {
var position: ICoordinateXY;
var size: number;
size = 64;
position = coordinate.toXY(size / 2);
super(game, game.world.centerX + position.x... | constructor | identifier_name |
Tile.ts | ///<reference path="../references.ts" />
module Hexes {
export enum TileType {
Blank, | Full
}
export enum TileState {
Covered,
Exposed
}
export interface ITile {
coordinate: ICoordinate;
type: TileType;
state: TileState;
}
export class Tile extends Phaser.Sprite implements ITile {
public coordinate: ICoordinate;
pu... | Empty, | random_line_split |
Tile.ts | ///<reference path="../references.ts" />
module Hexes {
export enum TileType {
Blank,
Empty,
Full
}
export enum TileState {
Covered,
Exposed
}
export interface ITile {
coordinate: ICoordinate;
type: TileType;
state: TileState;
}
... |
}
}
| {
var position: ICoordinateXY;
var size: number;
size = 64;
position = coordinate.toXY(size / 2);
super(game, game.world.centerX + position.x, game.world.centerY + position.y, "hex_512", 0);
this.width = size;
this.height = size;
... | identifier_body |
dist_async_kvstore.py | #!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... |
if __name__ == "__main__":
test_gluon_trainer_type()
| def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
... | identifier_body |
dist_async_kvstore.py | #!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... | test_gluon_trainer_type() | conditional_block | |
dist_async_kvstore.py | #!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... | ():
def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
... | test_gluon_trainer_type | identifier_name |
dist_async_kvstore.py | # distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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/l... | #!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file | random_line_split | |
config.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule, ExamplesRouterViewerComponent } from '../../../shared';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
SharedModule,
AppModule,
... | examples: [
{
title: 'Nested Forms (fieldGroup wrapper)',
description: `
This example demonstrates how to nest formly-form's using custom templates
`,
component: AppComponent,
files: [
{
... | random_line_split | |
config.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule, ExamplesRouterViewerComponent } from '../../../shared';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
SharedModule,
AppModule,
... | {}
| ConfigModule | identifier_name |
index.ts | import {debugPromiseChain} from "./lib/debug/debug-promise-chain";
import {formatDate} from "./lib/data-convert/format-date";
import {addSortToQuery} from "./lib/query/add-sort-to-query";
import {addPaginationToQuery} from "./lib/query/add-pagination-to-query";
import {setOrUnsetAttributesOfObject} from "./lib/object/s... | import {fieldRequiredCheck} from "./lib/form-data/field-required-check";
import {exposeInnerWithPrefixFunc, exposeInnerWithPrefix} from "./lib/object/expose-inner-with-prefix";
export {
debugPromiseChain,
formatDate,
addSortToQuery, addPaginationToQuery,
setOrUnsetAttributesOfObject, unsetKeysOfObject,... | import {unsetKeysOfObject} from "./lib/object/unset-keys-of-object";
import {convertKeysToInt} from "./lib/data-convert/convert-keys-to-int";
import {convertKeysToDate} from "./lib/data-convert/convert-keys-to-date"; | random_line_split |
realloc-16687.rs | // Copyright 2013-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-MI... |
unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
if PRINT {
println!("reallocate(ptr=0x{:010x} old_size={} size={} align={})",
ptr as usize, old_size, size, align);
}
let ret = heap::reallocate(ptr, old_size, size,... | {
if PRINT { println!("deallocate(ptr=0x{:010x} size={} align={})",
ptr as usize, size, align);
}
heap::deallocate(ptr, size, align);
} | identifier_body |
realloc-16687.rs | // Copyright 2013-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-MI... | }
// Test 2: turn the square back into a triangle, top to bottom.
unsafe fn test_2(ascend: &mut [*mut u8]) {
let old_size = idx_to_size(COUNT-1);
for i in 0..COUNT / 2 {
let (p0, p1, new_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i));
assert!(new_size < old_siz... | random_line_split | |
realloc-16687.rs | // Copyright 2013-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-MI... |
if PRINT {
println!("reallocate(ptr=0x{:010x} old_size={} size={} align={}) \
ret: 0x{:010x}",
ptr as usize, old_size, size, align, ret as usize);
}
ret
}
fn idx_to_size(i: usize) -> usize { (i+1) * 10 }
// Allocate pairs of ... | { alloc::oom() } | conditional_block |
realloc-16687.rs | // Copyright 2013-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-MI... | (ascend: &mut [*mut u8]) {
let new_size = idx_to_size(COUNT-1);
for i in 0..COUNT / 2 {
let (p0, p1, old_size) = (ascend[2*i], ascend[2*i+1], idx_to_size(i));
assert!(old_size < new_size);
ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
sanity_ch... | test_1 | identifier_name |
issue-53789-2.rs | // Regression test for #53789.
//
// compile-pass
#![feature(nll)]
#![allow(unused_variables)]
use std::collections::BTreeMap;
use std::ops::Range;
use std::cmp::Ord;
macro_rules! valuetree {
() => {
type ValueTree =
<Self::Strategy as $crate::Strategy>::Value;
};
}
macro_rules! product_... | <S, F> {
source: S,
fun: F,
}
impl<S, F> Map<S, F> {
pub fn new(source: S, fun: F) -> Self {
unimplemented!()
}
}
}
fn main() { }
| Map | identifier_name |
issue-53789-2.rs | // Regression test for #53789.
//
// compile-pass
#![feature(nll)]
#![allow(unused_variables)]
use std::collections::BTreeMap;
use std::ops::Range;
use std::cmp::Ord;
macro_rules! valuetree {
() => {
type ValueTree =
<Self::Strategy as $crate::Strategy>::Value;
};
}
macro_rules! product_... | #[derive(Clone)]
pub struct Map<S, F> {
source: S,
fun: F,
}
impl<S, F> Map<S, F> {
pub fn new(source: S, fun: F) -> Self {
unimplemented!()
}
}
}
fn main() { } | unimplemented!()
}
}
| random_line_split |
test_structural.py | structural
from statsmodels.tsa.statespace.structural import UnobservedComponents
from .results import results_structural
from statsmodels.tools import add_constant
from numpy.testing import assert_equal, assert_almost_equal, assert_raises, assert_allclose
from nose.exc import SkipTest
try:
import matplotlib.pyp... | ():
run_ucm('local_linear_deterministic_trend')
def test_local_linear_trend():
run_ucm('local_linear_trend')
def test_smooth_trend():
run_ucm('smooth_trend')
def test_random_trend():
run_ucm('random_trend')
def test_cycle():
run_ucm('cycle')
def test_seasonal():
run_ucm('seasonal')
d... | test_local_linear_deterministic_trend | identifier_name |
test_structural.py | structural
from statsmodels.tsa.statespace.structural import UnobservedComponents
from .results import results_structural
from statsmodels.tools import add_constant
from numpy.testing import assert_equal, assert_almost_equal, assert_raises, assert_allclose
from nose.exc import SkipTest
try:
import matplotlib.pyp... |
def test_lltrend_cycle_seasonal_reg_ar1():
run_ucm('lltrend_cycle_seasonal_reg_ar1')
def test_mle_reg():
endog = np.arange(100)*1.0
exog = endog*2
# Make the fit not-quite-perfect
endog[::2] += 0.01
endog[1::2] -= 0.01
with warnings.catch_warnings(record=True) as w:
mod1 = Unob... | run_ucm('rtrend_ar1') | identifier_body |
test_structural.py | structural
from statsmodels.tsa.statespace.structural import UnobservedComponents
from .results import results_structural
from statsmodels.tools import add_constant
from numpy.testing import assert_equal, assert_almost_equal, assert_raises, assert_allclose | from nose.exc import SkipTest
try:
import matplotlib.pyplot as plt
have_matplotlib = True
except ImportError:
have_matplotlib = False
dta = macrodata.load_pandas().data
dta.index = pd.date_range(start='1959-01-01', end='2009-07-01', freq='QS')
def run_ucm(name):
true = getattr(results_structural, n... | random_line_split | |
test_structural.py | structural
from statsmodels.tsa.statespace.structural import UnobservedComponents
from .results import results_structural
from statsmodels.tools import add_constant
from numpy.testing import assert_equal, assert_almost_equal, assert_raises, assert_allclose
from nose.exc import SkipTest
try:
import matplotlib.pyp... |
endog = endog[2:]
endog += np.dot(exog, beta)
# Now just test that the starting parameters are approximately what they
# ought to be (could make this arbitrarily precise by increasing nobs,
# but that would slow down the test for no real gain)
mod = UnobservedComponents(endog, exog=exog, a... | endog[t+1] = phi[0] * endog[t] + phi[1] * endog[t-1] + eps[t] | conditional_block |
Search.tsx | import React, { useRef, useEffect, useState } from "react";
import { fractureFiles } from "fractures-library/src/index";
import { HiSearch, HiX } from "react-icons/hi";
import classNames from "@sindresorhus/class-names";
import SearchResults from "./components/SearchResults";
import styled from "styled-components";
imp... | .fr-search__input:active,
.fr-search__input:focus {
border-color: var(--purple-500);
box-shadow: 0 0 0 1px var(--purple-500);
}
`;
export default Search; | color: var(--gray-300);
}
.fr-search__input--focus, | random_line_split |
Search.tsx | import React, { useRef, useEffect, useState } from "react";
import { fractureFiles } from "fractures-library/src/index";
import { HiSearch, HiX } from "react-icons/hi";
import classNames from "@sindresorhus/class-names";
import SearchResults from "./components/SearchResults";
import styled from "styled-components";
imp... |
};
window?.addEventListener("keydown", handleKeys);
return () => {
window?.removeEventListener("keydown", handleKeys);
};
}, []);
const resetSearch = () => {
setResults([]);
setValue("");
setFocus(false);
inputRef?.current.blur();
};
const searchRule = (value: string) => {
const results: ... | {
resetSearch();
} | conditional_block |
test-bi-symbol-custom.js | /*
* Some Duktape specific Symbol tests.
*/
/*@include util-buffer.js@*/
/*===
TypeError
TypeError
{"foo":123,"baz":[1,2,null,4,5]}
{foo:123,baz:[1,2,null,4,5]}
0
0
SETTER called number 123 symbol Symbol(accessor)
GETTER called symbol Symbol(accessor)
dummy-getter
===*/
function test() { | print(e.name);
}
// Uint8Array.allocPlain() rejects symbols with TypeError.
try {
Uint8Array.allocPlain(Symbol.for('foo'));
} catch (e) {
print(e.name);
}
// For now, Symbols don't serialize as JX/JC property keys or values.
var obj = {
foo: 123,
[ S... | // Because Symbols fail with TypeError in string concatenation, this
// Duktape 1.x idiom to create an internal string no longer works.
try {
print(Duktape.enc('jx', bufferToStringRaw(Duktape.dec('hex', 'ff')) + 'Value'));
} catch (e) { | random_line_split |
test-bi-symbol-custom.js | /*
* Some Duktape specific Symbol tests.
*/
/*@include util-buffer.js@*/
/*===
TypeError
TypeError
{"foo":123,"baz":[1,2,null,4,5]}
{foo:123,baz:[1,2,null,4,5]}
0
0
SETTER called number 123 symbol Symbol(accessor)
GETTER called symbol Symbol(accessor)
dummy-getter
===*/
function test() | quux: Symbol.iterator,
baz: [ 1, 2, Symbol(), 4, 5 ]
}
print(JSON.stringify(obj));
print(Duktape.enc('jx', obj));
// Date instances have a hidden _Value (\x82Value) property.
// It is not returned by Object.getOwnPropertySymbols() directly
// or via a Proxy.
var date = new ... | {
// Because Symbols fail with TypeError in string concatenation, this
// Duktape 1.x idiom to create an internal string no longer works.
try {
print(Duktape.enc('jx', bufferToStringRaw(Duktape.dec('hex', 'ff')) + 'Value'));
} catch (e) {
print(e.name);
}
// Uint8Array.allocPlai... | identifier_body |
test-bi-symbol-custom.js | /*
* Some Duktape specific Symbol tests.
*/
/*@include util-buffer.js@*/
/*===
TypeError
TypeError
{"foo":123,"baz":[1,2,null,4,5]}
{foo:123,baz:[1,2,null,4,5]}
0
0
SETTER called number 123 symbol Symbol(accessor)
GETTER called symbol Symbol(accessor)
dummy-getter
===*/
function | () {
// Because Symbols fail with TypeError in string concatenation, this
// Duktape 1.x idiom to create an internal string no longer works.
try {
print(Duktape.enc('jx', bufferToStringRaw(Duktape.dec('hex', 'ff')) + 'Value'));
} catch (e) {
print(e.name);
}
// Uint8Array.allocP... | test | identifier_name |
util.rs | //! Contains utility things used in glium's internals
use std::default::Default;
use std::hash::Hasher;
/// A speedy hash algorithm for node ids and def ids. The hashmap in
/// libcollections by default uses SipHash which isn't quite as speedy as we
/// want. In the compiler we're not really worried about DOS attempt... | let FnvHasher(mut hash) = *self;
for byte in bytes {
hash = hash ^ (*byte as u64);
hash = hash * 0x100000001b3;
}
*self = FnvHasher(hash);
}
fn finish(&self) -> u64 { self.0 }
} | impl Hasher for FnvHasher {
fn write(&mut self, bytes: &[u8]) { | random_line_split |
util.rs | //! Contains utility things used in glium's internals
use std::default::Default;
use std::hash::Hasher;
/// A speedy hash algorithm for node ids and def ids. The hashmap in
/// libcollections by default uses SipHash which isn't quite as speedy as we
/// want. In the compiler we're not really worried about DOS attempt... | (u64);
impl Default for FnvHasher {
fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) }
}
impl Hasher for FnvHasher {
fn write(&mut self, bytes: &[u8]) {
let FnvHasher(mut hash) = *self;
for byte in bytes {
hash = hash ^ (*byte as u64);
hash = hash * 0x100000001... | FnvHasher | identifier_name |
test_client_rendering.py | from funcweb.widget_validation import WidgetSchemaFactory
from funcweb.widget_automation import WidgetListFactory,RemoteFormAutomation,RemoteFormFactory
from func.overlord.client import Overlord, Minions
import socket
import func.utils
class TestClientWidgetRender(object):
minion = None
def test_all_minions(s... | (self):
print "\n******testing minion : %s**********"%(self.minion)
fc = Overlord(self.minion)
modules = fc.system.list_modules()
display_modules={}
print "Getting the modules that has exported arguments"
for module in modules.itervalues():
for mod in module:... | remote_widget_render | identifier_name |
test_client_rendering.py | from funcweb.widget_validation import WidgetSchemaFactory
from funcweb.widget_automation import WidgetListFactory,RemoteFormAutomation,RemoteFormFactory
from func.overlord.client import Overlord, Minions
import socket
import func.utils
class TestClientWidgetRender(object):
minion = None
def test_all_minions(s... | minion_arguments = other_options['args']
if minion_arguments:
wlist_object = WidgetListFactory(minion_arguments,minion=self.minion,module=module,method=method_name)
wlist_object = wlist_object.get_widgetlist_object()
#print wlist_object
... | conditional_block | |
test_client_rendering.py | from funcweb.widget_validation import WidgetSchemaFactory
from funcweb.widget_automation import WidgetListFactory,RemoteFormAutomation,RemoteFormFactory
from func.overlord.client import Overlord, Minions
import socket
import func.utils
class TestClientWidgetRender(object):
| print "%s will be rendered"%(mod)
display_modules[mod]=exported_methods
#do the rendering work here
for module,exp_meths in display_modules.iteritems():
for method_name,other_options in exp_meths.iteritems():
minion_arguments = other_o... | minion = None
def test_all_minions(self):
minions =Minions("*").get_all_hosts()
for m in minions:
self.minion = m
self.remote_widget_render()
def remote_widget_render(self):
print "\n******testing minion : %s**********"%(self.minion)
fc = Overlord(self.m... | identifier_body |
test_client_rendering.py | from funcweb.widget_validation import WidgetSchemaFactory
from funcweb.widget_automation import WidgetListFactory,RemoteFormAutomation,RemoteFormFactory
from func.overlord.client import Overlord, Minions
import socket
import func.utils
class TestClientWidgetRender(object):
minion = None
def test_all_minions(s... | print "%s.%s.%s rendered"%(self.minion,module,method_name) | wlist_object = wlist_object.get_widgetlist_object()
#print wlist_object
wf = WidgetSchemaFactory(minion_arguments)
schema_man=wf.get_ready_schema()
minion_form = RemoteFormAutomation(wlist_object,schema_man) | random_line_split |
lib.rs | extern crate bazel_protos;
extern crate digest;
extern crate grpcio;
extern crate protobuf;
extern crate sha2;
use std::collections::BTreeMap;
pub mod local;
pub mod remote;
#[cfg(test)]
mod test_server;
///
/// A process to be executed.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ExecuteProcessReque... | pub stderr: Vec<u8>,
pub exit_code: i32,
} | #[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExecuteProcessResult {
pub stdout: Vec<u8>, | random_line_split |
lib.rs | extern crate bazel_protos;
extern crate digest;
extern crate grpcio;
extern crate protobuf;
extern crate sha2;
use std::collections::BTreeMap;
pub mod local;
pub mod remote;
#[cfg(test)]
mod test_server;
///
/// A process to be executed.
///
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct | {
///
/// The arguments to execute.
///
/// The first argument should be an absolute or relative path to the binary to execute.
///
/// No PATH lookup will be performed unless a PATH environment variable is specified.
///
/// No shell expansion will take place.
///
pub argv: Vec<String>,
///
//... | ExecuteProcessRequest | identifier_name |
otr.js | (options) {
if (!(this instanceof OTR)) return new OTR(options)
// options
options = options || {}
// private keys
if (!options.priv)
throw new Error('Requires long-lived DSA key.')
this.priv = options.priv ? options.priv : new DSA()
this.fragment_size = options.fragment_size || 0
if (this.fragm... | OTR | identifier_name | |
otr.js | this.their_keyid = 0
this.their_priv_pk = null
this.their_instance_tag = '\x00\x00\x00\x00'
// our keys
this.our_dh = this.dh()
this.our_old_dh = this.dh()
this.our_keyid = 2
// session keys
this.sessKeys = [ new Array(2), new Array(2) ]
// saved
this.storedMgs = []
this.oldMacKeys = []
//... | random_line_split | ||
otr.js |
var CryptoJS = require('../vendor/crypto.js')
var BigInt = require('../vendor/bigint.js')
var CONST = require('./const.js')
var HLP = require('./helpers.js')
var Parse = require('./parse.js')
var AKE = require('./ake.js')
var SM = require('./sm.js')
var DSA = require('./dsa.js')
// expose CONST for consistency with d... | {
smwPath = path.join(__dirname, smwPath)
try {
// load optional dep. in node
Worker = require('webworker-threads').Worker
} catch (err) {}
} | conditional_block | |
otr.js | this.outgoing = []
// instance tag
this.our_instance_tag = options.instance_tag || OTR.makeInstanceTag()
// debug
this.debug = !!options.debug
// smp in webworker options
// this is still experimental and undocumented
this.smw = options.smw
// init vals
this.init()
// bind methods
var self ... | {
if (!(this instanceof OTR)) return new OTR(options)
// options
options = options || {}
// private keys
if (!options.priv)
throw new Error('Requires long-lived DSA key.')
this.priv = options.priv ? options.priv : new DSA()
this.fragment_size = options.fragment_size || 0
if (this.fragment_size <... | identifier_body | |
01_ExampleCell.py | #/###################/#
# Import modules
#
#ImportModules
import ShareYourSystem as SYS
#/###################/#
# Build the model
#
#Definition an instance
MyNeurongrouper=SYS.NeurongrouperClass(
).neurongroup(
#NeurongroupingBrianDict
{
'N':10,
'model':
'''
dv/dt = (-(v+60*mV)+11*mV + 5.*mV*sqrt(2... | 'Run':{}
},
)
#/###################/#
# Print
#
#Definition the AttestedStr
print('MyNeurongrouper is ')
SYS._print(MyNeurongrouper)
#/###################/#
# Do one simulation
#
"""
#Print
from brian2 import Network,ms,mV
MyNetwork=Network()
map(
MyNetwork.add,
SYS.flat(
[
MyNeurongrouper.Neurongrou... | 'v':[('Run',[0,1])],
},
#NeurongroupingSpikesDict
{ | random_line_split |
udp.rs | extern crate futures;
#[macro_use]
extern crate tokio_core;
use std::io;
use std::net::SocketAddr;
use futures::{Future, Poll};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {:?}", stringify!($... |
struct SendMessage {
socket: UdpSocket,
addr: SocketAddr,
}
impl Future for SendMessage {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
let n = try_nb!(self.socket.send_to(b"1234", &self.addr));
assert_eq!(n, 4);
Ok(().into())
}
}... | {
let mut l = t!(Core::new());
let a = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
let b = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
let a_addr = t!(a.local_addr());
let b_addr = t!(b.local_addr());
let send = SendMessage { socket: a, addr: b_addr };
le... | identifier_body |
udp.rs | extern crate futures;
#[macro_use]
extern crate tokio_core;
use std::io;
use std::net::SocketAddr;
use futures::{Future, Poll};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {:?}", stringify!($... | (&mut self) -> Poll<(), io::Error> {
let mut buf = [0; 32];
let (n, addr) = try_nb!(self.socket.recv_from(&mut buf));
assert_eq!(n, 4);
assert_eq!(&buf[..4], b"1234");
assert_eq!(addr, self.expected_addr);
Ok(().into())
}
}
| poll | identifier_name |
udp.rs | extern crate futures;
#[macro_use]
extern crate tokio_core;
| use std::io;
use std::net::SocketAddr;
use futures::{Future, Poll};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
})
}
#[test]
fn send_messages() {
let mut l ... | random_line_split | |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (RPackage):
"""Circular Statistics, from "Topics in Circular Statistics" (2001)
Circular Statistics, from "Topics in Circular Statistics" (2001) S.
Rao Jammalamadaka and A. SenGupta, World Scientific."""
homepage = "https://cloud.r-project.org/package=CircStats"
url = "https://cloud.r-project... | RCircstats | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
| """Circular Statistics, from "Topics in Circular Statistics" (2001)
Circular Statistics, from "Topics in Circular Statistics" (2001) S.
Rao Jammalamadaka and A. SenGupta, World Scientific."""
homepage = "https://cloud.r-project.org/package=CircStats"
url = "https://cloud.r-project.org/src/con... | from spack import *
class RCircstats(RPackage): | random_line_split |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RCircstats(RPackage):
| """Circular Statistics, from "Topics in Circular Statistics" (2001)
Circular Statistics, from "Topics in Circular Statistics" (2001) S.
Rao Jammalamadaka and A. SenGupta, World Scientific."""
homepage = "https://cloud.r-project.org/package=CircStats"
url = "https://cloud.r-project.org/src/contrib... | identifier_body | |
build.rs | extern crate gcc;
use std::env;
fn main() | } else if cfg!(target_os = "macos") {
minidfs_config
.include(format!("{}/include/darwin", val));
}
// TODO - to be changed to consider a dependent platform.
},
Err(e) => { panic!("JAVA_HOME shell environment must be set: {}", e); }
}
minidfs_config.compile("libminidfs.a... | {
// for libhdfs.a
match env::var("HADOOP_HOME") {
Ok(val) => {
println!("cargo:rustc-link-search=native={}/lib/native", val);
},
Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); }
}
// for jvm.h and linking to jni libraries
let mut minidfs_config = gcc::Config::ne... | identifier_body |
build.rs | extern crate gcc;
use std::env;
fn | () {
// for libhdfs.a
match env::var("HADOOP_HOME") {
Ok(val) => {
println!("cargo:rustc-link-search=native={}/lib/native", val);
},
Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); }
}
// for jvm.h and linking to jni libraries
let mut minidfs_config = gcc::Config:... | main | identifier_name |
build.rs | extern crate gcc;
use std::env;
fn main() {
// for libhdfs.a
match env::var("HADOOP_HOME") {
Ok(val) => {
println!("cargo:rustc-link-search=native={}/lib/native", val);
},
Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); }
}
// for jvm.h and linking to jni librarie... | minidfs_config.compile("libminidfs.a");
} | random_line_split | |
build.rs | extern crate gcc;
use std::env;
fn main() {
// for libhdfs.a
match env::var("HADOOP_HOME") {
Ok(val) => {
println!("cargo:rustc-link-search=native={}/lib/native", val);
},
Err(e) => { panic!("HADOOP_HOME shell environment must be set: {}", e); }
}
// for jvm.h and linking to jni librarie... |
}
minidfs_config.compile("libminidfs.a");
}
| { panic!("JAVA_HOME shell environment must be set: {}", e); } | conditional_block |
doc_link.ts | import { ExternalUrl } from "../external_urls";
/** A centralized list of all documentation slugs in the app makes it easier to
* rename / move links in the future. */
export const DOC_SLUGS = {
"weed-detection": "Weed Detector",
"camera-calibration": "Camera Calibration",
"the-farmbot-web-app": "Web App",
"f... | export const docLink = (slug?: DocSlug) =>
`${ExternalUrl.softwareDocs}/${slug || ""}`; | /** WHY?: The function keeps things DRY. It also makes life easier when the
* documentation URL / slug name changes. */ | random_line_split |
service.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | {
pub opcode: u64,
pub sess: u64,
pub data: ExchangeData,
}
/// The delegate/obtain reply message
#[repr(C, packed)]
pub struct ExchangeReply {
pub res: u64,
pub data: ExchangeData,
}
/// The close request message
#[repr(C, packed)]
pub struct Close {
pub opcode: u64,
pub sess: u64,
}
//... | Exchange | identifier_name |
service.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... |
/// The delegate/obtain reply message
#[repr(C, packed)]
pub struct ExchangeReply {
pub res: u64,
pub data: ExchangeData,
}
/// The close request message
#[repr(C, packed)]
pub struct Close {
pub opcode: u64,
pub sess: u64,
}
/// The shutdown request message
#[repr(C, packed)]
pub struct Shutdown {
... | pub data: ExchangeData,
} | random_line_split |
service.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... |
}
write!(f, "]")
}
}
impl Unmarshallable for ExchangeData {
fn unmarshall(s: &mut Source) -> Self {
let mut res = ExchangeData {
caps: s.pop_word(),
args: unsafe { intrinsics::uninit() },
};
res.args.count = s.pop_word();
for i in 0..res.... | {
write!(f, ", ")?;
} | conditional_block |
path.rs | use std::fmt;
use std::hash::{Hash, Hasher};
use std::slice::{Iter, IterMut};
#[derive(Clone, PartialEq, Hash, Debug)]
pub enum Fragment {
Index(usize),
Name(String)
}
impl fmt::Display for Fragment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Fragment::Index(... | (&self) -> usize {
self.fragments.len()
}
pub fn from_str(path: &str) -> Option<Path> {
if path.is_empty() {
return None;
}
let is_relative = path.starts_with('.');
// If the path is relative remove the first dot
let new_path = if is_relative {
... | len | identifier_name |
path.rs | #[derive(Clone, PartialEq, Hash, Debug)]
pub enum Fragment {
Index(usize),
Name(String)
}
impl fmt::Display for Fragment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Fragment::Index(ref index) => write!(f, "{}", index),
Fragment::Name(ref name) => w... | use std::fmt;
use std::hash::{Hash, Hasher};
use std::slice::{Iter, IterMut};
| random_line_split | |
path.rs | use std::fmt;
use std::hash::{Hash, Hasher};
use std::slice::{Iter, IterMut};
#[derive(Clone, PartialEq, Hash, Debug)]
pub enum Fragment {
Index(usize),
Name(String)
}
impl fmt::Display for Fragment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Fragment::Index(... |
return self.fragments == other.fragments;
}
}
impl Hash for Path {
fn hash<H: Hasher>(&self, state: &mut H) {
self.to_string().hash(state);
}
} | {
return false;
} | conditional_block |
path.rs | use std::fmt;
use std::hash::{Hash, Hasher};
use std::slice::{Iter, IterMut};
#[derive(Clone, PartialEq, Hash, Debug)]
pub enum Fragment {
Index(usize),
Name(String)
}
impl fmt::Display for Fragment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Fragment::Index(... |
pub fn iter(&self) -> Iter<Fragment> {
self.fragments.iter()
}
pub fn len(&self) -> usize {
self.fragments.len()
}
pub fn from_str(path: &str) -> Option<Path> {
if path.is_empty() {
return None;
}
let is_relative = path.starts_with('.');
... | {
self.fragments.last()
} | identifier_body |
Repository.ts | export class RepositoryKey {
constructor(
public provider: string,
public id: string
) |
public toString(): string {
return this.provider + ":" + this.id;
}
public equals(other: RepositoryKey): boolean {
return this.provider === other.provider
&& this.id === other.id;
}
}
export class Repository {
constructor(
public key: RepositoryKey,
public gitHubMetadata: RepositoryGitHubMetadata = ... | {} | identifier_body |
Repository.ts | export class RepositoryKey {
constructor(
public provider: string,
public id: string
) {}
public toString(): string {
return this.provider + ":" + this.id;
}
public equals(other: RepositoryKey): boolean {
return this.provider === other.provider
&& this.id === other.id;
}
}
export class Repository {
... | (input: any): RepositoryGitHubMetadata {
return new RepositoryGitHubMetadata(
input.owner.login,
input.name,
input.description,
input.language,
input.owner.type,
input.owner.avatar_url
);
}
}
export class RepositoryRepoCreatorMetadata {
constructor(
public sponsored: boolean = false,
public... | deserialize | identifier_name |
Repository.ts | export class RepositoryKey {
constructor(
public provider: string,
public id: string
) {}
public toString(): string {
return this.provider + ":" + this.id;
}
public equals(other: RepositoryKey): boolean {
return this.provider === other.provider
&& this.id === other.id;
}
}
export class Repository {
... | return new RepositoryRepoCreatorMetadata(
input.sponsored,
input.favorite,
input.my_sponsored,
input.favorite_count,
input.expiration_date
);
}
} | random_line_split | |
lib.rs | #![feature(str_checked_slicing)]
const DIGITS: [&str; 10] = [
" _ | ||_| ", // 0
" | | ", // 1
" _ _||_ ", // 2
" _ _| _| ", // 3
" |_| | ", // 4
" _ |_ _| ", // 5
" _ |_ |_| ", // 6
" _ | | ", // 7
" _ |_||_| ", // 8
" _ |_| _| ", // 9
];
con... | (input: &str) -> Result<String, String> {
let v = input.split(|x| x == '\n').collect::<Vec<_>>();
let lines = v.len();
if lines == 0 || lines % DIGITS_LINES != 0 {
return Err("Invalid lines".to_string());
}
let rows = v[0].len();
if rows == 0 || rows % DIGITS_ROWS != 0 {
return... | convert | identifier_name |
lib.rs | #![feature(str_checked_slicing)]
const DIGITS: [&str; 10] = [
" _ | ||_| ", // 0
" | | ", // 1
" _ _||_ ", // 2
" _ _| _| ", // 3
" |_| | ", // 4
" _ |_ _| ", // 5
" _ |_ |_| ", // 6
" _ | | ", // 7
" _ |_||_| ", // 8
" _ |_| _| ", // 9
];
con... | let line = i * DIGITS_LINES;
let number = format!(
"{}{}{}{}",
v[line].get(row..row + DIGITS_ROWS).unwrap(),
v[line + 1].get(row..row + DIGITS_ROWS).unwrap(),
v[line + 2].get(row..row + DIGITS_ROWS).unwrap(),
v[line... | {
let v = input.split(|x| x == '\n').collect::<Vec<_>>();
let lines = v.len();
if lines == 0 || lines % DIGITS_LINES != 0 {
return Err("Invalid lines".to_string());
}
let rows = v[0].len();
if rows == 0 || rows % DIGITS_ROWS != 0 {
return Err(format!("Invalid {} row at line 1",... | identifier_body |
lib.rs | #![feature(str_checked_slicing)]
const DIGITS: [&str; 10] = [
" _ | ||_| ", // 0
" | | ", // 1
" _ _||_ ", // 2
" _ _| _| ", // 3
" |_| | ", // 4
" _ |_ _| ", // 5
" _ |_ |_| ", // 6
" _ | | ", // 7
" _ |_||_| ", // 8
" _ |_| _| ", // 9
];
con... |
if v.iter().any(|x| x.len() != rows) {
return Err("Invalid rows".to_string());
}
let mut result = String::new();
for i in 0..lines / DIGITS_LINES {
for j in 0..rows / DIGITS_ROWS {
let row = j * DIGITS_ROWS;
let line = i * DIGITS_LINES;
let number =... | {
return Err(format!("Invalid {} row at line 1", rows));
} | conditional_block |
lib.rs | #![feature(str_checked_slicing)]
const DIGITS: [&str; 10] = [
" _ | ||_| ", // 0
" | | ", // 1
" _ _||_ ", // 2
" _ _| _| ", // 3
" |_| | ", // 4
" _ |_ _| ", // 5
" _ |_ |_| ", // 6 | const DIGITS_ROWS: usize = 3;
const DIGITS_LINES: usize = 4;
pub fn convert(input: &str) -> Result<String, String> {
let v = input.split(|x| x == '\n').collect::<Vec<_>>();
let lines = v.len();
if lines == 0 || lines % DIGITS_LINES != 0 {
return Err("Invalid lines".to_string());
}
let row... | " _ | | ", // 7
" _ |_||_| ", // 8
" _ |_| _| ", // 9
];
| random_line_split |
layout.ts |
public sourcesById:{[id:string]: Node}
public attributesById:{[id:string]: Node}
constructor(public sources:Node[] = [], public attributes:Node[] = [], public edges:Edge[] = [], public minimumSize?:[number, number]) {}
/**
* Attempt to stochastically place nodes to minimize edge intersections, ... |
/**
* Given a source and its dependents, lay them out into a radial group.
*/
protected layoutSourceGroup(source:Node, group:Node[]):{positions:NodePositions, bounds:Bounds} {
let hw = source.width / 2;
let hh = source.height / 2;
let bounds = {left: -hw, right: hw, top: -hh, botto... | {
let hw = node.width / 2;
let hh = node.height / 2;
let x = radius * Math.cos(angle);
let y = radius * Math.sin(angle);
let myBounds = {left: x - hw, top: y - hh, right: x + hw, bottom: y + hh};
positions[node.id] = [x, y];
bounds.push(myBounds);
for(let other of bounds)... | identifier_body |
layout.ts |
public sourcesById:{[id:string]: Node}
public attributesById:{[id:string]: Node}
constructor(public sources:Node[] = [], public attributes:Node[] = [], public edges:Edge[] = [], public minimumSize?:[number, number]) {}
/**
* Attempt to stochastically place nodes to minimize edge intersections, ... | (source:Node, group:Node[]):{positions:NodePositions, bounds:Bounds} {
let hw = source.width / 2;
let hh = source.height / 2;
let bounds = {left: -hw, right: hw, top: -hh, bottom: hh};
let positions:NodePositions = {};
positions[source.id] = | layoutSourceGroup | identifier_name |
layout.ts | bottom: node.y + hh};
fixedLayout.bounds = mergeIntoBB(fixedLayout.bounds, nodeBounds);
fixedLayout.subBounds.push(nodeBounds);
fixedLayout.positions[node.id] = [node.x, node.y];
}
// Pre-compute the layouts for source groups so we can focus on placements.
let sourceLayouts =... | }
}
if(!fits) { layout.misfits += nodeCount; }
| random_line_split | |
layout.ts | edge:" + JSON.stringify(edge)); }
if(!sourceToTarget[edge.source]) { sourceToTarget[edge.source] = []; }
sourceToTarget[edge.source].push(edge.target);
if(!targetToSources[edge.target]) { targetToSources[edge.target] = []; }
targetToSources[edge.target].push(edge.source);
}
... | {
failed = !this.placeInCircle(group[ix + 1], radius, angle + Math.PI, positions, subBounds) || failed;
} | conditional_block | |
mod.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | //
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General ... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.