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 |
|---|---|---|---|---|
pico.py | #
# This file is part of pySMT.
#
# Copyright 2014 Andrea Micheli and Marco Gario
#
# 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
... |
res = picosat.picosat_sat(self.pico, -1)
if res == picosat.PICOSAT_SATISFIABLE:
self.latest_model = self.get_model()
return True
else:
self.latest_model = None
return False
def get_value(self, item):
if self.latest_model is None:
... | self.push()
self._add_cnf_assertion(missing)
self.pending_pop = True | conditional_block |
pico.py | #
# This file is part of pySMT.
#
# Copyright 2014 Andrea Micheli and Marco Gario
#
# 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
... | (self, lit):
mult = 1
var = lit
if lit.is_not():
mult = -1
var = lit.arg(0)
vid = self._get_var_id(var)
return vid * mult
@clear_pending_pop
@catch_conversion_error
def add_assertion(self, formula, named=None):
# First, we get rid of... | _get_pico_lit | identifier_name |
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style ... | _ => {
try!(write!(dest, "/"));
try!(height.to_css(dest));
}
}
}
try!(write!(dest, " "));
self.font_family.to_css(dest)
}
}
</%helpers:shorthand>
| {
if let DeclaredValue::Value(ref style) = *self.font_style {
try!(style.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref variant) = *self.font_variant {
try!(variant.to_css(dest));
try!(write!(... | identifier_body |
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style ... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let DeclaredValue::Value(ref style) = *self.font_style {
try!(style.to_css(dest));
try!(write!(dest, " "));
}
if let DeclaredValue::Value(ref variant) = *self.font_variant {
... | to_css_declared | identifier_name |
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style ... |
}
size = Some(try!(font_size::parse(context, input)));
break
}
#[inline]
fn count<T>(opt: &Option<T>) -> u8 {
if opt.is_some() { 1 } else { 0 }
}
if size.is_none() || (count(&style) + count(&weight) + count(&variant) + nb_normals) ... | {
variant = Some(value);
continue
} | conditional_block |
font.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="font" sub_properties="font-style ... | </%helpers:shorthand> | random_line_split | |
on-exit.ts | 'use strict';
//dts
import {IGlobalSumanObj} from "../../../suman-types/dts/global";
//polyfills
const process = require('suman-browser-polyfills/modules/process');
const global = require('suman-browser-polyfills/modules/global');
//core
import fs = require('fs');
import path = require('path');
import EE = require('... | export const onExit = function (code: number) {
if (code > 0) {
//make a beep noise if a failing run
resultBroadcaster.emit(String(events.RUNNER_EXIT_CODE_GREATER_THAN_ZERO), code);
}
else {
resultBroadcaster.emit(String(events.RUNNER_EXIT_CODE_IS_ZERO));
}
if (code > 0) {
const logsDir = _... | random_line_split | |
on-exit.ts | 'use strict';
//dts
import {IGlobalSumanObj} from "../../../suman-types/dts/global";
//polyfills
const process = require('suman-browser-polyfills/modules/process');
const global = require('suman-browser-polyfills/modules/global');
//core
import fs = require('fs');
import path = require('path');
import EE = require('... |
if (code > 0) {
const logsDir = _suman.sumanConfig.logsDir || _suman.sumanHelperDirRoot + '/logs';
const sumanCPLogs = path.resolve(logsDir + '/runs/');
const logsPath = path.resolve(sumanCPLogs + '/' + _suman.timestamp + '-' + _suman.runId);
console.log('\n', ' => At least one test experienced an... | {
resultBroadcaster.emit(String(events.RUNNER_EXIT_CODE_IS_ZERO));
} | conditional_block |
test_BioCompass.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
from click.testing import CliRunner
from BioCompass import cli
def test_importcli():
runner = CliRunner() | result = runner.invoke(cli.main)
assert result.exit_code == 0
#assert 'BioCompass.cli.main' in result.output
help_result = runner.invoke(cli.main, ['--help'])
assert help_result.exit_code == 0
#assert 'Usage: main [OPTIONS] MGBFILE' in help_result.output
import pandas as pd
from BioCompass.Bio... | random_line_split | |
test_BioCompass.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
from click.testing import CliRunner
from BioCompass import cli
def test_importcli():
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
#assert 'BioCompass.cli.main' in result.output
help_result = runner.invoke(c... | """ Uncataloged product should return hypothetical
"""
df = pd.DataFrame(
{'product': ['ipsisLitteris']})
out = find_category_from_product(df)
assert (out['category'] == 'hypothetical').all() | identifier_body | |
test_BioCompass.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
from click.testing import CliRunner
from BioCompass import cli
def test_importcli():
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
#assert 'BioCompass.cli.main' in result.output
help_result = runner.invoke(c... | ():
""" Uncataloged product should return hypothetical
"""
df = pd.DataFrame(
{'product': ['ipsisLitteris']})
out = find_category_from_product(df)
assert (out['category'] == 'hypothetical').all()
| test_find_category_from_product_hypothetical | identifier_name |
disk_sub.py | import sys
import numpy as np
import pylab
import matplotlib.pyplot as plt
import scipy.integrate
import scipy.optimize
from collections import namedtuple
import geo
import astro_help as ah
import disk_sub as disk
RADIAN=57.29598
C=2.997925e10
MSOL=1.979e33
G=6.670e-8
YR=3.1556925e7
EPSILON=1e-6
PI=3.1416
STEFAN_BOLT... |
def lnu_disk (f,m,mdot,rmin,rmax):
tref=tdisk(m, mdot, rmin)
rtemp=np.logspace(np.log10(rmin),np.log10(rmax),num=100)
rdisk=[]
lnu=0.0
for j in range(len(rtemp)-1):
rdisk.append((rtemp[j]+rtemp[j+1])/2.0)
r=rdisk[j]/rmin
area=PI*(rtemp[j+1]*rtemp[j+1]-rtemp[j]*rtemp[j])
t=(disk.teff(tref,r))
lnu=lnu+(... | tref=tdisk(m, mdot, rmin)
nfreq=1000
freq=np.logspace(np.log10(f1),np.log10(f2),nfreq)
spec=np.empty(nfreq)
dfreq=freq[1]-freq[0]
rtemp=np.logspace(np.log10(rmin),np.log10(rmax),num=100)
rdisk=[]
for j in range(len(rtemp)-1):
rdisk.append((rtemp[j]+rtemp[j+1])/2.0)
r=rdisk[j]/rmin
area=PI*(rtemp[j+1]*rtemp... | identifier_body |
disk_sub.py | import sys
import numpy as np
import pylab
import matplotlib.pyplot as plt
import scipy.integrate
import scipy.optimize
from collections import namedtuple
import geo
import astro_help as ah
import disk_sub as disk
RADIAN=57.29598
C=2.997925e10
MSOL=1.979e33
G=6.670e-8
YR=3.1556925e7
EPSILON=1e-6
PI=3.1416
STEFAN_BOLT... | (f1,f2,m,mdot,rmin,rmax):
tref=tdisk(m, mdot, rmin)
nfreq=10
f1a=10**float(int(np.log10(f1)))
f2a=10**float(int(np.log10(f2))+1)
nrange=int(np.log10((f2a/f1a)))
freq=[]
dfreq=[]
ftemp=f1a
df=f1a/nfreq
for i in range(nrange):
for j in range(nfreq*9):
ftemp=ftemp+df
if ftemp > f2:
break
if ftemp... | spec_disk2 | identifier_name |
disk_sub.py | import sys
import numpy as np
import pylab
import matplotlib.pyplot as plt
import scipy.integrate
import scipy.optimize
from collections import namedtuple
import geo
import astro_help as ah
import disk_sub as disk
RADIAN=57.29598
C=2.997925e10
MSOL=1.979e33
G=6.670e-8
YR=3.1556925e7
EPSILON=1e-6
PI=3.1416
STEFAN_BOLT... |
def spec_disk (f1,f2,m,mdot,rmin,rmax):
tref=tdisk(m, mdot, rmin)
nfreq=(f2/f1)*100
freq=np.linspace(f1,f2,nfreq)
spec=np.empty(nfreq)
dfreq=freq[1]-freq[0]
rtemp=np.logspace(np.log10(rmin),np.log10(rmax),num=100)
rdisk=[]
for j in range(len(rtemp)-1):
rdisk.append((rtemp[j]+rtemp[j+1])/2.0)
r=rdisk[j]/rm... | return (q) | random_line_split |
disk_sub.py | import sys
import numpy as np
import pylab
import matplotlib.pyplot as plt
import scipy.integrate
import scipy.optimize
from collections import namedtuple
import geo
import astro_help as ah
import disk_sub as disk
RADIAN=57.29598
C=2.997925e10
MSOL=1.979e33
G=6.670e-8
YR=3.1556925e7
EPSILON=1e-6
PI=3.1416
STEFAN_BOLT... |
return (freq,spec)
def spec_disk1 (f1,f2,m,mdot,rmin,rmax):
tref=tdisk(m, mdot, rmin)
nfreq=1000
freq=np.logspace(np.log10(f1),np.log10(f2),nfreq)
spec=np.empty(nfreq)
dfreq=freq[1]-freq[0]
rtemp=np.logspace(np.log10(rmin),np.log10(rmax),num=100)
rdisk=[]
for j in range(len(rtemp)-1):
rdisk.append((rte... | rdisk.append((rtemp[j]+rtemp[j+1])/2.0)
r=rdisk[j]/rmin
area=PI*(rtemp[j+1]*rtemp[j+1]-rtemp[j]*rtemp[j])
t=(disk.teff(tref,r))
for i in range(len(freq)):
spec[i]=spec[i]+(ah.planck_nu(t,freq[i])*area*PI*2) | conditional_block |
admin.py | from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from services.models import Service, ServiceType, Alias
# See
# <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter>
# for documen... | class StartsWithListFilter(SimpleListFilter):
title = _('Starts with')
parameter_name = 'starts_with'
def lookups(self, request, model_admin):
def first_two(s):
s = unicode(s)
if len(s) < 2:
return s
else:
return s[:2]
pr... | random_line_split | |
admin.py | from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from services.models import Service, ServiceType, Alias
# See
# <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter>
# for documen... |
else:
return queryset
class AliasAdmin(admin.ModelAdmin):
list_filter = (StartsWithListFilter,)
admin.site.register(Service)
admin.site.register(ServiceType)
admin.site.register(Alias, AliasAdmin)
| return queryset.filter(name__istartswith=self.value()) | conditional_block |
admin.py | from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from services.models import Service, ServiceType, Alias
# See
# <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter>
# for documen... |
admin.site.register(Service)
admin.site.register(ServiceType)
admin.site.register(Alias, AliasAdmin)
| list_filter = (StartsWithListFilter,) | identifier_body |
admin.py | from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from services.models import Service, ServiceType, Alias
# See
# <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter>
# for documen... | (self, request, queryset):
if self.value():
return queryset.filter(name__istartswith=self.value())
else:
return queryset
class AliasAdmin(admin.ModelAdmin):
list_filter = (StartsWithListFilter,)
admin.site.register(Service)
admin.site.register(ServiceType)
admin.site.regi... | queryset | identifier_name |
fabfile.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yan Yan'
'''
Deployment toolkit.
'''
import os, re
from datetime import datetime
from fabric.api import *
env.user = 'michael'
env.sudo_user = 'root'
env.hosts = ['192.168.0.3']
db_user = 'www-data'
db_password = 'www-data'
_TAR_FILE = 'dist-awesome.tar... | print ('ERROR: already the oldest version.')
old = files[index + 1]
print ('==================================================')
for f in files:
if f == current:
print (' Current ---> %s' % current)
elif f == old:
print (' ... | '''
rollback to previous version
'''
with cd(_REMOTE_BASE_DIR):
r = run('ls -p -1')
files = [s[:-1] for s in RE_FILES.split(r) if s.startswith('www-') and s.endswith('/')]
files.sort(cmp=lambda s1, s2: 1 if s1 < s2 else -1)
r = run('ls -l www')
ss = r.split(' -> ')
... | identifier_body |
fabfile.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yan Yan'
'''
Deployment toolkit.
'''
import os, re
from datetime import datetime
from fabric.api import *
env.user = 'michael'
env.sudo_user = 'root'
env.hosts = ['192.168.0.3']
db_user = 'www-data'
db_password = 'www-data'
_TAR_FILE = 'dist-awesome.tar... | ():
return os.path.abspath('.')
def _now():
return datetime.now().strftime('%y-%m-%d_%H.%M.%S')
def backup():
'''
Dump entire database on server and backup to local.
'''
dt = _now()
f = 'backup-awesome-%s.sql' % dt
with cd('/tmp'):
run('mysqldump --user=%s --password=%s --skip-... | _current_path | identifier_name |
fabfile.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yan Yan'
'''
Deployment toolkit.
'''
import os, re
from datetime import datetime
from fabric.api import *
env.user = 'michael'
env.sudo_user = 'root'
env.hosts = ['192.168.0.3']
db_user = 'www-data'
db_password = 'www-data'
_TAR_FILE = 'dist-awesome.tar... | sudo('tar -xzvf %s' % _REMOTE_TMP_TAR)
with cd(_REMOTE_BASE_DIR):
sudo('rm -f www')
sudo('ln -s %s www' % newdir)
sudo('chown www-data:www-data www')
sudo('chown -R www-data:www-data %s' % newdir)
with settings(warn_only=True):
sudo('supervisorctl stop awesome')
... | with cd('%s/%s' % (_REMOTE_BASE_DIR, newdir)): | random_line_split |
fabfile.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yan Yan'
'''
Deployment toolkit.
'''
import os, re
from datetime import datetime
from fabric.api import *
env.user = 'michael'
env.sudo_user = 'root'
env.hosts = ['192.168.0.3']
db_user = 'www-data'
db_password = 'www-data'
_TAR_FILE = 'dist-awesome.tar... |
old = files[index + 1]
print ('==================================================')
for f in files:
if f == current:
print (' Current ---> %s' % current)
elif f == old:
print (' Rollback to ---> %s' % old)
else:
... | print ('ERROR: already the oldest version.') | conditional_block |
fit.js | import {default as geoStream} from "../stream";
import boundsStream from "../path/bounds";
function fit(project, extent, object) {
var w = extent[1][0] - extent[0][0],
h = extent[1][1] - extent[0][1],
clip = project.clipExtent && project.clipExtent();
project
.scale(150)
.translate([0, 0])... | {
return function(extent, object) {
return fit(project, extent, object);
};
} | identifier_body | |
fit.js | import {default as geoStream} from "../stream";
import boundsStream from "../path/bounds";
function fit(project, extent, object) {
var w = extent[1][0] - extent[0][0],
h = extent[1][1] - extent[0][1],
clip = project.clipExtent && project.clipExtent();
project
.scale(150)
.translate([0, 0])... | (project) {
return function(extent, object) {
return fit(project, extent, object);
};
}
| fitExtent | identifier_name |
fit.js | import {default as geoStream} from "../stream";
import boundsStream from "../path/bounds";
function fit(project, extent, object) {
var w = extent[1][0] - extent[0][0],
h = extent[1][1] - extent[0][1],
clip = project.clipExtent && project.clipExtent();
project
.scale(150)
.translate([0, 0])... | }
export function fitSize(project) {
return function(size, object) {
return fit(project, [[0, 0], size], object);
};
}
export function fitExtent(project) {
return function(extent, object) {
return fit(project, extent, object);
};
} | .scale(k * 150)
.translate([x, y]); | random_line_split |
create-content.component.ts | import {Component, Inject, OnInit} from '@angular/core';
import {MD_DIALOG_DATA, MdDialogRef} from '@angular/material';
import {SitesService} from '../../shared/domain/sites.service';
import {ContentService} from '../../shared/domain/content.service';
@Component({
selector: 'app-create-content',
templateUrl: '... | console.error(err);
this.isLoading = false;
});
console.log(this.item);
}
} | }
this.content.createItem(this.item).then((result) => {
this.dialogRef.close();
}).catch(err => { | random_line_split |
create-content.component.ts | import {Component, Inject, OnInit} from '@angular/core';
import {MD_DIALOG_DATA, MdDialogRef} from '@angular/material';
import {SitesService} from '../../shared/domain/sites.service';
import {ContentService} from '../../shared/domain/content.service';
@Component({
selector: 'app-create-content',
templateUrl: '... |
save() {
this.isLoading = true;
if (this.model.isWebpage) {
this.item.webpage.title = this.item.name;
}
this.content.createItem(this.item).then((result) => {
this.dialogRef.close();
}).catch(err => {
console.error(err);
this.i... | {
} | identifier_body |
create-content.component.ts | import {Component, Inject, OnInit} from '@angular/core';
import {MD_DIALOG_DATA, MdDialogRef} from '@angular/material';
import {SitesService} from '../../shared/domain/sites.service';
import {ContentService} from '../../shared/domain/content.service';
@Component({
selector: 'app-create-content',
templateUrl: '... | (
public dialogRef: MdDialogRef<CreateContentComponent>,
@Inject(MD_DIALOG_DATA) data,
private sites: SitesService,
private content: ContentService,
) {
this.model = data.model;
this.item.modelId = this.model._id;
if (this.model.isWebpage) {
this.i... | constructor | identifier_name |
create-content.component.ts | import {Component, Inject, OnInit} from '@angular/core';
import {MD_DIALOG_DATA, MdDialogRef} from '@angular/material';
import {SitesService} from '../../shared/domain/sites.service';
import {ContentService} from '../../shared/domain/content.service';
@Component({
selector: 'app-create-content',
templateUrl: '... |
sites.getActiveSite().subscribe(site => {
this.item.siteId = site._id;
});
}
ngOnInit() {
}
save() {
this.isLoading = true;
if (this.model.isWebpage) {
this.item.webpage.title = this.item.name;
}
this.content.createItem(this.item... | {
this.item.webpage = {
title: '',
url: '',
meta: {
description: '',
}
}
} | conditional_block |
macro_import.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&mut self, item: &ast::Item) {
// We're only interested in `extern crate`.
match item.node {
ast::ItemExternCrate(_) => {}
_ => {
visit::walk_item(self, item);
return;
}
}
// Parse the attributes relating to macros.
... | visit_item | identifier_name |
macro_import.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // do nothing.
}
}
impl<'a> MacroLoader<'a> {
fn load_macros<'b>(&mut self,
vi: &ast::Item,
import: Option<MacroSelection>,
reexport: MacroSelection) {
if let Some(sel) = import.as_ref() {
if sel.is_empty() && reex... | }
fn visit_mac(&mut self, _: &ast::Mac) {
// bummer... can't see macro imports inside macros. | random_line_split |
macro_import.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub type MacroSelection = HashMap<token::InternedString, Span>;
// note that macros aren't expanded yet, and therefore macros can't add macro imports.
impl<'a, 'v> Visitor<'v> for MacroLoader<'a> {
fn visit_item(&mut self, item: &ast::Item) {
// We're only interested in `extern crate`.
match item... | {
let mut loader = MacroLoader::new(sess);
// We need to error on `#[macro_use] extern crate` when it isn't at the
// crate root, because `$crate` won't work properly. Identify these by
// spans, because the crate map isn't set up yet.
for item in &krate.module.items {
if let ast::ItemExter... | identifier_body |
macro_import.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
"macro_use" => {
let names = attr.meta_item_list();
if names.is_none() {
// no names => load all
import = None;
}
if let (Some(sel), Some(names)) = (import.as_mut(), names) {
... | {
self.sess.span_err(attr.span, "#[plugin] on `extern crate` is deprecated");
self.sess.fileline_help(attr.span, &format!("use a crate attribute instead, \
i.e. #![plugin({})]",
... | conditional_block |
sensor_list.tsx | import * as React from "react";
import { readPin } from "../../devices/actions";
import { SensorListProps } from "./interfaces";
import { sortResourcesById } from "../../util";
import { Row, Col } from "../../ui";
import { isNumber } from "lodash";
import { ALLOWED_PIN_MODES } from "farmbot";
import { t } from "../../i... | {value}
</span>
</div>}
</div>;
};
export const SensorList = (props: SensorListProps) =>
<div className="sensor-list">
{sortResourcesById(props.sensors).map(sensor => {
const { label, mode, pin } = sensor.body;
const pinNumber = (isNumber(pin) && isFinite(pin)) ? p... | random_line_split | |
projectiles.py | # Projectiles
import pygame
import environment
from models import Projectile
class Laser(Projectile):
def | (self, laser_x, laser_y, sign=None, speed=20):
self.laser_height = 20
self.laser_width = environment.WINDOW_WIDTH - laser_x
self.laser_rect = pygame.Rect(laser_x, laser_y, self.laser_width, self.laser_height)
Projectile.__init__(self, self.laser_rect, sign)
self.base_speed = spe... | __init__ | identifier_name |
projectiles.py | # Projectiles
import pygame
import environment
from models import Projectile
class Laser(Projectile):
def __init__(self, laser_x, laser_y, sign=None, speed=20):
self.laser_height = 20
self.laser_width = environment.WINDOW_WIDTH - laser_x
self.laser_rect = pygame.Rect(laser_x, laser_y, sel... | def is_out_of_screen(self):
return self.right > environment.WINDOW_WIDTH | random_line_split | |
projectiles.py | # Projectiles
import pygame
import environment
from models import Projectile
class Laser(Projectile):
def __init__(self, laser_x, laser_y, sign=None, speed=20):
self.laser_height = 20
self.laser_width = environment.WINDOW_WIDTH - laser_x
self.laser_rect = pygame.Rect(laser_x, laser_y, sel... | """ def __init__(self, spawn_x, spawn_y):
self.bullet_width = 10
self.bullet_height = 3
self.bullet_rect = pygame.Rect(spawn_x, spawn_y, self.bullet_width, self.bullet_height)
Projectile.__init__(self, self.bullet_rect)
self.base_speed = 20
"""
def __init__(self, posx=0, ... | identifier_body | |
lib.js | var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2Math = Box2D.Common.Math.b2Math... | i = interval;
if (0 < j) {
--j;
func();
} else {
createjs.Ticker.removeEventListener("tick", tick);
}
}
}
createjs.Ticker.addEventListener("tick", tick);
} | --i;
} else { | random_line_split |
lib.js | var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2Math = Box2D.Common.Math.b2Math... |
str = str.split('&');
for (var i = 0; i < str.length; ++i){
item = str[i].split("=");
if(item[0] != ''){
arr[item[0]] = typeof(item[1]) == 'undefined' ? true : dec(item[1]);
}
}
return arr;
}
function inspect(dict) {
var str = '';
for (var key in dict){
... | { str = str.split('?')[1]; } | conditional_block |
lib.js | var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2Math = Box2D.Common.Math.b2Math... |
function inspect(dict) {
var str = '';
for (var key in dict){
str += key + "=" + dict[key] + "\n";
}
alert(str);
}
function randomPM() { return Math.random() * 2 - 1; }
function color(r, g, b) {
var f = function(g) {
return ('0' + Math.floor(g()).toString(16)).slice(-2);
};
... | {
var dec = decodeURIComponent;
var arr = [];
var item;
if (typeof(str) == 'undefined') { return arr; }
if (str.indexOf('?', 0) > -1) { str = str.split('?')[1]; }
str = str.split('&');
for (var i = 0; i < str.length; ++i){
item = str[i].split("=");
if(item[0] != ''){
... | identifier_body |
lib.js | var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2Math = Box2D.Common.Math.b2Math... | (r, g, b) {
var f = function(g) {
return ('0' + Math.floor(g()).toString(16)).slice(-2);
};
return "#" + f(r) + f(g) + f(b);
}
function whitish() { return Math.random() * 64 + 192; }
function light() { return Math.random() * 128 + 128; }
function middle() { return Math.random() * 128 + 64; }... | color | identifier_name |
htmldialogelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding... | (&self) -> DOMString {
let return_value = self.return_value.borrow();
return_value.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue
fn SetReturnValue(&self, return_value: DOMString) {
*self.return_value.borrow_mut() = return_value;
}
// https://ht... | ReturnValue | identifier_name |
htmldialogelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding... |
// Step 3
if let Some(new_value) = return_value {
*self.return_value.borrow_mut() = new_value;
}
// TODO: Step 4 implement pending dialog stack removal
// Step 5
win.task_manager()
.dom_manipulation_task_source()
.queue_simple_event... | {
return;
} | conditional_block |
htmldialogelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding... | HTMLDialogElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
return_value: DomRefCell::new(DOMString::new()),
}
}
#[allow(unrooted_must_root)]
pub fn new(
local_name: LocalName,
prefix: Option<Prefix>,
document: &... | document: &Document,
) -> HTMLDialogElement { | random_line_split |
htmldialogelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding... | // Step 5
win.task_manager()
.dom_manipulation_task_source()
.queue_simple_event(target, atom!("close"), &win);
}
}
| {
let element = self.upcast::<Element>();
let target = self.upcast::<EventTarget>();
let win = window_from_node(self);
// Step 1 & 2
if element
.remove_attribute(&ns!(), &local_name!("open"))
.is_none()
{
return;
}
// ... | identifier_body |
board.py | import numpy
class Board(object):
BLACK = 1
WHITE = -1
def __init__(self):
self.board = numpy.zeros((8,8), int)
self.board[3][3] = Board.WHITE
self.board[4][4] = Board.WHITE
self.board[3][4] = Board.BLACK
self.board[4][3] = Board.BLACK
self.remaining_pieces... | (self,tile,move):
"""
Updates board with new movement if is a valid move
@param int tile
1 for BLACK
-1 for WHITE
@param int move
0-63 vector position
"""
row = move // 8
col = move % 8
moves = self.isValidMove(tile,col,... | updateBoard | identifier_name |
board.py | import numpy
class Board(object):
BLACK = 1
WHITE = -1
def __init__(self):
self.board = numpy.zeros((8,8), int)
self.board[3][3] = Board.WHITE
self.board[4][4] = Board.WHITE
self.board[3][4] = Board.BLACK
self.board[4][3] = Board.BLACK
self.remaining_pieces... |
return flipTiles
| for dirRow in ((-1),(0),(1)):
if dirCol == dirRow and dirCol == 0:
continue
c = dirCol + col
r = dirRow + row
while self.isOnBoard(c,r) and self.board[c][r] != 0:
if self.board[c][r] == tile:
... | conditional_block |
board.py | import numpy
class Board(object):
BLACK = 1
WHITE = -1
| self.board[3][3] = Board.WHITE
self.board[4][4] = Board.WHITE
self.board[3][4] = Board.BLACK
self.board[4][3] = Board.BLACK
self.remaining_pieces = 8*8-4
self.score = {Board.BLACK: 2, Board.WHITE: 2}
def getScore(self):
""" Returns actual score """
r... | def __init__(self):
self.board = numpy.zeros((8,8), int) | random_line_split |
board.py | import numpy
class Board(object):
BLACK = 1
WHITE = -1
def __init__(self):
self.board = numpy.zeros((8,8), int)
self.board[3][3] = Board.WHITE
self.board[4][4] = Board.WHITE
self.board[3][4] = Board.BLACK
self.board[4][3] = Board.BLACK
self.remaining_pieces... |
def isOnBoard(self,c,r):
""" Returns true if valid position or false otherwise """
return (c>=0) and (c<=7) and (r>=0) and (r<=7)
def getRemainingPieces(self):
""" Returns remaining pieces """
return self.remaining_pieces
def next(self,tile,action):
"""
Up... | """ Returns actual state of board in 1 Dimension of 128 positions,
half for black pieces positions, other half for white positions """
oneD = self.get1DBoard()
shapedBoard = numpy.zeros(129,int)
idx = 0
for pos in oneD:
if pos == 0:
shapedBoard[idx] = ... | identifier_body |
web.py | # -*- coding:utf-8 -*-
"""
web基类
Author: huangtao
Date: 2017/8/8
Update: 2017/12/12 1. 增加do_prepare/do_complete函数;
2017/12/17 1. 增加中间件;
2017/12/18 1. 修改错误返回类型;
2. 增加 query_params 及 data 属性方法;
3. 删除 do_http_error 方法;
2018/01/17 1. 跨域增加设置 Access-Contr... | me, None)
if not func:
raise exceptions.NotFound()
await self.do_prepare()
await func(*args, **kwargs)
await self.do_complete()
async def do_prepare(self):
""" 准备工作
* 在执行http方法之前,可以做类似统计、权限校验等操作
"""
# 中间件
middlewares = options.midd... | nc_na | identifier_name |
web.py | # -*- coding:utf-8 -*-
"""
web基类
Author: huangtao
Date: 2017/8/8
Update: 2017/12/12 1. 增加do_prepare/do_complete函数;
2017/12/17 1. 增加中间件;
2017/12/18 1. 修改错误返回类型;
2. 增加 query_params 及 data 属性方法;
3. 删除 do_http_error 方法;
2018/01/17 1. 跨域增加设置 Access-Contr... | conditional_block | ||
web.py | # -*- coding:utf-8 -*-
"""
web基类
Author: huangtao
Date: 2017/8/8
Update: 2017/12/12 1. 增加do_prepare/do_complete函数;
2017/12/17 1. 增加中间件;
2017/12/18 1. 修改错误返回类型;
2. 增加 query_params 及 data 属性方法;
3. 删除 do_http_error 方法;
2018/01/17 1. 跨域增加设置 Access-Contr... | await self.do_prepare()
await func(*args, **kwargs)
await self.do_complete()
async def do_prepare(self):
""" 准备工作
* 在执行http方法之前,可以做类似统计、权限校验等操作
"""
# 中间件
middlewares = options.middlewares
for m in middlewares:
await m.prepare(self)
as... | raise exceptions.NotFound()
| identifier_body |
web.py | # -*- coding:utf-8 -*-
"""
web基类
Author: huangtao
Date: 2017/8/8
Update: 2017/12/12 1. 增加do_prepare/do_complete函数;
2017/12/17 1. 增加中间件;
2017/12/18 1. 修改错误返回类型;
2. 增加 query_params 及 data 属性方法;
3. 删除 do_http_error 方法;
2018/01/17 1. 跨域增加设置 Access-Contr... |
class WebHandler(RequestHandler):
""" web基类
"""
@property
def query_params(self):
if not hasattr(self, '_query_params'):
self._query_params = {}
for key in self.request.arguments.keys():
value = self.get_argument(key)
self._query_params[k... | random_line_split | |
test_volumes_get.py | # Copyright 2012 OpenStack Foundation
# All 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 requ... |
@classmethod
def setup_clients(cls):
super(VolumesGetTestJSON, cls).setup_clients()
cls.client = cls.volumes_extensions_client
@test.idempotent_id('f10f25eb-9775-4d9d-9cbe-1cf54dae9d5f')
def test_volume_create_get_delete(self):
# CREATE, GET, DELETE Volume
volume = Non... | skip_msg = ("%s skipped as Cinder is not available" % cls.__name__)
raise cls.skipException(skip_msg) | conditional_block |
test_volumes_get.py | # Copyright 2012 OpenStack Foundation
# All 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 requ... | (cls):
super(VolumesGetTestJSON, cls).skip_checks()
if not CONF.service_available.cinder:
skip_msg = ("%s skipped as Cinder is not available" % cls.__name__)
raise cls.skipException(skip_msg)
@classmethod
def setup_clients(cls):
super(VolumesGetTestJSON, cls).set... | skip_checks | identifier_name |
test_volumes_get.py | # Copyright 2012 OpenStack Foundation
# All 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 requ... | 'from the created Volume')
self.assertThat(fetched_volume['metadata'].items(),
matchers.ContainsAll(metadata.items()),
'The fetched Volume metadata misses data '
'from the created Volume') | 'from the created Volume')
self.assertEqual(volume['id'],
fetched_volume['id'],
'The fetched Volume is different ' | random_line_split |
test_volumes_get.py | # Copyright 2012 OpenStack Foundation
# All 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 requ... |
@classmethod
def setup_clients(cls):
super(VolumesGetTestJSON, cls).setup_clients()
cls.client = cls.volumes_extensions_client
@test.idempotent_id('f10f25eb-9775-4d9d-9cbe-1cf54dae9d5f')
def test_volume_create_get_delete(self):
# CREATE, GET, DELETE Volume
volume = Non... | super(VolumesGetTestJSON, cls).skip_checks()
if not CONF.service_available.cinder:
skip_msg = ("%s skipped as Cinder is not available" % cls.__name__)
raise cls.skipException(skip_msg) | identifier_body |
fetch.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
def load(refresh=False):
num_total_changes = 0
# When we are loading or reloading (refresh) don't let any other threads
# make changes to the object manager, we want consistent view.
with cfg.om.locked():
# Go through and load all the PVs, VGs and LVs
pvs, num_changes = load_pvs(refr... | random_line_split | |
fetch.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
return num_total_changes
| cfg.om.register_object(l, refresh) | conditional_block |
fetch.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | num_total_changes += num_changes
for l in lvs:
cfg.om.register_object(l, refresh)
return num_total_changes
| num_total_changes = 0
# When we are loading or reloading (refresh) don't let any other threads
# make changes to the object manager, we want consistent view.
with cfg.om.locked():
# Go through and load all the PVs, VGs and LVs
pvs, num_changes = load_pvs(refresh=refresh)
num_total_... | identifier_body |
fetch.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | (refresh=False):
num_total_changes = 0
# When we are loading or reloading (refresh) don't let any other threads
# make changes to the object manager, we want consistent view.
with cfg.om.locked():
# Go through and load all the PVs, VGs and LVs
pvs, num_changes = load_pvs(refresh=refre... | load | identifier_name |
loadingPoisFromApplicationModel.js | /* this is a dummy implementation to create poi-data, which are passed over to JS / Wikitude SDK on first location update */
function onLocationUpdated(position) {
// var latitude = position.coords.latitude;
// var longitude = position.coords.longitude;
// var altitude = position.coords.altitude;
// var placesAmoun... | }
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
} | random_line_split | |
loadingPoisFromApplicationModel.js |
/* this is a dummy implementation to create poi-data, which are passed over to JS / Wikitude SDK on first location update */
function | (position) {
// var latitude = position.coords.latitude;
// var longitude = position.coords.longitude;
// var altitude = position.coords.altitude;
// var placesAmount = 10;
// var poiData = [];
//
// // creates dummy poi-data around given lat/lon
// for (var i=0; i< placesAmount; i++) {
// poiData.push({ 'id'... | onLocationUpdated | identifier_name |
loadingPoisFromApplicationModel.js |
/* this is a dummy implementation to create poi-data, which are passed over to JS / Wikitude SDK on first location update */
function onLocationUpdated(position) |
function onLocationError(error) {
alert("Not able to fetch location.");
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
| {
// var latitude = position.coords.latitude;
// var longitude = position.coords.longitude;
// var altitude = position.coords.altitude;
// var placesAmount = 10;
// var poiData = [];
//
// // creates dummy poi-data around given lat/lon
// for (var i=0; i< placesAmount; i++) {
// poiData.push({ 'id': (i+1), 'l... | identifier_body |
embeddedCodeEditorWidget.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (e:IConfigurationChangedEvent): void {
super.updateOptions(this._parentEditor.getRawConfiguration());
super.updateOptions(this._overwriteOptions);
}
public updateOptions(newOptions:IEditorOptions): void {
objects.mixin(this._overwriteOptions, newOptions, true);
super.updateOptions(this._overwriteOptions);
}... | _onParentConfigurationChanged | identifier_name |
embeddedCodeEditorWidget.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public updateOptions(newOptions:IEditorOptions): void {
objects.mixin(this._overwriteOptions, newOptions, true);
super.updateOptions(this._overwriteOptions);
}
} | {
super.updateOptions(this._parentEditor.getRawConfiguration());
super.updateOptions(this._overwriteOptions);
} | identifier_body |
embeddedCodeEditorWidget.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | super.updateOptions(this._parentEditor.getRawConfiguration());
super.updateOptions(this._overwriteOptions);
}
public updateOptions(newOptions:IEditorOptions): void {
objects.mixin(this._overwriteOptions, newOptions, true);
super.updateOptions(this._overwriteOptions);
}
} |
this._lifetimeDispose.push(parentEditor.addListener2(EventType.ConfigurationChanged, (e:IConfigurationChangedEvent) => this._onParentConfigurationChanged(e)));
}
private _onParentConfigurationChanged(e:IConfigurationChangedEvent): void { | random_line_split |
channelmergernode.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT};
use crate::dom::baseaudiocontext::BaseAudioContext;
us... |
if options.numberOfInputs < 1 || options.numberOfInputs > MAX_CHANNEL_COUNT {
return Err(Error::IndexSize);
}
let node = AudioNode::new_inherited(
AudioNodeInit::ChannelMergerNode(options.into()),
context,
node_options,
options.numbe... | {
return Err(Error::InvalidState);
} | conditional_block |
channelmergernode.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT};
use crate::dom::baseaudiocontext::BaseAudioContext;
us... | if node_options.count != 1 || node_options.mode != ChannelCountMode::Explicit {
return Err(Error::InvalidState);
}
if options.numberOfInputs < 1 || options.numberOfInputs > MAX_CHANNEL_COUNT {
return Err(Error::IndexSize);
}
let node = AudioNode::new_inh... | ChannelCountMode::Explicit,
ChannelInterpretation::Speakers,
);
| random_line_split |
channelmergernode.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT};
use crate::dom::baseaudiocontext::BaseAudioContext;
us... | (options: &'a ChannelMergerOptions) -> Self {
Self {
channels: options.numberOfInputs as u8,
}
}
}
| from | identifier_name |
channelmergernode.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT};
use crate::dom::baseaudiocontext::BaseAudioContext;
us... |
}
| {
Self {
channels: options.numberOfInputs as u8,
}
} | identifier_body |
webpack.build.config.babel.js | // import webpack plugins
import {
DefinePlugin,
BannerPlugin,
optimize,
} from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
function | ({ paths, pkg, isLive, screwIE8 }) {
const banner = `${pkg.name} - ${pkg.version}\nMade with love by ${pkg.author}`;
if (isLive) {
console.log('Building for LIVE env...');
console.log(`Build root -> "${paths.liveBasePath}"`);
}
return {
// Define vendor entry point needed for splitting
entry: ... | makeConfig | identifier_name |
webpack.build.config.babel.js | // import webpack plugins
import {
DefinePlugin,
BannerPlugin,
optimize,
} from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
function makeConfig({ paths, pkg, isLive, screwIE8 }) | },
module: {
loaders: [
// Define CSS setup w/ ExtractTextPlugin
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', [
'css?camelCase&modules&importLoaders=1&' +
'localIdentName=[folder]--[local]---[emoji:1]',
'postcss?source... | {
const banner = `${pkg.name} - ${pkg.version}\nMade with love by ${pkg.author}`;
if (isLive) {
console.log('Building for LIVE env...');
console.log(`Build root -> "${paths.liveBasePath}"`);
}
return {
// Define vendor entry point needed for splitting
entry: {
// Exclude all node_modules... | identifier_body |
webpack.build.config.babel.js | // import webpack plugins
import {
DefinePlugin,
BannerPlugin,
optimize,
} from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
function makeConfig({ paths, pkg, isLive, screwIE8 }) {
const banner = `${pkg.name} - ${pkg.version}\nMa... | // Define vendor entry point needed for splitting
entry: {
// Exclude all node_modules that hasn't a package.json as main file for example alt-utils
// vendor: Object.keys(pkg.dependencies).filter((v) => v !== 'alt-utils'),
vendor: Object.keys(pkg.dependencies),
},
output: {
// p... | console.log('Building for LIVE env...');
console.log(`Build root -> "${paths.liveBasePath}"`);
}
return { | random_line_split |
webpack.build.config.babel.js | // import webpack plugins
import {
DefinePlugin,
BannerPlugin,
optimize,
} from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
function makeConfig({ paths, pkg, isLive, screwIE8 }) {
const banner = `${pkg.name} - ${pkg.version}\nMa... |
return {
// Define vendor entry point needed for splitting
entry: {
// Exclude all node_modules that hasn't a package.json as main file for example alt-utils
// vendor: Object.keys(pkg.dependencies).filter((v) => v !== 'alt-utils'),
vendor: Object.keys(pkg.dependencies),
},
output:... | {
console.log('Building for LIVE env...');
console.log(`Build root -> "${paths.liveBasePath}"`);
} | conditional_block |
datatypes.py | ## Python implementation of MBMA (Van den Bosch & Daelemans 1999)
## Copyright (C) 2011 Folgert Karsdorp
## Author: Folgert Karsdorp <fbkarsdorp@gmail.com>
## URL: <http://github.com/fbkarsdorp/mbmp>
## For licence information, see LICENCE.TXT
class Morpheme(object):
"""
A data class representing a m... | (self, mrepr='tokens-and-lemmas'):
"""
Return a string representation of the morpheme.
Args:
- mrepr: Choose a morpheme representation:
- tokens = token representation
- lemmas = lemma representation
- tokens-and-lemmas... | pprint | identifier_name |
datatypes.py |
## Copyright (C) 2011 Folgert Karsdorp
## Author: Folgert Karsdorp <fbkarsdorp@gmail.com>
## URL: <http://github.com/fbkarsdorp/mbmp>
## For licence information, see LICENCE.TXT
class Morpheme(object):
"""
A data class representing a morpheme. Each morpheme specifies
a token form, a lemma form an... | ## Python implementation of MBMA (Van den Bosch & Daelemans 1999)
| random_line_split | |
datatypes.py | ## Python implementation of MBMA (Van den Bosch & Daelemans 1999)
## Copyright (C) 2011 Folgert Karsdorp
## Author: Folgert Karsdorp <fbkarsdorp@gmail.com>
## URL: <http://github.com/fbkarsdorp/mbmp>
## For licence information, see LICENCE.TXT
class Morpheme(object):
| Morpheme(token='clapp', lemma='clapp', pos='V')
"""
self.token = token
self.pos = pos
self.lemma = lemma
# if lemma is not specified, default to token
if not self.lemma:
self.lemma = self.token
def __repr__(self):
return 'Mor... | """
A data class representing a morpheme. Each morpheme specifies
a token form, a lemma form and its part-of-speech tag.
"""
def __init__(self, token='', pos=None, lemma=''):
"""
Constructor.
Args:
- token (str): the token representation of a morpheme
... | identifier_body |
datatypes.py | ## Python implementation of MBMA (Van den Bosch & Daelemans 1999)
## Copyright (C) 2011 Folgert Karsdorp
## Author: Folgert Karsdorp <fbkarsdorp@gmail.com>
## URL: <http://github.com/fbkarsdorp/mbmp>
## For licence information, see LICENCE.TXT
class Morpheme(object):
"""
A data class representing a m... |
else:
leaf = self.token
elif mrepr == 'lemmas':
leaf = self.lemma
else:
leaf = self.token
return leaf
| leaf = '='.join([self.token, self.lemma]) | conditional_block |
sph_shabal.rs | extern crate libc;
use std::default::Default;
#[repr(C)]
pub struct sph_shabal_context {
pub buf: [u8; 64],
pub ptr: libc::size_t,
pub a: [u32; 12],
pub b: [u32; 16],
pub c: [u32; 16],
pub w_high: u32,
pub w_low: u32,
}
impl Default for sph_shabal_context {
fn default() -> sph_shabal_... | (input: &[u8]) -> [u8; 32] {
let mut output: [u8; 32] = [0; 32];
unsafe {
let mut shabal_ctx: sph_shabal_context = Default::default();
let shabal_ctx_ptr: *mut libc::c_void = &mut shabal_ctx as *mut _ as *mut libc::c_void;
sph_shabal256_init(shabal_ctx_ptr);
sph_shabal256(shabal_... | shabal256 | identifier_name |
sph_shabal.rs | extern crate libc;
use std::default::Default;
#[repr(C)]
pub struct sph_shabal_context {
pub buf: [u8; 64],
pub ptr: libc::size_t,
pub a: [u32; 12],
pub b: [u32; 16],
pub c: [u32; 16],
pub w_high: u32,
pub w_low: u32, |
impl Default for sph_shabal_context {
fn default() -> sph_shabal_context {
sph_shabal_context {
buf: [0u8; 64],
ptr: 0,
a: [0u32; 12],
b: [0u32; 16],
c: [0u32; 16],
w_high: 0,
w_low: 0,
}
}
}
pub fn shabal256(i... | } | random_line_split |
mod.rs | use super::ObjectSafetyViolation;
use crate::infer::InferCtxt;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{struct_span_err, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_span::{MultiSpan, Span};
use std::... |
}
let has_multi_span = !multi_span.is_empty();
let mut note_span = MultiSpan::from_spans(multi_span.clone());
if let (Some(trait_span), true) = (trait_span, has_multi_span) {
note_span
.push_span_label(trait_span, "this trait cannot be made into an object...".to_string());
}
... | {
let spans = violation.spans();
let msg = if trait_span.is_none() || spans.is_empty() {
format!("the trait cannot be made into an object because {}", violation.error_msg())
} else {
format!("...because {}", violation.error_msg())
};
... | conditional_block |
mod.rs | use super::ObjectSafetyViolation;
use crate::infer::InferCtxt;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{struct_span_err, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_span::{MultiSpan, Span};
use std::... | if let ObjectSafetyViolation::SizedSelf(sp) = &violation {
if !sp.is_empty() {
// Do not report `SizedSelf` without spans pointing at `SizedSelf` obligations
// with a `Span`.
reported_violations.insert(ObjectSafetyViolation::SizedSelf(vec![].into()));... | {
let trait_str = tcx.def_path_str(trait_def_id);
let trait_span = tcx.hir().get_if_local(trait_def_id).and_then(|node| match node {
hir::Node::Item(item) => Some(item.ident.span),
_ => None,
});
let span = tcx.sess.source_map().guess_head_span(span);
let mut err = struct_span_err!(
... | identifier_body |
mod.rs | use super::ObjectSafetyViolation;
use crate::infer::InferCtxt;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{struct_span_err, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_span::{MultiSpan, Span};
use std::... | }
}
}
let has_multi_span = !multi_span.is_empty();
let mut note_span = MultiSpan::from_spans(multi_span.clone());
if let (Some(trait_span), true) = (trait_span, has_multi_span) {
note_span
.push_span_label(trait_span, "this trait cannot be made into an object...".... | violation.solution(&mut err); | random_line_split |
mod.rs | use super::ObjectSafetyViolation;
use crate::infer::InferCtxt;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{struct_span_err, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_span::{MultiSpan, Span};
use std::... | (
&self,
error_span: Span,
item_name: Symbol,
_impl_item_def_id: DefId,
trait_item_def_id: DefId,
requirement: &dyn fmt::Display,
) -> DiagnosticBuilder<'tcx> {
let msg = "impl has stricter requirements than trait";
let sp = self.tcx.sess.source_map().... | report_extra_impl_obligation | identifier_name |
functions_e.js | ['radiobutton',['RadioButton',['../classsfg_1_1RadioButton.html#a28fd84cfce44c8974a75b4b611c71356',1,'sfg::RadioButton']]],
['radiobuttongroup',['RadioButtonGroup',['../classsfg_1_1RadioButtonGroup.html#a4390105cd61884e5827f9eec3ddb9f85',1,'sfg::RadioButtonGroup']]],
['range',['Range',['../classsfg_1_1Range.html#... | var searchData=
[ | random_line_split | |
defer.ts | import { Observable } from '../Observable';
import { SubscribableOrPromise } from '../types';
import { from } from './from'; // lol
import { empty } from './empty';
/**
* Creates an Observable that, on subscribe, calls an Observable factory to
* make an Observable for each new Observer.
*
* <span class="informal">... | input = observableFactory();
} catch (err) {
subscriber.error(err);
return undefined;
}
const source = input ? from(input) : empty();
return source.subscribe(subscriber);
});
} | return new Observable(subscriber => {
let input: SubscribableOrPromise<T> | void;
try { | random_line_split |
defer.ts | import { Observable } from '../Observable';
import { SubscribableOrPromise } from '../types';
import { from } from './from'; // lol
import { empty } from './empty';
/**
* Creates an Observable that, on subscribe, calls an Observable factory to
* make an Observable for each new Observer.
*
* <span class="informal">... | <T>(observableFactory: () => SubscribableOrPromise<T> | void): Observable<T> {
return new Observable(subscriber => {
let input: SubscribableOrPromise<T> | void;
try {
input = observableFactory();
} catch (err) {
subscriber.error(err);
return undefined;
}
const source = input ? fr... | defer | identifier_name |
defer.ts | import { Observable } from '../Observable';
import { SubscribableOrPromise } from '../types';
import { from } from './from'; // lol
import { empty } from './empty';
/**
* Creates an Observable that, on subscribe, calls an Observable factory to
* make an Observable for each new Observer.
*
* <span class="informal">... | {
return new Observable(subscriber => {
let input: SubscribableOrPromise<T> | void;
try {
input = observableFactory();
} catch (err) {
subscriber.error(err);
return undefined;
}
const source = input ? from(input) : empty();
return source.subscribe(subscriber);
});
} | identifier_body | |
build.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
"""
Build the `public` folders and setup languages
"""
import os, frappe, json, shutil, re
# from cssmin import cssmin
app_pat... | except ValueError, e:
print path
print 'JSON syntax error {0}'.format(str(e))
return build_maps
timestamps = {}
def pack(target, sources, no_compress, verbose):
from cStringIO import StringIO
outtype, outtxt = target.split(".")[-1], ''
jsm = JavascriptMinify()
for f in sources:
suffix = None
... | random_line_split | |
build.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
"""
Build the `public` folders and setup languages
"""
import os, frappe, json, shutil, re
# from cssmin import cssmin
app_pat... |
source_paths.append(s)
build_maps[target] = source_paths
except ValueError, e:
print path
print 'JSON syntax error {0}'.format(str(e))
return build_maps
timestamps = {}
def pack(target, sources, no_compress, verbose):
from cStringIO import StringIO
outtype, outtxt = target.split(".")... | s = os.path.join(app_path, source) | conditional_block |
build.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
"""
Build the `public` folders and setup languages
"""
import os, frappe, json, shutil, re
# from cssmin import cssmin
app_pat... |
def watch(no_compress):
"""watch and rebuild if necessary"""
setup()
import time
compile_less()
build(no_compress=True)
while True:
compile_less()
if files_dirty():
build(no_compress=True)
time.sleep(3)
def make_asset_dirs(make_copy=False):
assets_path = os.path.join(frappe.local.sites_path, "asse... | """concat / minify js files"""
# build js files
setup()
make_asset_dirs(make_copy=make_copy)
build(no_compress, verbose) | identifier_body |
build.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
"""
Build the `public` folders and setup languages
"""
import os, frappe, json, shutil, re
# from cssmin import cssmin
app_pat... | (path, content):
'''returns HTML template content as Javascript code, adding it to `frappe.templates`'''
return """frappe.templates["{key}"] = '{content}';\n""".format(\
key=path.rsplit("/", 1)[-1][:-5], content=scrub_html_template(content))
def scrub_html_template(content):
'''Returns HTML content with removed w... | html_to_js_template | identifier_name |
tree-box.js | /* jshint node: true, esnext: true */
'use strict';
var React = require('react');
var modes = require('js-git/lib/modes');
var BlobBox = require('./blob-box');
var TreeBox = React.createClass({
getInitialState : function () {
return this._getState();
},
componentDidMount: function() {
this.props.obje... |
}));
},
_displayChildren : function (child) {
this.props.dispatch({ action : 'PATH_DISPLAYED', path : this.props.path, child });
},
_hideChildren : function (child) {
this.props.dispatch({ action : 'PATH_HIDDEN', path : this.props.path, child });
}
});
module.exports = TreeBox;
| {
return React.DOM.li({ key : child, onClick : this._displayChildren.bind(this, child) }, '+ ' + child);
} | conditional_block |
tree-box.js | /* jshint node: true, esnext: true */
'use strict';
var React = require('react');
var modes = require('js-git/lib/modes');
var BlobBox = require('./blob-box');
var TreeBox = React.createClass({
getInitialState : function () {
return this._getState();
},
componentDidMount: function() {
this.props.obje... | _displayChildren : function (child) {
this.props.dispatch({ action : 'PATH_DISPLAYED', path : this.props.path, child });
},
_hideChildren : function (child) {
this.props.dispatch({ action : 'PATH_HIDDEN', path : this.props.path, child });
}
});
module.exports = TreeBox; | return React.DOM.li({ key : child, onClick : this._displayChildren.bind(this, child) }, '+ ' + child);
}
}));
},
| random_line_split |
main.py | (line)
self.save()
def learn(self, line):
line = line.strip()
words = line.split(' ')
words = [self.sanitize(word) for word in words]
for i in range(len(words) - 2):
prefix = words[i], words[i + 1]
follow = words[i + 2]
self.brain.add(pref... |
def handle_invite(self, room_id, invite_state):
# join rooms if invited
try:
self.client.join_room(room_id)
logging.info('Joined room: %s' % room_id)
except MatrixRequestError as e:
if e.code == 404:
# room was deleted after invite or som... | """Returns whether the message contains the bot's name.
Considers both display name and username.
"""
regex = "({}|{})".format(
self.config.display_name, self.config.username)
return re.search(regex, message, flags=re.IGNORECASE) | identifier_body |
main.py | (self, brain_file):
self.brain = MarkovDatabaseBrain(brain_file)
def sanitize(self, word):
"""Removes any awkward whitespace characters from the given word.
Removes '\n', '\r', and '\\u2028' (unicode newline character)."""
return word.replace('\n', '').replace('\r', '').replace('\u... | __init__ | identifier_name | |
main.py | '!rate'
]
def sigterm_handler(_signo, _stack_frame):
"""Raises SystemExit(0), causing everything to cleanly shut down."""
sys.exit(0)
class ConfigParser(ConfigParser):
# allow case-sensitive option names
# needed for saving per-room response rates
optionxform = str
class Backend(object):
... | import queue
import codecs
from database import MarkovDatabaseBrain
COMMANDS = [ | random_line_split | |
main.py | (line)
self.save()
def learn(self, line):
line = line.strip()
words = line.split(' ')
words = [self.sanitize(word) for word in words]
for i in range(len(words) - 2):
prefix = words[i], words[i + 1]
follow = words[i + 2]
self.brain.add(pref... |
num = random.randint(1, total)
total = 0
for p in possibilities:
total += possibilities[p]
if total >= num:
break
return p
def reply(self, message):
if self.brain.is_empty():
return ''
seed = None
# try t... | total += possibilities[p] | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.