file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ExtractSpecificVertices.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExtractSpecificVertices.py
--------------------
Date : October 2016
Copyright : (C) 2016 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
******... | (self, parameters, context, feedback):
source = self.parameterAsSource(parameters, self.INPUT, context)
if source is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
fields = source.fields()
fields.append(QgsField('vertex_pos', QVariant.Int... | processAlgorithm | identifier_name |
ExtractSpecificVertices.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExtractSpecificVertices.py
--------------------
Date : October 2016
Copyright : (C) 2016 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
******... |
(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
fields, wkb_type, source.sourceCrs(), QgsFeatureSink.RegeneratePrimaryKey)
if sink is None:
raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
... | wkb_type = QgsWkbTypes.addZ(wkb_type) | conditional_block |
ExtractSpecificVertices.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExtractSpecificVertices.py
--------------------
Date : October 2016
Copyright : (C) 2016 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
******... | INPUT = 'INPUT'
OUTPUT = 'OUTPUT'
VERTICES = 'VERTICES'
def group(self):
return self.tr('Vector geometry')
def groupId(self):
return 'vectorgeometry'
def __init__(self):
super().__init__()
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessi... | class ExtractSpecificVertices(QgisAlgorithm): | random_line_split |
expf32.rs | #![feature(core, core_intrinsics, core_float)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::expf32;
use core::num::Float;
use core::f32;
// pub fn expf32(x: f32) -> f32;
#[test]
fn expf32_test1() |
#[test]
fn expf32_test2() {
let x: f32 = f32::infinity();
let result: f32 = unsafe { expf32(x) };
assert_eq!(result, f32::infinity());
}
#[test]
fn expf32_test3() {
let x: f32 = f32::neg_infinity();
let result: f32 = unsafe { expf32(x) };
assert_eq!(result, 0.0);
}
#[test]
fn... | {
let x: f32 = f32::nan();
let result: f32 = unsafe { expf32(x) };
assert_eq!(result.is_nan(), true);
} | identifier_body |
expf32.rs | #![feature(core, core_intrinsics, core_float)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::expf32;
use core::num::Float;
use core::f32;
// pub fn expf32(x: f32) -> f32;
#[test]
fn expf32_test1() {
let x: f32 = f32::nan();
let result: f32 = unsafe { expf32(x) }; | }
#[test]
fn expf32_test2() {
let x: f32 = f32::infinity();
let result: f32 = unsafe { expf32(x) };
assert_eq!(result, f32::infinity());
}
#[test]
fn expf32_test3() {
let x: f32 = f32::neg_infinity();
let result: f32 = unsafe { expf32(x) };
assert_eq!(result, 0.0);
}
#[test]
... |
assert_eq!(result.is_nan(), true); | random_line_split |
expf32.rs | #![feature(core, core_intrinsics, core_float)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::expf32;
use core::num::Float;
use core::f32;
// pub fn expf32(x: f32) -> f32;
#[test]
fn expf32_test1() {
let x: f32 = f32::nan();
let result: f32 = unsafe { expf32(x) };
ass... | () {
let x: f32 = f32::infinity();
let result: f32 = unsafe { expf32(x) };
assert_eq!(result, f32::infinity());
}
#[test]
fn expf32_test3() {
let x: f32 = f32::neg_infinity();
let result: f32 = unsafe { expf32(x) };
assert_eq!(result, 0.0);
}
#[test]
fn expf32_test4() {
let x: f32 = 1... | expf32_test2 | identifier_name |
sass.js | var nodeSass = require('node-sass'),
fs = require('fs');
module.exports = class Sass {
constructor(config){
this.config = config;
if (this.config.compileAtBootup) {
this.compile();
}
if (this.config.watch) {
this.startWatch();
}
}
get timeTaken(){
return parseInt(proces... | () {
let throttleId;
fs.watch(this.config.arguments.watchFolder, { recursive: true }, (eventType, filename) => {
if (throttleId) { clearTimeout(throttleId); }
throttleId = setTimeout(() => {
throttleId = null;
this.compile();
}, 50);
});
}
getFormattedTime(){
let... | startWatch | identifier_name |
sass.js | var nodeSass = require('node-sass'),
fs = require('fs');
module.exports = class Sass {
constructor(config){
this.config = config;
if (this.config.compileAtBootup) {
this.compile();
}
if (this.config.watch) {
this.startWatch();
}
}
get timeTaken(){
return parseInt(proces... | } |
getFormattedTime(){
let d = new Date();
return d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
} | random_line_split |
sass.js | var nodeSass = require('node-sass'),
fs = require('fs');
module.exports = class Sass {
constructor(config){
this.config = config;
if (this.config.compileAtBootup) {
this.compile();
}
if (this.config.watch) |
}
get timeTaken(){
return parseInt(process.hrtime(this.timeBegun)[1] / 1000000) + 'ms';
}
writeOutputFile(css) {
let dst = this.config.arguments.outFile;
fs.writeFile(dst, css, (err)=>{
err
? console.warn(this.getFormattedTime(), 'Error writing compiled SASS to outFile:', err)
... | {
this.startWatch();
} | conditional_block |
sass.js | var nodeSass = require('node-sass'),
fs = require('fs');
module.exports = class Sass {
constructor(config) |
get timeTaken(){
return parseInt(process.hrtime(this.timeBegun)[1] / 1000000) + 'ms';
}
writeOutputFile(css) {
let dst = this.config.arguments.outFile;
fs.writeFile(dst, css, (err)=>{
err
? console.warn(this.getFormattedTime(), 'Error writing compiled SASS to outFile:', err)
:... | {
this.config = config;
if (this.config.compileAtBootup) {
this.compile();
}
if (this.config.watch) {
this.startWatch();
}
} | identifier_body |
WalkingState.rs | # Velocity
# AngularVelocity
# Relative Orientation
# Relative Angular Velocity
#----------------
# Heading
-0.000295
# Root(pelvis)
0 0.943719 0
0.999705 0.001812 0.000000 -0.024203
0.085812 0.006683 0.046066
0.020659 0.025804 -0.043029
# pelvis_lowerback
0.999456 -0.008591 -0.000383 0.031834
0.0... | # order is:
# Heading
# Position
# Orientation
| random_line_split | |
logisticRegression.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sys
from sklearn import linear_model
from sklearn.metrics import precision_score, recall_score, f1_score
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('train', help='Training Data')
p... |
else:
mode = 'a'
pandas.DataFrame({'pred':ypred}).to_csv(args.out, mode=mode, header='%.3f %.3f %.3f'%(prec, rec, f1score))
n += 1
if __name__ == '__main__':
main()
| mode='w' | conditional_block |
logisticRegression.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sys
from sklearn import linear_model
from sklearn.metrics import precision_score, recall_score, f1_score
import argparse
def | ():
parser = argparse.ArgumentParser()
parser.add_argument('train', help='Training Data')
parser.add_argument('labels', help='Training Labels')
parser.add_argument('test', help='Test Data')
parser.add_argument('data_cv', help='Data for CrossValidation')
parser.add_argument('label_cv', help='Lab... | main | identifier_name |
logisticRegression.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sys
from sklearn import linear_model
from sklearn.metrics import precision_score, recall_score, f1_score
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('train', help='Training Data')
p... |
### Reading cross-validation set
Xcv = pandas.read_table(args.data_cv, sep=' ', header=None)
print(ic, Xcv.shape)
ycv = pandas.read_table(args.label_cv, sep=' ', header=None)[0].values
ycv[np.where(ycv != ic)[0]] = -1
ycv[np.where(ycv == ic)[0]] = 1
print('CrossValidation %d %d for labe... | break
| random_line_split |
logisticRegression.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sys
from sklearn import linear_model
from sklearn.metrics import precision_score, recall_score, f1_score
import argparse
def main():
|
if __name__ == '__main__':
main()
| parser = argparse.ArgumentParser()
parser.add_argument('train', help='Training Data')
parser.add_argument('labels', help='Training Labels')
parser.add_argument('test', help='Test Data')
parser.add_argument('data_cv', help='Data for CrossValidation')
parser.add_argument('label_cv', help='Labels for ... | identifier_body |
LiDAR_tools.py | import numpy as np
import laspy as las
# Determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs. This function
# returns True or False. The algorithm is called
# the "Ray Casting Method".
# the point_in_poly algorithm was found here:
# http://geospatialpython.com/2011/01/point-in-pol... | (in_pts,target_xy,radius):
pts = np.zeros((0,in_pts.shape[1]))
if in_pts.shape[0]>0:
x,y,inside = points_in_radius(in_pts[:,0],in_pts[:,1],target_xy[0],target_xy[1],radius)
pts = in_pts[inside,:]
else:
print( "\t\t\t no points in neighbourhood")
return pts
| filter_lidar_data_by_neighbourhood | identifier_name |
LiDAR_tools.py | import numpy as np
import laspy as las
# Determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs. This function
# returns True or False. The algorithm is called
# the "Ray Casting Method".
# the point_in_poly algorithm was found here:
# http://geospatialpython.com/2011/01/point-in-pol... |
# This retrieves all points within circular neighbourhood, Terget point is the location around which the neighbourhood search is conducted, for a specified search radius. x and y are vectors with the x and y coordinates of the test points
def points_in_radius(x,y,target_x, target_y,radius):
inside=np.zeros(x.si... | n = len(poly)
inside=np.zeros(x.size,dtype=bool)
xints=np.zeros(x.size)
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y=poly[i % n]
if p1y!=p2y:
xints[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)] = (y[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p... | identifier_body |
LiDAR_tools.py | import numpy as np
import laspy as las
# Determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs. This function
# returns True or False. The algorithm is called
# the "Ray Casting Method".
# the point_in_poly algorithm was found here:
# http://geospatialpython.com/2011/01/point-in-pol... | inside_temp=None
else:
x,y,inside = points_in_poly(in_pts[:,0],in_pts[:,1],polygon)
pts = in_pts[inside,:]
else:
print("\t\t\t no points in polygon")
return pts
# filter lidar by circular neighbourhood
def filter_lidar_data_by_neighbourhood(in_pts,target_xy,radiu... | y = in_pts[inside,1]
x_temp=None
y_temp=None | random_line_split |
LiDAR_tools.py | import numpy as np
import laspy as las
# Determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs. This function
# returns True or False. The algorithm is called
# the "Ray Casting Method".
# the point_in_poly algorithm was found here:
# http://geospatialpython.com/2011/01/point-in-pol... |
p1x,p1y = p2x,p2y
return inside
# This one is my own version of the ray-trace algorithm which utilises the numpy arrays so that a list of x and y coordinates can be processed in one call and only points inside polygon are returned alongside the indices in case required for future referencing. This saves... | if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside | conditional_block |
VModal.tsx | /**
* Created by xiaoduan on 2016/11/22.
*/
import * as React from 'react';
import './css/VModal.less';
import {Modal,Button} from 'antd';
import GenericComponent from "../abstract/GenericComponent";
export interface IVModelPassDown {
handleOk?: Function;
}
interface IVModalProps extends IVModelPassDown {
t... | onOk={handleOk}
onCancel={handleCancel}
>
{children}
</Modal>
)
}
} | <Modal {...newProps}
width={width}
className={className}
visible={visible} | random_line_split |
VModal.tsx | /**
* Created by xiaoduan on 2016/11/22.
*/
import * as React from 'react';
import './css/VModal.less';
import {Modal,Button} from 'antd';
import GenericComponent from "../abstract/GenericComponent";
export interface IVModelPassDown {
handleOk?: Function;
}
interface IVModalProps extends IVModelPassDown {
t... | () {
this.props.handleOk&&this.props.handleOk();
}
public getChildren(): JSX.Element[] {
const {children, handleOk} =this.props;
return super.passPropsChildren(children, {handleOk});
}
public handleCancel() {
const {handleCancel} = this.props;
handleCancel();
... | handleOk | identifier_name |
VModal.tsx | /**
* Created by xiaoduan on 2016/11/22.
*/
import * as React from 'react';
import './css/VModal.less';
import {Modal,Button} from 'antd';
import GenericComponent from "../abstract/GenericComponent";
export interface IVModelPassDown {
handleOk?: Function;
}
interface IVModalProps extends IVModelPassDown {
t... |
private getFilterProps() {
let newProps = {};
for (let key in this.props) {
const targetValue = this.props[key];
if (typeof targetValue != 'undefined') {
newProps[key] = targetValue;
}
}
return newProps
}
public render() {
... | {
const {size} = this.props;
if (size === 'large') {
return '80%';
}
else if (size === 'small') {
return '40%';
}
return;
} | identifier_body |
VModal.tsx | /**
* Created by xiaoduan on 2016/11/22.
*/
import * as React from 'react';
import './css/VModal.less';
import {Modal,Button} from 'antd';
import GenericComponent from "../abstract/GenericComponent";
export interface IVModelPassDown {
handleOk?: Function;
}
interface IVModalProps extends IVModelPassDown {
t... |
}
return newProps
}
public render() {
const newProps=this.getFilterProps();
const {handleCancel, handleOk} = this;
const {visible} = this.state;
const children = this.getChildren();
const width = this.props.width || this.getStandardWidth();
const ... | {
newProps[key] = targetValue;
} | conditional_block |
store.ts | import {
Action as ReduxAction,
createStore as reduxCreateStore,
Store as ReduxStore, | StoreEnhancer,
Unsubscribe
} from 'redux';
import { Action, TypedAction } from './action';
import { Reducer } from './reducer';
/**
* Internal reset action type
*/
const RESET = '@@ngfk/RESET';
export class Store<State, ActionMap> implements ReduxStore<State> {
protected redux: ReduxStore<State>;
p... | random_line_split | |
store.ts | import {
Action as ReduxAction,
createStore as reduxCreateStore,
Store as ReduxStore,
StoreEnhancer,
Unsubscribe
} from 'redux';
import { Action, TypedAction } from './action';
import { Reducer } from './reducer';
/**
* Internal reset action type
*/
const RESET = '@@ngfk/RESET';
export class St... |
}
export type Dispatch<ActionMap> = {
/**
* Dispatches the provided action, triggering a state update.
* @param action The action
*/
<Action extends ReduxAction>(action: Action): Action;
/**
* Dispatches the provided action, triggering a state update. This method
* enforces type ... | {
// Construct and return a new reducer function
const extended: any = (state?: State, action?: Action<any>): State => {
// If we receive a reset action, skip the originalReducer and
// simply return the new state provided in the action payload.
if (action && action.t... | identifier_body |
store.ts | import {
Action as ReduxAction,
createStore as reduxCreateStore,
Store as ReduxStore,
StoreEnhancer,
Unsubscribe
} from 'redux';
import { Action, TypedAction } from './action';
import { Reducer } from './reducer';
/**
* Internal reset action type
*/
const RESET = '@@ngfk/RESET';
export class | <State, ActionMap> implements ReduxStore<State> {
protected redux: ReduxStore<State>;
protected initial?: State;
/**
* Creates a new instance of the Store class.
* @param reducer The root reducer
* @param initial The initial state
*/
constructor(
protected reducer: Reducer<S... | Store | identifier_name |
store.ts | import {
Action as ReduxAction,
createStore as reduxCreateStore,
Store as ReduxStore,
StoreEnhancer,
Unsubscribe
} from 'redux';
import { Action, TypedAction } from './action';
import { Reducer } from './reducer';
/**
* Internal reset action type
*/
const RESET = '@@ngfk/RESET';
export class St... |
// The rest of the actions are forwarded to the originalReducer
return originalReducer(state, action);
};
return extended;
}
}
export type Dispatch<ActionMap> = {
/**
* Dispatches the provided action, triggering a state update.
* @param action The action
... | {
return action.payload;
} | conditional_block |
ruutu.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ruutu\.fi/video/(... | ):
for child in node:
if child.tag.endswith('Files'):
extract_formats(child)
elif child.tag.endswith('File'):
video_url = child.text
if (not video_url or video_url in processed_urls or
any... | ct_formats(node | identifier_name |
ruutu.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ruutu\.fi/video/(... | elif child.tag.endswith('File'):
video_url = child.text
if (not video_url or video_url in processed_urls or
any(p in video_url for p in ('NOT_USED', 'NOT-USED'))):
return
processed_urls.append(vid... | ct_formats(child)
| conditional_block |
ruutu.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ruutu\.fi/video/(... |
video_xml = self._download_xml(
'http://gatling.ruutu.fi/media-xml-cache?id=%s' % video_id, video_id)
formats = []
processed_urls = []
def extract_formats(node):
for child in node:
if child.tag.endswith('Files'):
extract_form... | video_id = self._match_id(url) | random_line_split |
ruutu.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ruutu\.fi/video/(... | extract_formats(video_xml.find('./Clip'))
self._sort_formats(formats)
return {
'id': video_id,
'title': xpath_attr(video_xml, './/Behavior/Program', 'program_name', 'title', fatal=True),
'description': xpath_attr(video_xml, './/Behavior/Program', 'description', ... | hild in node:
if child.tag.endswith('Files'):
extract_formats(child)
elif child.tag.endswith('File'):
video_url = child.text
if (not video_url or video_url in processed_urls or
any(p in video_url for ... | identifier_body |
simple.py | """
Test usage of docker 'start' command
initialize:
1) prepare docker container, but don't start it
run_once:
2) execute docker start using the nonexisting name
3) execute the new container using `docker run`
4) execute docker start using the running docker name
5) stop the container
6) execute docker start using the... |
else:
subargs = []
subargs.append("--name %s" % name)
fin = DockerImage.full_name_from_defaults(self.config)
subargs.append(fin)
subargs.append("bash")
subargs.append("-c")
subargs.append("'echo STARTED: $(date); while :; do sleep 0.1; done'")
... | subargs = [arg for arg in
self.config['run_options_csv'].split(',')] | conditional_block |
simple.py | """
Test usage of docker 'start' command
initialize:
1) prepare docker container, but don't start it
run_once:
2) execute docker start using the nonexisting name
3) execute the new container using `docker run`
4) execute docker start using the running docker name
5) stop the container
6) execute docker start using the... | (self):
super(simple, self).postprocess()
name = self.sub_stuff['container_name']
logs = AsyncDockerCmd(self, "logs", ['-f', name])
logs.execute()
utils.wait_for(lambda: logs.stdout.count("\n") == 2, 5, step=0.1)
out = logs.stdout
self.failif(out.count("\n") != 2,... | postprocess | identifier_name |
simple.py | """
Test usage of docker 'start' command
initialize:
1) prepare docker container, but don't start it
run_once:
2) execute docker start using the nonexisting name
3) execute the new container using `docker run`
4) execute docker start using the running docker name
5) stop the container
6) execute docker start using the... | from autotest.client.shared import utils
class simple(subtest.SubSubtest):
def _init_stuff(self):
""" Initialize stuff """
self.sub_stuff['container_name'] = None # name of the container
def initialize(self):
super(simple, self).initialize()
self._init_stuff()
con... | from dockertest import config, subtest
from dockertest.containers import DockerContainers
from dockertest.dockercmd import AsyncDockerCmd, DockerCmd
from dockertest.output import mustpass, mustfail
from dockertest.images import DockerImage | random_line_split |
simple.py | """
Test usage of docker 'start' command
initialize:
1) prepare docker container, but don't start it
run_once:
2) execute docker start using the nonexisting name
3) execute the new container using `docker run`
4) execute docker start using the running docker name
5) stop the container
6) execute docker start using the... |
def cleanup(self):
super(simple, self).cleanup()
name = self.sub_stuff.get('container_name')
if name and self.config.get('remove_after_test'):
DockerContainers(self).clean_all([name])
| super(simple, self).postprocess()
name = self.sub_stuff['container_name']
logs = AsyncDockerCmd(self, "logs", ['-f', name])
logs.execute()
utils.wait_for(lambda: logs.stdout.count("\n") == 2, 5, step=0.1)
out = logs.stdout
self.failif(out.count("\n") != 2, "The container ... | identifier_body |
vendor.rs | use crate::command_prelude::*;
use cargo::ops;
use std::path::PathBuf;
pub fn cli() -> App {
subcommand("vendor")
.about("Vendor all dependencies for a project locally")
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg_manifest_path()
.arg(Arg::with_name("path").hel... | {
// We're doing the vendoring operation ourselves, so we don't actually want
// to respect any of the `source` configuration in Cargo itself. That's
// intended for other consumers of Cargo, but we want to go straight to the
// source, e.g. crates.io, to fetch crates.
if !args.is_present("respect-s... | identifier_body | |
vendor.rs | use crate::command_prelude::*;
use cargo::ops;
use std::path::PathBuf;
pub fn cli() -> App {
subcommand("vendor")
.about("Vendor all dependencies for a project locally")
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg_manifest_path()
.arg(Arg::with_name("path").hel... | } else if args.is_present("only-git-deps") {
Some("--only-git-deps")
} else if args.is_present("disallow-duplicates") {
Some("--disallow-duplicates")
} else {
None
};
if let Some(flag) = crates_io_cargo_vendor_flag {
return Err(anyhow::format_err!(
"\
the ... | // that users currently using the flag aren't tripped up.
let crates_io_cargo_vendor_flag = if args.is_present("no-merge-sources") {
Some("--no-merge-sources")
} else if args.is_present("relative-path") {
Some("--relative-path") | random_line_split |
vendor.rs | use crate::command_prelude::*;
use cargo::ops;
use std::path::PathBuf;
pub fn cli() -> App {
subcommand("vendor")
.about("Vendor all dependencies for a project locally")
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg_manifest_path()
.arg(Arg::with_name("path").hel... | (config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
// We're doing the vendoring operation ourselves, so we don't actually want
// to respect any of the `source` configuration in Cargo itself. That's
// intended for other consumers of Cargo, but we want to go straight to the
// source, e.g. crat... | exec | identifier_name |
borrowed-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
// lldb-command:print *unique_val_ref
// lldb-check:[...]$4 = SomeStruct { x: 13, y: 26.5 }
// lldb-command:print *unique_val_interior_ref_1
// lldb-check:[...]$5 = 13
// lldb-command:print *unique_val_interior_ref_2
// lldb-check:[...]$6 = 26.5
#![allow(unused_variable)]
struct SomeStruct {
x: int,
y: f64... | // lldb-check:[...]$2 = 23.5
// lldb-command:print *ref_to_unnamed
// lldb-check:[...]$3 = SomeStruct { x: 11, y: 24.5 } | random_line_split |
borrowed-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
x: int,
y: f64
}
fn main() {
let stack_val: SomeStruct = SomeStruct { x: 10, y: 23.5 };
let stack_val_ref: &SomeStruct = &stack_val;
let stack_val_interior_ref_1: &int = &stack_val.x;
let stack_val_interior_ref_2: &f64 = &stack_val.y;
let ref_to_unnamed: &SomeStruct = &SomeStruct { x: 11... | SomeStruct | identifier_name |
gulpfile.js | var gulp = require('gulp');
var karma = require('karma').server;
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var path = require('path');
var plumber = require('gulp-plumber');
var runSequence = require('run-sequence');
var jshint = require('gulp-jshint'... | gulp.task('watch', function () {
// Watch JavaScript files
gulp.watch(sourceFiles, ['process-all']);
});
/**
* Validate source JavaScript
*/
gulp.task('jshint', function () {
return gulp.src(lintFiles)
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.repor... | /**
* Watch task
*/ | random_line_split |
mem.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/. */
//! Memory profiling functions.
use ipc_channel::ipc::{self, IpcReceiver};
use ipc_channel::router::ROUTER;
use p... |
// Insert the path and size into the forest, adding any trees and nodes as necessary.
fn insert(&mut self, path: &[String], size: usize) {
let (head, tail) = path.split_first().unwrap();
// Get the right tree, creating it if necessary.
if !self.trees.contains_key(head) {
se... | {
ReportsForest {
trees: HashMap::new(),
}
} | identifier_body |
mem.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/. */
//! Memory profiling functions.
use ipc_channel::ipc::{self, IpcReceiver};
use ipc_channel::router::ROUTER;
use p... | reporters: HashMap<String, Reporter>,
}
const JEMALLOC_HEAP_ALLOCATED_STR: &'static str = "jemalloc-heap-allocated";
const SYSTEM_HEAP_ALLOCATED_STR: &'static str = "system-heap-allocated";
impl Profiler {
pub fn create(period: Option<f64>) -> ProfilerChan {
let (chan, port) = ipc::channel().unwrap();... | /// The port through which messages are received.
pub port: IpcReceiver<ProfilerMsg>,
/// Registered memory reporters. | random_line_split |
mem.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/. */
//! Memory profiling functions.
use ipc_channel::ipc::{self, IpcReceiver};
use ipc_channel::router::ROUTER;
use p... | (&mut self) {
// Fill in sizes of interior nodes, and recursively sort the sub-trees.
for (_, tree) in &mut self.trees {
tree.compute_interior_node_sizes_and_sort();
}
// Put the trees into a sorted vector. Primary sort: degenerate trees (those containing a
// single... | print | identifier_name |
index.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
function sendList(){
$("#loading").show();
setTimeout('$("#loading").hide();', 1000);
}
function capturePhoto(){
navigator.camera.getPicture(
photoTakeSucces,
photoTakeError,
{
sourceType:Camera.PictureSourceType.CAMERA,
quality:60,
desti... | {
navigator.camera.getPicture(
photoTakeSucces,
photoTakeError,
{
sourceType:Camera.PictureSourceType.PHOTOLIBRARY,
quality:60,
destinationType: Camera.DestinationType.DATA_URL,
// mediaType: Camera.MediaType.PICTURE,
// correctOrie... | identifier_body |
index.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | (data){
// $("#loading").show();
// $("#home").hide();
// $("#photo").show();
// setTimeout('$("#loading").hide();', 500);
// document.getElementById('cameraPic').src="data:image/jpeg;base64,"+data;
alert('picture taken');
}
function home(){
//$(".fullscreen").css('opacity',0);
$(".ful... | photoTakeSucces | identifier_name |
index.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | }
function photoTakeError(){
setTimeout(function() { //iOS Quirck
alert("Error");
}, 0);
}
function test(){
console.log('test');
$("#home").hide();
$("#photo").show();
}
function test(){
console.log("test2");
$("#home").hide();
$("#photo").show();
}
function photoTakeSucces(da... | function cameraCleanupError(){
console.log("Cleanup NIET gelukt"); | random_line_split |
voter_data_download.py | import urllib2
import os
baseurl = "http://ceoaperms.ap.gov.in/TS_Rolls/PDFGeneration.aspx?urlPath=D:\SSR2016_Final\Telangana\AC_001\English\S29A"
constituencyCount = 0
constituencyTotal = 229
while constituencyCount <= constituencyTotal:
pdfCount = 1
notDone = True
constituencyCount = constituencyCount ... | f.close()
else:
notDone = False
except urllib2.URLError, e:
if e.code == 404:
notDone = False | random_line_split | |
voter_data_download.py | import urllib2
import os
baseurl = "http://ceoaperms.ap.gov.in/TS_Rolls/PDFGeneration.aspx?urlPath=D:\SSR2016_Final\Telangana\AC_001\English\S29A"
constituencyCount = 0
constituencyTotal = 229
while constituencyCount <= constituencyTotal:
pdfCount = 1
notDone = True
constituencyCount = constituencyCount ... | notDone = False | conditional_block | |
app.js | #!/usr/bin/env node
var argv = require('yargs').argv;
var prompt = require('prompt');
/////import the help.js file here, in essence help becomes the function//
var help = require('./app/help');
var zipFile = require('./app/zipfile');
var csvToJson = require('/.app/csvToJson');
var fs = require('fs');
if (argv.help){... | (name) {
console.log('Hello ' + name);
var options = { encoding: 'utf8'};
// print the bigfile
var stream = fs.createReadStream('./app/bigfile');
stream.pipe(process.stdout);
process.stdout.write('Hello ' + name + ' Again!\n');
}
| printHelloMessage | identifier_name |
app.js | #!/usr/bin/env node
var argv = require('yargs').argv;
var prompt = require('prompt');
/////import the help.js file here, in essence help becomes the function//
var help = require('./app/help');
var zipFile = require('./app/zipfile');
var csvToJson = require('/.app/csvToJson');
var fs = require('fs');
if (argv.help){... | if (argv.file) {
zipFile(argv.file);
}
if (argv.csv) {
csvToJson(argv.csv);
}
//printing msg based on the argv statement/////
prompt.override = argv;
prompt.message = prompt.delimiter = '';
prompt.start();
prompt.get('name', function (err, result) {
printHelloMessage(result.name);
});
function prin... | }
| random_line_split |
app.js | #!/usr/bin/env node
var argv = require('yargs').argv;
var prompt = require('prompt');
/////import the help.js file here, in essence help becomes the function//
var help = require('./app/help');
var zipFile = require('./app/zipfile');
var csvToJson = require('/.app/csvToJson');
var fs = require('fs');
if (argv.help){... |
//printing msg based on the argv statement/////
prompt.override = argv;
prompt.message = prompt.delimiter = '';
prompt.start();
prompt.get('name', function (err, result) {
printHelloMessage(result.name);
});
function printHelloMessage(name) {
console.log('Hello ' + name);
var options = { encoding: ... | {
csvToJson(argv.csv);
} | conditional_block |
app.js | #!/usr/bin/env node
var argv = require('yargs').argv;
var prompt = require('prompt');
/////import the help.js file here, in essence help becomes the function//
var help = require('./app/help');
var zipFile = require('./app/zipfile');
var csvToJson = require('/.app/csvToJson');
var fs = require('fs');
if (argv.help){... | {
console.log('Hello ' + name);
var options = { encoding: 'utf8'};
// print the bigfile
var stream = fs.createReadStream('./app/bigfile');
stream.pipe(process.stdout);
process.stdout.write('Hello ' + name + ' Again!\n');
} | identifier_body | |
cucumber-upload.js | 'use strict';
const Joi = require('joi');
const uuid = require('uuid');
const reqUtils = require('../utils/requestUtils');
const R = require('ramda');
//fixme: allow unknown fields and just require absolutely mandatory ones
const cucumberSchema = Joi.array().items(Joi.object().keys({
id: Joi.string().required(),
... | payload: {
//allow: ['multipart/form-data'],
parse: true,
output: 'stream'
},
validate: {
query: {
evaluation: Joi.string().min(1).required(),
evaluationTag: Joi.string().min(1).re... | path: '/upload/cucumber',
config: {
tags: ['upload'], | random_line_split |
expr-match-unique.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 test_box() {
let res: Box<_> = match true { true => { box 100 }, _ => panic!() };
assert_eq!(*res, 100);
}
pub fn main() { test_box(); } | random_line_split | |
expr-match-unique.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 ... |
pub fn main() { test_box(); }
| {
let res: Box<_> = match true { true => { box 100 }, _ => panic!() };
assert_eq!(*res, 100);
} | identifier_body |
expr-match-unique.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 ... | () { test_box(); }
| main | identifier_name |
aws.py | """
This is the default template for our main set of AWS servers.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0614
import json
from .common import *
from logsettings import get_logger_config
import os
# speci... |
# Celery Broker
CELERY_BROKER_TRANSPORT = ENV_TOKENS.get("CELERY_BROKER_TRANSPORT", "")
CELERY_BROKER_HOSTNAME = ENV_TOKENS.get("CELERY_BROKER_HOSTNAME", "")
CELERY_BROKER_VHOST = ENV_TOKENS.get("CELERY_BROKER_VHOST", "")
CELERY_BROKER_USER = AUTH_TOKENS.get("CELERY_BROKER_USER", "")
CELERY_BROKER_PASSWORD = AUTH_TOK... | DATADOG['api_key'] = AUTH_TOKENS['DATADOG_API'] | conditional_block |
aws.py | """
This is the default template for our main set of AWS servers.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0614
import json
from .common import *
from logsettings import get_logger_config
import os
# speci... | for feature, value in ENV_TOKENS.get('MITX_FEATURES', {}).items():
MITX_FEATURES[feature] = value
LOGGING = get_logger_config(LOG_DIR,
logging_env=ENV_TOKENS['LOGGING_ENV'],
syslog_addr=(ENV_TOKENS['SYSLOG_SERVER'], 514),
debug=Fal... | #Timezone overrides
TIME_ZONE = ENV_TOKENS.get('TIME_ZONE', TIME_ZONE)
| random_line_split |
registry.js | /*jslint node: true */
"use strict";
const _ = require('lodash'),
debug = require('debug')('node-registry:registry'),
EventEmitter = require('../event-emitter'),
OrderedConfiguration = require('../ordered-configuration'),
utils = require('../utils'),
server = require('../server'),
Environment = require('../envir... |
const initializers = this.__initializers;
if (initializer && _.isFunction(initializer.initializer)) {
initializers.add(initializer);
} else {
throw new TypeError('Initializer must contain an initializer method');
}
},
/**
* Run the configured initalizers. After all of them are invoked,
* start u... | {
throw new Error('You can only register an initializer before the server is started.');
} | conditional_block |
registry.js | /*jslint node: true */
"use strict";
const _ = require('lodash'),
debug = require('debug')('node-registry:registry'),
EventEmitter = require('../event-emitter'),
OrderedConfiguration = require('../ordered-configuration'),
utils = require('../utils'),
server = require('../server'),
Environment = require('../envir... | ,
/**
* Get the execution mode of the applcation from the
* {{#crossLink "Environemnt"}}{{/crossLink}}.
*
* Defaults to 'development'.
*
* @method getExecutionMode
* @return LogicalExpression
* @default development
*/
getExecutionMode: function() {
return this.environment.getExecutionMode();
},
... | {
let server;
if (this.__container.isRegistered(SERVER_REGISTRATION_KEY)) {
server = this.get(SERVER_REGISTRATION_KEY);
} else {
server = this.project.loadServer(this);
}
if(server && _.isFunction(server.start)) {
server.start(callback);
} else {
throw new Error('Could not detect any Server r... | identifier_body |
registry.js | /*jslint node: true */
"use strict";
const _ = require('lodash'),
debug = require('debug')('node-registry:registry'),
EventEmitter = require('../event-emitter'),
OrderedConfiguration = require('../ordered-configuration'),
utils = require('../utils'),
server = require('../server'),
Environment = require('../envir... | environment: new Environment()
}).extend(ContainerAware);
/**
* Get the Sinlgeton Registry instance.
*
* @method getInstance
* @param {} opts
* @static
* @return {Registry}
*/
module.exports.getInstance = function(opts) {
if (!this.instance) {
this.instance = Registry.create(opts || {});
}
return this.in... | * @type {Environment}
*/ | random_line_split |
registry.js | /*jslint node: true */
"use strict";
const _ = require('lodash'),
debug = require('debug')('node-registry:registry'),
EventEmitter = require('../event-emitter'),
OrderedConfiguration = require('../ordered-configuration'),
utils = require('../utils'),
server = require('../server'),
Environment = require('../envir... | (callback) {
let server;
if (this.__container.isRegistered(SERVER_REGISTRATION_KEY)) {
server = this.get(SERVER_REGISTRATION_KEY);
} else {
server = this.project.loadServer(this);
}
if(server && _.isFunction(server.start)) {
server.start(callback);
} else {
throw new Error('Could not detect a... | startServer | identifier_name |
Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
},
dist: {
src: ['assets/magnific.js', 'assets/jquery-vimeothumb.js'],
dest: 'magnific_popup/blocks/magnific_popup/magnific/magnific-co... | // the banner is inserted at the top of the output
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'magnific_popup/blocks/magnific_popup/magnific/magnific-combined-1.0.0.min.js': ['<%= concat.dist.dest %>']
}
}
... | options: { | random_line_split |
Tasks.js | import React, { Component, PropTypes } from 'react';
import { TextInput, ScrollView, Text, View, TouchableHighlight } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import DropdownAlert from 'react-native-dropdownalert';
import Swipeout from 'react-native-swipe-out';
import Modal from 'r... |
const list = this.tasksOpen();
return list.map((task) => {
const swipeButtons = [
{
text: 'Delete',
backgroundColor: 'red',
color: 'white',
onPress: () => this.deleteTask(task),
},
{
text: 'Done',
type: 'primary',
... | {
return;
} | conditional_block |
Tasks.js | import React, { Component, PropTypes } from 'react';
import { TextInput, ScrollView, Text, View, TouchableHighlight } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import DropdownAlert from 'react-native-dropdownalert';
import Swipeout from 'react-native-swipe-out';
import Modal from 'r... |
undoTask(task) {
this.props.markTaskIncomplete(task);
}
saveTask() {
const taskTitle = this.state.formTaskTitle;
this.setState({formTaskTitle: ''});
this.props.addTask(taskTitle);
this.closeForm();
}
_titleOnChange(text) {
this.setState({formTaskTitle: text});
}
openForm() {
... | {
this.props.markTaskComplete(task);
} | identifier_body |
Tasks.js | import React, { Component, PropTypes } from 'react';
import { TextInput, ScrollView, Text, View, TouchableHighlight } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import DropdownAlert from 'react-native-dropdownalert';
import Swipeout from 'react-native-swipe-out';
import Modal from 'r... | (task) {
this.props.markTaskComplete(task);
}
undoTask(task) {
this.props.markTaskIncomplete(task);
}
saveTask() {
const taskTitle = this.state.formTaskTitle;
this.setState({formTaskTitle: ''});
this.props.addTask(taskTitle);
this.closeForm();
}
_titleOnChange(text) {
this.set... | completeTask | identifier_name |
Tasks.js | import React, { Component, PropTypes } from 'react';
import { TextInput, ScrollView, Text, View, TouchableHighlight } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import DropdownAlert from 'react-native-dropdownalert';
import Swipeout from 'react-native-swipe-out';
import Modal from 'r... | if(this.props.showtabs == 'done') {
return;
}
const list = this.tasksOpen();
return list.map((task) => {
const swipeButtons = [
{
text: 'Delete',
backgroundColor: 'red',
color: 'white',
onPress: () => this.deleteTask(task),
},
... | }
listOpenTasks() { | random_line_split |
connector.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | d = {
'id': self.id,
'name': self.name,
'version': self.version,
'class': getattr(self, 'class'),
'link-config': [ link_config.to_dict() for link_config in self.link_config ],
'job-config': {},
'all-config-resources': self.config_resources
}
if 'FROM' in self.job_config... | identifier_body | |
connector.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | connector_dict['job_config']['FROM'] = [ Config.from_dict(from_config_dict) for from_config_dict in connector_dict['job-config']['FROM'] ]
if 'TO' in connector_dict['job-config']:
connector_dict['job_config']['TO'] = [ Config.from_dict(to_config_dict) for to_config_dict in connector_dict['job-config']['... | random_line_split | |
connector.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | (connector_dict):
connector_dict.setdefault('link_config', [])
connector_dict['link_config'] = [ Config.from_dict(link_config_dict) for link_config_dict in connector_dict['link-config'] ]
connector_dict.setdefault('job_config', {})
connector_dict['job_config'] = {}
if 'FROM' in connector_dict['job... | from_dict | identifier_name |
connector.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... |
if 'TO' in self.job_config:
d['job-config']['TO'] = [ job_config.to_dict() for job_config in self.job_config['TO'] ]
return d
| d['job-config']['FROM'] = [ job_config.to_dict() for job_config in self.job_config['FROM'] ] | conditional_block |
callbacks.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | trait Object<T> {
fn call(&self, args: T);
}
impl<UserData> Object<Args> for ::Callback<fn($($arg_ty),*, &UserData), UserData> {
fn call(&self, ($($arg),*,): Args) {
(self.f)($($arg),*, &self.data);
}
}
pub fn set<UserData: 's... | random_line_split | |
callbacks.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | <'a>(window: &'a *mut ffi::GLFWwindow) -> &'a Sender<(f64, WindowEvent)> {
mem::transmute(ffi::glfwGetWindowUserPointer(*window))
}
macro_rules! window_callback(
(fn $name:ident () => $event:ident) => (
pub extern "C" fn $name(window: *mut ffi::GLFWwindow) {
unsafe { get_sender(&window).sen... | get_sender | identifier_name |
callbacks.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
macro_rules! window_callback(
(fn $name:ident () => $event:ident) => (
pub extern "C" fn $name(window: *mut ffi::GLFWwindow) {
unsafe { get_sender(&window).send((ffi::glfwGetTime() as f64, $event)); }
}
);
(fn $name:ident ($($ext_arg:ident: $ext_arg_ty:ty),*) => $event:ident($... | {
mem::transmute(ffi::glfwGetWindowUserPointer(*window))
} | identifier_body |
env.py | # -*- coding: utf-8 -*-
## Copyright © 2012, Matthias Urlichs <matthias@urlichs.de>
##
## 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 op... | elf, h, logger=None):
"""Calculate a weighted factor for history entry @h, based on the given environmental parameters"""
ql=(
(6,(True,True,True)),
(4,(False,True,True)),
(4,(True,False,True)),
(4,(True,True,False)),
(1,(True,False,False)),
(1,(False,True,False)),
(1,(False,False,True)),
)
... | v_factor(s | identifier_name |
env.py | # -*- coding: utf-8 -*-
## Copyright © 2012, Matthias Urlichs <matthias@urlichs.de>
##
## 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 op... | q &= Q(temp__isnull=not qtemp)
q &= Q(wind__isnull=not qwind)
q &= Q(sun__isnull=not qsun)
sum_f = 0
sum_w = 0
try:
ec = self.env_cache[tws]
except KeyError:
self.env_cache[tws] = ec = list(self.items.filter(q))
for ef in ec:
d=0
if qtemp:
d += (h.temp-ef.temp)**2
if qwind:
d += ... | if qtemp and h.temp is None: return None
if qwind and h.wind is None: return None
if qsun and h.sun is None: return None
q=Q() | random_line_split |
env.py | # -*- coding: utf-8 -*-
## Copyright © 2012, Matthias Urlichs <matthias@urlichs.de>
##
## 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 op... | d = d**(p*0.5)
if d < 0.001: # close enough
return ef.factor
sum_f += ef.factor/d
sum_w += 1/d
if not sum_w:
return None
return sum_f / sum_w
def env_factor(self, h, logger=None):
"""Calculate a weighted factor for history entry @h, based on the given environmental parameters"""
ql=(
(6,... | += (h.sun-ef.sun)**2
| conditional_block |
env.py | # -*- coding: utf-8 -*-
## Copyright © 2012, Matthias Urlichs <matthias@urlichs.de>
##
## 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 op... | name = m.CharField(max_length=200)
comment = m.CharField(max_length=200,blank=True)
site = m.ForeignKey(Site,related_name="envgroups")
factor = m.FloatField(default=1.0, help_text="Base Factor")
rain = m.BooleanField(default=True,help_text="stop when it's raining?")
def __init__(self,*a,**k):
super(EnvGroup,se... | eturn self.name
| identifier_body |
uv.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 ... | * This base module currently contains a historical, rust-based
* implementation of a few libuv operations that hews closely to
* the patterns of the libuv C-API. It was used, mostly, to explore
* some implementation details and will most likely be deprecated
* in the near future.
*
* The `ll` module contains low... | * These modules are seeing heavy work, currently, and the final
* API layout should not be inferred from its current form.
* | random_line_split |
density_calc.py | #!/usr/bin/env python
import math
fin = open('figs/single-rod-in-water.dat', 'r')
fout = open('figs/single-rods-calculated-density.dat', 'w')
kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin
first = 1
nm = 18.8972613
for line in fin:
current = str(line)
pieces = current.split('\t')... |
else:
if ((float(pieces[0])/2*nm - r2) > 0.25):
r1 = r2
r2 = float(pieces[0])/2*nm
E1 = E2
E2 = float(pieces[1]) # actually it's energy per unit length!
length = 1 # arbitrary
r = (r1 + r2)/2
dEdR = (E2-E1)/(r2-r1)*length
... | r2 = float(pieces[0])/2*nm
E2 = float(pieces[1])
first = 0 | conditional_block |
density_calc.py | #!/usr/bin/env python
import math
fin = open('figs/single-rod-in-water.dat', 'r')
fout = open('figs/single-rods-calculated-density.dat', 'w')
kB = 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin
first = 1
nm = 18.8972613
for line in fin:
current = str(line)
pieces = current.split('\t')... | fin.close()
fout.close() | random_line_split | |
L0rootsPatterns.ts | import fs = require('fs');
import mockanswer = require('vsts-task-lib/mock-answer');
import mockrun = require('vsts-task-lib/mock-run');
import path = require('path');
let taskPath = path.join(__dirname, '..', 'copyfiles.js');
let runner: mockrun.TaskMockRunner = new mockrun.TaskMockRunner(taskPath);
runner.setInput('... | fs.chmodSync = null;
runner.registerMock('fs', fs);
runner.run(); | }
});
// as a precaution, disable fs.chmodSync. it should not be called during this scenario. | random_line_split |
subscribers.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... |
@receiver(publisher.compute_all_scores_encodings_deadlines)
def compute_all_scores_encodings_deadlines(sender, **kwargs):
scores_encodings_deadline.recompute_all_deadlines(kwargs['academic_calendar'])
| cores_encodings_deadline.compute_deadline_by_student(kwargs['session_exam_deadline'])
| identifier_body |
subscribers.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | scores_encodings_deadline.compute_deadline_by_student(kwargs['session_exam_deadline'])
@receiver(publisher.compute_all_scores_encodings_deadlines)
def compute_all_scores_encodings_deadlines(sender, **kwargs):
scores_encodings_deadline.recompute_all_deadlines(kwargs['academic_calendar']) | @receiver(publisher.compute_student_score_encoding_deadline)
def compute_student_score_encoding_deadline(sender, **kwargs): | random_line_split |
subscribers.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | sender, **kwargs):
scores_encodings_deadline.recompute_all_deadlines(kwargs['academic_calendar'])
| ompute_all_scores_encodings_deadlines( | identifier_name |
clustertree.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... |
return self._intercluster_dist
def _get_silh(self):
if self._silhouette is None:
self.get_silhouette()
return self._silhouette
def _get_prof(self):
if self._profile is None:
self._calculate_avg_profile()
return self._profile
def _get_std(se... | self.get_silhouette() | conditional_block |
clustertree.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... |
def set_distance_function(self, fn):
""" Sets the distance function used to calculate cluster
distances and silouette index.
ARGUMENTS:
fn: a pointer to python function acepting two arrays (numpy) as
arguments.
EXAMPLE:
# A simple euclidean distanc... | return "ClusterTree node (%s)" %hex(self.__hash__()) | identifier_body |
clustertree.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... | (self):
""" This internal function updates the mean profile
associated to an internal node. """
# Updates internal values
self._profile, self._std_profile = clustvalidation.get_avg_profile(self)
# cosmetic alias
#: .. currentmodule:: ete3
#
ClusterTree = ClusterNode
| _calculate_avg_profile | identifier_name |
clustertree.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... |
# Initialize tree with array data
if text_array:
self.link_to_arraytable(text_array)
if newick:
self.set_distance_function(fdist)
def __repr__(self):
return "ClusterTree node (%s)" %hex(self.__hash__())
def set_distance_function(self, fn):
""" ... | self.features.add("deviation") | random_line_split |
PropertyPathInterface.d.ts | declare namespace Jymfony.Contracts.PropertyAccess {
export class PropertyPathInterface implements Iterable<string> {
/**
* Returns the path as string.
*/
toString(): string;
/**
* Returns the element at given index.
*
* @throws {Jymfony.Contract... | }
} | /**
* Returns the last element of the path.
*/
public readonly last: number; | random_line_split |
PropertyPathInterface.d.ts | declare namespace Jymfony.Contracts.PropertyAccess {
export class | implements Iterable<string> {
/**
* Returns the path as string.
*/
toString(): string;
/**
* Returns the element at given index.
*
* @throws {Jymfony.Contracts.PropertyAccess.Exception.OutOfBoundsException}
*/
getElement(index: numb... | PropertyPathInterface | identifier_name |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{DEFAULT_BUILD_DIR, DEFAULT_PACKAGE_DIR, DEFAULT_SOURCE_DIR, DEFAULT_STORAGE_DIR};
use anyhow::anyhow;
use move_coverage::coverage_map::{CoverageMap, ExecCoverageMapWithModules};
use move_lang::{
command_line::{read_bool_... | (path: &str) -> anyhow::Result<()> {
let path = Path::new(path);
if path.exists() {
anyhow::bail!("{:#?} already exists. Remove {:#?} and re-run this command if creating it as a test directory was intentional.", path, path);
}
let format_src_dir = |dir| format!("{}/{}", DEFAULT_SOURCE_DIR, dir... | create_test_scaffold | identifier_name |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{DEFAULT_BUILD_DIR, DEFAULT_PACKAGE_DIR, DEFAULT_SOURCE_DIR, DEFAULT_STORAGE_DIR};
use anyhow::anyhow;
use move_coverage::coverage_map::{CoverageMap, ExecCoverageMapWithModules};
use move_lang::{
command_line::{read_bool_... | }
let mut output = "".to_string();
// for tracing file path: always use the absolute path so we do not need to worry about where
// the VM is executed.
let trace_file = env::current_dir()?
.join(&build_output)
.join(DEFAULT_TRACE_FILE);
// Disable colors in error reporting from... | random_line_split | |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{DEFAULT_BUILD_DIR, DEFAULT_PACKAGE_DIR, DEFAULT_SOURCE_DIR, DEFAULT_STORAGE_DIR};
use anyhow::anyhow;
use move_coverage::coverage_map::{CoverageMap, ExecCoverageMapWithModules};
use move_lang::{
command_line::{read_bool_... |
pub fn run_all(args_path: &str, cli_binary: &str, track_cov: bool) -> anyhow::Result<()> {
let mut test_total: u64 = 0;
let mut test_passed: u64 = 0;
let mut cov_info = ExecCoverageMapWithModules::empty();
// find `args.txt` and iterate over them
for entry in move_lang::find_filenames(&[args_path... | {
let args_file = io::BufReader::new(File::open(args_path)?).lines();
// path where we will run the binary
let exe_dir = args_path.parent().unwrap();
let cli_binary_path = Path::new(cli_binary).canonicalize()?;
let storage_dir = Path::new(exe_dir).join(DEFAULT_STORAGE_DIR);
let build_output = Pa... | identifier_body |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{DEFAULT_BUILD_DIR, DEFAULT_PACKAGE_DIR, DEFAULT_SOURCE_DIR, DEFAULT_STORAGE_DIR};
use anyhow::anyhow;
use move_coverage::coverage_map::{CoverageMap, ExecCoverageMapWithModules};
use move_lang::{
command_line::{read_bool_... |
}
}
ret
}
fn collect_coverage(
trace_file: &Path,
build_dir: &Path,
storage_dir: &Path,
) -> anyhow::Result<ExecCoverageMapWithModules> {
fn find_compiled_move_filenames(path: &Path) -> anyhow::Result<Vec<String>> {
if path.exists() {
move_lang::find_filenames(&[pat... | {
ret.push_str("\x1B[91m");
ret.push_str(x);
ret.push_str("\x1B[0m");
ret.push('\n');
} | conditional_block |
WidgetUtil.js | // Copyright (c) 2007 Divmod.
// See LICENSE for details.
|
/**
* Make a node suitable for passing as the first argument to a
* L{Nevow.Athena.Widget} constructor.
*
* @param athenaID: the athena ID of the widget this node belongs to.
* defaults to '1'.
* @type athenaID: C{Number}
*
* @return: a node.
*/
Nevow.Test.WidgetUtil.makeWidgetNode = function makeWidgetNode(... | /**
* Utilities for testing L{Nevow.Athena.Widget} subclasses.
*/ | random_line_split |
WidgetUtil.js | // Copyright (c) 2007 Divmod.
// See LICENSE for details.
/**
* Utilities for testing L{Nevow.Athena.Widget} subclasses.
*/
/**
* Make a node suitable for passing as the first argument to a
* L{Nevow.Athena.Widget} constructor.
*
* @param athenaID: the athena ID of the widget this node belongs to.
* defaults ... |
var node = document.createElement('div');
node.id = Nevow.Athena.Widget.translateAthenaID(athenaID);
return node;
}
/**
* Tell athena that there is a widget with the ID C{athenaID}.
*
* @param widget: a widget (the one to associate with C{athenaID}).
* @type widget: L{Nevow.Athena.Widget}
*
* @para... | {
athenaID = 1;
} | conditional_block |
TaskManagerPlugin.py | """ Container for TaskManager plug-ins, to handle the destination of the tasks
"""
import six
from DIRAC import gLogger
from DIRAC.Core.Utilities.List import fromChar
from DIRAC.Core.Utilities.SiteSEMapping import getSitesForSE
from DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers
from DIRAC.Configura... |
except KeyError:
pass
if not seList or seList == ["Unknown"]:
return destSites
for se in seList:
res = getSitesForSE(se)
if not res["OK"]:
gLogger.warn("Could not get Sites associated to SE", res["Message"])
else:
... | if isinstance(self.params["TargetSE"], six.string_types):
seList = fromChar(self.params["TargetSE"])
elif isinstance(self.params["TargetSE"], list):
seList = self.params["TargetSE"] | conditional_block |
TaskManagerPlugin.py | """ Container for TaskManager plug-ins, to handle the destination of the tasks
"""
import six
from DIRAC import gLogger
from DIRAC.Core.Utilities.List import fromChar
from DIRAC.Core.Utilities.SiteSEMapping import getSitesForSE
from DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers
from DIRAC.Configura... | (self):
"""By default, all sites are allowed to do every job.
The actual rules are freely specified in the Operation JobTypeMapping section.
The content of the section may look like this:
User
{
Exclude = PAK
Exclude += Ferrara
Exclude += Bologna
... | _ByJobType | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.