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 |
|---|---|---|---|---|
profile.py | import copy
from collections import OrderedDict
from collections import defaultdict
from conans.model.env_info import EnvValues
from conans.model.options import OptionsValues
from conans.model.values import Values
class Profile(object):
"""A profile contains a set of setting (with values), environment variables
... | def __init__(self):
# Sections
self.settings = OrderedDict()
self.package_settings = defaultdict(OrderedDict)
self.env_values = EnvValues()
self.options = OptionsValues()
self.build_requires = OrderedDict() # conan_ref Pattern: list of conan_ref
@property
de... | random_line_split | |
profile.py | import copy
from collections import OrderedDict
from collections import defaultdict
from conans.model.env_info import EnvValues
from conans.model.options import OptionsValues
from conans.model.values import Values
class Profile(object):
"""A profile contains a set of setting (with values), environment variables
... |
def update_settings(self, new_settings):
"""Mix the specified settings with the current profile.
Specified settings are prioritized to profile"""
assert(isinstance(new_settings, OrderedDict))
# apply the current profile
res = copy.copy(self.settings)
if new_settin... | self.build_requires.setdefault(pattern, []).extend(req_list) | conditional_block |
Parameter.py | param = dict(
useAIon=True,
verbose=False,
chargePreXlinkIons=[1, 3],
chargePostXlinkIons=[2, 5],
basepeakint = 100.0, | modRes = '',
modMass = 0.0,
linkermass = 136.10005,
ms1tol = dict(measure='ppm', val=5),
ms2tol = dict(measure='da', val=0.01),
minmz = 200,
maxmz = 2000,
mode = 'conservative',
patternstring = '^[ACDEFGHIKLMNPQRSTVWY]*K[ACDEFGHIKLMNPQRSTVWY]+$',
fixedMod = [],
neutralloss=dict(
h2oLoss=dict(
mass=-18.0... | dynamicrange = 0.001,
missedsites = 2,
minlength = 4,
maxlength = 51, | random_line_split |
Parameter.py | param = dict(
useAIon=True,
verbose=False,
chargePreXlinkIons=[1, 3],
chargePostXlinkIons=[2, 5],
basepeakint = 100.0,
dynamicrange = 0.001,
missedsites = 2,
minlength = 4,
maxlength = 51,
modRes = '',
modMass = 0.0,
linkermass = 136.10005,
ms1tol = dict(measure='ppm', val=5),
ms2tol = dict(measure='da', ... | aa = param['fixedMod'][i][0]
delta = param['fixedMod'][i][1]
mass[aa] += delta | conditional_block | |
move_cell.rs | //! A cell type that can move values into and out of a shared reference.
//!
//! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent
//! ownership is required.
use std::cell::UnsafeCell;
use std::mem;
/// A cell type that can move values into and out of a shared reference.
pub s... |
}
| {
MoveCell::new()
} | identifier_body |
move_cell.rs | //! A cell type that can move values into and out of a shared reference.
//!
//! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent
//! ownership is required.
use std::cell::UnsafeCell;
use std::mem;
/// A cell type that can move values into and out of a shared reference.
pub s... | (&self) -> &Option<T> {
& *self.0.get()
}
/// Place a value into this `MoveCell`, returning the previous value, if present.
pub fn put(&self, val: T) -> Option<T> {
mem::replace(unsafe { self.as_mut() }, Some(val))
}
/// Take the value out of this `MoveCell`, leaving nothing... | as_ref | identifier_name |
move_cell.rs | //! A cell type that can move values into and out of a shared reference.
//!
//! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent
//! ownership is required.
use std::cell::UnsafeCell;
use std::mem;
/// A cell type that can move values into and out of a shared reference.
pub s... | }
unsafe fn as_ref(&self) -> &Option<T> {
& *self.0.get()
}
/// Place a value into this `MoveCell`, returning the previous value, if present.
pub fn put(&self, val: T) -> Option<T> {
mem::replace(unsafe { self.as_mut() }, Some(val))
}
/// Take the value out of this ... | &mut *self.0.get() | random_line_split |
util.rs | use std::fmt;
use std::io::{IoErrorKind, IoResult};
#[derive(Copy)]
pub struct FormatBytes(pub u64);
impl FormatBytes {
#[inline]
fn to_kb(self) -> f64 {
(self.0 as f64) / 1.0e3
}
#[inline]
fn to_mb(self) -> f64 {
(self.0 as f64) / 1.0e6
}
#[inline]
fn to_gb(self)... |
FormatTime(hours, minutes, seconds)
}
}
impl fmt::String for FormatTime {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.write_fmt(format_args!("{}:{:02}:{:02}", self.0, self.1, self.2))
}
} | let minutes = (tot_min % 60) as u8;
let hours = tot_min / 60; | random_line_split |
util.rs | use std::fmt;
use std::io::{IoErrorKind, IoResult};
#[derive(Copy)]
pub struct FormatBytes(pub u64);
impl FormatBytes {
#[inline]
fn to_kb(self) -> f64 {
(self.0 as f64) / 1.0e3
}
#[inline]
fn to_mb(self) -> f64 {
(self.0 as f64) / 1.0e6
}
#[inline]
fn to_gb(self)... | (pub u64, pub u8, pub u8);
impl FormatTime {
pub fn from_s(s: u64) -> FormatTime {
let seconds = (s % 60) as u8;
let tot_min = s / 60;
let minutes = (tot_min % 60) as u8;
let hours = tot_min / 60;
FormatTime(hours, minutes, seconds)
}
}
impl f... | FormatTime | identifier_name |
middleware.py | """
The middlewares in this file do mobile detection, provide a user override,
and provide a cookie override. They must be used in the correct order.
MobileMiddleware must always come after any of the other middlewares in this
file in `settings.MIDDLEWARE_CLASSES`.
"""
import urllib
from warnings import warn
from djan... |
if hasattr(request, 'BROWSER'):
# UA Detection already figured this out.
request.MOBILE = request.BROWSER.mobile
return
# Make a guess based on UA if nothing else has figured it out.
request.MOBILE = ('mobile' in ua)
def process_response(self, request,... | request.MOBILE = (mc == 'yes')
return | conditional_block |
middleware.py | """
The middlewares in this file do mobile detection, provide a user override,
and provide a cookie override. They must be used in the correct order.
MobileMiddleware must always come after any of the other middlewares in this
file in `settings.MIDDLEWARE_CLASSES`.
"""
import urllib
from warnings import warn
from djan... | (object):
"""Add ``request.BROWSER`` which has information from the User-Agent
``request.BROWSER`` has the following attributes:
- browser: The user's browser, eg: "Firefox".
- browser_version: The browser's version, eg: "14.0.1"
- platform: The general platform the user is using, eg "Windows".
... | UserAgentMiddleware | identifier_name |
middleware.py | """
The middlewares in this file do mobile detection, provide a user override,
and provide a cookie override. They must be used in the correct order.
MobileMiddleware must always come after any of the other middlewares in this
file in `settings.MIDDLEWARE_CLASSES`.
"""
import urllib
from warnings import warn
from djan... | 2. If a cookie is set indicating a mobile preference, follow it.
3. If user agent parsing has already happened, trust it's judgement about
mobile-ness. (i.e. `request.BROWSER.mobile`)
4. Otherwise, set `request.MOBILE` to True if the string "mobile" is in the
user agent (case insensitive), and... | is set accordingly. | random_line_split |
middleware.py | """
The middlewares in this file do mobile detection, provide a user override,
and provide a cookie override. They must be used in the correct order.
MobileMiddleware must always come after any of the other middlewares in this
file in `settings.MIDDLEWARE_CLASSES`.
"""
import urllib
from warnings import warn
from djan... |
def process_request(self, request):
prefixer = urlresolvers.Prefixer(request)
urlresolvers.set_url_prefix(prefixer)
full_path = prefixer.fix(prefixer.shortened_path)
if self._is_lang_change(request):
# Blank out the locale so that we can set a new one. Remove lang
... | """
1. Search for the locale.
2. Save it in the request.
3. Strip them from the URL.
"""
def __init__(self):
if not settings.USE_I18N or not settings.USE_L10N:
warn('USE_I18N or USE_L10N is False but LocaleURLMiddleware is '
'loaded. Consider removing fjord.base... | identifier_body |
tab-link-harness.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing';
import {TabLinkHarnessFilters} from './tab-h... | (): Promise<void> {
await (await this.host()).click();
}
}
| click | identifier_name |
tab-link-harness.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing';
import {TabLinkHarnessFilters} from './tab-h... | return host.hasClass('mat-tab-disabled');
}
/** Clicks on the link. */
async click(): Promise<void> {
await (await this.host()).click();
}
} | random_line_split | |
perm.rs | use centrifuge::{Store, Message};
pub struct PermStore<'a> {
sequence: usize,
position: usize,
data: &'a mut [u8]
}
#[derive(Debug)]
pub struct PermMsg<'a> {
sequence: usize,
data: &'a [u8],
}
impl <'a> PermStore<'a> {
pub fn new(data: &'a mut [u8]) -> Self {
PermStore {
... |
#[inline]
fn get_remaining_slice(&mut self) -> &'a mut [u8] {
let start = self.position;
let end = self.data.len();
self.get_slice_from_to(start, end)
}
}
impl <'a> Message for PermMsg<'a> {
fn get_sequence(&self) -> usize {
self.sequence
}
fn get_data(&self) -... | {
self.get_slice(from, to - from)
} | identifier_body |
perm.rs | use centrifuge::{Store, Message};
pub struct PermStore<'a> {
sequence: usize,
position: usize,
data: &'a mut [u8]
}
#[derive(Debug)]
pub struct PermMsg<'a> {
sequence: usize,
data: &'a [u8],
}
impl <'a> PermStore<'a> {
pub fn new(data: &'a mut [u8]) -> Self {
PermStore {
... | let pos = self.position;
PermMsg {
sequence: seq,
data: self.get_slice_from_to(start, pos)
}
}
}
#[cfg(test)]
pub mod test {
use centrifuge::*;
#[test]
pub fn test_perm() {
use centrifuge::perm::*;
let mut sequence_nums = Vec... | self.sequence += 1;
let seq = self.sequence; | random_line_split |
perm.rs | use centrifuge::{Store, Message};
pub struct PermStore<'a> {
sequence: usize,
position: usize,
data: &'a mut [u8]
}
#[derive(Debug)]
pub struct PermMsg<'a> {
sequence: usize,
data: &'a [u8],
}
impl <'a> PermStore<'a> {
pub fn | (data: &'a mut [u8]) -> Self {
PermStore {
sequence: 0,
position: 0,
data: data
}
}
#[inline]
fn get_slice(&mut self, from: usize, len: usize) -> &'a mut [u8] {
use std::slice::from_raw_parts_mut;
let ptr = self.data.as_mut_ptr();
... | new | identifier_name |
gulpfile.js | var pkg = require('./package.json'),
gulp = require('gulp'),
gutil = require('gulp-util'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
livereload = require('gulp-livereload'),
rename = require('gulp-rename'),
coffeelint = require('gulp-coffeelint'),
jade =... | livereload.listen();
gulp.watch('src/coffee/*.coffee', ['coffee']);
gulp.watch('src/jade/*.jade', ['jade']);
gulp.watch('src/less/*.less', ['less']);
}); | random_line_split | |
validators.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import re
from rest_framework.serializers import ValidationError
def name(value):
'''Matches names of people, countries and and other thing... | Matches numbers and spaces.'''
if re.match(r'^[\d\s]+$', value) is None:
raise ValidationError('This field can only contain numbers and spaces.')
def email(value):
'''Loosely matches email addresses.'''
if re.match(r'^[\w_.+-]+@[\w-]+\.[\w\-.]+$', value) is None:
raise ValidationError('Thi... | ''' | identifier_name |
validators.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import re
from rest_framework.serializers import ValidationError
def name(value):
'''Matches names of people, countries and and other thing... | if not value:
raise ValidationError('This field is required.') | '''Requires that a field be non-empty.''' | random_line_split |
validators.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import re
from rest_framework.serializers import ValidationError
def name(value):
'''Matches names of people, countries and and other thing... | ue):
'''Loosely matches email addresses.'''
if re.match(r'^[\w_.+-]+@[\w-]+\.[\w\-.]+$', value) is None:
raise ValidationError('This is an invalid email address.')
def phone_international(value):
'''Loosely matches phone numbers.'''
if re.match(r'^[\d\-x\s\+\(\)]+$', value) is None:
ra... | Error('This field can only contain numbers and spaces.')
def email(val | conditional_block |
validators.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import re
from rest_framework.serializers import ValidationError
def name(value):
| ddress(value):
'''Matches street addresses.'''
if re.match(r'^[\w\s\.\-\'àèéìòóôù]+$', value) is None:
raise ValidationError('This field contains invalid characters.')
def numeric(value):
'''Matches numbers and spaces.'''
if re.match(r'^[\d\s]+$', value) is None:
raise ValidationError(... | '''Matches names of people, countries and and other things.'''
if re.match(r'^[A-Za-z\s\.\-\'àèéìòóôù]+$', value) is None:
raise ValidationError('This field contains invalid characters.')
def a | identifier_body |
ecom_products.py | THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE US... | _set_total_num(s)
if c.get("num_products") is None:
c["num_products"]=0
for s in c.get("sub_brands",[]):
c["num_products"]+=s["num_products"]
for c in top_brands:
_set_total_num(c)
return top_brands
def get_price_range(products, checked):
if not p... | for s in c.get("sub_brands",[]): | random_line_split |
ecom_products.py | THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE US... | (products=None):
root_company = ["All Companies"]
if products:
suppliers = []
products = filter(lambda product: product and product.company_id and product.type != "service", products)
companies = map(lambda product: product.company_id, products)
for company in companies:
... | get_supps | identifier_name |
ecom_products.py | THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE US... | if not categ_id:
continue
categ=categ_ids[categ_id]
categ["num_products"]=num
def _set_total_num(c):
for s in c.get("sub_categories",[]):
_set_total_num(s)
if c.get("num_products") is None:
c["num_products"]=0
for s in c.get("sub_ca... | print("get_categs")
res=get_model("product").read_group(["categ_id"],condition=condition)
categ_nums={}
for r in res:
categ_id=r["categ_id"][0] if r["categ_id"] else None
categ_nums.setdefault(categ_id,0)
categ_nums[categ_id]+=r["_count"]
res=get_model("product.categ").search_rea... | identifier_body |
ecom_products.py | netforce.model import get_model
from netforce.database import get_connection, get_active_db # XXX: move this
from netforce.locale import set_active_locale, get_active_locale
from .cms_base import BaseController
def list_parent(obj, lst):
if obj.parent_id:
lst = list_parent(obj.parent_id, lst)
lst.app... | user_id=int(user_id)
user=get_model("base.user").browse(user_id)
contact = user.contact_id
if contact.sale_price_list_id.id:
browse_ctx["pricelist_id"] =contact.sale_price_list_id.id | conditional_block | |
shootout-fasta-redux.rs | copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither ... | impl<'a, W: Writer> RepeatFasta<'a, W> {
fn new(alu: &'static str, w: &'a mut W) -> RepeatFasta<'a, W> {
RepeatFasta { alu: alu, out: w }
}
fn make(&mut self, n: uint) -> IoResult<()> {
let alu_len = self.alu.len();
let mut buf = Vec::from_elem(alu_len + LINE_LEN, 0u8);
let ... | alu: &'static str,
out: &'a mut W
}
| random_line_split |
shootout-fasta-redux.rs | copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither ... | (&mut self, max: f32) -> f32 {
self.seed = (self.seed * IA + IC) % IM;
max * (self.seed as f32) / (IM as f32)
}
fn nextc(&mut self) -> u8 {
let r = self.rng(1.0);
for a in self.lookup.iter() {
if a.p >= r {
return a.c;
}
}
... | rng | identifier_name |
shootout-fasta-redux.rs | copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither ... |
}
0
}
fn make(&mut self, n: uint) -> IoResult<()> {
let lines = n / LINE_LEN;
let chars_left = n % LINE_LEN;
let mut buf = [0, ..LINE_LEN + 1];
for _ in range(0, lines) {
for i in range(0u, LINE_LEN) {
buf[i] = self.nextc();
... | {
return a.c;
} | conditional_block |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/op... | (): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ensures that a request is sent only if the filter text changed
.switchMap((term) => term // switch to new observable each time the term ... | ngOnInit | identifier_name |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/op... |
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
| {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ensures that a request is sent only if the filter text changed
.switchMap((term) => term // switch to new observable each time the term changes
... | identifier_body |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/op... | .switchMap((term) => term // switch to new observable each time the term changes
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if there was no search term
: Observable.of<Hero[]>([]))
.catch((error) => {
... |
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ensures that a request is sent only if the filter text changed | random_line_split |
wsgi.py | """
WSGI config for sms_relay project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... | application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application) | from django.core.wsgi import get_wsgi_application | random_line_split |
backends.py | # -*- coding: utf-8 -*-
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.conf import settings
import requests
import logging
logger = logging.getLogger(__name__)
class Newsletter2GoEmailBackend(BaseEmailBackend):
n2g_api_endpoint = '... | (self, emails):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
if not emails:
return
num_sent = 0
for email in emails:
if not email.recipients():
continue
from_ema... | send_messages | identifier_name |
backends.py | # -*- coding: utf-8 -*-
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.conf import settings
import requests
import logging
logger = logging.getLogger(__name__)
class Newsletter2GoEmailBackend(BaseEmailBackend):
n2g_api_endpoint = '... |
return num_sent
| payload = {
'key': settings.NEWSLETTER2GO_API_KEY,
'to': recipient,
'from': from_email,
'subject': email.subject,
}
payload['html' if email.content_subtype == 'html' else 'text'] = email.body
... | conditional_block |
backends.py | # -*- coding: utf-8 -*-
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.conf import settings
import requests
import logging
logger = logging.getLogger(__name__)
class Newsletter2GoEmailBackend(BaseEmailBackend):
|
for recipient in recipients:
payload = {
'key': settings.NEWSLETTER2GO_API_KEY,
'to': recipient,
'from': from_email,
'subject': email.subject,
}
payload['html' if email.content_su... | n2g_api_endpoint = 'https://www.newsletter2go.de/de/api/send/email/'
def send_messages(self, emails):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
if not emails:
return
num_sent = 0
for email in e... | identifier_body |
backends.py | # -*- coding: utf-8 -*-
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.conf import settings | logger = logging.getLogger(__name__)
class Newsletter2GoEmailBackend(BaseEmailBackend):
n2g_api_endpoint = 'https://www.newsletter2go.de/de/api/send/email/'
def send_messages(self, emails):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
... |
import requests
import logging
| random_line_split |
loadProfile.js | game.LoadProfile = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function() {
me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('load-screen')), -10);
//puts load screen in when game starts
document.getElementById("inpu... | document.getElementById("load").style.visibility = "hidden";
}
}); | */
onDestroyEvent: function() {
document.getElementById("input").style.visibility = "hidden"; | random_line_split |
launch.component.spec.ts | import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';
import { FormsModule } from '@angular/forms';
import { ClarityModule } from '@clr/angular'... |
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
LaunchComponent,
BuilderMockComponent,
FreeTextMockComponent
],
imports: [
FormsModule,
ClarityModule,
RouterTestingModule.withRoutes([]),
BrowserAnimationsMo... | let component: LaunchComponent;
let fixture: ComponentFixture<LaunchComponent>; | random_line_split |
launch.component.spec.ts | import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';
import { FormsModule } from '@angular/forms';
import { ClarityModule } from '@clr/angular'... | {
@Input() task: Task;
@Input() properties: Array<string> = [];
@Input() arguments: Array<string> = [];
@Output() updateProperties = new EventEmitter();
@Output() updateArguments = new EventEmitter();
@Output() exportProperties = new EventEmitter();
@Output() copyProperties = new EventEmitter();
@Outpu... | FreeTextMockComponent | identifier_name |
pipe_unix.rs | ;
use libc;
use std::c_str::CString;
use std::intrinsics;
use std::io;
use std::mem;
use std::rt::rtio;
use std::unstable::mutex;
use super::{IoResult, retry};
use super::net;
use super::util;
use super::c;
use super::file::fd_t;
fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> {
match unsafe { libc::socket(libc... | }
}
impl rtio::RtioUnixAcceptor for UnixAcceptor { | random_line_split | |
pipe_unix.rs | at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use alloc::arc::Arc;
use libc;
use std::c_str::CString;
use std::intrinsics;
use std::io;
use std::mem;
use std::rt::rtio;
use std::unstable::mutex;
use super::{IoResult, retry};
use super::net;
use super::ut... | (addr: &CString,
timeout: Option<u64>) -> IoResult<UnixStream> {
connect(addr, libc::SOCK_STREAM, timeout).map(|inner| {
UnixStream::new(Arc::new(inner))
})
}
fn new(inner: Arc<Inner>) -> UnixStream {
UnixStream {
inner: inner,
read... | connect | identifier_name |
charts.component.ts | import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Ng2Highcharts, Ng2Highmaps, Ng2Highstocks} from 'ng2-highcharts';
@Component({
moduleId: module.id,
selector: 'sd-charts',
templateUrl: 'charts.component.html'
})
export class ChartsComponent implements OnInit {
chart... | (): any {
setInterval(() => {
this.chartOptions = {
chart: {
type: 'line'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
... | ngOnInit | identifier_name |
charts.component.ts | import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Ng2Highcharts, Ng2Highmaps, Ng2Highstocks} from 'ng2-highcharts';
@Component({
moduleId: module.id,
selector: 'sd-charts',
templateUrl: 'charts.component.html'
})
export class ChartsComponent implements OnInit {
chart... | data: [12566, 12116, 11446, 10749, 10439, 973, 914, 4054, 732, 34, 2]
}
]
};
chartMap = {};
mapData = [
{
'code': 'DE.SH',
'value': 728
},
{
'code': 'DE.BE',
'value': 710
},
{
'code': 'DE.MV',
'value': 963
},
{
'code': 'DE.HB',
'value': 541
},
{
'code': 'DE.HH',
... | data: [115, 162, 150, 187, 172, 973, 914, 4054, 732, 34, 2]
}, {
name: 'COR', | random_line_split |
table_cache.py | """Cache util functions for ReSDKTables."""
import os
import pickle
import sys
from shutil import rmtree
from typing import Any
from resdk.__about__ import __version__
def _default_cache_dir() -> str:
"""Return default cache directory specific for the current OS.
Code originally from Orange3.misc.environ.
... | if not os.path.exists(pickle_file) or override:
with open(pickle_file, "wb") as handle:
pickle.dump(obj, handle, protocol=pickle.HIGHEST_PROTOCOL) | :return:
""" | random_line_split |
table_cache.py | """Cache util functions for ReSDKTables."""
import os
import pickle
import sys
from shutil import rmtree
from typing import Any
from resdk.__about__ import __version__
def _default_cache_dir() -> str:
"""Return default cache directory specific for the current OS.
Code originally from Orange3.misc.environ.
... |
def save_pickle(obj: Any, pickle_file: str, override=False) -> None:
"""Save given object into a pickle file.
:param obj: object to bi pickled
:param pickle_file: file path
:param override: if True than override existing file
:return:
"""
if not os.path.exists(pickle_file) or override:
... | """Load object from the pickle file.
:param pickle_file: file path
:return: un-pickled object
"""
if os.path.exists(pickle_file):
with open(pickle_file, "rb") as handle:
return pickle.load(handle) | identifier_body |
table_cache.py | """Cache util functions for ReSDKTables."""
import os
import pickle
import sys
from shutil import rmtree
from typing import Any
from resdk.__about__ import __version__
def _default_cache_dir() -> str:
"""Return default cache directory specific for the current OS.
Code originally from Orange3.misc.environ.
... | (pickle_file: str) -> Any:
"""Load object from the pickle file.
:param pickle_file: file path
:return: un-pickled object
"""
if os.path.exists(pickle_file):
with open(pickle_file, "rb") as handle:
return pickle.load(handle)
def save_pickle(obj: Any, pickle_file: str, override=... | load_pickle | identifier_name |
table_cache.py | """Cache util functions for ReSDKTables."""
import os
import pickle
import sys
from shutil import rmtree
from typing import Any
from resdk.__about__ import __version__
def _default_cache_dir() -> str:
"""Return default cache directory specific for the current OS.
Code originally from Orange3.misc.environ.
... |
elif os.name == "posix":
base = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
else:
base = os.path.expanduser("~/.cache")
return base
def cache_dir_resdk_base() -> str:
"""Return base ReSDK cache directory."""
return os.path.join(_default_cache_dir(), "ReSDK")
def ... | base = os.getenv("APPDATA", os.path.expanduser("~/AppData/Local")) | conditional_block |
storage.js | $(document).delegate('.storage_graph_link', 'click', function(e){
var anchor = this,
el = $(anchor),
id = el.attr('data-status');
if(e.ctrlKey || e.metaKey){
return true;
}else{
e.preventDefault();
}
var cell = document.getElementById(id);
var text = el.html();
if (text == '[:: show ::]') {
ancho... |
data = $('#piechartMeta',cell).text();
graphPieChart($('#piechart',cell)[0],eval('('+data+')'));
}
});
}
} else {
anchor.innerHTML = '[:: show ::]';
cell.style.display = 'none';
cell.parentNode.style.display = 'none';
}
}) | {
$.ajax({
type: "get",
url: anchor.href,
success : function(response, textStatus) {
cell.style.display = 'block';
cell.parentNode.style.display = 'block';
cell.innerHTML = response;
var data = $('#countTrendMeta',cell).text();
graphLineChart($('#countTrend',cell)[0],eval(... | conditional_block |
storage.js | $(document).delegate('.storage_graph_link', 'click', function(e){
var anchor = this,
el = $(anchor),
id = el.attr('data-status');
if(e.ctrlKey || e.metaKey){
return true;
}else{
e.preventDefault();
}
var cell = document.getElementById(id);
var text = el.html();
if (text == '[:: show ::]') {
ancho... | } else {
$.ajax({
type: "get",
url: anchor.href,
success : function(response, textStatus) {
cell.style.display = 'block';
cell.parentNode.style.display = 'block';
cell.innerHTML = response;
var data = $('#countTrendMeta',cell).text();
graphLineChart($('#countTrend',cell)... | random_line_split | |
home.js | import journey from "lib/journey/journey.js";
import template from "./home.html";
import Ractive from "Ractive.js";
var home = {
// this function is called when we enter the route
enter: function ( route, prevRoute, options ) {
/*%injectPath%*/
// Create our view, and assign it to the route under the property '... | }
} );
},
// this function is called when we leave the route
leave: function ( route, nextRoute, options ) {
// Remove the view from the DOM
route.view.teardown();
}
};
export default home; | setTimeout(function() {
$('#home-demo').removeClass('invisible').addClass("rollIn");
}, 500); | random_line_split |
bytevec.rs | use std::fmt::Debug;
use std::{fmt, ops};
/// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data
///
/// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers.
/// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON.
#[derive... | (&self) -> &[u8] {
&self.bytes[..]
}
}
impl ops::DerefMut for ByteVec {
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.bytes[..]
}
}
| deref | identifier_name |
bytevec.rs | use std::fmt::Debug;
use std::{fmt, ops};
/// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data
///
/// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers.
/// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON.
#[derive... | }
impl Debug for ByteVec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.bytes, f)
}
}
impl From<ByteVec> for Vec<u8> {
fn from(wrapper: ByteVec) -> Vec<u8> {
wrapper.bytes
}
}
impl From<Vec<u8>> for ByteVec {
fn from(bytes: Vec<u8>) -> Self {
Byt... | pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
ByteVec {
bytes: bytes.into(),
}
} | random_line_split |
bytevec.rs | use std::fmt::Debug;
use std::{fmt, ops};
/// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data
///
/// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers.
/// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON.
#[derive... |
}
impl AsMut<Vec<u8>> for ByteVec {
fn as_mut(&mut self) -> &mut Vec<u8> {
&mut self.bytes
}
}
impl AsMut<[u8]> for ByteVec {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.bytes
}
}
impl ops::Deref for ByteVec {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.by... | {
&self.bytes
} | identifier_body |
furniture-nn-analysis.component.ts | import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { ApiService } from '../shared/api.service';
import {NNAnalysisResponse, TokenInfo}from '../model/nn-analysis-response';
@Component({
selector: 'my-furni... | else {
return 'black';
}
}
analyzeByNN() {
console.log("Analysis click");
this.apiService.analyzeByFurnitureNN(encodeURIComponent(this.textToAnalyze)).subscribe(r => this.nnResults = r);
}
}
| {
return 'grey';
} | conditional_block |
furniture-nn-analysis.component.ts | import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
|
@Component({
selector: 'my-furniture-nn-analysis',
templateUrl: './furniture-nn-analysis.component.html',
styleUrls: ['./furniture-nn-analysis.component.scss']
})
export class FurnitureNnAnalysisComponent implements OnInit {
private textToAnalyze: string = "la comida estaba buena";
private nnResults: string... | import { ApiService } from '../shared/api.service';
import {NNAnalysisResponse, TokenInfo}from '../model/nn-analysis-response'; | random_line_split |
furniture-nn-analysis.component.ts | import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { ApiService } from '../shared/api.service';
import {NNAnalysisResponse, TokenInfo}from '../model/nn-analysis-response';
@Component({
selector: 'my-furni... | (tokenInfo: TokenInfo): string {
switch(tokenInfo.entity){
case 'FOOD': return 'red';
case 'SERVICE': return 'orange';
case 'AMBIENCE': return 'purple';
default: return 'silver';
}
}
chooseColor(result:string){
if(result.indexOf('OTHER')>=0){
return 'grey';
}else {
... | getEntityStyle | identifier_name |
karma.conf.js | // Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-05-11 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: tr... |
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
/... |
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false, | random_line_split |
data-binding-lookup.pipe.ts | /*
* 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 ... | * This pipe checks to see if an IValue is stored for a given input value. If so,
* it looks up and returns the value stored at a bindingPath within a dataset
*/
@Pipe({ name: 'dataBindingLookupPipe' })
export class DataBindingLookupPipe implements PipeTransform {
transform(inputValue: any, _refreshTrigger: Symbol)... | random_line_split | |
data-binding-lookup.pipe.ts | /*
* 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 ... |
}
| {
if (!isDataBoundValue(inputValue)) return inputValue;
const { mergedProperties, loadedData } = rendererState;
return lookupDataBoundValue(inputValue, mergedProperties, loadedData);
} | identifier_body |
data-binding-lookup.pipe.ts | /*
* 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 ... | implements PipeTransform {
transform(inputValue: any, _refreshTrigger: Symbol): any | undefined {
if (!isDataBoundValue(inputValue)) return inputValue;
const { mergedProperties, loadedData } = rendererState;
return lookupDataBoundValue(inputValue, mergedProperties, loadedData);
}
}
| DataBindingLookupPipe | identifier_name |
polyfills.ts | import { expectFileToMatch } from '../../utils/fs';
import { ng } from '../../utils/process';
import { getGlobalVariable } from '../../utils/env';
import { oneLineTrim } from 'common-tags';
export default function () {
// Skip this in Appveyor tests.
if (getGlobalVariable('argv').appveyor) |
return Promise.resolve()
.then(() => ng('build'))
// files were created successfully
.then(() => expectFileToMatch('dist/polyfills.bundle.js', 'core-js'))
.then(() => expectFileToMatch('dist/polyfills.bundle.js', 'zone.js'))
// index.html lists the right bundles
.then(() => expectFileToMatch... | {
return Promise.resolve();
} | conditional_block |
polyfills.ts | import { expectFileToMatch } from '../../utils/fs';
import { ng } from '../../utils/process';
import { getGlobalVariable } from '../../utils/env';
import { oneLineTrim } from 'common-tags';
|
return Promise.resolve()
.then(() => ng('build'))
// files were created successfully
.then(() => expectFileToMatch('dist/polyfills.bundle.js', 'core-js'))
.then(() => expectFileToMatch('dist/polyfills.bundle.js', 'zone.js'))
// index.html lists the right bundles
.then(() => expectFileToMatch(... | export default function () {
// Skip this in Appveyor tests.
if (getGlobalVariable('argv').appveyor) {
return Promise.resolve();
} | random_line_split |
main.rs | extern crate meltdown;
extern crate url;
extern crate gtk;
use url::Url;
use std::thread;
use std::path::Path;
use std::ffi::OsStr;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use gtk::prelude::*;
use gtk::Builder;
use gtk::MessageDialog;
use meltdown::{manager, join_part_files, config};
pub enum UIM... | .max_connection(configurations.max_connection)
.file(&file_name)
.finish();
let complete_name = file_name.clone();
let (tx, rx) = channel();
let main_tx_clone = main_tx.clone();
let _ = thread::spawn(move || {
match manager.start(r... | {
let _ = config::setup_config_directories();
let configurations = config::read_config();
let url_vec = url_vec.split("\n").collect::<Vec<&str>>();
let submitted_tasks = url_vec.len();
let (main_tx, main_rx) = channel();
for url in url_vec {
let prefix = config::default_cache_dir().unwr... | identifier_body |
main.rs | extern crate meltdown;
extern crate url;
extern crate gtk;
use url::Url;
use std::thread;
use std::path::Path;
use std::ffi::OsStr;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use gtk::prelude::*;
use gtk::Builder;
use gtk::MessageDialog;
use meltdown::{manager, join_part_files, config};
pub enum | {
Finished,
Paused,
Aborted
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("meltdown_ui.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
let window: gtk::Windo... | UIMessage | identifier_name |
main.rs | extern crate meltdown;
extern crate url;
extern crate gtk;
use url::Url;
use std::thread;
use std::path::Path;
use std::ffi::OsStr;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use gtk::prelude::*;
use gtk::Builder;
use gtk::MessageDialog;
use meltdown::{manager, join_part_files, config};
pub enum UIM... | Aborted
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("meltdown_ui.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
let window: gtk::Window = builder.get_object("windo... | Finished,
Paused, | random_line_split |
main.rs | extern crate meltdown;
extern crate url;
extern crate gtk;
use url::Url;
use std::thread;
use std::path::Path;
use std::ffi::OsStr;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use gtk::prelude::*;
use gtk::Builder;
use gtk::MessageDialog;
use meltdown::{manager, join_part_files, config};
pub enum UIM... |
};
let url_path_vec = download_url.path_segments().unwrap().collect::<Vec<&str>>();
let file_name = url_path_vec[url_path_vec.len() - 1].to_owned();
manager.add_url(download_url.clone())
.max_connection(configurations.max_connection)
.file(&file_name)
... | {
println!("{:?} is not a valid Url", url);
continue
} | conditional_block |
associated-types-eq-hr.rs | // Check testing of equality constraints in a higher-ranked context.
pub trait TheTrait<T> {
type A;
fn get(&self, t: T) -> Self::A;
}
struct IntStruct {
x: isize,
}
impl<'a> TheTrait<&'a isize> for IntStruct {
type A = &'a isize;
fn get(&self, t: &'a isize) -> &'a isize {
t
}
}
st... |
fn tuple_two<T>()
where
T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'y isize>,
{
// not ok for tuple, two lifetimes and we pick second
}
fn tuple_three<T>()
where
T: for<'x> TheTrait<(&'x isize, &'x isize), A = &'x isize>,
{
// ok for tuple
}
fn tuple_four<T>()
where
T: for<'x, 'y> TheT... | {
// not ok for tuple, two lifetimes and we pick first
} | identifier_body |
associated-types-eq-hr.rs | // Check testing of equality constraints in a higher-ranked context.
pub trait TheTrait<T> {
type A;
fn get(&self, t: T) -> Self::A;
}
struct IntStruct {
x: isize,
}
impl<'a> TheTrait<&'a isize> for IntStruct {
type A = &'a isize;
fn get(&self, t: &'a isize) -> &'a isize {
t
}
}
st... | fn tuple_four<T>()
where
T: for<'x, 'y> TheTrait<(&'x isize, &'y isize)>,
{
// not ok for tuple, two lifetimes, and lifetime matching is invariant
}
pub fn call_foo() {
foo::<IntStruct>();
foo::<UintStruct>(); //~ ERROR type mismatch
}
pub fn call_bar() {
bar::<IntStruct>(); //~ ERROR type mismatc... | // ok for tuple
}
| random_line_split |
associated-types-eq-hr.rs | // Check testing of equality constraints in a higher-ranked context.
pub trait TheTrait<T> {
type A;
fn get(&self, t: T) -> Self::A;
}
struct IntStruct {
x: isize,
}
impl<'a> TheTrait<&'a isize> for IntStruct {
type A = &'a isize;
fn get(&self, t: &'a isize) -> &'a isize {
t
}
}
st... | <T>()
where
T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'x isize>,
{
// not ok for tuple, two lifetimes and we pick first
}
fn tuple_two<T>()
where
T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'y isize>,
{
// not ok for tuple, two lifetimes and we pick second
}
fn tuple_three<T>()
whe... | tuple_one | identifier_name |
wasm-file-writer.ts | import {CodeGenerationContext} from "./code-generation/code-generation-context";
/**
* Writes the WASM file output and generates the URL used to fetch the WASM file
*
* E.g. when no bundler is used, then the url to load the wasm file is just the relative path of the
* wasm file to the js file. However, if webpack,... | * @param content the Wasm Module content
* @param codeGenerationContext the code generation context
* @returns the url to the file
*/
writeWasmFile(fileName: string, content: Buffer, codeGenerationContext: CodeGenerationContext): string;
} | /**
* Writes the wasm file and returns a url that can be used to load the file
* @param fileName the name of the wasm file | random_line_split |
conftest.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import pytest
from cryptography.hazmat.backends import _available_backen... | (parser):
parser.addoption(
"--backend", action="store", metavar="NAME",
help="Only run tests matching the backend NAME."
)
| pytest_addoption | identifier_name |
conftest.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import pytest
from cryptography.hazmat.backends import _available_backen... |
def pytest_addoption(parser):
parser.addoption(
"--backend", action="store", metavar="NAME",
help="Only run tests matching the backend NAME."
) | def pytest_runtest_setup(item):
check_backend_support(item) | random_line_split |
conftest.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import pytest
from cryptography.hazmat.backends import _available_backen... |
# If you pass an empty list to parametrize Bad Things(tm) happen
# as of pytest 2.6.4 when the test also has a parametrize decorator
skip_if_empty(filtered_backends, required_interfaces)
metafunc.parametrize("backend", filtered_backends)
@pytest.mark.trylast
def pytest_runtest_setup... | if all(
isinstance(backend, iface) for iface in required_interfaces
):
filtered_backends.append(backend) | conditional_block |
conftest.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import pytest
from cryptography.hazmat.backends import _available_backen... | parser.addoption(
"--backend", action="store", metavar="NAME",
help="Only run tests matching the backend NAME."
) | identifier_body | |
gameboy.rs | use super::cpu::*;
use super::mmu::*;
use super::mem_map;
use std::str;
pub struct Gameboy {
cpu: CPU,
mmu: MMU,
}
impl Gameboy {
pub fn new(boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy {
Gameboy {
cpu: CPU::new(),
mmu: MMU::new(boot_rom, cart_rom),
}
}... | println!("Cartridge Type: {0}", mem_map::cartridge_type(cart_type));
// Cart ROM size
let rom_size = self.mmu.read(0x0148);
println!("ROM Size: {0}", mem_map::rom_size(rom_size));
// Cart RAM size
let ram_size = self.mmu.read(0x0149);
println!("RAM Size: {0}", m... | println!("SBG Flag: {0:#x}", sgb_flag);
// Cart Type
let cart_type = self.mmu.read(0x0147); | random_line_split |
gameboy.rs | use super::cpu::*;
use super::mmu::*;
use super::mem_map;
use std::str;
pub struct Gameboy {
cpu: CPU,
mmu: MMU,
}
impl Gameboy {
pub fn | (boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy {
Gameboy {
cpu: CPU::new(),
mmu: MMU::new(boot_rom, cart_rom),
}
}
pub fn power_up(&mut self) {
println!("");
println!("####################");
// Read Name
let buffer = &[
... | new | identifier_name |
gameboy.rs | use super::cpu::*;
use super::mmu::*;
use super::mem_map;
use std::str;
pub struct Gameboy {
cpu: CPU,
mmu: MMU,
}
impl Gameboy {
pub fn new(boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy {
Gameboy {
cpu: CPU::new(),
mmu: MMU::new(boot_rom, cart_rom),
}
}... |
}
| {
self.cpu.step(&mut self.mmu);
} | identifier_body |
sat5_cobbler_config.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
tags = ['Satellite_5', 'Spacewalk']
name = 'Basic Cobbler settings are correct'
def etc_cobbler_settings(data):
"""
Verify settings in /etc/cobbler/settings:
redhat_management_type: "site"
redhat_management_server: "satellite.example.com"
server... | if opts_found != 1:
out.append("Option module in section authentication not found in /etc/cobbler/modules.conf")
for o in (etc_cobbler_modules_conf_authentication_module,):
if o != '':
out.append(o)
return out
def main(data):
"""
For hostname check noticed in the KB article we have different ru... | else:
etc_cobbler_modules_conf_authentication_module = 'In /etc/cobbler/modules.conf there should be \'module = authn_spacewalk\''
| random_line_split |
sat5_cobbler_config.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
tags = ['Satellite_5', 'Spacewalk']
name = 'Basic Cobbler settings are correct'
def etc_cobbler_settings(data):
"""
Verify settings in /etc/cobbler/settings:
redhat_management_type: "site"
redhat_management_server: "satellite.example.com"
server... | (result):
out = ""
out += "Certain config options in Cobbler configuratin should be set as expected:\n"
for e in result['errors']:
out += " %s\n" % e
out += "See https://access.redhat.com/solutions/27936"
return out
| text | identifier_name |
sat5_cobbler_config.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
tags = ['Satellite_5', 'Spacewalk']
name = 'Basic Cobbler settings are correct'
def etc_cobbler_settings(data):
"""
Verify settings in /etc/cobbler/settings:
redhat_management_type: "site"
redhat_management_server: "satellite.example.com"
server... |
if re.match('^\s*redhat_management_server\s*:', line):
opts_found += 1
val = line.split(':')[1].strip()
if re.search(r'[\'"]?\b%s\b[\'"]?' % hostname, val):
etc_cobbler_settings_redhat_management_server = ''
else:
etc_cobbler_settings_redhat_management_server = 'In /etc/cob... | etc_cobbler_settings_redhat_management_type = 'In /etc/cobbler/settings there should be \'redhat_management_type: "site"\'' | conditional_block |
sat5_cobbler_config.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
tags = ['Satellite_5', 'Spacewalk']
name = 'Basic Cobbler settings are correct'
def etc_cobbler_settings(data):
| etc_cobbler_settings_redhat_management_type = ''
else:
etc_cobbler_settings_redhat_management_type = 'In /etc/cobbler/settings there should be \'redhat_management_type: "site"\''
if re.match('^\s*redhat_management_server\s*:', line):
opts_found += 1
val = line.split(':')[1].strip(... | """
Verify settings in /etc/cobbler/settings:
redhat_management_type: "site"
redhat_management_server: "satellite.example.com"
server: satellite.example.com
Teoretically we can have one option specified multiple times, so we want
to evaluate only last one.
"""
out = []
opts_found = 0
hostname ... | identifier_body |
sample.py | '''
Created on 2015年1月19日
@author: Guan-yu Willie Chen
'''
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
import time
#browser = webdriver.Firefox()
#browser = webdriver.Ie()
browser = ... | 詢
browser.find_element_by_xpath("//input[@name='queryBtn']").click()
# 分頁
browser.find_element_by_xpath("//input[@id='gotoPageNo']").send_keys(Keys.BACKSPACE)
browser.find_element_by_xpath("//input[@id='gotoPageNo']").send_keys("3")
browser.find_element_by_xpath("//div[@id='turnpage']/table/tbody/tr/td/input[@valu... | (1)
# 查 | conditional_block |
sample.py | '''
Created on 2015年1月19日
@author: Guan-yu Willie Chen
'''
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
|
#browser = webdriver.Firefox()
#browser = webdriver.Ie()
browser = webdriver.Chrome("chromedriver.exe")
URL = ""
browser.get(URL+"/insurance/gs/sp/spLogin")
# 登入
browser.find_element_by_xpath("//input[@id='login:userName']").send_keys('')
browser.find_element_by_xpath("//input[@id='login:password']")... | import time
| random_line_split |
index.tsx | /**
* 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... | stopTimer();
}
}
}, 30);
}
return stopTimer;
}, [endTime, isRunning, startTime]);
return (
<TimerLabel type={status} role="timer">
{clockStr}
</TimerLabel>
);
}
| {
const [clockStr, setClockStr] = useState('00:00:00.00');
const timer = useRef<ReturnType<typeof setInterval>>();
useEffect(() => {
const stopTimer = () => {
if (timer.current) {
clearInterval(timer.current);
timer.current = undefined;
}
};
if (isRunning) {
timer.c... | identifier_body |
index.tsx | /**
* 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... |
}, 30);
}
return stopTimer;
}, [endTime, isRunning, startTime]);
return (
<TimerLabel type={status} role="timer">
{clockStr}
</TimerLabel>
);
}
| {
const endDttm = endTime || now();
if (startTime < endDttm) {
setClockStr(fDuration(startTime, endDttm));
}
if (!isRunning) {
stopTimer();
}
} | conditional_block |
index.tsx | /**
* 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... | ({
endTime,
isRunning,
startTime,
status = 'success',
}: TimerProps) {
const [clockStr, setClockStr] = useState('00:00:00.00');
const timer = useRef<ReturnType<typeof setInterval>>();
useEffect(() => {
const stopTimer = () => {
if (timer.current) {
clearInterval(timer.current);
... | Timer | identifier_name |
index.tsx | /**
* 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... | isRunning,
startTime,
status = 'success',
}: TimerProps) {
const [clockStr, setClockStr] = useState('00:00:00.00');
const timer = useRef<ReturnType<typeof setInterval>>();
useEffect(() => {
const stopTimer = () => {
if (timer.current) {
clearInterval(timer.current);
timer.current ... | endTime, | random_line_split |
menu.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... | (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "obje... | _classCallCheck | identifier_name |
menu.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... | Menu.propTypes = {};
exports.default = Menu; | random_line_split | |
menu.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... |
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enum... | { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | identifier_body |
menu.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("... | subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Menu = function (_Component)... | { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } | conditional_block |
authentication.py | import re, os, M2Crypto, base64, util
import lostexhaust.config as config
| rsakey = M2Crypto.RSA.load_pub_key(os.path.join(config.get('rootDir'), config.get("catlinRsaPemFile")))
def check_token_validity(token, ip, timestamp):
parsed = parse_token(decrypt_rsa(token))
if parsed is None:
return False
else:
(parsed_person_id, parsed_timestamp, parsed_ip) = parsed
... | random_line_split | |
authentication.py | import re, os, M2Crypto, base64, util
import lostexhaust.config as config
rsakey = M2Crypto.RSA.load_pub_key(os.path.join(config.get('rootDir'), config.get("catlinRsaPemFile")))
def check_token_validity(token, ip, timestamp):
parsed = parse_token(decrypt_rsa(token))
if parsed is None:
return False
... | (token):
parsed = parse_token(decrypt_rsa(token))
if parsed is None:
return None
else:
(parsed_person_id, parsed_timestamp, parsed_ip) = parsed
return parsed_person_id
| get_person_from_token | identifier_name |
authentication.py | import re, os, M2Crypto, base64, util
import lostexhaust.config as config
rsakey = M2Crypto.RSA.load_pub_key(os.path.join(config.get('rootDir'), config.get("catlinRsaPemFile")))
def check_token_validity(token, ip, timestamp):
|
def decrypt_rsa(encoded):
try:
cipher = base64.b16decode(encoded)
plain = rsakey.public_decrypt(cipher, M2Crypto.RSA.pkcs1_padding)
return plain
except:
return ""
def parse_token(unencrypted_token):
tokens = unencrypted_token.split("|")
if (len(tokens) != 3):
r... | parsed = parse_token(decrypt_rsa(token))
if parsed is None:
return False
else:
(parsed_person_id, parsed_timestamp, parsed_ip) = parsed
# todo: check if person_id is valid
valid_person_id = True
valid_ip = parsed_ip == ip or ip == "127.0.0.1"
valid_timestamp = (ti... | identifier_body |
authentication.py | import re, os, M2Crypto, base64, util
import lostexhaust.config as config
rsakey = M2Crypto.RSA.load_pub_key(os.path.join(config.get('rootDir'), config.get("catlinRsaPemFile")))
def check_token_validity(token, ip, timestamp):
parsed = parse_token(decrypt_rsa(token))
if parsed is None:
return False
... | (parsed_person_id, parsed_timestamp, parsed_ip) = parsed
return parsed_person_id | conditional_block | |
format.ts | import { FilterOrGroup, OrderBy, DataViewRequest } from "./core";
import { isFilterGroup } from "./functions";
export function filterToString(filter: FilterOrGroup, format?: (v: any) => string): string | null {
if (filter == null)
return null;
if (isFilterGroup(filter))
return filter.filters.m... | if (value instanceof Date)
return `"${value.toISOString()}"`;
if (typeof(value) == 'string')
return `"${value}"`;
return value;
}
export function orderByToString(orderBy: OrderBy[]): string | null {
if(orderBy == null)
return null;
return orderBy.map(x => `${x.field} ... | }
function formatValue(value: any): string { | random_line_split |
format.ts | import { FilterOrGroup, OrderBy, DataViewRequest } from "./core";
import { isFilterGroup } from "./functions";
export function filterToString(filter: FilterOrGroup, format?: (v: any) => string): string | null {
if (filter == null)
return null;
if (isFilterGroup(filter))
return filter.filters.m... | (request: DataViewRequest, prefix: string = "") : string {
var result = `${prefix}skip=${request.skip}&${prefix}take=${request.take}`;
var filterString = filterToString(request.filter);
var orderByString = orderByToString(request.orderBy);
if(filterString != null)
result += `&${prefix}filt... | requestToQueryString | identifier_name |
format.ts | import { FilterOrGroup, OrderBy, DataViewRequest } from "./core";
import { isFilterGroup } from "./functions";
export function filterToString(filter: FilterOrGroup, format?: (v: any) => string): string | null {
if (filter == null)
return null;
if (isFilterGroup(filter))
return filter.filters.m... | {
var result = `${prefix}skip=${request.skip}&${prefix}take=${request.take}`;
var filterString = filterToString(request.filter);
var orderByString = orderByToString(request.orderBy);
if(filterString != null)
result += `&${prefix}filter=${encodeURIComponent(filterString)}`;
if(orderByS... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.