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 |
|---|---|---|---|---|
RecomputeParameters.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------#
# #
# This file is part of the Parametric Workbench #
# ... | eeCADGui.addCommand('RecomputeParameters', RecomputeParameters())
| arameter.Parameter.getAvailableParameters():
return True
else:
return False
Fr | conditional_block |
RecomputeParameters.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------#
# #
# This file is part of the Parametric Workbench #
# ... | f):
""" Active only when there is a document, and Parameters have been created """
if not FreeCAD.ActiveDocument:
return False
else:
if Parameter.Parameter.getAvailableParameters():
return True
else:
return False
FreeCADGui.add... | tive(sel | identifier_name |
RecomputeParameters.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------#
# #
# This file is part of the Parametric Workbench #
# ... | def IsActive(self):
""" Active only when there is a document, and Parameters have been created """
if not FreeCAD.ActiveDocument:
return False
else:
if Parameter.Parameter.getAvailableParameters():
return True
else:
return Fal... | obj in Parameter.Parameter.getAvailableParameters():
obj.touch()
FreeCAD.ActiveDocument.recompute()
return True
| identifier_body |
RecomputeParameters.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------#
# #
# This file is part of the Parametric Workbench #
# ... |
def Activated(self):
for obj in Parameter.Parameter.getAvailableParameters():
obj.touch()
FreeCAD.ActiveDocument.recompute()
return True
def IsActive(self):
""" Active only when there is a document, and Parameters have been created """
if not FreeCAD.ActiveD... | random_line_split | |
Algorithms.py | __all__ = [
"getMin"
]
__doc__ = "Different algorithms used for optimization"
import Optizelle.Unconstrained.State
import Optizelle.Unconstrained.Functions
from Optizelle.Utility import *
from Optizelle.Properties import *
from Optizelle.Functions import *
| if smanip is None:
smanip = StateManipulator()
# Check the arguments
checkVectorSpace("X",X)
checkMessaging("msg",msg)
Optizelle.Unconstrained.Functions.checkT("fns",fns)
Optizelle.Unconstrained.State.checkT("state",state)
checkStateManipulator("smanip",smanip)
# Call the optim... | def getMin(X, msg, fns, state, smanip=None):
"""Solves an unconstrained optimization problem
Basic solve: getMin(X,msg,fns,state)
Solve with a state manipulator: getMin(X,msg,fns,state,smanip)
""" | random_line_split |
Algorithms.py | __all__ = [
"getMin"
]
__doc__ = "Different algorithms used for optimization"
import Optizelle.Unconstrained.State
import Optizelle.Unconstrained.Functions
from Optizelle.Utility import *
from Optizelle.Properties import *
from Optizelle.Functions import *
def getMin(X, msg, fns, state, smanip=None):
"""Solv... |
# Check the arguments
checkVectorSpace("X",X)
checkMessaging("msg",msg)
Optizelle.Unconstrained.Functions.checkT("fns",fns)
Optizelle.Unconstrained.State.checkT("state",state)
checkStateManipulator("smanip",smanip)
# Call the optimization
UnconstrainedAlgorithmsGetMin(X,msg,fns,state,... | smanip = StateManipulator() | conditional_block |
Algorithms.py | __all__ = [
"getMin"
]
__doc__ = "Different algorithms used for optimization"
import Optizelle.Unconstrained.State
import Optizelle.Unconstrained.Functions
from Optizelle.Utility import *
from Optizelle.Properties import *
from Optizelle.Functions import *
def getMin(X, msg, fns, state, smanip=None):
| """Solves an unconstrained optimization problem
Basic solve: getMin(X,msg,fns,state)
Solve with a state manipulator: getMin(X,msg,fns,state,smanip)
"""
if smanip is None:
smanip = StateManipulator()
# Check the arguments
checkVectorSpace("X",X)
checkMessaging("msg",msg)
Optizell... | identifier_body | |
Algorithms.py | __all__ = [
"getMin"
]
__doc__ = "Different algorithms used for optimization"
import Optizelle.Unconstrained.State
import Optizelle.Unconstrained.Functions
from Optizelle.Utility import *
from Optizelle.Properties import *
from Optizelle.Functions import *
def | (X, msg, fns, state, smanip=None):
"""Solves an unconstrained optimization problem
Basic solve: getMin(X,msg,fns,state)
Solve with a state manipulator: getMin(X,msg,fns,state,smanip)
"""
if smanip is None:
smanip = StateManipulator()
# Check the arguments
checkVectorSpace("X",X)
... | getMin | identifier_name |
mutedrainbow_sky.js | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* 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 sou... | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRE... | random_line_split | |
collectionBasedTreeReducerGenerator.ts | import { CLEAR_QUERY_WAS_CLICKED } from '../actions';
import { Nodes } from '../types';
import { GenericCollectionAction } from '../types';
import { Selected } from '../types';
export const collectionBasedTreeReducerGenerator = (collection = '', collectionBasedTreeReducer: any) => {
... | }
return collectionBasedTreeReducer(state, action, textSearchState);
};
}; | if (action.collection !== collection && action.type !== CLEAR_QUERY_WAS_CLICKED) {
return state; | random_line_split |
collectionBasedTreeReducerGenerator.ts | import { CLEAR_QUERY_WAS_CLICKED } from '../actions';
import { Nodes } from '../types';
import { GenericCollectionAction } from '../types';
import { Selected } from '../types';
export const collectionBasedTreeReducerGenerator = (collection = '', collectionBasedTreeReducer: any) => {
... |
return collectionBasedTreeReducer(state, action, textSearchState);
};
};
| {
return state;
} | conditional_block |
iterable_differs.ts | import {isBlank, isPresent, CONST} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from '../change_detector_ref';
import {Provider, SkipSelfMetadata, OptionalMetadata, Injectable} from '... |
static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers {
if (isPresent(parent)) {
var copied = ListWrapper.clone(parent.factories);
factories = factories.concat(copied);
return new IterableDiffers(factories);
} else {
return new IterableDiffers(f... | {} | identifier_body |
iterable_differs.ts | import {isBlank, isPresent, CONST} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from '../change_detector_ref';
import {Provider, SkipSelfMetadata, OptionalMetadata, Injectable} from '... | factories = factories.concat(copied);
return new IterableDiffers(factories);
} else {
return new IterableDiffers(factories);
}
}
/**
* Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
* inherited {@link IterableDiffers} instance with the prov... | constructor(public factories: IterableDifferFactory[]) {}
static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers {
if (isPresent(parent)) {
var copied = ListWrapper.clone(parent.factories); | random_line_split |
iterable_differs.ts | import {isBlank, isPresent, CONST} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from '../change_detector_ref';
import {Provider, SkipSelfMetadata, OptionalMetadata, Injectable} from '... |
}
}
| {
throw new BaseException(`Cannot find a differ supporting object '${iterable}'`);
} | conditional_block |
iterable_differs.ts | import {isBlank, isPresent, CONST} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from '../change_detector_ref';
import {Provider, SkipSelfMetadata, OptionalMetadata, Injectable} from '... | (iterable: any): IterableDifferFactory {
var factory = this.factories.find(f => f.supports(iterable));
if (isPresent(factory)) {
return factory;
} else {
throw new BaseException(`Cannot find a differ supporting object '${iterable}'`);
}
}
}
| find | identifier_name |
try.it.ts | import * as $ from 'jquery';
import '../assets/styles/extras.scss';
interface InitializationParams {
origin: string;
runnerSnippetUrl: string;
wacUrl: string;
}
(() => {
(window as any).in_try_it_mode = true;
(window as any).initializeTryIt = initializeTryIt;
let snippetId;
function initi... |
snippetId = event.data.id;
}
}
})();
| {
return;
} | conditional_block |
try.it.ts | import * as $ from 'jquery';
import '../assets/styles/extras.scss';
interface InitializationParams {
origin: string;
runnerSnippetUrl: string;
wacUrl: string;
}
(() => {
(window as any).in_try_it_mode = true;
(window as any).initializeTryIt = initializeTryIt;
let snippetId;
function initi... |
})();
| {
window.addEventListener('message', receiveMessage, false);
$(document).ready(() => {
let url = params.wacUrl;
let session = new (OfficeExtension as any).EmbeddedSession(url, { id: 'embed-frame', container: document.getElementById('panel-bottom') });
session.init().t... | identifier_body |
try.it.ts | import * as $ from 'jquery';
import '../assets/styles/extras.scss';
interface InitializationParams {
origin: string;
runnerSnippetUrl: string;
wacUrl: string;
}
(() => {
(window as any).in_try_it_mode = true;
(window as any).initializeTryIt = initializeTryIt;
let snippetId;
function | (params: InitializationParams): void {
window.addEventListener('message', receiveMessage, false);
$(document).ready(() => {
let url = params.wacUrl;
let session = new (OfficeExtension as any).EmbeddedSession(url, { id: 'embed-frame', container: document.getElementById('panel-bott... | initializeTryIt | identifier_name |
try.it.ts | import * as $ from 'jquery';
import '../assets/styles/extras.scss';
interface InitializationParams {
origin: string;
runnerSnippetUrl: string;
wacUrl: string;
}
(() => {
(window as any).in_try_it_mode = true;
(window as any).initializeTryIt = initializeTryIt;
let snippetId;
function initi... | }
})(); | return;
}
snippetId = event.data.id;
} | random_line_split |
dump.py | #!/usr/bin/env python
# cardinal_pythonlib/sqlalchemy/dump.py
"""
===============================================================================
Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version ... |
writeline_nl(fileobj,
sql_comment(f"Schema (for dialect {dialect_name}):"))
engine = create_engine(f"{dialect_name}://",
strategy="mock", executor=dump)
metadata.create_all(engine, checkfirst=checkfirst)
# ... checkfirst doesn't seem to be working for the mo... | compsql = querysql.compile(dialect=engine.dialect)
writeline_nl(fileobj, f"{compsql};") | identifier_body |
dump.py | #!/usr/bin/env python
# cardinal_pythonlib/sqlalchemy/dump.py
"""
===============================================================================
Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version ... |
writeline_nl(fileobj, SEP2)
log.debug("... done")
def dump_database_as_insert_sql(engine: Engine,
fileobj: TextIO = sys.stdout,
include_ddl: bool = False,
multirow: bool = False) -> None:
"""
Reads an enti... | found_one = False
for r in cursor:
found_one = True
row_dict = dict(r)
statement = table.insert(values=row_dict)
# insert_str = literal_query(statement)
insert_str = get_literal_query(statement, bind=engine)
# log.debug("row_dict: {}", row_... | conditional_block |
dump.py | #!/usr/bin/env python
# cardinal_pythonlib/sqlalchemy/dump.py
"""
===============================================================================
Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version ... | if multirow:
log.warning("dump_data_as_insert_sql: multirow parameter substitution "
"not working yet")
multirow = False
# literal_query = make_literal_query_fn(dialect)
meta = MetaData(bind=engine)
log.debug("... retrieving schema")
table = Table(table_name, me... | if not dialect.supports_multivalues_insert:
multirow = False | random_line_split |
dump.py | #!/usr/bin/env python
# cardinal_pythonlib/sqlalchemy/dump.py
"""
===============================================================================
Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version ... | (engine: Engine,
baseobj: object,
fileobj: TextIO) -> None:
"""
Sends an object, and all its relations (discovered via "relationship"
links) as ``INSERT`` commands in SQL, to ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
... | dump_orm_tree_as_insert_sql | identifier_name |
R114.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com>
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 Softwar... | -0.3546364e-11*f],
"pow": [1, 2, 3, 4]}
platzer = {
"__type__": "Helmholtz",
"__name__": "Bender equation of state for R-114 of Platzer (1990)",
"__doi__": {"autor": "Platzer, B., Polt, A., Maurer, G.",
"title": "Thermophysical Properties of ... |
f = 1/8.31451*170.93
CP1 = {"ao": 0.97651380e-1*f,
"an": [0.3240861e-2*f, -0.5895364e-5*f, 0.6737929e-8*f, | random_line_split |
R114.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com>
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 Softwar... | EoS):
"""Multiparameter equation of state for R114"""
name = "1,2-dichloro-1,1,2,2-tetrafluoroethane"
CASNumber = "76-14-2"
formula = "CClF2CClF2"
synonym = "R114"
_refPropName = "R114"
_coolPropName = "R114"
rhoc = unidades.Density(579.969)
Tc = unidades.Temperature(418.83)
Pc =... | 14(M | identifier_name |
R114.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com>
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 Softwar... | "Multiparameter equation of state for R114"""
name = "1,2-dichloro-1,1,2,2-tetrafluoroethane"
CASNumber = "76-14-2"
formula = "CClF2CClF2"
synonym = "R114"
_refPropName = "R114"
_coolPropName = "R114"
rhoc = unidades.Density(579.969)
Tc = unidades.Temperature(418.83)
Pc = unidades.Pr... | identifier_body | |
num_instances_constraint.py | # Copyright (c) 2014 Cisco Systems Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
LOG.debug(_("%(host)s can accept %(num)s requested instances "
"according to NumInstancesConstraint."),
{'host': hosts[i],
'num': acceptable_num_instances})
| self.variables.append([var_matrix[i][j]])
self.coefficients.append([1])
self.constants.append(0)
self.operators.append('==') | conditional_block |
num_instances_constraint.py | # Copyright (c) 2014 Cisco Systems Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | (self, variables, hosts, filter_properties):
num_hosts = len(hosts)
num_instances = filter_properties.get('num_instances')
var_matrix = variables.host_instance_matrix
max_instances = CONF.max_instances_per_host
for i in xrange(num_hosts):
num_host_instances = hosts... | _generate_components | identifier_name |
num_instances_constraint.py | # Copyright (c) 2014 Cisco Systems Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | num_hosts = len(hosts)
num_instances = filter_properties.get('num_instances')
var_matrix = variables.host_instance_matrix
max_instances = CONF.max_instances_per_host
for i in xrange(num_hosts):
num_host_instances = hosts[i].num_instances
acceptable_num_instance... | identifier_body | |
num_instances_constraint.py | # Copyright (c) 2014 Cisco Systems Inc. | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | # All Rights Reserved. | random_line_split |
mem.rs | // Copyright 2012-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... | /// one field of a struct by replacing it with another value. The normal approach
/// doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// // error: cannot move out of dereference of `&mut`-pointer
/// ... | /// in a mutable location. For example, this function allows consumption of | random_line_split |
mem.rs | // Copyright 2012-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... | <T>() -> uint {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the type that `_val` points to in bytes.
#[inline]
#[stable]
pub fn size_of_val<T>(_val: &T) -> uint {
size_of::<T>()
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields.... | size_of | identifier_name |
mem.rs | // Copyright 2012-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... |
/// Disposes of a value.
///
/// This function can be used to destroy any value by allowing `drop` to take
/// ownership of its argument.
///
/// # Example
///
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1i);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
/// drop(mutab... | {
swap(dest, &mut src);
src
} | identifier_body |
TransferList.tsx | import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText f... |
setChecked(newChecked);
};
const handleAllRight = () => {
setRight(right.concat(left));
setLeft([]);
};
const handleCheckedRight = () => {
setRight(right.concat(leftChecked));
setLeft(not(left, leftChecked));
setChecked(not(checked, leftChecked));
};
const handleCheckedLeft = ()... | {
newChecked.splice(currentIndex, 1);
} | conditional_block |
TransferList.tsx | import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText f... | {
const classes = useStyles();
const [checked, setChecked] = React.useState<number[]>([]);
const [left, setLeft] = React.useState<number[]>([0, 1, 2, 3]);
const [right, setRight] = React.useState<number[]>([4, 5, 6, 7]);
const leftChecked = intersection(checked, left);
const rightChecked = intersection(che... | identifier_body | |
TransferList.tsx | import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText f... | (a: number[], b: number[]) {
return a.filter(value => b.indexOf(value) === -1);
}
function intersection(a: number[], b: number[]) {
return a.filter(value => b.indexOf(value) !== -1);
}
export default function TransferList() {
const classes = useStyles();
const [checked, setChecked] = React.useState<number[]>(... | not | identifier_name |
TransferList.tsx | import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText f... | </Grid>
);
} | random_line_split | |
col.py | # -*- coding: utf-8 -*-
|
import crypto_util
import store
from db import db_session, Submission
from journalist_app.decorators import login_required
from journalist_app.forms import ReplyForm
from journalist_app.utils import (make_star_true, make_star_false, get_source,
delete_collection, col_download_unread,... | from flask import (Blueprint, redirect, url_for, render_template, flash,
request, abort, send_file, current_app)
from flask_babel import gettext
from sqlalchemy.orm.exc import NoResultFound | random_line_split |
col.py | # -*- coding: utf-8 -*-
from flask import (Blueprint, redirect, url_for, render_template, flash,
request, abort, send_file, current_app)
from flask_babel import gettext
from sqlalchemy.orm.exc import NoResultFound
import crypto_util
import store
from db import db_session, Submission
from journalis... | ():
actions = {'download-unread': col_download_unread,
'download-all': col_download_all, 'star': col_star,
'un-star': col_un_star, 'delete': col_delete}
if 'cols_selected' not in request.form:
flash(gettext('No collections selected.'), 'error')
... | process | identifier_name |
col.py | # -*- coding: utf-8 -*-
from flask import (Blueprint, redirect, url_for, render_template, flash,
request, abort, send_file, current_app)
from flask_babel import gettext
from sqlalchemy.orm.exc import NoResultFound
import crypto_util
import store
from db import db_session, Submission
from journalis... |
# getlist is cgi.FieldStorage.getlist
cols_selected = request.form.getlist('cols_selected')
action = request.form['action']
if action not in actions:
return abort(500)
method = actions[action]
return method(cols_selected)
@view.route('/<filesystem_id>... | flash(gettext('No collections selected.'), 'error')
return redirect(url_for('main.index')) | conditional_block |
col.py | # -*- coding: utf-8 -*-
from flask import (Blueprint, redirect, url_for, render_template, flash,
request, abort, send_file, current_app)
from flask_babel import gettext
from sqlalchemy.orm.exc import NoResultFound
import crypto_util
import store
from db import db_session, Submission
from journalis... |
return view
| """Sends a client the contents of a single submission."""
if '..' in fn or fn.startswith('/'):
abort(404)
try:
Submission.query.filter(
Submission.filename == fn).one().downloaded = True
db_session.commit()
except NoResultFound as e:
... | identifier_body |
dump.rs | use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn main() {
let stdout = io::stdout();
let mut out = stdout.loc... | {
let strbuf: String;
let protocol_name = match rec.protocol_identifier() {
Some(1) => "ICMP",
Some(4) => "IPIP",
Some(6) => "TCP",
Some(17) => "UDP",
Some(41) => "IP6IP",
Some(47) => "GRE",
Some(50) => "ESP",
Some(58) => "ICMP",
Some(n... | identifier_body | |
dump.rs | use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn | () {
let stdout = io::stdout();
let mut out = stdout.lock();
for arg in env::args().skip(1) {
match File::open(&arg) {
Ok(ref mut file) => dump_file(&mut out, file),
Err(err) => writeln!(out, "Could not open {}: {}", arg, err).unwrap()
}
}
}
fn dump_file<F,W>(mut... | main | identifier_name |
dump.rs | use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn main() {
let stdout = io::stdout();
let mut out = stdout.loc... | //println!("raw template: {:?}", &template_raw[..]);
let template: DataTemplate = DataTemplate {
template_id: template_id,
field_count: (template_length / 4) as u16,
fields: TemplateFieldIter { raw: &template_raw[..]}
};
ext... | writeln!(out, "template_id: {}, template_length: {}", template_id, template_length).unwrap();
let mut template_raw = Vec::with_capacity(template_length);
file.take(template_length as u64).read_to_end(&mut template_raw).unwrap(); | random_line_split |
dump.rs | use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr};
extern crate flate2;
use flate2::read::ZlibDecoder;
extern crate netflowv9;
use netflowv9::*;
fn main() {
let stdout = io::stdout();
let mut out = stdout.loc... | else {
break;
}
}
}
fn print_record<W>(w: &mut W, rec: &Record) where W: Write {
let strbuf: String;
let protocol_name = match rec.protocol_identifier() {
Some(1) => "ICMP",
Some(4) => "IPIP",
Some(6) => "TCP",
Some(17) => "UDP",
Some(41) => ... | {
records.read_exact(&mut len[..]).unwrap();
let template_id = unsafe { mem::transmute::<[u8;2], u16>(tid).to_be()};
let record_length = unsafe { mem::transmute::<[u8;2], u16>(len).to_be() as usize};
records.read_exact(&mut buf[..record_length]).unwrap();
// p... | conditional_block |
more-gates.rs | // Copyright 2018 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 ... |
#[proc_macro_attribute]
pub fn attr2mac2(_: TokenStream, _: TokenStream) -> TokenStream {
"macro foo2(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac1(_: TokenStream) -> TokenStream {
"macro_rules! foo3 { (a) => (a) }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac2(_: TokenStream) -> TokenStream... | {
"macro_rules! foo1 { (a) => (a) }".parse().unwrap()
} | identifier_body |
more-gates.rs | // Copyright 2018 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 ... | (_: TokenStream) -> TokenStream {
"macro foo4(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn tricky(_: TokenStream) -> TokenStream {
"fn foo() {
macro_rules! foo { (a) => (a) }
}".parse().unwrap()
}
| mac2mac2 | identifier_name |
more-gates.rs | // Copyright 2018 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 ... | "macro_rules! foo1 { (a) => (a) }".parse().unwrap()
}
#[proc_macro_attribute]
pub fn attr2mac2(_: TokenStream, _: TokenStream) -> TokenStream {
"macro foo2(a) { a }".parse().unwrap()
}
#[proc_macro]
pub fn mac2mac1(_: TokenStream) -> TokenStream {
"macro_rules! foo3 { (a) => (a) }".parse().unwrap()
}
#[p... |
#[proc_macro_attribute]
pub fn attr2mac1(_: TokenStream, _: TokenStream) -> TokenStream { | random_line_split |
interfacebsort_1_1quick__sort__gen.js | var interfacebsort_1_1quick__sort__gen =
[
[ "quick_sort_vec_gen_dble", "interfacebsort_1_1quick__sort__gen_a026a7eee27468ff06ba0a0505fe6a5ce.html#a026a7eee27468ff06ba0a0505fe6a5ce", null ],
[ "quick_sort_vec_gen_int", "interfacebsort_1_1quick__sort__gen_a69e4550f2d7428dbbbb3b2017c9d3384.html#a69e4550f2d7428dbb... | [ "quick_sort_vec_gen_map_dble", "interfacebsort_1_1quick__sort__gen_a27669196bddc9d3d659db1cba4fe18b1.html#a27669196bddc9d3d659db1cba4fe18b1", null ],
[ "quick_sort_vec_gen_map_int", "interfacebsort_1_1quick__sort__gen_a388e1b92b263b8bc1ed53186db2c2f77.html#a388e1b92b263b8bc1ed53186db2c2f77", null ],
[ "qu... | random_line_split | |
framerate.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/. */
use actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_tra... |
fn stop_recording(&mut self) {
if !self.is_recording {
return;
}
self.is_recording = false;
self.start_time = None;
}
}
impl Drop for FramerateActor {
fn drop(&mut self) {
self.stop_recording();
}
}
| {
if self.is_recording {
return;
}
self.start_time = Some(precise_time_ns());
self.is_recording = true;
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
sel... | identifier_body |
framerate.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/. */
use actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_tra... | (&self) -> String {
self.name.clone()
}
fn handle_message(&self,
_registry: &ActorRegistry,
_msg_type: &str,
_msg: &json::Object,
_stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(ActorMessage... | name | identifier_name |
framerate.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/. */
use actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_tra... |
self.start_time = Some(precise_time_ns());
self.is_recording = true;
let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
fn stop_recordi... | {
return;
} | conditional_block |
framerate.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/. */
use actor::{Actor, ActorMessageStatus, ActorRegistry};
use actors::timeline::HighResolutionStamp;
use devtools_tra... | let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline,
self.name());
self.script_sender.send(msg).unwrap();
}
}
pub fn take_pending_ticks(&mut self) -> Vec<HighResolutionStamp> {
mem::r... | random_line_split | |
mysql.ts | import KnexMySQL, { parseDefaultValue } from 'knex-schema-inspector/dist/dialects/mysql';
import { SchemaOverview } from '../types/overview';
import { SchemaInspector } from '../types/schema';
export default class MySQL extends KnexMySQL implements SchemaInspector {
async overview(): Promise<SchemaOverview> {
const... |
overview[column.table_name].columns[column.column_name] = {
...column,
default_value: column.extra === 'auto_increment' ? 'AUTO_INCREMENT' : parseDefaultValue(column.default_value),
is_nullable: column.is_nullable === 'YES',
is_generated: column.extra?.endsWith('GENERATED') ?? false,
data_type:... | {
dataType = 'boolean';
} | conditional_block |
mysql.ts | import KnexMySQL, { parseDefaultValue } from 'knex-schema-inspector/dist/dialects/mysql';
import { SchemaOverview } from '../types/overview';
import { SchemaInspector } from '../types/schema';
export default class MySQL extends KnexMySQL implements SchemaInspector {
async | (): Promise<SchemaOverview> {
const columns = await this.knex.raw(
`
SELECT
C.TABLE_NAME as table_name,
C.COLUMN_NAME as column_name,
C.COLUMN_DEFAULT as default_value,
C.IS_NULLABLE as is_nullable,
C.COLUMN_TYPE as data_type,
C.COLUMN_KEY as column_key,
C.CHARACTER_MAXIMUM_LENGTH as... | overview | identifier_name |
mysql.ts | import KnexMySQL, { parseDefaultValue } from 'knex-schema-inspector/dist/dialects/mysql';
import { SchemaOverview } from '../types/overview';
import { SchemaInspector } from '../types/schema';
export default class MySQL extends KnexMySQL implements SchemaInspector {
async overview(): Promise<SchemaOverview> {
const... | const overview: SchemaOverview = {};
for (const column of columns[0]) {
if (column.table_name in overview === false) {
const primaryKeys = columns[0].filter((nested: { column_key: string; table_name: string }) => {
return nested.table_name === column.table_name && nested.column_key === 'PRI';
});
... | [this.knex.client.database()]
);
| random_line_split |
mysql.ts | import KnexMySQL, { parseDefaultValue } from 'knex-schema-inspector/dist/dialects/mysql';
import { SchemaOverview } from '../types/overview';
import { SchemaInspector } from '../types/schema';
export default class MySQL extends KnexMySQL implements SchemaInspector {
async overview(): Promise<SchemaOverview> |
}
| {
const columns = await this.knex.raw(
`
SELECT
C.TABLE_NAME as table_name,
C.COLUMN_NAME as column_name,
C.COLUMN_DEFAULT as default_value,
C.IS_NULLABLE as is_nullable,
C.COLUMN_TYPE as data_type,
C.COLUMN_KEY as column_key,
C.CHARACTER_MAXIMUM_LENGTH as max_length,
C.EXTRA as ... | identifier_body |
nnet.py | import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell, GRUCell, MultiRNNCell, DropoutWrapper
from tqdm import tqdm
from decoder import pointer_decoder
import dataset
import matplotlib.pyplot as plt
# TODO
"""
Michel:
_____________________________________________________________________
... | ():
# Config
args={}
args['batch_size']=32
args['max_length']=5
args['input_dimension']=2
args['input_embed']=16
args['init_bias_c']=-args['max_length']/2
args['num_neurons']=256
args['init_range']=1
args['temperature_decay']=1
# Build Model and Reward
... | train | identifier_name |
nnet.py | import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell, GRUCell, MultiRNNCell, DropoutWrapper
from tqdm import tqdm
from decoder import pointer_decoder
import dataset
import matplotlib.pyplot as plt
# TODO
"""
Michel:
_____________________________________________________________________
... |
def build_critic(self):
# Embed input sequence (for critic)
W_embed_c = tf.Variable(tf.truncated_normal([1,self.input_new_dimension,self.input_embed_c]), name="critic_W_embed")
with tf.variable_scope("Critic"):
if self.step>0:
tf.get_variable_scope(... | self.input_coordinates = tf.placeholder(tf.float32, [self.batch_size, self.max_length, self.input_dimension], name="Input")
self.input_description = tf.placeholder(tf.float32, [self.batch_size, self.max_length, self.input_new_dimension], name="Input")
# Embed input sequence
W_embed = tf.Var... | identifier_body |
nnet.py | import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell, GRUCell, MultiRNNCell, DropoutWrapper
from tqdm import tqdm
from decoder import pointer_decoder
import dataset
import matplotlib.pyplot as plt
# TODO
"""
Michel:
_____________________________________________________________________
... | # Loss
self.loss2=tf.losses.mean_squared_error(self.reward,self.prediction_c)
# Minimize step
self.train_step2 = self.opt2.minimize(self.loss2)
def run_episode(self,sess):
# Get feed_dict
training_set = dataset.DataGenerator()
coord_batc... | self.opt2 = tf.train.AdamOptimizer(learning_rate=0.01,beta1=0.9,beta2=0.9,epsilon=0.1)
| random_line_split |
nnet.py | import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell, GRUCell, MultiRNNCell, DropoutWrapper
from tqdm import tqdm
from decoder import pointer_decoder
import dataset
import matplotlib.pyplot as plt
# TODO
"""
Michel:
_____________________________________________________________________
... |
plt.figure(1)
plt.subplot(211)
plt.plot(avg_ac_deviation)
plt.ylabel('Critic average deviation (%)')
plt.xlabel('Epoch')
plt.subplot(212)
plt.plot(avg_seq_proba)
plt.ylabel('Actor average seq proba')
plt.xlabel('Epoch')
plt.s... | seq_input, permutation, seq_proba, b_s, trip, circuit_length, reward = model.run_episode(sess)
# Store Actor-Critic deviation & seq proba
avg_ac_deviation.append(sess.run(tf.reduce_mean(100*(reward-b_s)/circuit_length)))
avg_seq_proba.append(sess.run(tf.reduce_mean(seq_proba)))
... | conditional_block |
15.2.3.13-2-7.js | /// Copyright (c) 2009 Microsoft Corporation
///
/// 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 copyright notice, this list of conditions and
/// ... |
ES5Harness.registerTest( {
id: "15.2.3.13-2-7",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-7.js",
description: "Object.isExtensible returns true for all built-in objects (Number)",
test: function testcase() {
var e = Object.isExtensible(Number);
if (e === true) {
return true;
... | /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| random_line_split |
15.2.3.13-2-7.js | /// Copyright (c) 2009 Microsoft Corporation
///
/// 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 copyright notice, this list of conditions and
/// ... |
},
precondition: function prereq() {
return fnExists(Object.isExtensible);
}
});
| {
return true;
} | conditional_block |
l10n.js | /**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | eleventy.addFilter('localeURL', (url, locale) => {
const changed = url.split('/');
if (changed[changed.length - 1] === '') {
changed.splice(-1, 1);
}
changed.splice(1, 1, locale);
return changed.join('/');
});
// Returns the native name for the language code
eleventy.addFilter('langNa... | // Transforms given date string into local date string
// Requires full-icu and NODE_ICU_DATA=node_modules/full-icu to function
eleventy.addFilter('date', (date, locale = 'en-US', format = {}) => new Date(date).toLocaleDateString(locale, format));
// Transforms given URL into a URL for the given locale | random_line_split |
l10n.js | /**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... |
changed.splice(1, 1, locale);
return changed.join('/');
});
// Returns the native name for the language code
eleventy.addFilter('langName', code => ISO6391.getNativeName(code));
};
| {
changed.splice(-1, 1);
} | conditional_block |
TemplateTest.py | """Fonctionnal testing for "Python In HTML" (PIH) and "HTML In Python" (HIP).
"""
__author__ = "Didier Wenzek (didier.wenzek@free.fr)"
# The code under test is in the .. directory.
import sys
sys.path.append('..')
# We use the Python unit testing framework
import unittest
import thread, time
from util import *
class... |
def test_PIH_PrintValue(self):
"""<%= an %> tags are used to print python value."""
addScript("value.pih")
page = getPage("/value.pih")
expected = getGoldenFile("value.out")
self.assertEqual(page.status, 200)
self.assertEqual(page.content + '\n', expected)
def test_PIH_Indentation(self):
"""Python in... | """<% and %> tags are used to insert python code in HTML."""
import time
addScript("time.pih")
page = getPage("/time.pih")
today = time.strftime("%d:%m:%y",time.localtime(time.time()))
expected = getGoldenFile("time.out", date=today)
self.assertEqual(page.status, 200)
self.assertEqual(page.content, expect... | identifier_body |
TemplateTest.py | """Fonctionnal testing for "Python In HTML" (PIH) and "HTML In Python" (HIP).
"""
__author__ = "Didier Wenzek (didier.wenzek@free.fr)"
# The code under test is in the .. directory.
import sys
sys.path.append('..')
# We use the Python unit testing framework
import unittest
import thread, time
from util import *
class... | self.assertEqual(page.status, 200)
self.assertEqual(page.content, expected)
if __name__ == "__main__":
unittest.main() | def test_HIP_Principes(self):
"""Literal text in python are printed to the response stream"""
addScript("the_smiths.hip")
page = getPage("/the_smiths.hip")
expected = getGoldenFile("the_smiths.out") | random_line_split |
TemplateTest.py | """Fonctionnal testing for "Python In HTML" (PIH) and "HTML In Python" (HIP).
"""
__author__ = "Didier Wenzek (didier.wenzek@free.fr)"
# The code under test is in the .. directory.
import sys
sys.path.append('..')
# We use the Python unit testing framework
import unittest
import thread, time
from util import *
class... | (self):
"""<% and %> tags are used to insert python code in HTML."""
import time
addScript("time.pih")
page = getPage("/time.pih")
today = time.strftime("%d:%m:%y",time.localtime(time.time()))
expected = getGoldenFile("time.out", date=today)
self.assertEqual(page.status, 200)
self.assertEqual(page.conte... | test_PIH_InsertPython | identifier_name |
TemplateTest.py | """Fonctionnal testing for "Python In HTML" (PIH) and "HTML In Python" (HIP).
"""
__author__ = "Didier Wenzek (didier.wenzek@free.fr)"
# The code under test is in the .. directory.
import sys
sys.path.append('..')
# We use the Python unit testing framework
import unittest
import thread, time
from util import *
class... | unittest.main() | conditional_block | |
playing.js | var currentXCoord=0;
var currentYCoord=0;
var containerDiv = "#inputSkateTrick";
var container = $(containerDiv);
var $status = $('#status');
container.bind("contextmenu",function(e){ return false; });
var xMax=parseInt(container.css('width'));
var yMax=parseInt(container.css('height'));
var yPositionChange = Math.... | (obj,no) {
var letter=[1];
letter[1]="s";
letter[2]="k";
letter[3]="a";
letter[4]="t";
letter[5]="e";
obj.html("");
for (i=1;i<=no;i++) {
obj.html(obj.html()+letter[i]);
}
}
function updateAndRender(data) {
//0 - game status
//1 - opponent name
//2 - player1 letters
//3 - player2 letters
//4 - current ... | renderLetters | identifier_name |
playing.js | var currentXCoord=0;
var currentYCoord=0;
var containerDiv = "#inputSkateTrick";
var container = $(containerDiv);
var $status = $('#status');
container.bind("contextmenu",function(e){ return false; });
var xMax=parseInt(container.css('width'));
var yMax=parseInt(container.css('height'));
var yPositionChange = Math.... | data: feet_coords,
async: false,
success: function(data) {
if (data=="false") {
alert("error");
}
data=data.split(';')
$('#wait').html('trick sent:<br/>'+positions[data[5]]+' '+data[4]);
updateAndRender(data);
},
fail: function(xml,err) {
}
});
}
var gameStatus=false;
var opponentName=fa... | type:"POST",
url:"/horse/index.php?r=gameAjax/sendTrick&id="+gameId, | random_line_split |
playing.js | var currentXCoord=0;
var currentYCoord=0;
var containerDiv = "#inputSkateTrick";
var container = $(containerDiv);
var $status = $('#status');
container.bind("contextmenu",function(e){ return false; });
var xMax=parseInt(container.css('width'));
var yMax=parseInt(container.css('height'));
var yPositionChange = Math.... |
if (player1Letters!==data[2]) {
player1Letters=data[2];
renderLetters($('#player1 .score'),player1Letters);
}
if (player2Letters!==data[3]) {
player2Letters=data[3];
renderLetters($('#player2 .score'),player2Letters);
}
if (currentTrick!==data[4] || currentTrickPosition!==data[5] || currentPlayer... | {
opponentName=data[1];
$('#wait').css("display","none");
$('#player'+(3-youAre)+' .pName').html(opponentName);
} | conditional_block |
playing.js | var currentXCoord=0;
var currentYCoord=0;
var containerDiv = "#inputSkateTrick";
var container = $(containerDiv);
var $status = $('#status');
container.bind("contextmenu",function(e){ return false; });
var xMax=parseInt(container.css('width'));
var yMax=parseInt(container.css('height'));
var yPositionChange = Math.... |
function moveShoe(x,y) {
if (!moveTheShoe) return false;
var renderX, renderY;
if (currentShoe == 1 && y >= yPositionChange) {
if (sw) {
if (currentPosition!=4) {
currentPosition = 4;
renderCurrentFoot();
}
} else {
if (currentPosition!=1) {
currentPosition = 1;
renderCurrentFoot();
... | {
if (!moveTheShoe) return false;
if (sw) {
sw=false;
} else {
sw=true;
}
moveShoe(currentXCoord,currentYCoord);
} | identifier_body |
score_encoding_export.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 ... | else:
if not(score is None and justification is None):
ws.cell(row=row_number, column=9).style = style_no_modification
ws.cell(row=row_number, column=10).style = style_no_modification
column_number += 1
def __display_creation_date_with_message_about_state(w... | if column_number < 9 or column_number > 10:
ws.cell(row=row_number, column=column_number).style = style_no_modification | random_line_split |
score_encoding_export.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 ... | ws):
ws.append([
str(_('justification')),
str(_('justification_values_accepted') % mdl.exam_enrollment.justification_label_authorized())
])
ws.append([
str(''),
str(_('justification_other_values') % justification_other_values())
])
ws.append([
str(_('numbered_... | _display_legends( | identifier_name |
score_encoding_export.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 ... |
column_number += 1
def __display_creation_date_with_message_about_state(ws, row_number):
date_format = str(_('date_format'))
printing_date = timezone.now()
printing_date = printing_date.strftime(date_format)
ws.cell(row=row_number, column=1).value = str('%s' % (_('warn_user_data_can_change')... | f not(score is None and justification is None):
ws.cell(row=row_number, column=9).style = style_no_modification
ws.cell(row=row_number, column=10).style = style_no_modification
| conditional_block |
score_encoding_export.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 ... |
def __get_session_exam_deadline(exam_enroll):
date_format = str(_('date_format'))
deadline = None
session_exam_deadline = mdl.exam_enrollment.get_session_exam_deadline(exam_enroll)
if session_exam_deadline:
deadline = session_exam_deadline.deadline_tutor_computed if session_exam_deadline.dead... | eturn "%s, %s" % (_('unjustified_absence_export_legend'),
_('justified_absence_export_legend'))
| identifier_body |
extra-unused-mut.rs | // extra unused mut lint tests for #51918
// check-pass
#![feature(generators, nll)]
#![deny(unused_mut)]
fn ref_argument(ref _y: i32) {}
// #51801
fn mutable_upvar() {
let mut x = 0;
move || {
x = 1;
};
} | x = 1;
yield;
};
}
// #51830
fn ref_closure_argument() {
let _ = Some(0).as_ref().map(|ref _a| true);
}
struct Expr {
attrs: Vec<u32>,
}
// #51904
fn parse_dot_or_call_expr_with(mut attrs: Vec<u32>) {
let x = Expr { attrs: vec![] };
Some(Some(x)).map(|expr|
expr.map(|mut e... |
// #50897
fn generator_mutable_upvar() {
let mut x = 0;
move || { | random_line_split |
extra-unused-mut.rs | // extra unused mut lint tests for #51918
// check-pass
#![feature(generators, nll)]
#![deny(unused_mut)]
fn ref_argument(ref _y: i32) {}
// #51801
fn mutable_upvar() {
let mut x = 0;
move || {
x = 1;
};
}
// #50897
fn generator_mutable_upvar() {
let mut x = 0;
move || {
x = 1;
... |
// #59620
fn nested_closures() {
let mut i = 0;
[].iter().for_each(|_: &i32| {
[].iter().for_each(move |_: &i32| {
i += 1;
});
});
}
fn main() {}
| {
match x {
Ok(mut r) | Err(mut r) if true => r = 1,
_ => (),
}
} | identifier_body |
extra-unused-mut.rs | // extra unused mut lint tests for #51918
// check-pass
#![feature(generators, nll)]
#![deny(unused_mut)]
fn ref_argument(ref _y: i32) {}
// #51801
fn mutable_upvar() {
let mut x = 0;
move || {
x = 1;
};
}
// #50897
fn generator_mutable_upvar() {
let mut x = 0;
move || {
x = 1;
... | (x: Result<i32, i32>) {
match x {
Ok(mut r) | Err(mut r) if true => r = 1,
_ => (),
}
}
// #59620
fn nested_closures() {
let mut i = 0;
[].iter().for_each(|_: &i32| {
[].iter().for_each(move |_: &i32| {
i += 1;
});
});
}
fn main() {}
| if_guard | identifier_name |
view-spec.ts | import { ViewDef, compileViewDefs } from './view-def'
import { Duration, createDuration, greatestDurationDenominator, DurationInput } from '../datelib/duration'
import { mapHash } from '../util/object'
import { ViewOptions, CalendarOptions, BASE_OPTION_DEFAULTS } from '../options'
import { ViewConfigInputHash, parseVie... | let durationInputMap: { [json: string]: Duration } = {}
function createDurationCached(durationInput: DurationInput) {
let json = JSON.stringify(durationInput)
let res = durationInputMap[json]
if (res === undefined) {
res = createDuration(durationInput)
durationInputMap[json] = res
}
return res
} | random_line_split | |
view-spec.ts | import { ViewDef, compileViewDefs } from './view-def'
import { Duration, createDuration, greatestDurationDenominator, DurationInput } from '../datelib/duration'
import { mapHash } from '../util/object'
import { ViewOptions, CalendarOptions, BASE_OPTION_DEFAULTS } from '../options'
import { ViewConfigInputHash, parseVie... | (durationInput: DurationInput) {
let json = JSON.stringify(durationInput)
let res = durationInputMap[json]
if (res === undefined) {
res = createDuration(durationInput)
durationInputMap[json] = res
}
return res
}
| createDurationCached | identifier_name |
view-spec.ts | import { ViewDef, compileViewDefs } from './view-def'
import { Duration, createDuration, greatestDurationDenominator, DurationInput } from '../datelib/duration'
import { mapHash } from '../util/object'
import { ViewOptions, CalendarOptions, BASE_OPTION_DEFAULTS } from '../options'
import { ViewConfigInputHash, parseVie... |
// hack to get memoization working
let durationInputMap: { [json: string]: Duration } = {}
function createDurationCached(durationInput: DurationInput) {
let json = JSON.stringify(durationInput)
let res = durationInputMap[json]
if (res === undefined) {
res = createDuration(durationInput)
durationInput... | {
let durationInput =
viewDef.overrides.duration ||
viewDef.defaults.duration ||
dynamicOptionOverrides.duration ||
optionOverrides.duration
let duration = null
let durationUnit = ''
let singleUnit = ''
let singleUnitOverrides: ViewOptions = {}
if (durationInput) {
duration = createDur... | identifier_body |
view-spec.ts | import { ViewDef, compileViewDefs } from './view-def'
import { Duration, createDuration, greatestDurationDenominator, DurationInput } from '../datelib/duration'
import { mapHash } from '../util/object'
import { ViewOptions, CalendarOptions, BASE_OPTION_DEFAULTS } from '../options'
import { ViewConfigInputHash, parseVie... |
}
}
let queryButtonText = (optionsSubset) => {
let buttonTextMap = optionsSubset.buttonText || {}
let buttonTextKey = viewDef.defaults.buttonTextKey as string
if (buttonTextKey != null && buttonTextMap[buttonTextKey] != null) {
return buttonTextMap[buttonTextKey]
}
if (buttonTextMa... | {
singleUnit = durationUnit
singleUnitOverrides = overrideConfigs[durationUnit] ? overrideConfigs[durationUnit].rawOptions : {}
} | conditional_block |
reporter.py | # -*- coding: utf-8 -*-
# Adapted from a contribution of Johan Dahlin
import collections
import errno
import re
import sys
try:
import multiprocessing
except ImportError: # Python 2.5
multiprocessing = None
import pep8
__all__ = ['multiprocessing', 'BaseQReport', 'QueueReport']
class BaseQReport(pep8.B... |
def start(self):
super(BaseQReport, self).start()
self.__class__._loaded = True
# spawn processes
for i in range(self.n_jobs):
p = multiprocessing.Process(target=self.process_main)
p.daemon = True
p.start()
def stop(self):
try:
... | if not self._loaded:
# Windows needs to parse again the configuration
from flake8.main import get_style_guide, DEFAULT_CONFIG
get_style_guide(parse_argv=True, config_file=DEFAULT_CONFIG)
for filename in iter(self.task_queue.get, 'DONE'):
self.input_file(filename) | identifier_body |
reporter.py | # -*- coding: utf-8 -*-
# Adapted from a contribution of Johan Dahlin
import collections
import errno
import re
import sys
try:
import multiprocessing
except ImportError: # Python 2.5
multiprocessing = None
import pep8
__all__ = ['multiprocessing', 'BaseQReport', 'QueueReport']
class BaseQReport(pep8.B... | if sys.platform == 'win32':
# Work around http://bugs.python.org/issue10845
sys.modules['__main__'].__file__ = __file__
def _cleanup_queue(self, queue):
while not queue.empty():
queue.get_nowait()
def _put_done(self):
# collect queues
for i i... | self.n_jobs = options.jobs
# init queues
self.task_queue = multiprocessing.Queue()
self.result_queue = multiprocessing.Queue() | random_line_split |
reporter.py | # -*- coding: utf-8 -*-
# Adapted from a contribution of Johan Dahlin
import collections
import errno
import re
import sys
try:
import multiprocessing
except ImportError: # Python 2.5
multiprocessing = None
import pep8
__all__ = ['multiprocessing', 'BaseQReport', 'QueueReport']
class BaseQReport(pep8.B... | (self):
return {'total_errors': self.total_errors,
'counters': self.counters,
'messages': self.messages}
def update_state(self, state):
self.total_errors += state['total_errors']
for key, value in state['counters'].items():
self.counters[key] += v... | get_state | identifier_name |
reporter.py | # -*- coding: utf-8 -*-
# Adapted from a contribution of Johan Dahlin
import collections
import errno
import re
import sys
try:
import multiprocessing
except ImportError: # Python 2.5
multiprocessing = None
import pep8
__all__ = ['multiprocessing', 'BaseQReport', 'QueueReport']
class BaseQReport(pep8.B... |
if self._show_pep8 and doc:
print(' ' + doc.strip())
sys.stdout.flush()
return self.file_errors
| if line_number > len(self.lines):
line = ''
else:
line = self.lines[line_number - 1]
print(line.rstrip())
sys.stdout.flush()
print(re.sub(r'\S', ' ', line[:offset]) + '^')
sys.stdout.flush() | conditional_block |
sidebar.component.ts | import {Component, OnDestroy} from '@angular/core';
import {DataService} from '../global/data.service';
import {SelectComponent} from '../components/select/select.component';
@Component({
selector: 'sidebar',
templateUrl: './app/sidebar/sidebar.component.html',
styleUrls: ['./app/sidebar/sidebar.component.... | if ($event.field && $event.value) {
this._dataService.addFilter({field: $event.field, values: [$event.value]});
}
}
onClearClick($event) {
this._dataService.clearFilter();
this.rows = [];
window.setTimeout(() => {
this.rows = this._dataService.res... |
onSelectChange($event) { | random_line_split |
sidebar.component.ts | import {Component, OnDestroy} from '@angular/core';
import {DataService} from '../global/data.service';
import {SelectComponent} from '../components/select/select.component';
@Component({
selector: 'sidebar',
templateUrl: './app/sidebar/sidebar.component.html',
styleUrls: ['./app/sidebar/sidebar.component.... |
}
}
| {
this._responseChangeSubscr.unsubscribe();
} | conditional_block |
sidebar.component.ts | import {Component, OnDestroy} from '@angular/core';
import {DataService} from '../global/data.service';
import {SelectComponent} from '../components/select/select.component';
@Component({
selector: 'sidebar',
templateUrl: './app/sidebar/sidebar.component.html',
styleUrls: ['./app/sidebar/sidebar.component.... | ():number {
return window.innerHeight;
}
constructor(private _dataService:DataService) {
console.log('sidebar constructor');
this.subscribeToDataResponse(true);
}
ngOnDestroy() {
if (this._responseChangeSubscr) {
this._responseChangeSubscr.unsubscribe();
... | height | identifier_name |
sidebar.component.ts | import {Component, OnDestroy} from '@angular/core';
import {DataService} from '../global/data.service';
import {SelectComponent} from '../components/select/select.component';
@Component({
selector: 'sidebar',
templateUrl: './app/sidebar/sidebar.component.html',
styleUrls: ['./app/sidebar/sidebar.component.... |
}
| {
if (state) {
this._responseChangeSubscr = this._dataService.responseChange$
.subscribe(
(response:any) => this.onResponseChange(response)
);
} else {
this._responseChangeSubscr.unsubscribe();
}
} | identifier_body |
trait-bounds-in-arc.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... | (&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num... | of_good_pedigree | identifier_name |
trait-bounds-in-arc.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... | bark_decibels: uint,
tricks_known: uint,
name: String,
}
struct Goldfyshe {
swim_speed: uint,
name: String,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
... | }
struct Dogge { | random_line_split |
trait-bounds-in-arc.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... |
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_string() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
name: "alan_turing".to_string(),
};
let dogge2 = Dogge {
... | { 0 } | identifier_body |
OrthographicCamera.js | 'use strict';
import { gl } from './Context';
import { mat4 } from 'gl-matrix';
import Camera from './Camera';
class OrthographicCamera extends Camera
{
constructor(
{
path,
uniforms,
background,
translucence,
right,
top,
name = 'orthographic.camera',
... |
set left(left)
{
this._left = left;
}
get right()
{
return this._right;
}
set right(right)
{
this._right = right;
}
get bottom()
{
return this._bottom;
}
set bottom(bottom)
{
this._bottom = bottom;
}
get top()... | {
return this._left;
} | identifier_body |
OrthographicCamera.js | 'use strict';
import { gl } from './Context';
import { mat4 } from 'gl-matrix';
import Camera from './Camera';
class OrthographicCamera extends Camera
{
constructor(
{
path,
uniforms,
background,
translucence,
right,
top,
name = 'orthographic.camera',
... | super({ name, path, uniforms, background, translucence });
this.left = left;
this.right = right;
this.bottom = bottom;
this.top = top;
this.near = near;
this.far = far;
this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera'];
... | bottom = -1,
near = 0.1,
far = 1
} = {})
{ | random_line_split |
OrthographicCamera.js | 'use strict';
import { gl } from './Context';
import { mat4 } from 'gl-matrix';
import Camera from './Camera';
class OrthographicCamera extends Camera
{
constructor(
{
path,
uniforms,
background,
translucence,
right,
top,
name = 'orthographic.camera',
... | (far)
{
this._far = far;
}
configure()
{
super.configure();
mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far);
mat4.identity(this.modelViewMatrix);
}
bind(program)
{
super.bind(program);
gl... | far | identifier_name |
FromEventPatternObservable.ts | import { isFunction } from '../util/isFunction';
import { Observable } from '../Observable';
import { Subscription } from '../Subscription';
import { Subscriber } from '../Subscriber';
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
export class FromEventPatternObservable... |
private _callAddHandler(handler: (e: any) => void, errorSubscriber: Subscriber<T>): any | null {
try {
return this.addHandler(handler) || null;
}
catch (e) {
errorSubscriber.error(e);
}
}
}
| {
try {
const result: T = this.selector(...args);
subscriber.next(result);
}
catch (e) {
subscriber.error(e);
}
} | identifier_body |
FromEventPatternObservable.ts | import { isFunction } from '../util/isFunction';
import { Observable } from '../Observable';
import { Subscription } from '../Subscription';
import { Subscriber } from '../Subscriber';
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
export class FromEventPatternObservable... |
subscriber.add(new Subscription(() => {
//TODO: determine whether or not to forward to error handler
removeHandler(handler, retValue) ;
}));
}
private _callSelector(subscriber: Subscriber<T>, args: Array<any>): void {
try {
const result: T = this.selector(...args);
subscriber.... | {
return;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.