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 |
|---|---|---|---|---|
url.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/. */
//! Common handling for the specified value CSS url() values.
use cssparser::CssStringWriter;
use gecko_bindings:... |
/// Returns true if the URL is definitely invalid. We don't eagerly resolve
/// URLs in gecko, so we just return false here.
/// use its |resolved| status.
pub fn is_invalid(&self) -> bool {
false
}
/// Returns true if this URL looks like a fragment.
/// See https://drafts.csswg.o... | {
Ok(SpecifiedUrl {
serialization: Arc::new(url.into_owned()),
extra_data: context.url_data.clone(),
})
} | identifier_body |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | assert!(non_intersection.is_none());
non_intersecting_ray = Ray::new(Vec3 { x: 0.0, y: 0.0, z: -2.0 }, Vec3 { x: -100.0, y: -100.0, z: 0.1 });
non_intersection = sphere.intersects(&non_intersecting_ray, 0.0, 10.0);
assert!(non_intersection.is_none());
// Ray in opposite direction
non_intersect... | {
let sphere = Sphere {
center: Vec3::zero(),
radius: 1.0,
material: Box::new(FlatMaterial { color: Vec3::one() })
};
// Tests actual intersection
let intersecting_ray = Ray::new(Vec3 { x: 0.0, y: 0.0, z: -2.0 }, Vec3 { x: 0.0, y: 0.0, z: 1.0 });
let intersection = sphere.in... | identifier_body |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | ;
let intersection_point = ray.origin + ray.direction.scale(t);
let n = (intersection_point - self.center).unit();
let u = 0.5 + n.z.atan2(n.x) / (::std::f64::consts::PI * 2.0);
let v = 0.5 - n.y.asin() / ::std::f64::consts::PI;
Some(Inte... | { t2 } | conditional_block |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | })
} else {
None
}
}
}
fn mut_transform(&mut self, transform: &Transform) {
let new_center = Mat4::mult_p(&transform.m, &self.center);
let new_radius = if transform.m.has_scale() {
self.radius * transform.m.scale()
... | u: u,
v: v,
position: intersection_point,
material: &self.material | random_line_split |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | (&self) -> Option<BBox> {
Some(BBox {
min: Vec3 {
x: self.center.x - self.radius,
y: self.center.y - self.radius,
z: self.center.z - self.radius
},
max: Vec3 {
x: self.center.x + self.radius,
y: s... | partial_bounding_box | identifier_name |
CustomRenderer.py | import sys
import wx
import wx.dataview as dv
#import os; print('PID:'+str(os.getpid())); raw_input("Press enter...")
#----------------------------------------------------------------------
class MyCustomRenderer(dv.DataViewCustomRenderer):
def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.... | | dv.DV_MULTIPLE
)
# Create an instance of the model
if model is None:
self.model = TestModel(data, log)
else:
self.model = model
self.dvc.AssociateModel(self.model)
... | | dv.DV_VERT_RULES | random_line_split |
CustomRenderer.py | import sys
import wx
import wx.dataview as dv
#import os; print('PID:'+str(os.getpid())); raw_input("Press enter...")
#----------------------------------------------------------------------
class MyCustomRenderer(dv.DataViewCustomRenderer):
| size = self.GetTextExtent(value)
return size
def Render(self, rect, dc, state):
if state != 0:
self.log.write('Render: %s, %d\n' % (rect, state))
if not state & dv.DATAVIEW_CELL_SELECTED:
# we'll draw a shaded background to see if the rect correctly
... | def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.__init__(self, *args, **kw)
self.log = log
self.value = None
def SetValue(self, value):
#self.log.write('MyCustomRenderer.SetValue: %s\n' % value)
self.value = value
return True
def GetValue(self):
... | identifier_body |
CustomRenderer.py | import sys
import wx
import wx.dataview as dv
#import os; print('PID:'+str(os.getpid())); raw_input("Press enter...")
#----------------------------------------------------------------------
class MyCustomRenderer(dv.DataViewCustomRenderer):
def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.... |
#----------------------------------------------------------------------
| main() | conditional_block |
CustomRenderer.py | import sys
import wx
import wx.dataview as dv
#import os; print('PID:'+str(os.getpid())); raw_input("Press enter...")
#----------------------------------------------------------------------
class MyCustomRenderer(dv.DataViewCustomRenderer):
def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.... | (self, cellRect, model, item, col):
self.log.write('Activate')
return False
#----------------------------------------------------------------------
# To help focus this sample on the custom renderer, we'll reuse the
# model class from another sample.
from IndexListModel import TestModel
class Test... | Activate | identifier_name |
ProductsView.js | Ti.include(Titanium.Filesystem.resourcesDirectory + "constants/appConstants.js");
var styles = require('globals').Styles;
var globals = require('globals').Globals;
function createProductView(context, product, position) {
/*
* Product View
*/
var view = Ti.UI.createView({
height : Ti.UI.SIZE,
bottom : 7 * dp,... | width : Ti.Platform.displayCaps.platformWidth,
backgroundColor : '#343434'
});
OuterView.add(divider);
row = Titanium.UI.createView({
backgroundSelectedColor : 'transparent',
height : Ti.UI.SIZE
});
} else {
//_left = (Ti.Platform.displayCaps.platformWidth / 2) + (7 * dp);
_left = (... | {
var row;
var _left = 7 * dp;
for (var i = 0; i < Products.length; i++) {
var view1 = createProductView(context, Products[i], {
left : _left
});
if (i == 0) {
row = Titanium.UI.createView({
backgroundSelectedColor : 'transparent',
height : Ti.UI.SIZE
});
}
row.add(view1);
if (((i - 1) %... | identifier_body |
ProductsView.js | Ti.include(Titanium.Filesystem.resourcesDirectory + "constants/appConstants.js");
var styles = require('globals').Styles;
var globals = require('globals').Globals;
function createProductView(context, product, position) {
/*
* Product View
*/
var view = Ti.UI.createView({
height : Ti.UI.SIZE,
bottom : 7 * dp,... | (context, Products) {
var scroll = Ti.UI.createScrollView({
height : 'auto',
top : 48 * dp,
width : Ti.Platform.displayCaps.platformWidth,
backgroundColor : 'transparent'
});
var OuterView = Ti.UI.createView({
height : 'auto',
layout : 'vertical',
width : Ti.Platform.displayCaps.platformWidth,
backg... | createScroll | identifier_name |
ProductsView.js | Ti.include(Titanium.Filesystem.resourcesDirectory + "constants/appConstants.js");
var styles = require('globals').Styles;
var globals = require('globals').Globals;
function createProductView(context, product, position) { | * Product View
*/
var view = Ti.UI.createView({
height : Ti.UI.SIZE,
bottom : 7 * dp,
top : 7 * dp,
left : position.left,
backgroundSelectedColor : styles.home_button.selectedBackgroundColor,
//width : (Ti.Platform.displayCaps.platformWidth - (42 * dp)) / 2,
width : (Ti.Platform.displayCaps.platformW... | /* | random_line_split |
ProductsView.js | Ti.include(Titanium.Filesystem.resourcesDirectory + "constants/appConstants.js");
var styles = require('globals').Styles;
var globals = require('globals').Globals;
function createProductView(context, product, position) {
/*
* Product View
*/
var view = Ti.UI.createView({
height : Ti.UI.SIZE,
bottom : 7 * dp,... | OuterView.add(divider);
row = Titanium.UI.createView({
backgroundSelectedColor : 'transparent',
height : Ti.UI.SIZE
});
} else {
//_left = (Ti.Platform.displayCaps.platformWidth / 2) + (7 * dp);
_left = (Ti.Platform.displayCaps.platformWidth / 2);
}
}
}
function createScroll(context, Prod... | {
var view1 = createProductView(context, Products[i], {
left : _left
});
if (i == 0) {
row = Titanium.UI.createView({
backgroundSelectedColor : 'transparent',
height : Ti.UI.SIZE
});
}
row.add(view1);
if (((i - 1) % 2 == 0) || (i == Products.length - 1)) {
_left = 7 * dp;
OuterView.ad... | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
mod errors;
use std::collections::HashSet;
use std::fmt;
use abomonation_derive::Abomonation;
use anyhow::Result;
use async_trait::async_... | {
Draft,
Public,
}
impl fmt::Display for Phase {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Phase::Draft => write!(f, "Draft"),
Phase::Public => write!(f, "Public"),
}
}
}
impl From<Phase> for u32 {
fn from(phase: Phase) -> u32 {
... | Phase | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
mod errors;
use std::collections::HashSet;
use std::fmt;
use abomonation_derive::Abomonation;
use anyhow::Result;
use async_trait::async_... | }
/// Phases tracks which commits are public, and which commits are draft.
///
/// A commit ordinarily becomes public when it is reachable from any
/// publishing bookmark. Once public, it never becomes draft again, even
/// if the public bookmark is deleted or moved elsewhere.
#[facet::facet]
#[async_trait]
pub trai... | 1 => Ok(Phase::Draft),
_ => Err(PhasesError::EnumError(phase_as_int)),
}
} | random_line_split |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
mod errors;
use std::collections::HashSet;
use std::fmt;
use abomonation_derive::Abomonation;
use anyhow::Result;
use async_trait::async_... |
}
impl From<Phase> for u32 {
fn from(phase: Phase) -> u32 {
match phase {
Phase::Public => 0,
Phase::Draft => 1,
}
}
}
impl TryFrom<u32> for Phase {
type Error = PhasesError;
fn try_from(phase_as_int: u32) -> Result<Phase, Self::Error> {
match phase_as... | {
match self {
Phase::Draft => write!(f, "Draft"),
Phase::Public => write!(f, "Public"),
}
} | identifier_body |
ticks.ts | import {
CountableTimeInterval,
timeMillisecond,
utcMillisecond,
timeSecond,
utcSecond,
timeMinute,
utcMinute,
timeHour,
utcHour,
timeWeek,
utcWeek,
timeSunday,
utcSunday,
timeMonday,
utcMonday,
timeTuesday,
utcTuesday,
timeWednesday,
utcWednes... |
// Set range to include last day in the domain since `interval.range` function is exclusive stop
stop.setDate(stop.getDate() + 1)
return timeType.every(Number(amount ?? 1))?.range(start, stop) ?? []
}
if (amount === undefined) {
... | const stop = new Date(originalStop) | random_line_split |
ticks.ts | import {
CountableTimeInterval,
timeMillisecond,
utcMillisecond,
timeSecond,
utcSecond,
timeMinute,
utcMinute,
timeHour,
utcHour,
timeWeek,
utcWeek,
timeSunday,
utcSunday,
timeMonday,
utcMonday,
timeTuesday,
utcTuesday,
timeWednesday,
utcWednes... |
if (typeof spec === 'string' && 'useUTC' in scale) {
// time interval
const matches = spec.match(timeIntervalRegexp)
if (matches) {
const [, amount, type] = matches
// UTC is used as it's more predictable
// however local time could be used too
... | {
return spec
} | conditional_block |
test_views.py | from .base import BasePageTests
from django.contrib.sites.models import Site
from django.contrib.redirects.models import Redirect
class PageViewTests(BasePageTests):
def test_page_view(self):
r = self.client.get('/one/')
self.assertEqual(r.context['page'], self.p1)
# drafts are available... | )
response = self.client.get(redirect.old_path)
self.assertEqual(response.status_code, 301)
self.assertEqual(response['Location'], redirect.new_path)
redirect.delete() | random_line_split | |
test_views.py | from .base import BasePageTests
from django.contrib.sites.models import Site
from django.contrib.redirects.models import Redirect
class | (BasePageTests):
def test_page_view(self):
r = self.client.get('/one/')
self.assertEqual(r.context['page'], self.p1)
# drafts are available only to staff users
self.p1.is_published = False
self.p1.save()
r = self.client.get('/one/')
self.assertEqual(r.status_... | PageViewTests | identifier_name |
test_views.py | from .base import BasePageTests
from django.contrib.sites.models import Site
from django.contrib.redirects.models import Redirect
class PageViewTests(BasePageTests):
| Check that redirects still have priority over pages.
"""
redirect = Redirect.objects.create(
old_path='/%s/' % self.p1.path,
new_path='http://redirected.example.com',
site=Site.objects.get_current()
)
response = self.client.get(redirect.old_pat... | def test_page_view(self):
r = self.client.get('/one/')
self.assertEqual(r.context['page'], self.p1)
# drafts are available only to staff users
self.p1.is_published = False
self.p1.save()
r = self.client.get('/one/')
self.assertEqual(r.status_code, 404)
s... | identifier_body |
lib.rs | use std::cmp::PartialEq;
#[derive(Debug, Clone)]
pub struct CustomSet<T> {
elems: Vec<T>,
}
impl<T> PartialEq for CustomSet<T>
where T: PartialEq + Clone + Copy
{
fn eq(&self, other: &CustomSet<T>) -> bool {
self.elems.len() == other.elems.len() &&
self.elems.iter().map(|e| other.contains(... |
pub fn is_disjoint(&self, set: &CustomSet<T>) -> bool {
if self.elems.is_empty() {
true
} else {
self.elems.iter().map(|e| !set.contains(e)).all(|x| x)
}
}
pub fn add(&mut self, elem: T) {
if !self.elems.contains(&elem) {
self.elems.push... |
} | random_line_split |
lib.rs |
use std::cmp::PartialEq;
#[derive(Debug, Clone)]
pub struct CustomSet<T> {
elems: Vec<T>,
}
impl<T> PartialEq for CustomSet<T>
where T: PartialEq + Clone + Copy
{
fn eq(&self, other: &CustomSet<T>) -> bool {
self.elems.len() == other.elems.len() &&
self.elems.iter().map(|e| other.contains... |
}
pub fn is_disjoint(&self, set: &CustomSet<T>) -> bool {
if self.elems.is_empty() {
true
} else {
self.elems.iter().map(|e| !set.contains(e)).all(|x| x)
}
}
pub fn add(&mut self, elem: T) {
if !self.elems.contains(&elem) {
self.el... | {
self.elems.iter().map(|e| set.contains(e)).all(|x| x)
} | conditional_block |
lib.rs |
use std::cmp::PartialEq;
#[derive(Debug, Clone)]
pub struct CustomSet<T> {
elems: Vec<T>,
}
impl<T> PartialEq for CustomSet<T>
where T: PartialEq + Clone + Copy
{
fn eq(&self, other: &CustomSet<T>) -> bool {
self.elems.len() == other.elems.len() &&
self.elems.iter().map(|e| other.contains... | (&self, other: &CustomSet<T>) -> Self {
self.elems.iter().chain(other.elems.iter()).fold(CustomSet::new(vec![]), |mut acc, val| {
acc.add(*val);
acc
})
}
}
| union | identifier_name |
DashboardActions.tsx | import React, { FC, useState } from 'react';
import { HorizontalGroup, LinkButton, Form , Field,Input, Button} from 'src/packages/datav-core/src/ui';
import { config, getHistory} from 'src/packages/datav-core/src';
import { Modal, message } from 'antd';
import { getBackendSrv } from 'src/core/services/backend/backend'... |
};
return (
<>
<HorizontalGroup spacing="md" align="center">
{/* {canEdit && <LinkButton href={actionUrl('new')}>New Dashboard</LinkButton>} */}
{!folderId && isEditor && <LinkButton onClick={() => setNewFolderVisible(true)}><FormattedMessage id="folder.add"/></LinkButton>}
{/* {canEdit &... | {
return true
} | conditional_block |
DashboardActions.tsx | import React, { FC, useState } from 'react';
import { HorizontalGroup, LinkButton, Form , Field,Input, Button} from 'src/packages/datav-core/src/ui';
import { config, getHistory} from 'src/packages/datav-core/src';
import { Modal, message } from 'antd';
import { getBackendSrv } from 'src/core/services/backend/backend'... | return `Cannot use 'General' as folder name`
}
const res = await getBackendSrv().get('/api/folder/checkExistByName',{name: name})
if (res.data == -1) {
return true
}
};
return (
<>
<HorizontalGroup spacing="md" align="center">
{/* {canEdit && <LinkButton href={actionUrl('n... | if (name.toLowerCase() === config.rootFolderName.toLowerCase()) { | random_line_split |
command.py | # -*- Mode: Python; tab-width: 4 -*-
# Copyright (c) 2005-2010 Slide, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyrig... |
def setsockopt(self, level, option, value):
return self.connection.setsockopt(level, option, value)
def getsockopt(self, level, option):
return self.connection.getsockopt(level, option)
def fileno(self):
return self.connection.fileno()
#
# end...
| return self.connection.gettimeout() | identifier_body |
command.py | # -*- Mode: Python; tab-width: 4 -*-
# Copyright (c) 2005-2010 Slide, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyrig... | (self):
return len(self._recv_data)
def read_command(self):
while not self._recv_size or self._recv_size > len(self._recv_data):
try:
partial = self.connection.recv(COMMAND_READ_SIZE)
except socket.error, e:
if e[0] == errno.EINTR:
... | recv_size | identifier_name |
command.py | # -*- Mode: Python; tab-width: 4 -*-
# Copyright (c) 2005-2010 Slide, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyrig... |
result = self.serializer.deserialize(self._recv_data[:self._recv_size])
self._recv_data = self._recv_data[self._recv_size:]
if len(self._recv_data) < 4:
self._recv_size = 0
else:
self._recv_size = struct.unpack('!i', self._recv_data[:4])[0]
self._re... | self._recv_size = struct.unpack('!i', self._recv_data[:4])[0]
self._recv_data = self._recv_data[4:] | conditional_block |
command.py | # -*- Mode: Python; tab-width: 4 -*-
# Copyright (c) 2005-2010 Slide, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyrig... | import select
import struct
import errno
import message
COMMAND_READ_SIZE = 32*1024
class ConnectionError(RuntimeError):
pass
class ReadWriter(object):
def __init__(self, connection, **kwargs):
self.connection = connection
self._recv_data = ''
self._recv_size = 0
self._send_d... | random_line_split | |
OverDropMode.js | /*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.mdnd.dropMode.OverDropMode"]){
dojo._hasResource["dojox.mdnd.dropMode.OverDropMode"]=true;
doj... |
return _3;
},updateAreas:function(_7){
var _8=_7.length;
for(var i=0;i<_8;i++){
this._updateArea(_7[i]);
}
},_updateArea:function(_9){
var _a=dojo.position(_9.node,true);
_9.coords.x=_a.x;
_9.coords.x2=_a.x+_a.w;
_9.coords.y=_a.y;
},initItems:function(_b){
dojo.forEach(_b.items,function(_c){
var _d=_c.item.node;
var _... | {
var x=_4.coords.x;
for(var i=0;i<_5;i++){
if(x<_3[i].coords.x){
for(var j=_5-1;j>=i;j--){
_3[j+1]=_3[j];
}
_3[i]=_4;
break;
}
}
if(i==_5){
_3.push(_4);
}
} | conditional_block |
OverDropMode.js | /*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.mdnd.dropMode.OverDropMode"]){
dojo._hasResource["dojox.mdnd.dropMode.OverDropMode"]=true;
doj... | var x=_1a.x;
var y=_1a.y;
var end=_19.length;
var _1d=0,_1e="right",_1f=false;
if(_1b==-1||arguments.length<3){
_1f=true;
}else{
if(this._checkInterval(_19,_1b,x,y)){
_1c=_1b;
}else{
if(this._oldXPoint<x){
_1d=_1b+1;
}else{
_1d=_1b-1;
end=0;
_1e="left";
}
_1f=true;
}
}
if(_1f){
if(_1e==="right"){
for(var i=_1d;i<end;i+... | },getDragPoint:function(_16,_17,_18){
return {"x":_18.x,"y":_18.y};
},getTargetArea:function(_19,_1a,_1b){
var _1c=0; | random_line_split |
setup.py | from setuptools import setup
from os import path, environ
from sys import argv
here = path.abspath(path.dirname(__file__))
try:
if argv[1] == "test":
environ['PYTHONPATH'] = here
except IndexError:
pass
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read() | description='Library Filesystem',
long_description=long_description,
author='Christof Hanke',
author_email='christof.hanke@induhviduals.de',
url='https://github.com/ya-induhvidual/libfs',
packages=['Libfs'],
license='MIT',
install_requires=['llfuse', 'mutagenx'],
test_suite="test/tes... |
setup(
name='libfs',
version='0.1', | random_line_split |
setup.py | from setuptools import setup
from os import path, environ
from sys import argv
here = path.abspath(path.dirname(__file__))
try:
if argv[1] == "test":
|
except IndexError:
pass
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='libfs',
version='0.1',
description='Library Filesystem',
long_description=long_description,
author='Christof Hanke',
author_email='christof.hanke@induhvidu... | environ['PYTHONPATH'] = here | conditional_block |
CircuitAdminPanel.tsx | import { BooleanLike } from "common/react";
import { useBackend } from "../backend";
import { Button, Table } from "../components";
import { Window } from "../layouts";
type CircuitAdminPanelData = {
circuits: {
ref: string;
name: string;
creator: string;
has_inserter: BooleanLike;
}[]
}
export co... | Player Panel
</Button>
)}
</Table.Cell>
</Table.Row>
);
})}
</Table>
</Window.Content>
</Window>
);
}; | random_line_split | |
PrintCommand.ts | import { LineResults } from "../LineResults";
import { CommandNames } from "../Names/CommandNames";
import { Command } from "./Command";
import { CommandMetadata } from "./Metadata/CommandMetadata";
import { SingleParameter } from "./Metadata/Parameters/SingleParameter";
/**
* Prints a string.
*/
export class PrintC... | * @param parameters The command's name, followed by any parameters.
* @returns Line(s) of code in the language.
*/
public render(parameters: string[]): LineResults {
let line = "";
line += this.language.syntax.printing.start;
if (parameters.length > 1) {
line +... |
/**
* Renders the command for a language with the given parameters.
* | random_line_split |
PrintCommand.ts | import { LineResults } from "../LineResults";
import { CommandNames } from "../Names/CommandNames";
import { Command } from "./Command";
import { CommandMetadata } from "./Metadata/CommandMetadata";
import { SingleParameter } from "./Metadata/Parameters/SingleParameter";
/**
* Prints a string.
*/
export class PrintC... |
line += this.language.syntax.printing.end;
return LineResults.newSingleLine(line)
.withAddSemicolon(true)
.withImports(this.language.syntax.printing.requiredImports);
}
}
| {
line += parameters[1];
} | conditional_block |
PrintCommand.ts | import { LineResults } from "../LineResults";
import { CommandNames } from "../Names/CommandNames";
import { Command } from "./Command";
import { CommandMetadata } from "./Metadata/CommandMetadata";
import { SingleParameter } from "./Metadata/Parameters/SingleParameter";
/**
* Prints a string.
*/
export class | extends Command {
/**
* Metadata on the command.
*/
private static metadata: CommandMetadata = new CommandMetadata(CommandNames.Print)
.withDescription("Prints a string")
.withParameters([new SingleParameter("contents", "Contents to be printed.", false)]);
/**
* @returns Met... | PrintCommand | identifier_name |
enemies.py | # -*- coding: utf-8 -*-
# File: enemy.py
# Author: Casey Jones
#
# Created on July 20, 2009, 4:48 PM
#
# This file is part of Alpha Beta Gamma (abg).
#
# ABG 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, ... | self.screen = screen
def create(self):
#range that the current player ship can shoot
where_spawn = random.randint(1, properties.width - Enemy.enemy.get_width())
lenemy = Enemy(where_spawn)
self.enemies.append(lenemy)
def move(self, bullet):
to_updat... |
def set_screen(self, screen): | random_line_split |
enemies.py | # -*- coding: utf-8 -*-
# File: enemy.py
# Author: Casey Jones
#
# Created on July 20, 2009, 4:48 PM
#
# This file is part of Alpha Beta Gamma (abg).
#
# ABG 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, ... | (self, index):
try:
to_update = self.enemies[index].enemyrect
self.screen.blit(self.blackSurface, self.enemies[index].enemyrect)
del self.enemies[index]
return to_update
except IndexError:
print("IndexError for enemy {0} of {1}".format(index, l... | remove | identifier_name |
enemies.py | # -*- coding: utf-8 -*-
# File: enemy.py
# Author: Casey Jones
#
# Created on July 20, 2009, 4:48 PM
#
# This file is part of Alpha Beta Gamma (abg).
#
# ABG 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, ... |
to_delete = []
to_update += [x.enemyrect for x in self.enemies]
if len(self.enemies) > 0:
for i in range(len(self.enemies)):
self.enemies[i].update(bullet)
self.screen.blit(self.blackSurface, self.enemies[i].enemyrect)
... | self.create() | conditional_block |
enemies.py | # -*- coding: utf-8 -*-
# File: enemy.py
# Author: Casey Jones
#
# Created on July 20, 2009, 4:48 PM
#
# This file is part of Alpha Beta Gamma (abg).
#
# ABG 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, ... | to_update += [x.enemyrect for x in self.enemies]
return to_update
def getEnemies(self):
return self.enemies
def remove(self, index):
try:
to_update = self.enemies[index].enemyrect
self.screen.blit(self.blackSurface, self.enemies[index].e... | to_update = []
if frametime.can_create_enemy():
self.create()
to_delete = []
to_update += [x.enemyrect for x in self.enemies]
if len(self.enemies) > 0:
for i in range(len(self.enemies)):
self.enemies[i].update(bullet)
... | identifier_body |
linkbox.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# 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 2 of the License, or
# (at you... | (self, link, button):
GObject.GObject.__init__(self)
self.set_spacing(6)
self.pack_start(link, False, True, 0)
if button:
self.pack_start(button, False, True, 0)
self.show()
| __init__ | identifier_name |
linkbox.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# 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 2 of the License, or
# (at you... | GObject.GObject.__init__(self)
self.set_spacing(6)
self.pack_start(link, False, True, 0)
if button:
self.pack_start(button, False, True, 0)
self.show() | identifier_body | |
linkbox.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# 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 2 of the License, or
# (at you... | #
# $Id$
__all__ = ["LinkBox"]
#-------------------------------------------------------------------------
#
# Standard python modules
#
#-------------------------------------------------------------------------
import logging
_LOG = logging.getLogger(".widgets.linkbox")
#--------------------------------------------... | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | random_line_split |
linkbox.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# 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 2 of the License, or
# (at you... |
self.show()
| self.pack_start(button, False, True, 0) | conditional_block |
ChatTwoTone.js | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime"; | }, "0"), /*#__PURE__*/_jsx("path", {
d: "M20 18c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14zm-16-.83V4h16v12H5.17L4 17.17zM6 12h8v2H6zm0-3h12v2H6zm0-3h12v2H6z"
}, "1")], 'ChatTwoTone'); | export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M20 4H4v13.17L5.17 16H20V4zm-6 10H6v-2h8v2zm4-3H6V9h12v2zm0-3H6V6h12v2z",
opacity: ".3" | random_line_split |
netsuite-test.js | /* eslint-env mocha */
'use strict'
const path = require('path')
const cwd = process.cwd()
const NetSuite = require(path.join(cwd, 'netsuite'))
const chai = require('chai') | const config = require('config')
describe('NetSuite class', function () {
this.timeout(24 * 60 * 60 * 1000)
it('should export a function', function () {
expect(NetSuite).to.be.a('function')
expect(new NetSuite({})).to.be.a('object')
})
it('should search and searchMoreWithId', async function () {
le... | const expect = chai.expect
| random_line_split |
green-bean-information.component.ts | import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ModalController} from '@ionic/angular';
import {UIBeanHelper} from '../../services/uiBeanHelper';
import {GreenBean} from '../../classes/green-bean/green-bean';
import {GreenBeanPopoverActionsComponent} from '../../app/r... |
public async repeatBean() {
this.uiAnalytics.trackEvent(GREEN_BEAN_TRACKING.TITLE, GREEN_BEAN_TRACKING.ACTIONS.REPEAT);
await this.uiGreenBeanHelper.repeatGreenBean(this.greenBean);
}
private async __deleteBean() {
const brews: Array<Brew> = this.uiBrewStorage.getAllEntries();
const relatedRoa... | {
return new Promise(async (resolve,reject) => {
this.uiAlert.showConfirm('DELETE_GREEN_BEAN_QUESTION', 'SURE_QUESTION', true)
.then(async () => {
await this.uiAlert.showLoadingSpinner();
// Yes
this.uiAnalytics.trackEvent(GREEN_BEAN_TRACKING.TITLE, GREEN_BEAN_TRACK... | identifier_body |
green-bean-information.component.ts | import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ModalController} from '@ionic/angular';
import {UIBeanHelper} from '../../services/uiBeanHelper';
import {GreenBean} from '../../classes/green-bean/green-bean';
import {GreenBeanPopoverActionsComponent} from '../../app/r... |
},250);
}
public daysOld(): number {
return this.greenBean.beanAgeInDays();
}
public async showGreenBean() {
await this.detailBean();
}
public async showBeanActions(event): Promise<void> {
event.stopPropagation();
event.stopImmediatePropagation();
this.uiAnalytics.trackEvent... | {
this.greenBeanRating.setRating(this.greenBean.rating);
} | conditional_block |
green-bean-information.component.ts | import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ModalController} from '@ionic/angular';
import {UIBeanHelper} from '../../services/uiBeanHelper';
import {GreenBean} from '../../classes/green-bean/green-bean';
import {GreenBeanPopoverActionsComponent} from '../../app/r... | try{
await this.deleteBean();
}catch(ex){}
await this.uiAlert.hideLoadingSpinner();
break;
case GREEN_BEAN_ACTION.BEANS_CONSUMED:
await this.beansConsumed();
break;
case GREEN_BEAN_ACTION.PHOTO_GALLERY:
await this.viewPhotos();
break;... | case GREEN_BEAN_ACTION.DELETE:
| random_line_split |
green-bean-information.component.ts | import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ModalController} from '@ionic/angular';
import {UIBeanHelper} from '../../services/uiBeanHelper';
import {GreenBean} from '../../classes/green-bean/green-bean';
import {GreenBeanPopoverActionsComponent} from '../../app/r... | () {
this.uiAnalytics.trackEvent(GREEN_BEAN_TRACKING.TITLE, GREEN_BEAN_TRACKING.ACTIONS.ARCHIVE);
this.greenBean.finished = true;
await this.uiGreenBeanStorage.update(this.greenBean);
this.uiToast.showInfoToast('TOAST_GREEN_BEAN_ARCHIVED_SUCCESSFULLY');
await this.resetSettings();
}
private asy... | beansConsumed | identifier_name |
issue-31424.rs | // Copyright 2016 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-MIT or ... | () {}
| main | identifier_name |
issue-31424.rs | // Copyright 2016 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-MIT or ... | {} | identifier_body | |
issue-31424.rs | // Copyright 2016 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-MIT or ... | (&mut self).bar(); //~ ERROR cannot borrow
}
}
fn main () {} | // In this case we could keep the suggestion, but to distinguish the
// two cases is pretty hard. It's an obscure case anyway.
fn bar(self: &mut Self) {
//~^ WARN function cannot return without recursing | random_line_split |
karma.conf.js | // Karma configuration
// Generated on Wed Feb 17 2016 10:45:47 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.o... | 'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-junit-reporter',
'karma-coverage'
],
// list of files to exclude
exclude: [],
// preprocess matching files befo... | ]
},
plugins: [
'karma-systemjs', | random_line_split |
puzzleEmbed.ts | import { Chessground } from 'chessground';
window.onload = () => {
const el = document.querySelector('#daily-puzzle') as HTMLElement,
board = el.querySelector('.mini-board') as HTMLAnchorElement,
[fen, orientation, lm] = board.getAttribute('data-state')!.split(','); | drawable: { enabled: false, visible: false },
viewOnly: true,
fen: fen,
lastMove: lm ? ([lm[0] + lm[1], lm[2] + lm[3]] as Key[]) : undefined,
orientation: orientation as 'white' | 'black',
});
const resize = () => {
if (el.offsetHeight > window.innerHeight)
el.style.maxWidth = window.... |
Chessground(board.firstChild as HTMLElement, {
coordinates: false, | random_line_split |
modal-actions.ts | import {IBalloonContent, IUrlScheme} from '../redux';
import {Store} from '../stores/store';
import {MODALS} from './constants';
export class ModalActions {
/**
* @param {Object} balloon
*/
public showBalloon(balloon: IBalloonContent): void |
public toggleDevTools(): void {
Store.dispatch({
type: MODALS.TOGGLE_DEV_TOOLS
});
}
public showUrlSchemeModal({url, disposition}: IUrlScheme): void {
Store.dispatch({
type: MODALS.SHOW_URL_SCHEME_MODAL,
data: {
bIsShowing: true,... | {
Store.dispatch({
type: MODALS.SHOW_TRAY_BALLOON,
data: balloon
});
} | identifier_body |
modal-actions.ts | import {IBalloonContent, IUrlScheme} from '../redux';
import {Store} from '../stores/store';
import {MODALS} from './constants';
export class ModalActions {
/**
* @param {Object} balloon
*/
public showBalloon(balloon: IBalloonContent): void {
Store.dispatch({
type: MODALS.SHOW_TR... |
export default new ModalActions(); | random_line_split | |
modal-actions.ts | import {IBalloonContent, IUrlScheme} from '../redux';
import {Store} from '../stores/store';
import {MODALS} from './constants';
export class | {
/**
* @param {Object} balloon
*/
public showBalloon(balloon: IBalloonContent): void {
Store.dispatch({
type: MODALS.SHOW_TRAY_BALLOON,
data: balloon
});
}
public toggleDevTools(): void {
Store.dispatch({
type: MODALS.TOGGLE_DEV_T... | ModalActions | identifier_name |
truncate_images.rs | //! Ensure truncated images are read without panics.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
extern crate glob;
extern crate image;
const BASE_PATH: [&'static str; 2] = [".", "tests"];
const IMAGE_DIR: &'static str = "images";
fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
whe... |
#[test]
#[ignore]
fn truncate_jpg() {
truncate_images("jpg")
}
#[test]
#[ignore]
fn truncate_hdr() {
truncate_images("hdr");
}
| {
truncate_images("ico")
} | identifier_body |
truncate_images.rs | //! Ensure truncated images are read without panics.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
extern crate glob;
extern crate image;
const BASE_PATH: [&'static str; 2] = [".", "tests"];
const IMAGE_DIR: &'static str = "images";
fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
whe... | () {
truncate_images("bmp")
}
#[test]
#[ignore]
fn truncate_ico() {
truncate_images("ico")
}
#[test]
#[ignore]
fn truncate_jpg() {
truncate_images("jpg")
}
#[test]
#[ignore]
fn truncate_hdr() {
truncate_images("hdr");
}
| truncate_bmp | identifier_name |
truncate_images.rs | //! Ensure truncated images are read without panics.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
extern crate glob;
extern crate image;
const BASE_PATH: [&'static str; 2] = [".", "tests"];
const IMAGE_DIR: &'static str = "images";
fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
whe... | None => decoder,
},
);
let pattern = &*format!("{}", path.display());
for path in glob::glob(pattern).unwrap().filter_map(Result::ok) {
func(path)
}
}
}
fn truncate_images(decoder: &str) {
process_images(IMAGE_DIR, Some(decoder), |path| {
... | path.push(
"*.".to_string() + match input_decoder {
Some(val) => val, | random_line_split |
models.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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
#... | from django.contrib.auth.models import User
from lolyx.llx.models import Website
class Resume(models.Model):
"""
The company object
"""
title = models.CharField(max_length=300,
verbose_name='Title')
status = models.IntegerField(default=0)
user = models.ForeignKe... | """
Models definition for resume
"""
from django.db import models | random_line_split |
models.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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
#... | models.Model):
"""
The company object
"""
title = models.CharField(max_length=300,
verbose_name='Title')
status = models.IntegerField(default=0)
user = models.ForeignKey(User)
email = models.EmailField(max_length=300)
email_verified = models.BooleanField(... | esume( | identifier_name |
models.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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
#... |
class PeopleRessource(models.Model):
resume = models.ForeignKey(Resume)
website = models.ForeignKey(Website)
login = models.CharField(max_length=300)
| ""
The company object
"""
title = models.CharField(max_length=300,
verbose_name='Title')
status = models.IntegerField(default=0)
user = models.ForeignKey(User)
email = models.EmailField(max_length=300)
email_verified = models.BooleanField(default=False)
... | identifier_body |
multiple_rules.rs | /*
Copyright ⓒ 2016 Daniel Keep.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distribu... | fn parse(s: &str) -> Result<Parsed, SE> {
scan! { s;
("line:", ..v) => Parsed::Line(v),
("word:", let v: Word) => Parsed::Word(v),
("i32:", let v) => Parsed::I32(v),
}
} | }
| random_line_split |
multiple_rules.rs | /*
Copyright ⓒ 2016 Daniel Keep.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distribu... | : &str) -> Result<Parsed, SE> {
scan! { s;
("line:", ..v) => Parsed::Line(v),
("word:", let v: Word) => Parsed::Word(v),
("i32:", let v) => Parsed::I32(v),
}
}
| rse(s | identifier_name |
multiple_rules.rs | /*
Copyright ⓒ 2016 Daniel Keep.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distribu... | scan! { s;
("line:", ..v) => Parsed::Line(v),
("word:", let v: Word) => Parsed::Word(v),
("i32:", let v) => Parsed::I32(v),
}
}
| identifier_body | |
cartogram.js | // Ratio of Obese (BMI >= 30) in U.S. Adults, CDC 2008
var data = [
, .187, .198, , .133, .175, .151, , .1, .125, .171, , .172, .133, , .108,
.142, .167, .201, .175, .159, .169, .177, .141, .163, .117, .182, .153, .195,
.189, .134, .163, .133, .151, .145, .13, .139, .169, .164, .175, .135, .152,
.169, , .132, .... | // A thick black stroke for the exterior.
svg.append("g")
.attr("class", "black")
.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path);
// A white overlay to hide interior black strokes.
svg.append("g")
.attr("class", "white")
.selectAll("path")
... |
d3.json("../data/us-states.json", function(json) {
var path = d3.geo.path();
| random_line_split |
extern-call-scrub.rs | // Copyright 2012 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-MIT or ... | (n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
println!(... | count | identifier_name |
extern-call-scrub.rs | // Copyright 2012 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-MIT or ... |
}
fn count(n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
... | {
count(data - 1) + count(data - 1)
} | conditional_block |
extern-call-scrub.rs | // Copyright 2012 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-MIT or ... | {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
println!("result = {}", result);
assert_eq!(result, 2048);
});
} | identifier_body | |
extern-call-scrub.rs | // Copyright 2012 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-MIT or ... | println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
println!("result = {}", result);
assert_eq!(result, 2048... | unsafe { | random_line_split |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... | () {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
let filename = args.arg_input;
let source = read_file(&filename).unwrap();
let ctxt = Context::new(filename, source);
let mut compiler = Compiler::new(&ctxt);
compiler.define_entrypoint("main", make_fn_ty!(&ctxt, fn(time... | main | identifier_name |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... | {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
let filename = args.arg_input;
let source = read_file(&filename).unwrap();
let ctxt = Context::new(filename, source);
let mut compiler = Compiler::new(&ctxt);
compiler.define_entrypoint("main", make_fn_ty!(&ctxt, fn(time: N... | identifier_body | |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... | else if args.cmd_stream {
play_stream(&compiler);
}
},
Err(issues) => println!("Compile Error!\n{}", issues),
}
}
| {
write_wav(&compiler, args.arg_output, args.flag_length);
} | conditional_block |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... |
#[allow(dead_code)]
fn main() {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
let filename = args.arg_input;
let source = read_file(&filename).unwrap();
let ctxt = Context::new(filename, source);
let mut compiler = Compiler::new(&ctxt);
compiler.define_entrypoint("main"... | use interpreter::common::{Context, read_file};
use interpreter::compiler::Compiler;
use interpreter::audio::{write_wav, play_stream}; | random_line_split |
mem.rs | mod system_reporter {
use super::{JEMALLOC_HEAP_ALLOCATED_STR, SYSTEM_HEAP_ALLOCATED_STR};
#[cfg(target_os = "linux")]
use libc::c_int;
#[cfg(all(feature = "unstable", not(target_os = "windows")))]
use libc::{c_void, size_t};
use profile_traits::mem::{Report, ReportKind, ReporterRequest};
#[... |
// We record each segment's resident size.
let mut seg_map: HashMap<String, usize> = HashMap::new();
| random_line_split | |
mem.rs | (&self) {
let elapsed = self.created.elapsed();
println!("Begin memory reports {}", elapsed.as_secs());
println!("|");
// Collect reports from memory reporters.
//
// This serializes the report-gathering. It might be worth creating a new scoped thread for
// each... | handle_print_msg | identifier_name | |
mem.rs | jemalloc-heap-unclassified" and
// "system-heap-unclassified" values.
let mut forest = ReportsForest::new();
let mut jemalloc_heap_reported_size = 0;
let mut system_heap_reported_size = 0;
let mut jemalloc_heap_allocated_size: Option<usize> = None;
let mut system_heap_... | self.path_seg,
count_str
);
for child in &self.children {
child.print(depth + 1);
}
}
}
/// A collection of ReportsTrees. It represents the data from multiple memory reports in a form
/// that's good to print.
struct ReportsForest {
trees: HashMap<S... | {
if !self.children.is_empty() {
assert_eq!(self.count, 0);
}
let mut indent_str = String::new();
for _ in 0..depth {
indent_str.push_str(" ");
}
let mebi = 1024f64 * 1024f64;
let count_str = if self.count > 1 {
format!(" [{... | identifier_body |
stdbuf.rs | opts::{Matches, Options};
use std::io::{self, Write};
use std::os::unix::process::ExitStatusExt;
use std::path::PathBuf;
use std::process::Command;
use uucore::fs::{canonicalize, CanonicalizeMode};
static NAME: &'static str = "stdbuf";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static LIBSTDBUF: &'stati... |
fn print_usage(opts: &Options) {
let brief =
"Run COMMAND, with modified buffering operations for its standard streams\n \
Mandatory arguments to long options are mandatory for short options too.";
let explanation =
"If MODE is 'L' the corresponding stream will be line buffered.\n \
... | {
println!("{} {}", NAME, VERSION);
} | identifier_body |
stdbuf.rs | opts::{Matches, Options};
use std::io::{self, Write};
use std::os::unix::process::ExitStatusExt;
use std::path::PathBuf;
use std::process::Command;
use uucore::fs::{canonicalize, CanonicalizeMode};
static NAME: &'static str = "stdbuf";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static LIBSTDBUF: &'stati... | () -> (&'static str, &'static str) {
("DYLD_LIBRARY_PATH", ".dylib")
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn preload_strings() -> (&'static str, &'static str) {
crash!(1, "Command not supported for this operating system!")
}
fn print_version() {
println!("{} {}", NAME, VERSION);
... | preload_strings | identifier_name |
stdbuf.rs | getopts::{Matches, Options};
use std::io::{self, Write};
use std::os::unix::process::ExitStatusExt;
use std::path::PathBuf;
use std::process::Command;
use uucore::fs::{canonicalize, CanonicalizeMode};
static NAME: &'static str = "stdbuf";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static LIBSTDBUF: &'s... | None => absolute_path.clone()
})
}
fn get_preload_env() -> (String, String) {
let (preload, extension) = preload_strings();
let mut libstdbuf = LIBSTDBUF.to_owned();
libstdbuf.push_str(extension);
// First search for library in directory of executable.
let mut path = exe_path().unwrap_o... | let exe_path = try!(std::env::current_exe());
let absolute_path = try!(canonicalize(exe_path, CanonicalizeMode::Normal));
Ok(match absolute_path.parent() {
Some(p) => p.to_path_buf(), | random_line_split |
lib.rs | //! Immutable binary search tree.
//!
//! This crate provides functional programming style binary search trees which returns modified
//! copy of original map or set with the new data, and preserves the original. Many features and
//! algorithms are borrowed from `Data.Map` of Haskell's standard library.
//!
//! See ht... | pub use map::TreeMap;
/// An endpoint of a range of keys.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum Bound<T> {
/// An infinite endpoint. Indicates that there is no bound in this direction.
Unbounded,
/// An inclusive bound.
Included(T),
/// An exclusive bound.
Excluded(T)
}
#... | random_line_split | |
lib.rs | //! Immutable binary search tree.
//!
//! This crate provides functional programming style binary search trees which returns modified
//! copy of original map or set with the new data, and preserves the original. Many features and
//! algorithms are borrowed from `Data.Map` of Haskell's standard library.
//!
//! See ht... | <T> {
/// An infinite endpoint. Indicates that there is no bound in this direction.
Unbounded,
/// An inclusive bound.
Included(T),
/// An exclusive bound.
Excluded(T)
}
#[cfg(test)]
impl<T: Arbitrary> Arbitrary for Bound<T> {
fn arbitrary<G: Gen>(g: &mut G) -> Bound<T> {
match g.si... | Bound | identifier_name |
bootstrap-modules.js | module.exports = {
scripts: {
//'transition': true,
//'alert': true,
//'button': true,
//'carousel': true,
//'collapse': true,
//'dropdown': true,
//'modal': true, | //'affix': true
},
styles: {
'mixins': true,
'normalize': true,
'print': true,
'glyphicons': true,
'scaffolding': true,
'type': true,
'code': true,
'grid': true,
'tables': true,
'forms': true,
'buttons': true,
... | //'tooltip': true,
//'popover': true,
//'scrollspy': true,
//'tab': true, | random_line_split |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | () {
let args = ::std::env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} <device>-<speed>-<package>", args[0]);
::std::process::exit(1);
}
let device_combination = &args[1];
let XC2DeviceSpeedPackage {
dev: device, spd: _, pkg: _
} = XC2DeviceSpe... | main | identifier_name |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | dev: device, spd: _, pkg: _
} = XC2DeviceSpeedPackage::from_str(device_combination).expect("invalid device name");
let node_vec = RefCell::new(Vec::new());
let wire_vec = RefCell::new(Vec::new());
get_device_structure(device,
|node_name: &str, node_type: &str, fb: u32, idx: u32| {
... | let XC2DeviceSpeedPackage { | random_line_split |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | println!("Node: {} {} {} {}", node_name, node_type, fb, idx);
let i = node_vec.len();
node_vec.push((node_name.to_owned(), node_type.to_owned(), fb, idx));
i
},
|wire_name: &str| {
let mut wire_vec = wire_vec.borrow_mut();
println!... | {
let args = ::std::env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} <device>-<speed>-<package>", args[0]);
::std::process::exit(1);
}
let device_combination = &args[1];
let XC2DeviceSpeedPackage {
dev: device, spd: _, pkg: _
} = XC2DeviceSpeedP... | identifier_body |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... |
let wire_ref = wire_ref - 1000000;
let node_vec = node_vec.borrow();
let wire_vec = wire_vec.borrow();
println!("Node connection: {} {} {} {} {} {} {} {} {}",
node_vec[node_ref].0, node_vec[node_ref].1, node_vec[node_ref].2, node_vec[node_ref].3,
... | {
panic!("node instead of wire");
} | conditional_block |
photo_loader_tests.py | # coding=utf-8
from elections.tests import VotaInteligenteTestCase as TestCase
from elections.models import Election
from django.core.urlresolvers import reverse
from candideitorg.models import Candidate
from django.core.management import call_command
class PhotoLoaderCase(TestCase):
def setUp(self):
|
def test_it_loads_the_photo_for_an_existing_candidate(self):
call_command('photo_loader', 'elections/tests/fixtures/candidate_photo_url.csv', verbosity=0)
jano = Candidate.objects.get(name=u"Alejandro Guillier")
otro = Candidate.objects.get(name=u"Manuel Rojas")
self.assertEquals... | super(PhotoLoaderCase, self).setUp() | identifier_body |
photo_loader_tests.py | # coding=utf-8
from elections.tests import VotaInteligenteTestCase as TestCase
from elections.models import Election
from django.core.urlresolvers import reverse
from candideitorg.models import Candidate
from django.core.management import call_command
class PhotoLoaderCase(TestCase):
def setUp(self):
supe... | (self):
call_command('photo_loader', 'elections/tests/fixtures/candidate_photo_url.csv', verbosity=0)
jano = Candidate.objects.get(name=u"Alejandro Guillier")
otro = Candidate.objects.get(name=u"Manuel Rojas")
self.assertEquals(jano.photo, 'http://upload.wikimedia.org/wikipedia/commons... | test_it_loads_the_photo_for_an_existing_candidate | identifier_name |
photo_loader_tests.py | # coding=utf-8
from elections.tests import VotaInteligenteTestCase as TestCase
from elections.models import Election
from django.core.urlresolvers import reverse
from candideitorg.models import Candidate
from django.core.management import call_command
class PhotoLoaderCase(TestCase):
def setUp(self):
supe... |
def test_it_prepends_url_when_provided(self):
call_command('photo_loader', 'elections/tests/fixtures/candidate_photo.csv', 'some.site/static/', verbosity=0)
jano = Candidate.objects.get(name=u"Alejandro Guillier")
otro = Candidate.objects.get(name=u"Manuel Rojas")
self.assertEqual... |
self.assertEquals(jano.photo, 'http://upload.wikimedia.org/wikipedia/commons/7/76/Alejandro_Guillier.jpg')
self.assertEquals(otro.photo, 'http://www.2eso.info/sinonimos/wp-content/uploads/2013/02/feo1.jpg') | random_line_split |
error.js | 'use strict'
var path = require('path')
, urltils = require('./util/urltils')
, logger = require('./logger').child({component : 'error_tracer'})
, NAMES = require('./metrics/names')
/*
*
* CONSTANTS
*
*/
var MAX_ERRORS = 20
/**
* Given either or both of a transaction and an exception, generate an... | if (config.capture_params) {
var reqParams = transaction.getTrace().parameters
var urlParams = urltils.parseParameters(url)
// clear out ignored params
config.ignored_params.forEach(function cb_forEach(k) {
// polymorphic hidden classes aren't an issue with data bags
delete u... | params.request_uri = url | random_line_split |
error.js | 'use strict'
var path = require('path')
, urltils = require('./util/urltils')
, logger = require('./logger').child({component : 'error_tracer'})
, NAMES = require('./metrics/names')
/*
*
* CONSTANTS
*
*/
var MAX_ERRORS = 20
/**
* Given either or both of a transaction and an exception, generate an... |
}
// this needs to be done *after* pulling custom params from transaction
var isHighSec = config.high_security
if (customParameters && !isHighSec) {
var ignored = []
if (transaction) ignored = config.ignored_params
Object.keys(customParameters).forEach(function cb_forEach(param) {
if (ignore... | {
var reqParams = transaction.getTrace().parameters
var urlParams = urltils.parseParameters(url)
// clear out ignored params
config.ignored_params.forEach(function cb_forEach(k) {
// polymorphic hidden classes aren't an issue with data bags
delete urlParams[k]
delete reqP... | conditional_block |
error.js | 'use strict'
var path = require('path')
, urltils = require('./util/urltils')
, logger = require('./logger').child({component : 'error_tracer'})
, NAMES = require('./metrics/names')
/*
*
* CONSTANTS
*
*/
var MAX_ERRORS = 20
/**
* Given either or both of a transaction and an exception, generate an... | message = exception.message
// only care about extracting the type if it's Error-like.
if (exception && exception.constructor && exception.constructor.name) {
type = exception.constructor.name
}
}
else if (transaction &&
transaction.statusCode &&
urltils.isError(config, t... | {
// the collector throws this out, so don't bother setting it
var timestamp = 0
, name = 'WebTransaction/Uri/*'
, message = ''
, type = 'Error'
, params = {
userAttributes : {},
agentAttributes : {},
intrinsics : {},
}
if (transaction && transactio... | identifier_body |
error.js | 'use strict'
var path = require('path')
, urltils = require('./util/urltils')
, logger = require('./logger').child({component : 'error_tracer'})
, NAMES = require('./metrics/names')
/*
*
* CONSTANTS
*
*/
var MAX_ERRORS = 20
/**
* Given either or both of a transaction and an exception, generate an... | (config) {
this.config = config
this.errorCount = 0
this.errors = []
this.seen = []
}
/**
* Every finished transaction goes through this handler, so do as
* little as possible.
*/
ErrorTracer.prototype.onTransactionFinished = function onTransactionFinished(transaction, metrics) {
if (!transa... | ErrorTracer | identifier_name |
ZI_PQSC.py | """
Driver for PQSC V1
Author: Michael Kerschbaum
Date: 2019/09
"""
import time
import sys
import os
import logging
import numpy as np
import pycqed
import json
import copy
import pycqed.instrument_drivers.physical_instruments.ZurichInstruments.ZI_base_instrument as zibase
log = logging.getLogger(__name__)
########... |
else:
raise_exceptions = True
# Asserted in case errors were found
found_errors = False
# Combine errors_to_ignore with commandline
_errors_to_ignore = copy.copy(self._errors_to_ignore)
if errors_to_ignore is not None:
_errors_to_ignore += error... | raise_exceptions = False
self._errors = {} | conditional_block |
ZI_PQSC.py | """
Driver for PQSC V1
Author: Michael Kerschbaum
Date: 2019/09
"""
import time
import sys
import os
import logging
import numpy as np
import pycqed
import json
import copy
import pycqed.instrument_drivers.physical_instruments.ZurichInstruments.ZI_base_instrument as zibase
log = logging.getLogger(__name__)
########... | cases - a parameter that can be used to define which combination of readout waveforms to actually
download to the instrument. As the instrument has a limited amount of memory available, it is
not currently possible to store all 1024 possible combinations of readout waveforms that would... | applied between when the AWG starts playing the readout waveform, and when it triggers the
actual readout. | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.