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 |
|---|---|---|---|---|
CheckboxSelectionModel.js | /*!
* js-file-browser
* Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file.
*
* With components from: Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.3.1
* Copyrigh... | Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this);
this.grid.on('render', function(){
Ext.fly(this.grid.getView().innerHd).on('mousedown', this.onHdMouseDown, this);
}, this);
},
/**
* @private
* Process and refire events routed from the GridView's p... | },
// private
initEvents : function(){ | random_line_split |
test_compact_csv_reader.py | from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvRea... | assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_... | random_line_split | |
test_compact_csv_reader.py | from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def | (stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
... | test_reader_raw | identifier_name |
test_compact_csv_reader.py | from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvRea... |
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, ... | r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']] | identifier_body |
layout_image.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread need... | {
id: PendingImageId,
cache: Arc<ImageCache>,
}
impl FetchResponseListener for LayoutImageContext {
fn process_request_body(&mut self) {}
fn process_request_eof(&mut self) {}
fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) {
self.cache.notify_pending_response(... | LayoutImageContext | identifier_name |
layout_image.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread need... | url: url,
origin: document.origin().immutable().clone(),
destination: Destination::Image,
pipeline_id: Some(document.global().pipeline_id()),
.. FetchRequestInit::default()
};
// Layout image loads do not delay the document load event.
document.loader().fetch_async_b... | {
let context = Arc::new(Mutex::new(LayoutImageContext {
id: id,
cache: cache,
}));
let document = document_from_node(node);
let window = document.window();
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context... | identifier_body |
layout_image.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread need... | }
fn process_response_eof(&mut self, response: Result<(), NetworkError>) {
self.cache.notify_pending_response(self.id,
FetchResponseMsg::ProcessResponseEOF(response));
}
}
impl PreInvoke for LayoutImageContext {}
pub fn fetch_image_for_layout(url: ServoU... | FetchResponseMsg::ProcessResponseChunk(payload)); | random_line_split |
http_shortcuts.py | from past.builtins import basestring
import os.path
import simplejson as json
from django.shortcuts import render as django_render
from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect
from django.utils.decorators import available_attrs
from functools import wraps
def render(requ... | if not basename.startswith("_"):
dirname = os.path.dirname(template)
template = "%s/_%s"%(dirname,basename)
response = django_render(request=request, template_name=template, context=context)
else:
response = django_render(request,
temp... | basename = os.path.basename(template) | random_line_split |
http_shortcuts.py | from past.builtins import basestring
import os.path
import simplejson as json
from django.shortcuts import render as django_render
from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect
from django.utils.decorators import available_attrs
from functools import wraps
def render(requ... |
return wrapper
def render_json(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def wrapper(request, *args, **kwargs):
_json = view_func(request, *args, **kwargs)
if not isinstance(_json, str) and not isinstance(_json, dict) and not isinstance(_json, list) and not isinsta... | return to | conditional_block |
http_shortcuts.py | from past.builtins import basestring
import os.path
import simplejson as json
from django.shortcuts import render as django_render
from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect
from django.utils.decorators import available_attrs
from functools import wraps
def render(requ... | (request, *args, **kwargs):
_json = view_func(request, *args, **kwargs)
if not isinstance(_json, str) and not isinstance(_json, dict) and not isinstance(_json, list) and not isinstance(_json, tuple):
return _json
return HttpResponse(json.dumps(_json), content_type="application/json")... | wrapper | identifier_name |
http_shortcuts.py | from past.builtins import basestring
import os.path
import simplejson as json
from django.shortcuts import render as django_render
from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect
from django.utils.decorators import available_attrs
from functools import wraps
def render(requ... |
def permanent_redirect(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def wrapper(request, *args, **kw):
to = view_func(request, *args, **kw)
if isinstance(to, basestring):
return HttpResponsePermanentRedirect(to)
else:
return to
retu... | if request.is_ajax() and not ignore_ajax:
basename = os.path.basename(template)
if not basename.startswith("_"):
dirname = os.path.dirname(template)
template = "%s/_%s"%(dirname,basename)
response = django_render(request=request, template_name=template, context=context)
... | identifier_body |
node.py | # Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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, m... |
def _worker(self):
self.ant.response_function = self._worker_response
self.ant.channel_event_function = self._worker_event
# TODO: check capabilities
self.ant.start()
def _main(self):
while self._running:
try:
(data_type, ch... | self._event_cond.acquire()
self._events.append((channel, event, data))
self._event_cond.notify()
self._event_cond.release() | conditional_block |
node.py | # Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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, m... | import Queue
from ant.base.ant import Ant
from ant.base.message import Message
from ant.easy.channel import Channel
from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special
_logger = logging.getLogger("garmin.ant.easy.node")
class Node():
def __init__(self):
self._res... | import threading
import logging | random_line_split |
node.py | # Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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, m... | ():
def __init__(self):
self._responses_cond = threading.Condition()
self._responses = collections.deque()
self._event_cond = threading.Condition()
self._events = collections.deque()
self._datas = Queue.Queue()
self.cha... | Node | identifier_name |
node.py | # Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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, m... |
def wait_for_event(self, ok_codes):
return wait_for_event(ok_codes, self._events, self._event_cond)
def wait_for_response(self, event_id):
return wait_for_response(event_id, self._responses, self._responses_cond)
def wait_for_special(self, event_id):
return wait_for_special(event... | self.ant.set_network_key(network, key)
return self.wait_for_response(Message.ID.SET_NETWORK_KEY) | identifier_body |
selector-css2.js | ById)
if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) {
nodes = Y.DOM.allById(id, root);
// try className
} else if (className) {
nodes = root.getElementsByClassName(className);
... | {
token.combinator = Y.Selector.combinators[match[1]];
} | conditional_block | |
selector-css2.js | the attribute and the current node's value of the attribute.
* @property operators
* @type object
*/
operators: {
'': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute
'~=': '(?:^|\\s+){val}(?:\\s+|... | },
_bruteQuery: function(selector, root, firstOnly) {
var ret = [],
nodes = [],
tokens = Selector._tokenize(selector),
token = tokens[tokens.length - 1],
rootDoc = Y.DOM._getDoc(root),
child,
id,... | 'first-child': function(node) {
return Y.DOM._children(node[PARENT_NODE])[0] === node;
} | random_line_split |
hkt_notes.rs | higher kinded types in rust
struct List<A> { ... }
/* note we could fully apply this or use
trait Functor for List { ... }
trait Functor for List<_> { ... }
fn (&self<A>
Functor<A> for List
when we implement a normal trait we have a hidden type parameter
if we look at Haskell for example, a simple show class loo... | (&self) -> String {
self.clone()
}
}
If we move to an example like:
// Could be named anything, just keeping with Haskell
// convention, this represents a container that can be mapped ove
//
class Functor f
map :: (a -> b) -> f a -> f b
instance Functor [] where
map f [] = []
map f (x:xs) = f x : map f x... | show | identifier_name |
hkt_notes.rs | higher kinded types in rust
struct List<A> { ... }
/* note we could fully apply this or use
trait Functor for List { ... }
trait Functor for List<_> { ... }
fn (&self<A>
Functor<A> for List
when we implement a normal trait we have a hidden type parameter
if we look at Haskell for example, a simple show class loo... | map f (x:xs) = f x : map f xs
trait Functor where Self<_> { ... }
impl Functor for List | class Functor f
map :: (a -> b) -> f a -> f b
instance Functor [] where
map f [] = [] | random_line_split |
ext.py | # -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import asyncio
import random
from .api import every, once_at, JobSchedule, default_schedule_manager
__all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday',
'every_thursday', 'every_friday', 'every_saturday', '... | ():
count = 0
while True:
rand = random.randrange(round(interval.total_seconds()))
tmp = round(start + interval.total_seconds() * count + rand - loop.time())
yield tmp
count += 1
schedule = JobSchedule(job, wait_time_gen(), loop=loop)
# add it to ... | wait_time_gen | identifier_name |
ext.py | # -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import asyncio
import random
from .api import every, once_at, JobSchedule, default_schedule_manager
__all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday',
'every_thursday', 'every_friday', 'every_saturday', '... |
schedule = JobSchedule(job, wait_time_gen(), loop=loop)
# add it to default_schedule_manager, so that user can aschedule.cancel it
default_schedule_manager.add_schedule(schedule)
return schedule
def every_day(job, loop=None):
return every(job, timedelta=timedelta(days=1), loop=loop)
def every_... | count = 0
while True:
rand = random.randrange(round(interval.total_seconds()))
tmp = round(start + interval.total_seconds() * count + rand - loop.time())
yield tmp
count += 1 | identifier_body |
ext.py | # -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import asyncio
import random
from .api import every, once_at, JobSchedule, default_schedule_manager
__all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday',
'every_thursday', 'every_friday', 'every_saturday', '... |
schedule = JobSchedule(job, wait_time_gen(), loop=loop)
# add it to default_schedule_manager, so that user can aschedule.cancel it
default_schedule_manager.add_schedule(schedule)
return schedule
def every_day(job, loop=None):
return every(job, timedelta=timedelta(days=1), loop=loop)
def every_... | rand = random.randrange(round(interval.total_seconds()))
tmp = round(start + interval.total_seconds() * count + rand - loop.time())
yield tmp
count += 1 | conditional_block |
ext.py | # -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import asyncio
import random
from .api import every, once_at, JobSchedule, default_schedule_manager
__all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday',
'every_thursday', 'every_friday', 'every_saturday', '... | every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop)
every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop)
every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop)
every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop)
every_friday = lambda job,... | random_line_split | |
lib.rs | //! Render to a window created by Glutin, using Glium's OpenGL functions
#[macro_use] extern crate log;
#[macro_use] extern crate glium;
extern crate breeze_backend;
use breeze_backend::{BackendAction, BackendResult, Renderer};
use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
use breeze_backend::viewport::View... |
_ => {}
}
}
Ok(vec![])
}
}
fn resize(vbuf: &mut VertexBuffer<Vertex>, win_w: u32, win_h: u32) {
let Viewport { x, y, w, h } = Viewport::for_window_size(win_w, win_h);
let (win_w, win_h) = (win_w as f32, win_h as f32);
let (x, y, w, h) = (x as f32 / win_w, y... | {
resize(&mut self.vbuf, w, h);
} | conditional_block |
lib.rs | //! Render to a window created by Glutin, using Glium's OpenGL functions
#[macro_use] extern crate log;
#[macro_use] extern crate glium;
extern crate breeze_backend;
use breeze_backend::{BackendAction, BackendResult, Renderer};
use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
use breeze_backend::viewport::View... | format: ClientFormat::U8U8U8,
});
let mut target = self.display.draw();
target.clear_color_srgb(0.0, 0.0, 0.0, 0.0);
target.draw(
&self.vbuf,
&NoIndices(PrimitiveType::TriangleStrip),
&self.program,
&uniform! {
... | data: Cow::Borrowed(frame_data),
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT, | random_line_split |
lib.rs | //! Render to a window created by Glutin, using Glium's OpenGL functions
#[macro_use] extern crate log;
#[macro_use] extern crate glium;
extern crate breeze_backend;
use breeze_backend::{BackendAction, BackendResult, Renderer};
use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
use breeze_backend::viewport::View... | (&mut self, frame_data: &[u8]) -> BackendResult<Vec<BackendAction>> {
// upload new texture data
self.texture.write(Rect {
left: 0,
bottom: 0,
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT,
}, RawImage2d {
data: Cow::Borrowed(frame_data),
... | render | identifier_name |
user.js | import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import { deleteUser, updateUserByUsername } from '../../lib/db'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
// You do not generally want to return the whole user object
// because it may contain sensi... | req.logOut()
res.status(204).end()
})
export default handler | random_line_split | |
user.js | import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import { deleteUser, updateUserByUsername } from '../../lib/db'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
// You do not generally want to return the whole user object
// because it may contain sensi... |
})
.put((req, res) => {
const { name } = req.body
const user = updateUserByUsername(req, req.user.username, { name })
res.json({ user })
})
.delete((req, res) => {
deleteUser(req)
req.logOut()
res.status(204).end()
})
export default handler
| {
next()
} | conditional_block |
schools_with_description_2020.py | import logging
from datetime import datetime
import math
import numpy as np
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
from ..models import SchoolWithDescription2020
from ..utilities import init_flask, time_delta, chunks, ItmToWGS84
school_fields = {
"school_id": "סמל_מוסד",
"school_name": "... | iption(
schools_description_filepath, schools_coordinates_filepath
)
truncate_schools_with_description()
new_items = 0
logging.info("inserting " + str(len(schools)) + " new schools")
for schools_chunk in chunks(schools, batch_size):
db.session.bulk_insert_... | _schools_with_descr | identifier_name |
schools_with_description_2020.py | import logging
from datetime import datetime
import math
import numpy as np
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
from ..models import SchoolWithDescription2020
from ..utilities import init_flask, time_delta, chunks, ItmToWGS84
school_fields = {
"school_id": "סמל_מוסד",
"school_name": "... | hool_tuple)
school = {
"school_id": get_numeric_value(school[school_fields["school_id"]], int),
"school_name": school_name,
"municipality_name": get_str_value(school[school_fields["municipality_name"]]),
"yishuv_name": get_str_value(school[school_fields["yishuv_na... | ppend(sc | conditional_block |
schools_with_description_2020.py | import logging
from datetime import datetime
import math
import numpy as np
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
from ..models import SchoolWithDescription2020
from ..utilities import init_flask, time_delta, chunks, ItmToWGS84
school_fields = {
"school_id": "סמל_מוסד",
"school_name": "... | location_accuracy = get_str_value(
df_coordinates.loc[
df_coordinates[school_fields["school_id"]] == school_id,
school_fields["location_accuracy"],
].values[0]
)
else:
x_coord = None
y_coord =... | %s'..." % schools_description_filepath)
df_schools = pd.read_excel(schools_description_filepath)
logging.info("\tReading schools coordinates data from '%s'..." % schools_coordinates_filepath)
df_coordinates = pd.read_excel(schools_coordinates_filepath)
schools = []
# get school_id
df_schools = d... | identifier_body |
schools_with_description_2020.py | import logging
from datetime import datetime
import math
import numpy as np
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
from ..models import SchoolWithDescription2020
from ..utilities import init_flask, time_delta, chunks, ItmToWGS84
school_fields = {
"school_id": "סמל_מוסד",
"school_name": "... | df_schools = df_schools.drop_duplicates(school_fields["school_id"])
# sort by school_id
df_schools = df_schools.sort_values(school_fields["school_id"], ascending=True)
all_schools_tuples = []
for _, school in df_schools.iterrows():
school_id = get_numeric_value(school[school_fields["school_i... | random_line_split | |
elastic.js | /*
* angular-elastic v2.4.2
* (c) 2014 Monospaced http://monospaced.com
* License: MIT
*/
angular.module('monospaced.elastic', [])
.constant('msdElasticConfig', {
append: ''
})
.directive('msdElastic', [
'$timeout', '$window', 'msdElasticConfig',
function($timeout, $window, config) {
'use... | () {
var mirrorStyle = mirrorInitStyle;
mirrored = ta;
// copy the essential styles from the textarea to the mirror
taStyle = getComputedStyle(ta);
angular.forEach(copyStyle, function(val) {
mirrorStyle += val + ':' + taStyle.getPropertyValue(va... | initMirror | identifier_name |
elastic.js | /*
* angular-elastic v2.4.2
* (c) 2014 Monospaced http://monospaced.com
* License: MIT
*/
angular.module('monospaced.elastic', [])
.constant('msdElasticConfig', {
append: ''
})
.directive('msdElastic', [
'$timeout', '$window', 'msdElasticConfig',
function($timeout, $window, config) {
'use... |
// set these properties before measuring dimensions
$ta.css({
'overflow': 'hidden',
'overflow-y': 'hidden',
'word-wrap': 'break-word'
});
// force text reflow
var text = ta.value;
ta.value = '';
ta.value = text;... | {
return;
} | conditional_block |
elastic.js | /*
* angular-elastic v2.4.2
* (c) 2014 Monospaced http://monospaced.com
* License: MIT
*/
angular.module('monospaced.elastic', [])
.constant('msdElasticConfig', {
append: ''
})
.directive('msdElastic', [
'$timeout', '$window', 'msdElasticConfig',
function($timeout, $window, config) {
'use... | taComputedStyleWidth = getComputedStyle(ta).getPropertyValue('width');
// ensure getComputedStyle has returned a readable 'used value' pixel width
if (taComputedStyleWidth.substr(taComputedStyleWidth.length - 2, 2) === 'px') {
// update mirror width in case the... | {
var taHeight,
taComputedStyleWidth,
mirrorHeight,
width,
overflow;
if (mirrored !== ta) {
initMirror();
}
// active flag prevents actions in function from calling adjust again
if... | identifier_body |
elastic.js | /*
* angular-elastic v2.4.2
* (c) 2014 Monospaced http://monospaced.com
* License: MIT
*/
angular.module('monospaced.elastic', [])
.constant('msdElasticConfig', {
append: ''
})
.directive('msdElastic', [
'$timeout', '$window', 'msdElasticConfig',
function($timeout, $window, config) {
'use... | mirrorStyle += val + ':' + taStyle.getPropertyValue(val) + ';';
});
mirror.setAttribute('style', mirrorStyle);
}
function adjust() {
var taHeight,
taComputedStyleWidth,
mirrorHeight,
width,
... |
mirrored = ta;
// copy the essential styles from the textarea to the mirror
taStyle = getComputedStyle(ta);
angular.forEach(copyStyle, function(val) { | random_line_split |
forms.py | from django import forms
from selectable.forms import AutoCompleteSelectField
from selectable.forms import AutoCompleteSelectWidget
from opendata.catalog.lookups import CityLookup, CountyLookup
from .models import Request
class SearchForm(forms.Form):
text = forms.CharField(required=False)
class RequestForm(fo... |
class Media:
js = (
"suggestions/js/form.js",
)
| county = AutoCompleteSelectField(
lookup_class=CountyLookup,
required=False,
widget=AutoCompleteSelectWidget(
lookup_class=CountyLookup,
attrs={"class": "suggestions-hidden suggestions-county"},
)
)
city = AutoCompleteSelectField(
lookup_class=City... | identifier_body |
forms.py | from django import forms
from selectable.forms import AutoCompleteSelectField
from selectable.forms import AutoCompleteSelectWidget
from opendata.catalog.lookups import CityLookup, CountyLookup
from .models import Request
class SearchForm(forms.Form):
text = forms.CharField(required=False)
class RequestForm(fo... | js = (
"suggestions/js/form.js",
) | model = Request
exclude = ('suggested_by', 'resources', 'rating', 'status', )
class Media: | random_line_split |
forms.py | from django import forms
from selectable.forms import AutoCompleteSelectField
from selectable.forms import AutoCompleteSelectWidget
from opendata.catalog.lookups import CityLookup, CountyLookup
from .models import Request
class SearchForm(forms.Form):
text = forms.CharField(required=False)
class | (forms.ModelForm):
county = AutoCompleteSelectField(
lookup_class=CountyLookup,
required=False,
widget=AutoCompleteSelectWidget(
lookup_class=CountyLookup,
attrs={"class": "suggestions-hidden suggestions-county"},
)
)
city = AutoCompleteSelectField(
... | RequestForm | identifier_name |
list_filtering.js | function changeQueryStr(name, value) {
var query = window.location.search.substring(1),
newQuery = '?', notFound = true,
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair == '' || pair[0] == 'page') continue;
if (pair... |
$(document).ready(init_filtering_stories);
$(document).ready(init_pagination); | }
| random_line_split |
list_filtering.js | function changeQueryStr(name, value) | });
window.history.pushState({path:newurl},'',newurl);
}
function init_filtering_stories(jQuery) {
$('#filtering input').change(function(){
var input = $(this), name = input[0].name, value=input.val();
changeQueryStr(name, value);
});
}
function init_pagination(jQuery) {
$('.pa... | {
var query = window.location.search.substring(1),
newQuery = '?', notFound = true,
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair == '' || pair[0] == 'page') continue;
if (pair[0] == name) { notFound = false; pair... | identifier_body |
list_filtering.js | function changeQueryStr(name, value) {
var query = window.location.search.substring(1),
newQuery = '?', notFound = true,
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair == '' || pair[0] == 'page') continue;
if (pair... |
else { newQuery = newQuery.slice(0,-1); }
var loc = window.location,
ajaxurl = '/ajax' + loc.pathname + newQuery,
newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery;
$.get(ajaxurl).done(function(data){
$('#ajax-content').html(data);
init_pagination();
... | { newQuery = ''; } | conditional_block |
list_filtering.js | function changeQueryStr(name, value) {
var query = window.location.search.substring(1),
newQuery = '?', notFound = true,
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair == '' || pair[0] == 'page') continue;
if (pair... | (jQuery) {
$('.pager a').on('click', function(e){
e.preventDefault();
var value = $(this).closest('li').data('pageNum');
if (value) changeQueryStr('page', String(value));
});
}
$(document).ready(init_filtering_stories);
$(document).ready(init_pagination);
| init_pagination | identifier_name |
gdcvault.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
HEADRequest,
sanitized_Request,
urlencode_postdata,
)
class GDCVaultIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?'
_NETRC_MACHINE = '... | (self, webpage_url, display_id):
username, password = self._get_login_info()
if username is None or password is None:
self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.')
return None
mobj = re.ma... | _login | identifier_name |
gdcvault.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
HEADRequest,
sanitized_Request,
urlencode_postdata,
)
class GDCVaultIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?'
_NETRC_MACHINE = '... |
xml_name = self._html_search_regex(
r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>',
start_page, 'xml filename', default=None)
if xml_name is None:
# Fallback to the older format
xml_name = self._html_search_regex(
r'<iframe src=".*?\... | start_page = login_res
# Grab the url from the authenticated page
xml_root = self._html_search_regex(
PLAYER_REGEX, start_page, 'xml root') | conditional_block |
gdcvault.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
HEADRequest,
sanitized_Request,
urlencode_postdata,
)
class GDCVaultIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?'
_NETRC_MACHINE = '... |
login_form = {
'email': username,
'password': password,
}
request = sanitized_Request(login_url, urlencode_postdata(login_form))
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
self._download_webpage(request, display_id, 'Logging ... | random_line_split | |
gdcvault.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
HEADRequest,
sanitized_Request,
urlencode_postdata,
)
class GDCVaultIE(InfoExtractor):
| },
'params': {
'skip_download': True, # Requires rtmpdump
}
},
{
'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or',
'md5': 'a5eb77996ef82118afbbe8e48731b98e',
'info_dict': {
'... | _VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?'
_NETRC_MACHINE = 'gdcvault'
_TESTS = [
{
'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple',
'md5': '7ce8388f544c88b7ac11c7ab1b593704',
'info_dict': {
... | identifier_body |
util.js | (data, callback) {
if (util.isArr(data)) {
for (var i = 0; i < data.length; i++) callback.call(null, data[i]);
} else if (util.isObj(data)) {
for (var k in data) callback.call(null, k, data[k]);
} else return false;
};
util.ucfirst = function (string) {
... | identifier_name | ||
util.js | * @returns {*}
*/
util.objMergeOnlyExists = function (objectBase, src) {
for (var key in src)
if (objectBase[key] !== undefined)
objectBase[key] = src[key];
return objectBase;
};
/**
* Merge an array `src` into the array `arrBase`
* @param arr... | * @param src | random_line_split | |
util.js | ]);
} else return false;
};
util.ucfirst = function (string) {
return string && string[0].toUpperCase() + string.slice(1);
};
util.node2html = function (element) {
var container = document.createElement("div");
container.appendChild(element.cloneNode(true));
ret... | done(err);
else if (i >= array.length)
done();
else if (i < array.length) {
var item = array[i++];
setTimeout(function () {
iterator(item, i - 1, next);
}, 0);
}
}
};
/**
*... | identifier_body | |
util.js |
}
return destination;
};
/**
* Clone object
* @param {Object} source
* @returns {*}
*/
util.objClone = function (source) {
if (source === null || typeof source !== 'object') return source;
var temp = source.constructor();
for (var key in source... | {
destination[property] = source[property];
} | conditional_block | |
process.py | import os
sys = os.system
CC = 'g++ {} -std=gnu++0x -Wall'
FLAG_clear = ['/c', '-c']
FLAG_window = ['/w', '-w']
FLAG_exit = ['/e', '-e']
def main():
print('List of existing <*.cpp> files:')
files = []
counter = 0
for file in os.listdir():
if file[-4:] == '.cpp':
counter += 1
files.append(file)
print('... | elif command == 'run':
if len(list(set(FLAG_clear).intersection(set(flags)))) > 0:
sys('cls')
print('Compiling...')
err = sys((CC+' -o {}.exe').format(name, name[:-4]))
if err:
print('Error during compiling. <{}>'.format(err))
else:
print('Compiled succesfully. Starting:\n' + '-' * 31)
if len(lis... | print('Error during compiling. <{}>'.format(err))
else:
print('Compiled succesfully.') | random_line_split |
process.py | import os
sys = os.system
CC = 'g++ {} -std=gnu++0x -Wall'
FLAG_clear = ['/c', '-c']
FLAG_window = ['/w', '-w']
FLAG_exit = ['/e', '-e']
def main():
| fileid = int(name[1:])
name = files[fileid - 1]
except:
pass
else:
flags = list(ex)
if command == 'open':
if len(list(set(FLAG_clear).intersection(set(flags)))) > 0:
sys('cls')
if len(list(set(FLAG_window).intersection(set(flags)))) > 0:
sys('start {}'.format(name))
else:
sys('{}'... | print('List of existing <*.cpp> files:')
files = []
counter = 0
for file in os.listdir():
if file[-4:] == '.cpp':
counter += 1
files.append(file)
print('{:->3d}) {}'.format(counter, file[:-4]))
name = ''
flags = []
command, *ex = input('Enter your <command> [<name>] [<*flags>]: ').split()
if len(ex):... | identifier_body |
process.py | import os
sys = os.system
CC = 'g++ {} -std=gnu++0x -Wall'
FLAG_clear = ['/c', '-c']
FLAG_window = ['/w', '-w']
FLAG_exit = ['/e', '-e']
def | ():
print('List of existing <*.cpp> files:')
files = []
counter = 0
for file in os.listdir():
if file[-4:] == '.cpp':
counter += 1
files.append(file)
print('{:->3d}) {}'.format(counter, file[:-4]))
name = ''
flags = []
command, *ex = input('Enter your <command> [<name>] [<*flags>]: ').split()
if len... | main | identifier_name |
process.py | import os
sys = os.system
CC = 'g++ {} -std=gnu++0x -Wall'
FLAG_clear = ['/c', '-c']
FLAG_window = ['/w', '-w']
FLAG_exit = ['/e', '-e']
def main():
print('List of existing <*.cpp> files:')
files = []
counter = 0
for file in os.listdir():
if file[-4:] == '.cpp':
counter += 1
files.append(file)
print('... |
print('List of existing <*.{}> files:'.format(name))
l = len(name)
for file in os.listdir():
if file[-l:] == name:
print('{:>20}'.format(file[:-l - 1]))
else:
print('List of all existing files:')
for file in os.listdir():
print('{:>20}'.format(file))
if len(list(set(FLAG_exit).intersect... | sys('cls') | conditional_block |
html_diff.py | from __future__ import absolute_import
from typing import Callable, Tuple, Text
from django.conf import settings
from diff_match_patch import diff_match_patch
import platform
import logging
# TODO: handle changes in link hrefs
def highlight_with_class(klass, text):
# type: (Text, Text) -> Text
return '<spa... |
if in_tag:
return False
return True
def highlight_html_differences(s1, s2):
# type: (Text, Text) -> Text
differ = diff_match_patch()
ops = differ.diff_main(s1, s2)
differ.diff_cleanupSemantic(ops)
retval = u''
in_tag = False
idx = 0
while idx < len(ops):
op, te... | if c == '<':
if in_tag:
return False
in_tag = True
elif c == '>':
if not in_tag:
return False
in_tag = False | conditional_block |
html_diff.py | from __future__ import absolute_import
from typing import Callable, Tuple, Text
from django.conf import settings
from diff_match_patch import diff_match_patch
import platform
import logging
# TODO: handle changes in link hrefs
def highlight_with_class(klass, text):
# type: (Text, Text) -> Text
return '<spa... | for type, text in chunks:
if type == 'text':
retval += highlight_func(text)
else:
retval += text
return retval
def verify_html(html):
# type: (Text) -> bool
# TODO: Actually parse the resulting HTML to ensure we don't
# create mal-formed markup. This is unfo... | # type: (List[Tuple[Text, Text]], Callable[[Text], Text]) -> Text
retval = u'' | random_line_split |
html_diff.py | from __future__ import absolute_import
from typing import Callable, Tuple, Text
from django.conf import settings
from diff_match_patch import diff_match_patch
import platform
import logging
# TODO: handle changes in link hrefs
def highlight_with_class(klass, text):
# type: (Text, Text) -> Text
return '<spa... | (text, in_tag):
# type: (Text, bool) -> Tuple[List[Tuple[Text, Text]], bool]
start = 0
idx = 0
chunks = [] # type: List[Tuple[Text, Text]]
for c in text:
if c == '<':
in_tag = True
if start != idx:
chunks.append(('text', text[start:idx]))
s... | chunkize | identifier_name |
html_diff.py | from __future__ import absolute_import
from typing import Callable, Tuple, Text
from django.conf import settings
from diff_match_patch import diff_match_patch
import platform
import logging
# TODO: handle changes in link hrefs
def highlight_with_class(klass, text):
# type: (Text, Text) -> Text
|
def highlight_inserted(text):
# type: (Text) -> Text
return highlight_with_class('highlight_text_inserted', text)
def highlight_deleted(text):
# type: (Text) -> Text
return highlight_with_class('highlight_text_deleted', text)
def highlight_replaced(text):
# type: (Text) -> Text
return highli... | return '<span class="%s">%s</span>' % (klass, text) | identifier_body |
request.spec.browser.ts | /*
* Copyright (c) 2019 by Filestack.
* Some rights reserved.
*
* 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 ... | import { FsRequest } from './request';
import { FsHttpMethod } from './types';
import { Dispatch } from './dispatch';
jest.mock('./dispatch');
const dispatchSpy = jest.fn(() => Promise.resolve('response'));
// @ts-ignore
Dispatch.prototype.request.mockImplementation(dispatchSpy);
describe('Request/Request', () => {
... | */
| random_line_split |
main.rs | extern crate itertools;
use std::ops::Add;
use itertools::Itertools;
struct Character {
hitpoints: u16,
damage: u16,
armor: u16
}
impl Character {
fn rounds(&self, opponent: &Character) -> u16 {
let round_damage: f64 =
if opponent.armor >= self.damage { 1 }
else... | for inventory in inventories.iter() {
additional.push(inventory + &rings.0);
additional.push(inventory + &rings.1);
additional.push(inventory + &(rings.0 + rings.1));
}
}
inventories.extend(additional);
for inventory in &in... | let mut additional = Vec::with_capacity(rings.len() * 3);
for rings in rings.iter().combinations() { | random_line_split |
main.rs |
extern crate itertools;
use std::ops::Add;
use itertools::Itertools;
struct Character {
hitpoints: u16,
damage: u16,
armor: u16
}
impl Character {
fn rounds(&self, opponent: &Character) -> u16 {
let round_damage: f64 =
if opponent.armor >= self.damage { 1 }
els... | as f64;
((opponent.hitpoints as f64) / round_damage).ceil() as u16
}
fn beats(&self, opponent: &Character) -> bool {
let a = self.rounds(opponent);
let b = opponent.rounds(&self);
a <= b
}
}
#[derive(Clone)]
struct Inventory {
cost: u16,
damage: u16,
armor:... | { self.damage - opponent.armor } | conditional_block |
main.rs |
extern crate itertools;
use std::ops::Add;
use itertools::Itertools;
struct | {
hitpoints: u16,
damage: u16,
armor: u16
}
impl Character {
fn rounds(&self, opponent: &Character) -> u16 {
let round_damage: f64 =
if opponent.armor >= self.damage { 1 }
else { self.damage - opponent.armor } as f64;
((opponent.hitpoints as f64) / round... | Character | identifier_name |
adjust_seasons_test.py | # test seasonal.adjust_seasons() options handling
#
# adjust_seasons() handles a variety of optional arguments.
# verify that adjust_trend() correctly calledfor different option combinations.
#
# No noise in this test set.
#
from __future__ import division
import numpy as np
from seasonal import fit_trend, adjust_seaso... |
def test_trend_line():
adjusted = adjust_seasons(DATA, trend="line")
assert adjusted.std() < DATA.std()
def test_explicit_trend():
trend = fit_trend(DATA, kind="line")
adjusted = adjust_seasons(DATA, trend=trend)
assert adjusted.std() < DATA.std()
def test_trend_period():
adjusted = adjust_s... | adjusted = adjust_seasons(DATA)
assert adjusted.std() < DATA.std() | identifier_body |
adjust_seasons_test.py | # test seasonal.adjust_seasons() options handling
#
# adjust_seasons() handles a variety of optional arguments.
# verify that adjust_trend() correctly calledfor different option combinations.
#
# No noise in this test set.
#
from __future__ import division
import numpy as np
from seasonal import fit_trend, adjust_seaso... | adjusted = adjust_seasons(DATA, period=PERIOD // 2) # no seasonality
assert adjusted is None
def test_seasons():
adjusted = adjust_seasons(DATA, seasons=SEASONS)
assert adjusted.std() < DATA.std() | assert adjusted.std() < DATA.std() | random_line_split |
adjust_seasons_test.py | # test seasonal.adjust_seasons() options handling
#
# adjust_seasons() handles a variety of optional arguments.
# verify that adjust_trend() correctly calledfor different option combinations.
#
# No noise in this test set.
#
from __future__ import division
import numpy as np
from seasonal import fit_trend, adjust_seaso... | ():
adjusted = adjust_seasons(DATA, period=PERIOD)
assert adjusted.std() < DATA.std()
adjusted = adjust_seasons(DATA, period=PERIOD // 2) # no seasonality
assert adjusted is None
def test_seasons():
adjusted = adjust_seasons(DATA, seasons=SEASONS)
assert adjusted.std() < DATA.std()
| test_period | identifier_name |
lib.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
#[cfg(feature = "allocator_api")]
use core::alloc::AllocError;
#[cfg(feature = "allocator_api")]
use core::ptr::NonNull;
#[cfg(feature = "allocator_api")]
unsafe impl core::alloc::Allocator for GlobalScudoAllocator {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
let layout = fit... | pub fn print_stats() {
unsafe { scudo_print_stats() }
}
} | random_line_split |
lib.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
#[test]
fn test_1byte_box_uses_scudo() {
// Unlike the other arbitrary size allocations, it seems
// Rust's test harness does have some 1 byte allocations so we cannot
// assert there are 0, then 1, then 0.
let before = count_allocations_by_size(1);
let b = Box::new(1i... | {
assert_eq!(count_allocations_by_size(28), 0);
let b = Box::new_in([3.0f32; 7], A);
assert_eq!(count_allocations_by_size(28), 1);
// Move b
(move || b)();
assert_eq!(count_allocations_by_size(28), 0);
} | identifier_body |
lib.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
/// Test-only function that returns the number of allocations of a given size.
fn count_allocations_by_size(size: usize) -> usize {
let mut size_and_count = (size, 0usize);
unsafe {
scudo_disable();
scudo_iterate(
contains,
&mut siz... | {
*count += 1;
} | conditional_block |
lib.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | () {
// Unlike the other arbitrary size allocations, it seems
// Rust's test harness does have some 1 byte allocations so we cannot
// assert there are 0, then 1, then 0.
let before = count_allocations_by_size(1);
let b = Box::new(1i8);
assert_eq!(count_allocations_by_siz... | test_1byte_box_uses_scudo | identifier_name |
15.2.3.6-4-372.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-372.js
* @description ES5 Attributes - success to update [[Enumerable]] attribute of data property ([[Writable]] is false, [[Enumerable]] is false, [[Configurable]] is true) to different value
*/
func... | enumerable: false,
configurable: true
});
var propertyDefineCorrect = obj.hasOwnProperty("prop");
var desc1 = Object.getOwnPropertyDescriptor(obj, "prop");
Object.defineProperty(obj, "prop", {
enumerable: true
});
var desc2 = Object.ge... | writable: false, | random_line_split |
15.2.3.6-4-372.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-372.js
* @description ES5 Attributes - success to update [[Enumerable]] attribute of data property ([[Writable]] is false, [[Enumerable]] is false, [[Configurable]] is true) to different value
*/
func... |
runTestCase(testcase);
| {
var obj = {};
Object.defineProperty(obj, "prop", {
value: 2010,
writable: false,
enumerable: false,
configurable: true
});
var propertyDefineCorrect = obj.hasOwnProperty("prop");
var desc1 = Object.getOwnPropertyDescriptor(obj, "... | identifier_body |
15.2.3.6-4-372.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-372.js
* @description ES5 Attributes - success to update [[Enumerable]] attribute of data property ([[Writable]] is false, [[Enumerable]] is false, [[Configurable]] is true) to different value
*/
func... | () {
var obj = {};
Object.defineProperty(obj, "prop", {
value: 2010,
writable: false,
enumerable: false,
configurable: true
});
var propertyDefineCorrect = obj.hasOwnProperty("prop");
var desc1 = Object.getOwnPropertyDescriptor(obj... | testcase | identifier_name |
transit.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
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, di... | () {
let eq_point1 = coords::EqPoint{
asc: 40.68021_f64.to_radians(),
dec: 18.04761_f64.to_radians()
};
let eq_point2 = coords::EqPoint{
asc: 41.73129_f64.to_radians(),
dec: 18.44092_f64.to_radians()
};
let eq_point3 = coords::EqPoint{
asc: 42.78204_f64.to_ra... | time | identifier_name |
transit.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
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, di... | let Theta0 = 177.74208_f64.to_radians();
let deltaT = time::delta_t(1988, 3);
let (h_rise, m_rise, s_rise) = transit::time(
&transit::TransitType::Rise,
&transit::TransitBody::StarOrPlanet,
&geograph_point,
&eq_point1,
&eq_point2,
&eq_point3,
Theta0,... | {
let eq_point1 = coords::EqPoint{
asc: 40.68021_f64.to_radians(),
dec: 18.04761_f64.to_radians()
};
let eq_point2 = coords::EqPoint{
asc: 41.73129_f64.to_radians(),
dec: 18.44092_f64.to_radians()
};
let eq_point3 = coords::EqPoint{
asc: 42.78204_f64.to_radia... | identifier_body |
transit.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
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, di... | #![allow(non_snake_case)]
extern crate astro;
use astro::*;
#[test]
#[allow(unused_variables)]
fn time() {
let eq_point1 = coords::EqPoint{
asc: 40.68021_f64.to_radians(),
dec: 18.04761_f64.to_radians()
};
let eq_point2 = coords::EqPoint{
asc: 41.73129_f64.to_radians(),
de... | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
| random_line_split |
nbbase.py | """Python API for composing notebook elements
The Python representation of a notebook is a nested structure of
dictionary subclasses that support attribute access
(IPython.utils.ipstruct.Struct). The functions in this module are merely
helpers to build the structs in the right form.
"""
# Copyright (c) IPython Develo... | (source='', **kwargs):
"""Create a new markdown cell"""
cell = NotebookNode(
cell_type='markdown',
source=source,
metadata=NotebookNode(),
)
cell.update(from_dict(kwargs))
validate(cell, 'markdown_cell')
return cell
def new_raw_cell(source='', **kwargs):
"""Create a... | new_markdown_cell | identifier_name |
nbbase.py | """Python API for composing notebook elements
The Python representation of a notebook is a nested structure of
dictionary subclasses that support attribute access
(IPython.utils.ipstruct.Struct). The functions in this module are merely
helpers to build the structs in the right form.
"""
# Copyright (c) IPython Develo... | if msg_type == 'execute_result':
return new_output(output_type=msg_type,
metadata=content['metadata'],
data=content['data'],
execution_count=content['execution_count'],
)
elif msg_type == 'stream':
return new_output(output_type=msg_type,
na... | content = msg['content']
| random_line_split |
nbbase.py | """Python API for composing notebook elements
The Python representation of a notebook is a nested structure of
dictionary subclasses that support attribute access
(IPython.utils.ipstruct.Struct). The functions in this module are merely
helpers to build the structs in the right form.
"""
# Copyright (c) IPython Develo... |
def new_notebook(name=None, metadata=None, worksheets=None):
"""Create a notebook by name, id and a list of worksheets."""
nb = NotebookNode()
nb.nbformat = nbformat
nb.nbformat_minor = nbformat_minor
if worksheets is None:
nb.worksheets = []
else:
nb.worksheets = list(workshee... | """Create a worksheet by name with with a list of cells."""
ws = NotebookNode()
if cells is None:
ws.cells = []
else:
ws.cells = list(cells)
ws.metadata = NotebookNode(metadata or {})
return ws | identifier_body |
nbbase.py | """Python API for composing notebook elements
The Python representation of a notebook is a nested structure of
dictionary subclasses that support attribute access
(IPython.utils.ipstruct.Struct). The functions in this module are merely
helpers to build the structs in the right form.
"""
# Copyright (c) IPython Develo... |
if metadata is None:
nb.metadata = new_metadata()
else:
nb.metadata = NotebookNode(metadata)
if name is not None:
nb.metadata.name = cast_unicode(name)
return nb
def new_metadata(name=None, authors=None, license=None, created=None,
modified=None, gistid=None):
"""Create... | nb.worksheets = list(worksheets) | conditional_block |
util.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import glob
import os
import hmac
import hashlib
import shutil
import socket
import subprocess
import struct
from twisted.internet import defer
from twisted.internet.interfaces i... | (*args):
"""
For every path in args, try to delete it as a file or a directory
tree. Ignores deletion errors.
"""
for f in args:
try:
os.unlink(f)
except OSError:
shutil.rmtree(f, ignore_errors=True)
def ip_from_int(ip):
""" Convert long int back to... | delete_file_or_tree | identifier_name |
util.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import glob
import os
import hmac
import hashlib
import shutil
import socket
import subprocess
import struct
from twisted.internet import defer
from twisted.internet.interfaces i... |
def find_keywords(args, key_filter=lambda x: not x.startswith("$")):
"""
This splits up strings like name=value, foo=bar into a dict. Does NOT deal
with quotes in value (e.g. key="value with space" will not work
By default, note that it takes OUT any key which starts with $ (i.e. a
single dollar... | """
Tries to return an IPAddress, otherwise returns a string.
TODO consider explicitly checking for .exit or .onion at the end?
"""
if ipaddr is not None:
try:
return ipaddr.IPAddress(addr)
except ValueError:
pass
return str(addr) | identifier_body |
util.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import glob
import os
import hmac
import hashlib
import shutil
import socket
import subprocess
import struct
from twisted.internet import defer
from twisted.internet.interfaces i... | except IOError:
return None
city, asn, country = list(map(maybe_create_db,
("/usr/share/GeoIP/GeoLiteCity.dat",
"/usr/share/GeoIP/GeoIPASNum.dat",
"/usr/share/GeoIP/GeoIP.dat")))
try:
import ipaddr as _ipaddr
ipaddr = _ip... | return create_geoip(path) | random_line_split |
util.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import glob
import os
import hmac
import hashlib
import shutil
import socket
import subprocess
import struct
from twisted.internet import defer
from twisted.internet.interfaces i... |
proc = subprocess.Popen(['lsof', '-i', '4tcp@%s:%s' % (addr, port)],
stdout=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
lines = stdout.split('\n')
if len(lines) > 1:
return int(lines[1].split()[1])
def hmac_sha256(key, msg):
"""
Adapted from rra... | if torstate is None:
return None
return int(torstate.tor_pid) | conditional_block |
clipboard-paste-textarea.component.ts | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs/Subject';
function onlyUnique(value, index, self): boolean {
return self.indexOf(value) === index;
}
@Component({
selector: 'app-clipboard-paste-textarea',
templateUrl: './clipboard-paste-textarea.compo... | () {
this.search
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.map(text => text.split('\n').filter(str => str))
.map(lines => this.distinctLines ? lines.filter(onlyUnique) : lines)
.subscribe(content => {... | ngOnInit | identifier_name |
clipboard-paste-textarea.component.ts | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs/Subject';
function onlyUnique(value, index, self): boolean {
return self.indexOf(value) === index;
}
@Component({
selector: 'app-clipboard-paste-textarea',
templateUrl: './clipboard-paste-textarea.compo... | export class ClipboardPasteTextareaComponent implements OnInit {
@Input() initialContent: string = '';
@Input() placeholder: string = 'paste stuff here';
@Input() distinctLines: boolean = false;
@Output() changed = new EventEmitter();
search = new Subject<string>();
input: string = '';
constructor() { }
... | styleUrls: ['./clipboard-paste-textarea.component.scss']
}) | random_line_split |
clipboard-paste-textarea.component.ts | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs/Subject';
function onlyUnique(value, index, self): boolean {
return self.indexOf(value) === index;
}
@Component({
selector: 'app-clipboard-paste-textarea',
templateUrl: './clipboard-paste-textarea.compo... |
}
| {
this.search
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.map(text => text.split('\n').filter(str => str))
.map(lines => this.distinctLines ? lines.filter(onlyUnique) : lines)
.subscribe(content => {
... | identifier_body |
clipboard-paste-textarea.component.ts | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs/Subject';
function onlyUnique(value, index, self): boolean {
return self.indexOf(value) === index;
}
@Component({
selector: 'app-clipboard-paste-textarea',
templateUrl: './clipboard-paste-textarea.compo... |
}
}
| {
this.input = this.initialContent;
this.search.next(this.input);
} | conditional_block |
rest-api.service.ts | import * as angular from 'angular';
import { SessionService } from '../session.service';
export class RestApiService {
static $inject: string[] = ['$http', 'sessionService'];
constructor(private $http: angular.IHttpService, private sessionService: SessionService) { }
get<T>(url: string, data?: any): angular.IP... |
delete<T>(url: string, data?: any): angular.IPromise<T> {
return this.send<T>('DELETE', url, data);
}
private send<T>(method: string, url: string, data: any): angular.IPromise<T> {
return this.sessionService.getSession()
.then(session => {
const httpConfig = { method, url, data, headers: ... | {
return this.send<T>('POST', url, data);
} | identifier_body |
rest-api.service.ts | import * as angular from 'angular';
import { SessionService } from '../session.service';
export class RestApiService {
static $inject: string[] = ['$http', 'sessionService'];
constructor(private $http: angular.IHttpService, private sessionService: SessionService) { }
get<T>(url: string, data?: any): angular.IP... | <T>(method: string, url: string, data: any): angular.IPromise<T> {
return this.sessionService.getSession()
.then(session => {
const httpConfig = { method, url, data, headers: { Authorization: 'Bearer ' + session.accessToken() }};
return this.$http<T>(httpConfig);
}).then(arg => {
... | send | identifier_name |
rest-api.service.ts | import * as angular from 'angular';
import { SessionService } from '../session.service';
export class RestApiService {
static $inject: string[] = ['$http', 'sessionService'];
constructor(private $http: angular.IHttpService, private sessionService: SessionService) { }
get<T>(url: string, data?: any): angular.IP... | return this.send<T>('DELETE', url, data);
}
private send<T>(method: string, url: string, data: any): angular.IPromise<T> {
return this.sessionService.getSession()
.then(session => {
const httpConfig = { method, url, data, headers: { Authorization: 'Bearer ' + session.accessToken() }};
... |
delete<T>(url: string, data?: any): angular.IPromise<T> { | random_line_split |
test_chart_title01.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class | (ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_title01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
sel... | TestCompareXLSXFiles | identifier_name |
test_chart_title01.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
| workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [46165376, 54462720]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
... | """
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_title01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir +... | identifier_body |
test_chart_title01.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
chart.add_series({'values': '=Sheet1!$A$1:$A$5',
'name': 'Foo'})
chart.set_title({'none': True})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual() | random_line_split | |
mail.py | #http://stackoverflow.com/questions/882712/sending-html-email-using-python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class MailAgent(object):
"""docstring for MailAgent"""
def __init__(self, mail, smtp, pseudo, passw):
|
def send(self, dest, object, text):
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = self.mail
msg['To'] = dest
# Create the body of the message (a plain-text and an HTML version).
html = "<html><he... | super(MailAgent, self).__init__()
self.mail = mail
self.smtp = smtp
self.pseudo = pseudo
self.passw = passw | identifier_body |
mail.py | #http://stackoverflow.com/questions/882712/sending-html-email-using-python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class MailAgent(object):
"""docstring for MailAgent"""
def __init__(self, mail, smtp, pseudo, passw):
super(MailAgent, self).__init__()
s... | mail.sendmail(self.mail, dest, msg.as_string())
mail.quit() | random_line_split | |
mail.py | #http://stackoverflow.com/questions/882712/sending-html-email-using-python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class MailAgent(object):
"""docstring for MailAgent"""
def | (self, mail, smtp, pseudo, passw):
super(MailAgent, self).__init__()
self.mail = mail
self.smtp = smtp
self.pseudo = pseudo
self.passw = passw
def send(self, dest, object, text):
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Sub... | __init__ | identifier_name |
win32spawn.py | import os
import threading
import Queue
# Windows import
import win32file
import win32pipe
import win32api
import win32con
import win32security
import win32process
import win32event
class Win32Spawn(object):
def __init__(self, cmd, shell=False):
self.queue = Queue.Queue()
self.is_terminated = Fal... |
except win32api.error:
finished = 1
if finished:
return
def start_pipe(self):
def worker(pipe):
return pipe.wait()
thrd = threading.Thread(target=worker, args=(self, ))
thrd.start()
| self.queue.put_nowait(data) | conditional_block |
win32spawn.py | import os
import threading
import Queue
# Windows import
import win32file
import win32pipe
import win32api
import win32con
import win32security
import win32process
import win32event
class Win32Spawn(object):
def __init__(self, cmd, shell=False):
self.queue = Queue.Queue()
self.is_terminated = Fal... | def worker(pipe):
return pipe.wait()
thrd = threading.Thread(target=worker, args=(self, ))
thrd.start() | identifier_body | |
win32spawn.py | import os
import threading
import Queue
# Windows import
import win32file
import win32pipe
import win32api
import win32con
import win32security
import win32process
import win32event
class Win32Spawn(object):
def __init__(self, cmd, shell=False):
self.queue = Queue.Queue()
self.is_terminated = Fal... | (self):
return self.queue.qsize()
def __wait_for_child(self):
# kick off threads to read from stdout and stderr of the child process
threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start()
threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).st... | qsize | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.