file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
jquery.slider.js | div>' +
'<input type="hidden" class="slider-value">' +
'</div>').insertAfter(target);
var t = $(target);
t.addClass('slider-f').hide();
var name = t.attr('name');
if (name){
slider.find('input.slider-value').attr('name', name);
t.removeAttr('name').attr('sliderName', name);
}
return ... |
}
function initValue(target){
var opts = $.data(target, 'slider').options;
var fn = opts.onChange;
opts.onChange = function(){};
setValue(target, opts.value);
opts.onChange = fn;
}
/**
* translate value to slider position
*/
function value2pos(target, value){
var state = $.data(... | {
opts.onChange.call(target, value, oldValue);
} | conditional_block |
jquery.slider.js | div>' +
'<input type="hidden" class="slider-value">' +
'</div>').insertAfter(target);
var t = $(target);
t.addClass('slider-f').hide();
var name = t.attr('name');
if (name){
slider.find('input.slider-value').attr('name', name);
t.removeAttr('name').attr('sliderName', name);
}
return ... | opts.onChange = function(){};
setValue(target, opts.value);
opts.onChange = fn;
}
/**
* translate value to slider position
*/
function value2pos(target, value){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (opts.mode == 'h'){
var po... | var opts = $.data(target, 'slider').options;
var fn = opts.onChange;
| random_line_split |
jquery.slider.js | div>' +
'<input type="hidden" class="slider-value">' +
'</div>').insertAfter(target);
var t = $(target);
t.addClass('slider-f').hide();
var name = t.attr('name');
if (name){
slider.find('input.slider-value').attr('name', name);
t.removeAttr('name').attr('sliderName', name);
}
return ... | (target, param){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (param){
if (param.width) opts.width = param.width;
if (param.height) opts.height = param.height;
}
if (opts.mode == 'h'){
slider.css('height', '');
slider.children('div')... | setSize | identifier_name |
it-contract-tab-reference-create-modal.controller.ts | (function (ng, app) {
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('it-contract.edit.references.create', {
url: 'createReference/:id',
onEnter: ['$state', '$stateParams', '$uibModal', 'user',
function ($state, $stateParams, $modal, u... |
app.controller("contract.referenceCreateModalCtrl",
["$scope", "$http","contract","notify","user",
function ($scope, $http,contract,notify,user) {
$scope.dismiss = function () {
$scope.$dismiss();
};
$scope.save = function (... | });
}
]
});
}]); | random_line_split |
party.py | trytond.transaction import Transaction
from trytond import backend
from sql import As, Literal, Column
from .user import RegistrationForm
from .i18n import _
__all__ = ['Address', 'Party', 'ContactMechanism']
class AddressForm(Form):
"""
A form resembling the party.address
"""
name = TextField(_('Na... |
return redirect(request.referrer)
abort(403)
class Party(ModelSQL, ModelView):
"Party"
__name__ = 'party.party'
nereid_users = fields.One2Many('nereid.user', 'party', 'Nereid Users')
def add_contact_mechanism_if_not_exists(self, type, value):
"""
Adds a contact ... | return jsonify(success=True) | conditional_block |
party.py | trytond.transaction import Transaction
from trytond import backend
from sql import As, Literal, Column
from .user import RegistrationForm
from .i18n import _
__all__ = ['Address', 'Party', 'ContactMechanism']
class | (Form):
"""
A form resembling the party.address
"""
name = TextField(_('Name'), [validators.Required(), ])
street = TextField(_('Street'), [validators.Required(), ])
streetbis = TextField(_('Street (Bis)'))
zip = TextField(_('Post Code'), [validators.Required(), ])
city = TextField(_('Ci... | AddressForm | identifier_name |
party.py | trytond.transaction import Transaction
from trytond import backend
from sql import As, Literal, Column
from .user import RegistrationForm
from .i18n import _
__all__ = ['Address', 'Party', 'ContactMechanism']
class AddressForm(Form):
|
class Address:
"""Party Address"""
__name__ = 'party.address'
__metaclass__ = PoolMeta
registration_form = RegistrationForm
@classmethod
def __register__(cls, module_name):
pool = Pool()
Party = pool.get('party.party')
ContactMechanism = pool.get('party.contact_mecha... | """
A form resembling the party.address
"""
name = TextField(_('Name'), [validators.Required(), ])
street = TextField(_('Street'), [validators.Required(), ])
streetbis = TextField(_('Street (Bis)'))
zip = TextField(_('Post Code'), [validators.Required(), ])
city = TextField(_('City'), [valid... | identifier_body |
party.py | trytond.transaction import Transaction
from trytond import backend
from sql import As, Literal, Column
from .user import RegistrationForm
from .i18n import _
__all__ = ['Address', 'Party', 'ContactMechanism']
class AddressForm(Form):
"""
A form resembling the party.address
"""
name = TextField(_('Na... | " Use party.address.create_address instead",
DeprecationWarning
)
return cls.create_address()
form = cls.get_address_form()
if address not in (a.id for a in request.nereid_user.party.addresses):
# Check if the address is in the list o... | "Address creation will be deprecated from edit_address handler." | random_line_split |
Root.tsx | import * as React from 'react'
import {Router, Route, IndexRoute} from 'react-router'
import {Store} from 'redux' | import {Provider} from 'react-redux'
import {ReactRouterReduxHistory} from 'react-router-redux'
import App from 'js/component/App'
import Home from 'js/component/Home'
import Repo from 'js/component/Repo'
import Repos from 'js/component/Repos'
import About from 'js/component/About'
const Root = ({store, history} : {s... | random_line_split | |
static-methods-crate.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 ... | } | Some(x) => x,
_ => fail2!("read failed!")
} | random_line_split |
static-methods-crate.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 ... | {
match read::readMaybe(s) {
Some(x) => x,
_ => fail2!("read failed!")
}
} | identifier_body | |
static-methods-crate.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 ... | <T:read>(s: ~str) -> T {
match read::readMaybe(s) {
Some(x) => x,
_ => fail2!("read failed!")
}
}
| read | identifier_name |
_get-mlms.py | # -*- coding: utf-8 -*-
import pyodbc
cs = {
'server':'ahwsqlinind019.ind1.stvincent.org',
'database':'st2cpr1.tst_153',
#'database':'st1bprvb.st1',
'user':'scmis',
'pw':'year04',
}
conn = pyodbc.connect(
driver='{SQL Server}',
server=cs['server'],
uid=cs['user'],
pwd=cs['pw'],
)
... |
cursor = conn.cursor()
sql = """
select Name
, replace(convert(varchar(max),Logic),'{{{SINGLE-QUOTE}}}',char(39)) as Logic"""+"""
from {db}.dbo.CV3MLM
where Active = 1
and Status = 4
order by 1""".format(db=cs['database'] or 'st2cpr1.tst_153')
for row in cursor.execute(sql):
with open(row.Name, '... | raise IOError | conditional_block |
_get-mlms.py | # -*- coding: utf-8 -*-
import pyodbc
cs = {
'server':'ahwsqlinind019.ind1.stvincent.org',
'database':'st2cpr1.tst_153',
#'database':'st1bprvb.st1',
'user':'scmis', | }
conn = pyodbc.connect(
driver='{SQL Server}',
server=cs['server'],
uid=cs['user'],
pwd=cs['pw'],
)
if not conn:
raise IOError
cursor = conn.cursor()
sql = """
select Name
, replace(convert(varchar(max),Logic),'{{{SINGLE-QUOTE}}}',char(39)) as Logic"""+"""
from {db}.dbo.CV3MLM
where Ac... | 'pw':'year04', | random_line_split |
test_geomutils.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
__version__='''$Id: test_geomutils.py 3355 2009-01-08 14:58:44Z jonas $'''
__doc__="""Tests for geometry utility functions."""
import unittest
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses
setOutDir(__... | assert pres == pout, "normalizeTRBL(%s) returned %s, expected %s" % (pin, pres, pout)
def makeSuite():
return makeSuiteForClasses(GeomTestCase)
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite()) | ((0, 1, 2, 3), (0, 1, 2, 3)),
)
for pin, pout in paddings:
pres = normalizeTRBL(pin) | random_line_split |
test_geomutils.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
__version__='''$Id: test_geomutils.py 3355 2009-01-08 14:58:44Z jonas $'''
__doc__="""Tests for geometry utility functions."""
import unittest
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses
setOutDir(__... |
def makeSuite():
return makeSuiteForClasses(GeomTestCase)
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
| "Test reportlab.lib.boxstuff.normalizePadding."
from reportlab.lib.geomutils import normalizeTRBL
paddings = (
(4, (4, 4, 4, 4)),
((0, 1), (0, 1, 0, 1)),
((0, 1, 2), (0, 1, 2, 1)),
((0, 1, 2, 3), (0, 1, 2, 3)),
)
for pin, pout in ... | identifier_body |
test_geomutils.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
__version__='''$Id: test_geomutils.py 3355 2009-01-08 14:58:44Z jonas $'''
__doc__="""Tests for geometry utility functions."""
import unittest
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses
setOutDir(__... | (self):
"Test reportlab.lib.boxstuff.normalizePadding."
from reportlab.lib.geomutils import normalizeTRBL
paddings = (
(4, (4, 4, 4, 4)),
((0, 1), (0, 1, 0, 1)),
((0, 1, 2), (0, 1, 2, 1)),
((0, 1, 2, 3), (0, 1, 2, 3)),
)
f... | test_padding | identifier_name |
test_geomutils.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
__version__='''$Id: test_geomutils.py 3355 2009-01-08 14:58:44Z jonas $'''
__doc__="""Tests for geometry utility functions."""
import unittest
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses
setOutDir(__... | unittest.TextTestRunner().run(makeSuite()) | conditional_block | |
objects-owned-object-owned-method.rs | // Copyright 2013 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 ... | impl FooTrait for BarStruct {
fn foo(self: Box<BarStruct>) -> usize {
self.x
}
}
pub fn main() {
let foo = box BarStruct{ x: 22 } as Box<FooTrait>;
assert_eq!(22, foo.foo());
} | random_line_split | |
objects-owned-object-owned-method.rs | // Copyright 2013 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 ... | {
x: usize
}
impl FooTrait for BarStruct {
fn foo(self: Box<BarStruct>) -> usize {
self.x
}
}
pub fn main() {
let foo = box BarStruct{ x: 22 } as Box<FooTrait>;
assert_eq!(22, foo.foo());
}
| BarStruct | identifier_name |
location_optimisation.py | from sklearn import cluster
import numpy as np
import datetime
#import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Location:
vehicle_data = None
@staticmethod
def get_data():
if Location.vehicle_data is not None:
return Location.vehicle_data.tolist()
else:
return None
@sta... | #plt.plot(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], 'bo')
#plt.legend(('Data', 'Centroids'), loc='upper left')
#plt.show()
#plt.savefig('plt-gen-' + datetime.datetime.now().isoformat() + '.png')
#plt.close(fig)
Location.vehicle_data = cluster_locations | data = Location.__preprocess(data)
kmeans = cluster.KMeans(no_clusters, max_iter=300, n_init=10, init='k-means++', precompute_distances='auto')
clusters = kmeans.fit_predict(data)
classes_count = np.zeros([no_clusters,2])
for i in range(0, clusters.size):
classes_count[clusters[i], 0] = clusters[i]
class... | identifier_body |
location_optimisation.py | from sklearn import cluster
import numpy as np
import datetime
#import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Location:
vehicle_data = None
@staticmethod
def get_data():
if Location.vehicle_data is not None:
return Location.vehicle_data.tolist()
else:
return None
@sta... | return lat_lng
@staticmethod
def set_optimal_locations(data, count=5, no_clusters=10):
data = Location.__preprocess(data)
kmeans = cluster.KMeans(no_clusters, max_iter=300, n_init=10, init='k-means++', precompute_distances='auto')
clusters = kmeans.fit_predict(data)
classes_count = np.zeros([no_clusters,... | for i in range(0, len(payload)):
lat_lng[i, 0] = payload[i]['positioning_system']['location']['lat']
lat_lng[i, 1] = payload[i]['positioning_system']['location']['lng'] | random_line_split |
location_optimisation.py | from sklearn import cluster
import numpy as np
import datetime
#import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Location:
vehicle_data = None
@staticmethod
def | ():
if Location.vehicle_data is not None:
return Location.vehicle_data.tolist()
else:
return None
@staticmethod
def __preprocess(payload):
lat_lng = np.empty([len(payload), 2])
for i in range(0, len(payload)):
lat_lng[i, 0] = payload[i]['positioning_system']['location']['lat']
lat_lng[i, 1] = pay... | get_data | identifier_name |
location_optimisation.py | from sklearn import cluster
import numpy as np
import datetime
#import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Location:
vehicle_data = None
@staticmethod
def get_data():
if Location.vehicle_data is not None:
|
else:
return None
@staticmethod
def __preprocess(payload):
lat_lng = np.empty([len(payload), 2])
for i in range(0, len(payload)):
lat_lng[i, 0] = payload[i]['positioning_system']['location']['lat']
lat_lng[i, 1] = payload[i]['positioning_system']['location']['lng']
return lat_lng
@staticmethod
... | return Location.vehicle_data.tolist() | conditional_block |
all_71.js | var searchData=
[ | ]; | ['q',['q',['../classmodel__parameters.html#a401ed98b6dc61030ca3c9079c1984316',1,'model_parameters']]],
['quadratic_5fpenalty',['quadratic_penalty',['../classquadratic__penalty.html',1,'quadratic_penalty'],['../classquadratic__penalty.html#a8778598e330b17d88354b253f798d497',1,'quadratic_penalty::quadratic_penalty()'... | random_line_split |
field_angle.js | /**
* Visual Blocks Editor
*
* Copyright 2013 Google Inc.
* http://blockly.googlecode.com/
*
* 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/LICEN... | if (dx < 0) {
angle += 180;
} else if (dy > 0) {
angle += 360;
}
angle = String(Math.round(angle));
Blockly.FieldTextInput.htmlInput_.value = angle;
this.setText(angle);
};
/**
* Insert a degree symbol.
* @param {?string} text New text.
*/
Blockly.FieldAngle.prototype.setText = function(text) {
... | // This shouldn't happen, but let's not let this error propogate further.
return;
}
angle = angle / Math.PI * 180;
// 0: East, 90: North, 180: West, 270: South. | random_line_split |
field_angle.js | /**
* Visual Blocks Editor
*
* Copyright 2013 Google Inc.
* http://blockly.googlecode.com/
*
* 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/LICEN... | return n;
};
| n = n % 360;
if (n < 0) {
n += 360;
}
n = String(n);
}
| conditional_block |
__init__.py | import fcntl |
log = logging.getLogger(__name__)
def read_file_line(filename):
with open(filename, 'r') as f:
return f.read().strip()
class Directory:
def __init__(self, path):
self.path = path
def __enter__(self):
log.info('Opening {}'.format(self.path))
self.fd = os.open(self.path, ... | import logging
import os | random_line_split |
__init__.py | import fcntl
import logging
import os
log = logging.getLogger(__name__)
def read_file_line(filename):
with open(filename, 'r') as f:
return f.read().strip()
class Directory:
def __init__(self, path):
self.path = path
def __enter__(self):
log.info('Opening {}'.format(self.path))... |
def lock(self):
return Flock(self.fd, fcntl.LOCK_EX)
class Flock:
def __init__(self, fd, op):
(self.fd, self.op) = (fd, op)
def __enter__(self):
log.info('Locking fd {}'.format(self.fd))
# If the fcntl() fails, an IOError is raised.
fcntl.flock(self.fd, self.op)
... | log.info('Closing {} with fd {}'.format(self.path, self.fd))
os.close(self.fd) | identifier_body |
__init__.py | import fcntl
import logging
import os
log = logging.getLogger(__name__)
def read_file_line(filename):
with open(filename, 'r') as f:
return f.read().strip()
class Directory:
def __init__(self, path):
self.path = path
def | (self):
log.info('Opening {}'.format(self.path))
self.fd = os.open(self.path, os.O_RDONLY)
log.info('Opened {} with fd {}'.format(self.path, self.fd))
return self
def __exit__(self, exc_type, exc_value, traceback):
log.info('Closing {} with fd {}'.format(self.path, self.fd))... | __enter__ | identifier_name |
error.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | }
} | display("Failed to start viewer")
}
| random_line_split |
convertito_2012_test.py | # The Hazard Library
# Copyright (C) 2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as | # published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GN... | random_line_split | |
convertito_2012_test.py | # The Hazard Library
# Copyright (C) 2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# T... | (self):
self.check('CONV2012/CONV_2012_MEAN.csv',
max_discrep_percentage=0.1)
def test_std_total(self):
self.check('CONV2012/CONV_2012_STDDEV.csv',
max_discrep_percentage=0.1)
| test_mean | identifier_name |
convertito_2012_test.py | # The Hazard Library
# Copyright (C) 2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# T... |
def test_std_total(self):
self.check('CONV2012/CONV_2012_STDDEV.csv',
max_discrep_percentage=0.1)
| self.check('CONV2012/CONV_2012_MEAN.csv',
max_discrep_percentage=0.1) | identifier_body |
gregorian.js.uncompressed.js | define(
"dojo/cldr/nls/zh-hk/gregorian", //begin v1.x content
{
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"quarters-format-wide": [
"第1季",
"第2季",
"第3季",
"第4季"
],
"eraAbbr": [
| "西元前",
"西元"
],
"dateFormat-medium": "yyyy/M/d",
"dateFormat-short": "y/M/d",
"timeFormat-full": "zzzzah時mm分ss秒",
"timeFormat-long": "zah時mm分ss秒",
"dateFormatItem-Ed": "d日(E)",
"dateFormatItem-h": "ah時",
"dateFormatItem-H": "H時",
"dateFormatItem-Md": "M/d",
"dateFormatItem-MEd": "M/d(E)",
"dat... | random_line_split | |
hello.rs | // Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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 http://opensource.org/licenses/MI... | font: RefCell::new(None),
});
let win_params = WindowParams {
window_name: title,
style: window::WS_OVERLAPPEDWINDOW,
x: 0,
y: 0,
width: 400,
height: 400,
parent: Window::null(),
menu: ptr::null_... | let wproc = Box::new(MainFrame {
win: Window::null(),
title: title.clone(),
text_height: text_height,
edit: RefCell::new(None), | random_line_split |
hello.rs | // Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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 http://opensource.org/licenses/MI... |
}
impl OnFocus for MainFrame {
fn on_focus(&self, _w: Window) {
self.edit.borrow().expect("edit is empty").set_focus();
}
}
impl OnMessage for MainFrame {
fn on_message(&self, _message: UINT, _wparam: WPARAM, _lparam: LPARAM) -> Option<LRESULT> {
match _message {
WM_COMMAND =>... | {
let font = self.font.borrow();
let pdc = PaintDc::new(self).expect("Paint DC");
pdc.dc.select_font(&font.expect("font is empty"));
pdc.dc.text_out(0, 0, self.title.as_ref());
} | identifier_body |
hello.rs | // Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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 http://opensource.org/licenses/MI... |
}
},
_ => { /* Other messages. */ }
}
None
}
}
impl MainFrame {
fn new(instance: Instance, title: String, text_height: isize) -> Option<Window> {
let icon = Image::load_resource(instance, IDI_ICON, ImageType::IMAGE_ICON, 0, 0);
let wnd_... | {} | conditional_block |
hello.rs | // Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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 http://opensource.org/licenses/MI... | {
win: Window,
title: String,
text_height: isize,
edit: RefCell<Option<Window>>,
font: RefCell<Option<Font>>,
}
wnd_proc!(MainFrame, win, WM_CREATE, WM_DESTROY, WM_SIZE, WM_SETFOCUS, WM_PAINT, ANY);
impl OnCreate for MainFrame {
fn on_create(&self, _cs: &CREATESTRUCTW) -> bool {
let r... | MainFrame | identifier_name |
rpc_server.py | #!/usr/bin/env python
import logging
from tornado.ioloop import IOLoop
from stormed import Connection, Message
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def on_connect():
global ch
ch = conn.channel()
ch.queue_declare(queue=... |
logging.basicConfig()
ch = None
conn = Connection(host='localhost')
conn.connect(on_connect)
io_loop = IOLoop.instance()
print ' [*] Waiting for messages. To exit press CTRL+C'
try:
io_loop.start()
except KeyboardInterrupt:
conn.close(io_loop.stop)
| n = int(msg.body)
print " [.] fib(%s)" % n
response = str(fib(n))
response_msg = Message(response, delivery_mode=2,
correlation_id=msg.correlation_id)
ch.publish(response_msg, exchange='', routing_key=msg.reply_to)
msg.ack() | identifier_body |
rpc_server.py | #!/usr/bin/env python
import logging
from tornado.ioloop import IOLoop
from stormed import Connection, Message
def | (n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def on_connect():
global ch
ch = conn.channel()
ch.queue_declare(queue='rpc_queue', durable=True)
ch.qos(prefetch_count=1)
ch.consume('rpc_queue', on_request)
def on_request(msg):
... | fib | identifier_name |
rpc_server.py | #!/usr/bin/env python
import logging
from tornado.ioloop import IOLoop
from stormed import Connection, Message
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1 | return fib(n-1) + fib(n-2)
def on_connect():
global ch
ch = conn.channel()
ch.queue_declare(queue='rpc_queue', durable=True)
ch.qos(prefetch_count=1)
ch.consume('rpc_queue', on_request)
def on_request(msg):
n = int(msg.body)
print " [.] fib(%s)" % n
response = str(fib(n))
r... | else: | random_line_split |
rpc_server.py | #!/usr/bin/env python
import logging
from tornado.ioloop import IOLoop
from stormed import Connection, Message
def fib(n):
if n == 0:
return 0
elif n == 1:
|
else:
return fib(n-1) + fib(n-2)
def on_connect():
global ch
ch = conn.channel()
ch.queue_declare(queue='rpc_queue', durable=True)
ch.qos(prefetch_count=1)
ch.consume('rpc_queue', on_request)
def on_request(msg):
n = int(msg.body)
print " [.] fib(%s)" % n
response = str(fi... | return 1 | conditional_block |
mark_tasks.py | # -*- coding: utf-8 -*-
#
# 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
#... | res.extend(new_state)
# Mark the dag run
if commit:
drs = DagRun.find(dag.dag_id, execution_date=execution_date)
for dr in drs:
dr.dag = dag
dr.update_state()
return res
| """
Set the state of a dag run and all task instances associated with the dag
run for a specific execution date.
:param dag: the DAG of which to alter state
:param execution_date: the execution date from which to start looking
:param state: the state to which the DAG need to be set
:param commit... | identifier_body |
mark_tasks.py | # -*- coding: utf-8 -*-
#
# 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
#... | (task, execution_date, upstream=False, downstream=False,
future=False, past=False, state=State.SUCCESS, commit=False):
"""
Set the state of a task instance and if needed its relatives. Can set state
for future tasks (calculated from execution_date) and retroactively
for past tasks. Will ve... | set_state | identifier_name |
mark_tasks.py | # -*- coding: utf-8 -*-
#
# 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
#... |
current_task = current_dag.get_task(task_id)
if isinstance(current_task, SubDagOperator):
# this works as a kind of integrity check
# it creates missing dag runs for subdagoperators,
# maybe this should be moved to dagrun.verify_integrity
... | continue | conditional_block |
mark_tasks.py | # -*- coding: utf-8 -*-
#
# 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
#... | if downstream:
relatives = task.get_flat_relatives(upstream=False)
task_ids += [t.task_id for t in relatives]
if upstream:
relatives = task.get_flat_relatives(upstream=True)
task_ids += [t.task_id for t in relatives]
# verify the integrity of the dag runs in case a task was ... | else:
dates = dag.date_range(start_date=start_date, end_date=end_date)
# find relatives (siblings = downstream, parents = upstream) if needed
task_ids = [task.task_id] | random_line_split |
simmap.js | // Define simmap namespace using a "module pattern" (essentially an
// anonymous closure) as demonstrated on
// http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/
//
// jQuery and Openlayers libraries are imported directly rather than
// referencing them as implied globals.
var simmap = (fun... |
}
);
}
});
// add any layers from the navigation portlet
// NOTE: should this be optional based on site? on the simmap?
// NOTE: check for layers that are in the current directory
jq('.navTreeItem .... | {
simmap.setVis(url, true)
simmap.centerOnLayer(url);
} | conditional_block |
simmap.js | // Define simmap namespace using a "module pattern" (essentially an
// anonymous closure) as demonstrated on
// http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/
//
// jQuery and Openlayers libraries are imported directly rather than
// referencing them as implied globals.
var simmap = (fun... | init: function() {
ol.ImgPath = "++resource++ol_images/";
var options = {
projection: "EPSG:3857",
theme: null,
//allOverlays: true,
};
olmap = new ol.Map('map', options);
olmap.addControl(new ol.Co... | random_line_split | |
twitch.typings.d.ts | declare namespace twitch {
interface Response {
_links: {
next: string,
self: string
},
_total: number,
videos: Video[]
}
interface Video {
_id: string,
_links: {
channel: string,
self: string
},
animated_preview_url: string,
broadcast_id: number,
... | tag_list: string,
thumbnails: {
type: string,
url: string
}[],
title: string,
url: string,
views: number
}
} | random_line_split | |
test_document_missing_changesets.py | # MajorMajor - Collaborative Document Editing Library
# Copyright (C) 2013 Ritchie Wilson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option)... | (self):
doc = Document(snapshot='')
doc.HAS_EVENT_LOOP = False
assert doc.missing_changesets == set([])
assert doc.pending_new_changesets == []
root = doc.get_root_changeset()
A = Changeset(doc.get_id(), "dummyuser", [root])
doc.receive_changeset(A)
... | test_missing_changesets | identifier_name |
test_document_missing_changesets.py | # MajorMajor - Collaborative Document Editing Library
# Copyright (C) 2013 Ritchie Wilson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option)... | C = Changeset(doc.get_id(), "user1", [A])
C.set_id("C")
doc.receive_changeset(C)
assert doc.missing_changesets == set([])
assert doc.pending_new_changesets == []
assert B.get_parents() == [C]
assert doc.get_ordered_changesets() == [root, A, C, B]
# Now a ... | def test_missing_changesets(self):
doc = Document(snapshot='')
doc.HAS_EVENT_LOOP = False
assert doc.missing_changesets == set([])
assert doc.pending_new_changesets == []
root = doc.get_root_changeset()
A = Changeset(doc.get_id(), "dummyuser", [root])
doc... | identifier_body |
test_document_missing_changesets.py | # MajorMajor - Collaborative Document Editing Library
# Copyright (C) 2013 Ritchie Wilson | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | # | random_line_split |
socket_event.rs | use td_rp::Buffer; | client_ip: String,
server_port: u16,
buffer: Buffer,
out_cache: Buffer,
online: bool,
websocket: bool,
}
impl SocketEvent {
pub fn new(socket_fd: i32, client_ip: String, server_port: u16) -> SocketEvent {
SocketEvent {
socket_fd: socket_fd,
cookie: 0,
... |
#[derive(Debug)]
pub struct SocketEvent {
socket_fd: i32,
cookie: u32, | random_line_split |
socket_event.rs | use td_rp::Buffer;
#[derive(Debug)]
pub struct SocketEvent {
socket_fd: i32,
cookie: u32,
client_ip: String,
server_port: u16,
buffer: Buffer,
out_cache: Buffer,
online: bool,
websocket: bool,
}
impl SocketEvent {
pub fn new(socket_fd: i32, client_ip: String, server_port: u16) -> S... | (&mut self, online: bool) {
self.online = online;
}
pub fn is_online(&self) -> bool {
self.online
}
pub fn set_websocket(&mut self, websocket: bool) {
self.websocket = websocket;
}
pub fn is_websocket(&self) -> bool {
self.websocket
}
}
| set_online | identifier_name |
socket_event.rs | use td_rp::Buffer;
#[derive(Debug)]
pub struct SocketEvent {
socket_fd: i32,
cookie: u32,
client_ip: String,
server_port: u16,
buffer: Buffer,
out_cache: Buffer,
online: bool,
websocket: bool,
}
impl SocketEvent {
pub fn new(socket_fd: i32, client_ip: String, server_port: u16) -> S... |
pub fn set_websocket(&mut self, websocket: bool) {
self.websocket = websocket;
}
pub fn is_websocket(&self) -> bool {
self.websocket
}
}
| {
self.online
} | identifier_body |
api.py | # coding: utf-8
import wolframalpha
from .exceptions import APIError
from .clients import turingclient, baiduclient
from .utils import get_mac_address, get_audio_info
class Wolfram(object):
| else:
raise APIError('Wolfram API failed.')
class TuringRobot(object):
"""A client for request Turing Robot.
Attributes:
key: The key string got from http://www.tuling123.com.
"""
def __init__(self, key):
self.key = key
def ask_turing(self, question):
... | """A client for request Wolfram.
Attributes:
key: The key string got from https://www.wolframalpha.com.
"""
def __init__(self, key):
self.key = key
def ask_wolfram(self, question):
client = wolframalpha.Client(self.key)
res = client.query(question)
if len(res.po... | identifier_body |
api.py | # coding: utf-8
import wolframalpha
from .exceptions import APIError
from .clients import turingclient, baiduclient
from .utils import get_mac_address, get_audio_info
class Wolfram(object):
"""A client for request Wolfram.
Attributes:
key: The key string got from https://www.wolframalpha.com.
"""... |
else:
raise APIError('Wolfram API failed.')
# to skip ascii character in case of error
texts = texts.encode('ascii', 'ignore')
return texts
else:
raise APIError('Wolfram API failed.')
class TuringRobot(object):
"""A client for re... | texts = pod.text | conditional_block |
api.py | # coding: utf-8
import wolframalpha
from .exceptions import APIError
from .clients import turingclient, baiduclient
from .utils import get_mac_address, get_audio_info
class Wolfram(object):
"""A client for request Wolfram.
Attributes:
key: The key string got from https://www.wolframalpha.com.
"""... | (self, file_, format_='wav',
cuid=None, ptc=1, lan='zh'):
"""Constructs and sends an Automatic Speech Recognition request.
Args:
file_: the open file with methods write(), close(), tell(), seek()
set through the __init__() method.
format_:(optional... | asr | identifier_name |
api.py | # coding: utf-8
import wolframalpha
from .exceptions import APIError
from .clients import turingclient, baiduclient
from .utils import get_mac_address, get_audio_info
class Wolfram(object):
"""A client for request Wolfram.
Attributes:
key: The key string got from https://www.wolframalpha.com.
"""... | try:
audio_info = get_audio_info(file_)
except Exception, e:
raise e
params['len'], params['rate'] = audio_info['nframes'], audio_info['framerate']
return baiduclient.asr(audio_info['content'], params)
def tts(self, tex, lan='zh', ctp=1,
cuid=None... | 'lan': lan
} | random_line_split |
set_cookie.rs | use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Inform... |
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
jar.add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
asser... | {
use header::Headers;
let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.se... | identifier_body |
set_cookie.rs | use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Inform... |
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply ... | {
try!(f.write_str("\r\nSet-Cookie: "));
} | conditional_block |
set_cookie.rs | use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Inform... | try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
... | }
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i != 0 { | random_line_split |
set_cookie.rs | use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Inform... | () {
use header::Headers;
let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers... | test_fmt | identifier_name |
serve-files.spec.ts | import SetupFlags from '../../core/use-cases/setup-flags';
import { CLIProgram } from '../../core/entities/cli-program';
import ConfigurationRepository from '../../core/repositories/config.repository';
import ServeFiles from './serve-files';
import Logger from '../../infrastructure/logging/logger';
const sinon = re... | });
}); | random_line_split | |
d3.bnet.js | /**
* Battle.net JavaScript utility class
*
* @package D3
*
* @author Nicolai Agersbæk <nicolai.agersbaek@gmail.com>
* @version 0.1.0
*/
var d3.bnet = (function (d3, $) {
if (d3 === {} || $ === {}) {
console.log("D3.Bnet: D3 or jQuery module not detected!");
}
var d3.bnet = {};
var self = d3.bnet;
var ... | }(d3 || {}, jQuery || {})); | random_line_split | |
d3.bnet.js | /**
* Battle.net JavaScript utility class
*
* @package D3
*
* @author Nicolai Agersbæk <nicolai.agersbaek@gmail.com>
* @version 0.1.0
*/
var d3.bnet = (function (d3, $) {
if (d3 === {} || $ === {}) {
console.log("D3.Bnet: D3 or jQuery module not detected!");
}
var d3.bnet = {};
var self = d3.bnet;
var ... | else if _is(data, "object") {
// Bnet import data object
return import(d);
} else {
return d3.error({
src: "d3.bnet.import",
data: d
});
}
}
function import(data) {
var required = {
};
}
_loaded("bnet");
return d3.bnet;
}(d3 || {}, jQuery || {})); |
// D3.Character object, get Battle.net details and import
return import(d.data.bnet);
} | conditional_block |
d3.bnet.js | /**
* Battle.net JavaScript utility class
*
* @package D3
*
* @author Nicolai Agersbæk <nicolai.agersbaek@gmail.com>
* @version 0.1.0
*/
var d3.bnet = (function (d3, $) {
if (d3 === {} || $ === {}) {
console.log("D3.Bnet: D3 or jQuery module not detected!");
}
var d3.bnet = {};
var self = d3.bnet;
var ... |
_loaded("bnet");
return d3.bnet;
}(d3 || {}, jQuery || {})); |
var required = {
};
}
| identifier_body |
d3.bnet.js | /**
* Battle.net JavaScript utility class
*
* @package D3
*
* @author Nicolai Agersbæk <nicolai.agersbaek@gmail.com>
* @version 0.1.0
*/
var d3.bnet = (function (d3, $) {
if (d3 === {} || $ === {}) {
console.log("D3.Bnet: D3 or jQuery module not detected!");
}
var d3.bnet = {};
var self = d3.bnet;
var ... | data) {
var required = {
};
}
_loaded("bnet");
return d3.bnet;
}(d3 || {}, jQuery || {})); | mport( | identifier_name |
main.component.ts | import { Component, OnInit } from '@angular/core'
import { fromEvent as observableFromEvent } from 'rxjs'
import { Router, RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'
import { ToastrService } from 'ngx-toastr'
import { ConfigService } from '../../services/con... |
menu: any[] = []
ngOnInit () {
if (!this.configService.profiles.length) {
this.router.navigate(['/setup'])
return
}
this.version = this.configService.version
this.profile = this.configService.getProfile()
if (this.profile) {
this.profileName = this.profile.name
thi... | {
this.router.events.subscribe((event: RouterEvent) => {
this._navigationInterceptor(event)
})
} | identifier_body |
main.component.ts | import { Component, OnInit } from '@angular/core'
import { fromEvent as observableFromEvent } from 'rxjs'
import { Router, RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'
import { ToastrService } from 'ngx-toastr'
import { ConfigService } from '../../services/con... |
if (event instanceof NavigationError) {
this._hideSpinner()
this.toastr.error('Could not load module. Check your internet connection', 'Load Failed')
}
}
private _hideSpinner (): void {
this.pageLoading = false
}
}
| {
this._hideSpinner()
} | conditional_block |
main.component.ts | import { Component, OnInit } from '@angular/core'
import { fromEvent as observableFromEvent } from 'rxjs'
import { Router, RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'
import { ToastrService } from 'ngx-toastr'
import { ConfigService } from '../../services/con... | this.configService.sidebarClosed = !this.configService.sidebarClosed
}
private _navigationInterceptor (event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.pageLoading = true
}
if (event instanceof NavigationEnd) {
this._hideSpinner()
}
if (event instanceof N... | }
toggleSidemenu () { | random_line_split |
main.component.ts | import { Component, OnInit } from '@angular/core'
import { fromEvent as observableFromEvent } from 'rxjs'
import { Router, RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'
import { ToastrService } from 'ngx-toastr'
import { ConfigService } from '../../services/con... | () {
this.isOnline = this.networkStatus && this.databaseStatus
}
toggleSidemenu () {
this.configService.sidebarClosed = !this.configService.sidebarClosed
}
private _navigationInterceptor (event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.pageLoading = true
}
i... | setStatus | identifier_name |
java.beans.EventHandler.d.ts | declare namespace java {
namespace beans {
class | implements java.lang.reflect.InvocationHandler {
public constructor(arg0: java.lang.Object | any, arg1: java.lang.String | string, arg2: java.lang.String | string, arg3: java.lang.String | string)
public getTarget(): java.lang.Object
public getAction(): java.lang.String
public getEventPropertyN... | EventHandler | identifier_name |
java.beans.EventHandler.d.ts | declare namespace java {
namespace beans {
class EventHandler implements java.lang.reflect.InvocationHandler {
public constructor(arg0: java.lang.Object | any, arg1: java.lang.String | string, arg2: java.lang.String | string, arg3: java.lang.String | string)
public getTarget(): java.lang.Object
... | }
} | public static create<T>(arg0: java.lang.Class<T>, arg1: java.lang.Object | any, arg2: java.lang.String | string, arg3: java.lang.String | string): T
public static create<T>(arg0: java.lang.Class<T>, arg1: java.lang.Object | any, arg2: java.lang.String | string, arg3: java.lang.String | string, arg4: java.la... | random_line_split |
conf.py | from django.conf import settings
from appconf import AppConf
class ModelDatabankAppConf(AppConf):
| DATA_PATH = "/tmp/model_databank_repositories"
SYMLINK_PATH = "/tmp/model_databank"
UPLOAD_PATH = "/tmp/uploads"
ZIP_EXTRACT_PATH = "/tmp/extracted_zip_files/"
DOWNLOAD_PATH = "/tmp/downloads"
REPOSITORY_URL_ROOT = 'http://127.0.0.1:8012'
MAX_REVISIONS = 500
MAX_REVISIONS_PER_PAGE = 100
... | """App specific settings. Overridable in global settings.
DATA_PATH: path to the real mercurial repositories; these should never
be manipulated directly. Active repositories are symlinked in the
SYMLINK_PATH directory by their slug name.
SYMLINK_PATH: path with symlinks to active model referen... | identifier_body |
conf.py | from django.conf import settings
from appconf import AppConf
class ModelDatabankAppConf(AppConf):
"""App specific settings. Overridable in global settings.
DATA_PATH: path to the real mercurial repositories; these should never
be manipulated directly. Active repositories are symlinked in the
... | MAX_REVISIONS: maximum total number of revisions shown for a model
MAX_REVISIONS_PER_PAGE: maximum number of revisions per page.
"""
DATA_PATH = "/tmp/model_databank_repositories"
SYMLINK_PATH = "/tmp/model_databank"
UPLOAD_PATH = "/tmp/uploads"
ZIP_EXTRACT_PATH = "/tmp/extracted_zip_files/... | REPOSITORY_URL_ROOT: root url for cloning repositories.
| random_line_split |
conf.py | from django.conf import settings
from appconf import AppConf
class ModelDatabankAppConf(AppConf):
"""App specific settings. Overridable in global settings.
DATA_PATH: path to the real mercurial repositories; these should never
be manipulated directly. Active repositories are symlinked in the
... | :
prefix = 'model_databank'
| Meta | identifier_name |
basic-information.js | var xue =xue || {};
xue.formCheck = xue.formCheck || {};
var fCheck = xue.formCheck;
/* 提示信息的css样式 */
fCheck.setTips = function(select, tips){
$(select).css({
'display': 'block',
}).html(tips);
};
/* 输入正确时,清除提醒 */
fCheck.clearTips = function(select){
$(select).css({
'display':'none'
}).html(null);... | }
if(result.sign === 2){
window.location.href = result.msg;
}
}
});
}
}
/* 学校格式验证 */
$.fn.school = function(){
var box = $(boxs.school),
val = box.val();
var text = box.next('.school-warning'),
block = text.add... | fCheck.clearTips(".nickname-warning");
fCheck.bordercss('.nickname');
$(box).data('lastVal',val);
return true; | random_line_split |
basic-information.js | var xue =xue || {};
xue.formCheck = xue.formCheck || {};
var fCheck = xue.formCheck;
/* 提示信息的css样式 */
fCheck.setTips = function(select, tips){
$(select).css({
'display': 'block',
}).html(tips);
};
/* 输入正确时,清除提醒 */
fCheck.clearTips = function(select){
$(select).css({
'display':'none'
}).html(null);... | });
}
}
});
});
var boxs = {
nickname: '.nickname',
school:'.school'
}
$.fn.nickname = function(){
var box = $(boxs.nickname),
val = box.val();
if (val == '') {
fCheck.setTips(".nickname-warning",'请输入昵称');
}else {
var reg = /^[0-9a-zA-Z\u4e00-... | arTips(".nickname-warning");
$.fn.nickname();
}else{
$(".nickname-warning").css({
display: 'block',
| conditional_block |
basic-information.js | var xue =xue || {};
xue.formCheck = xue.formCheck || {};
var fCheck = xue.formCheck;
/* 提示信息的css样式 */
fCheck.setTips = function(select, tips){
$(select).css({
'display': 'block',
}).html(tips);
};
/* 输入正确时,清除提醒 */
fCheck.clearTips = function(select){
$(select).css({
'display':'none'
}).html(null);... | e'});",6000);
} | tr("rel") && $("#month").find("option:selected").text() == $("#month").attr("rel") && $("#day").find("option:selected").text() == $("#day").attr("rel")) {
alert('您没有修改或新增任何资料');
return false;
}else{
setTimeout($.fn.nickname(),200);
$.fn.school();
}
if ($('.nickname-warning').... | identifier_body |
basic-information.js | var xue =xue || {};
xue.formCheck = xue.formCheck || {};
var fCheck = xue.formCheck;
/* 提示信息的css样式 */
fCheck.setTips = function(select, tips){
$(select).css({
'display': 'block',
}).html(tips);
};
/* 输入正确时,清除提醒 */
fCheck.clearTips = function(select){
$(select).css({
'display':'none'
}).html(null);... | ).attr("rel") && $("#month").find("option:selected").text() == $("#month").attr("rel") && $("#day").find("option:selected").text() == $("#day").attr("rel")) {
alert('您没有修改或新增任何资料');
return false;
}else{
setTimeout($.fn.nickname(),200);
$.fn.school();
}
if ($('.nickname-warnin... | ) == $("#year" | identifier_name |
altdataview.js | ;
/**
* The view for alt data.
*
* @param {goog.events.EventTarget=} opt_eventTarget The parent event target.
* @constructor
* @extends {i18n.input.chrome.inputview.elements.Element}
*/
i18n.input.chrome.inputview.elements.content.AltDataView = function(
opt_eventTarget) {
goog.base(this, '', ElementType... | {
var screenCoordinate = coordinate.clone();
// This is a hack. Ideally, we should be able to use window.screenX/Y to get
// cooridnate of the top left corner of VK window. But VK window is special
// and the values are set to 0 all the time. We should fix the problem in
// Chrome.
screenCoordinate.y += scr... | identifier_body | |
altdataview.js | .PADDING_ = 8;
/**
* The URL of the window which displays accented characters.
*
* @type {string}
* @private
*/
AltDataView.ACCENTS_WINDOW_URL_ = 'imewindows/accents.html';
/**
* Index of highlighted accent. Use this index to represent no highlighted
* accent.
*
* @type {number}
* @private
*/
AltDataView... | var keyElem = this.addKey_(characters[i], isRTL);
goog.style.setSize(keyElem, w, h);
this.altdataElements_.push(keyElem);
if (i != characters.length - 1) {
this.addSeparator_(height);
}
}
goog.style.setPosition(this.getElement(), left, elemTop);
this.highlightItem(Math.... | {
// The total width of the characters + the separators, every separator has
// width = 1.
var altDataWindowWidth = w * characters.length;
var altDataWindowHeight = h;
var left = parentKeyLeftTop.x;
if ((left + altDataWindowWidth) > screen.width) {
// If no enough space at the right, then... | conditional_block |
altdataview.js | (coordinate) {
var screenCoordinate = coordinate.clone();
// This is a hack. Ideally, we should be able to use window.screenX/Y to get
// cooridnate of the top left corner of VK window. But VK window is special
// and the values are set to 0 all the time. We should fix the problem in
// Chrome.
screenCoordi... | convertToScreenCoordinate | identifier_name | |
altdataview.js | View.PADDING_ = 8;
/**
* The URL of the window which displays accented characters.
*
* @type {string}
* @private
*/
AltDataView.ACCENTS_WINDOW_URL_ = 'imewindows/accents.html';
/**
* Index of highlighted accent. Use this index to represent no highlighted
* accent.
*
* @type {number}
* @private
*/
AltData... | var numOfColumns = Math.min(numOfKeys, maxColumns);
var numOfRows = Math.ceil(numOfKeys / numOfColumns);
var startKeyIndex = this.getStartKeyIndex_(parentKeyLeftTop.x, numOfColumns,
width, screen.width);
var altDataWindowWidth = numOfColumns * w;
var altDataWindowHeight = numOfRows * h;
... | random_line_split | |
erase_regions.rs | use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty, ..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx... |
impl TypeFolder<'tcx> for RegionEraserVisitor<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
if ty.needs_infer() { ty.super_fold_with(self) } else { Ok(self.tcx.erase_regions_ty(ty)) }
}
fn fold_bind... | random_line_split | |
erase_regions.rs | use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty, ..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx... |
}
fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> Result<ty::Binder<'tcx, T>, Self::Error>
where
T: TypeFoldable<'tcx>,
{
let u = self.tcx.anonymize_late_bound_regions(t);
u.super_fold_with(self)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Re... | { Ok(self.tcx.erase_regions_ty(ty)) } | conditional_block |
erase_regions.rs | use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty, ..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx... | (&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
// because late-bound regions affect subtyping, we can't
// erase the bound/free distinction, but we can replace
// all free regions with 'erased.
//
// Note that we *CAN* replace early-bound regions -- t... | fold_region | identifier_name |
erase_regions.rs | use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty, ..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx... |
impl<'tcx> TyCtxt<'tcx> {
/// Returns an equivalent value with all free regions removed (note
/// that late-bound regions remain, because they are important for
/// subtyping, but they are anonymized and normalized as well)..
pub fn erase_regions<T>(self, value: T) -> T
where
T: TypeFoldab... | {
// N.B., use `super_fold_with` here. If we used `fold_with`, it
// could invoke the `erase_regions_ty` query recursively.
ty.super_fold_with(&mut RegionEraserVisitor { tcx }).into_ok()
} | identifier_body |
rest.service.ts | import { Injectable } from '@angular/core';
import { Response, RequestOptionsArgs } from '@angular/http';
import { AuthorizedHttp } from './authorized-http.service';
import { Observable } from 'rxjs';
@Injectable()
export class RestService {
HOST:string = 'http://localhost:3004';
constructor(
private authori... | (url: string, data?: Object, options?: RequestOptionsArgs): Observable<any> {
return this.authorizedHttp.put(this.getUrl(url), data, options).map((resp: Response) => resp.json());
}
getUrl(url: string): string {
return `${this.HOST}${url}`;
}
}
| put | identifier_name |
rest.service.ts | import { Injectable } from '@angular/core';
import { Response, RequestOptionsArgs } from '@angular/http';
import { AuthorizedHttp } from './authorized-http.service';
import { Observable } from 'rxjs';
@Injectable()
export class RestService {
HOST:string = 'http://localhost:3004';
constructor(
private authori... |
post(url: string, data?: Object, options?: RequestOptionsArgs): Observable<any> {
return this.authorizedHttp.post(this.getUrl(url), data, options).map((resp: Response) => resp.json());
}
put(url: string, data?: Object, options?: RequestOptionsArgs): Observable<any> {
return this.authorizedHttp.put(this... | {
return this.authorizedHttp.delete(this.getUrl(url), options).map((resp: Response) => resp.json());
} | identifier_body |
rest.service.ts | import { Injectable } from '@angular/core';
import { Response, RequestOptionsArgs } from '@angular/http';
import { AuthorizedHttp } from './authorized-http.service';
import { Observable } from 'rxjs';
@Injectable()
export class RestService {
HOST:string = 'http://localhost:3004';
constructor(
private authori... | return this.authorizedHttp.delete(this.getUrl(url), options).map((resp: Response) => resp.json());
}
post(url: string, data?: Object, options?: RequestOptionsArgs): Observable<any> {
return this.authorizedHttp.post(this.getUrl(url), data, options).map((resp: Response) => resp.json());
}
put(url: strin... | }
delete(url: string, options?: RequestOptionsArgs): Observable<any> { | random_line_split |
server.js | import Koa from 'koa'
import body from 'koa-bodyparser'
import convert from 'koa-convert'
import cors from 'koa-cors'
import mongoose from 'mongoose'
import config from './config'
import mongooseConfig from './config/mongoose'
import routeRegistry from './routeRegistry'
const app = new Koa()
app.context.db = mongoose
... | await next()
const ms = new Date() - start
ctx.set(`X-Response-Time: ${ms}`)
ctx.set('X-Server: node')
})
app.use(async function (ctx, next) {
const start = new Date()
await next()
const ms = new Date() - start
console.info(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
routeRegistry(app)
const { server } ... | app.use(convert(cors({ origin: true, methods: ['OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'] })))
app.use(async function (ctx, next) {
const start = new Date() | random_line_split |
test-vnode0.js | // @flow
/* eslint-disable */
import {
periodic,
now,
merge,
never,
newStream,
propagateEventTask
} from '@most/core'
import {disposeBoth, disposeWith} from '@most/disposable'
import {newDefaultScheduler, asap} from '@most/scheduler'
import M from '../m'
import tree from './element'
import type {Pith} from ... | (vnode, cb) {
if (f.patchedNodes.has(vnode)) return
const listener = () => console.log('patch', vnode)
vnode.node.addEventListener('click', listener)
console.log('addEventListener')
f.patchedNodes.set(vnode, () => {
console.log('removeEventListener')
vnode.node.removeEve... | f | identifier_name |
test-vnode0.js | // @flow
/* eslint-disable */
import {
periodic,
now,
merge,
never,
newStream,
propagateEventTask
} from '@most/core'
import {disposeBoth, disposeWith} from '@most/disposable'
import {newDefaultScheduler, asap} from '@most/scheduler'
import M from '../m'
import tree from './element'
import type {Pith} from ... | newStream((sink, scheduler) => {
console.log('sink')
return disposeBoth(
asap(propagateEventTask(f, sink), scheduler),
disposeWith(() => {
f.patchedNodes.forEach(d => d())
f.patchedNodes.clear()
}, null)
)
})
)
// put.tex... | })
}
f.patchedNodes = new Map()
put.put( | random_line_split |
test-vnode0.js | // @flow
/* eslint-disable */
import {
periodic,
now,
merge,
never,
newStream,
propagateEventTask
} from '@most/core'
import {disposeBoth, disposeWith} from '@most/disposable'
import {newDefaultScheduler, asap} from '@most/scheduler'
import M from '../m'
import tree from './element'
import type {Pith} from ... | {
return (put, on) => {
put.node('button', {on: {click: 'A'}})(put => {
put.text('A')
})
put.text(
M.of(on)
.map(x => x.action)
.startWith('')
.valueOf()
)
}
} | identifier_body | |
classify.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 expr_is_simple_block(e: @ast::Expr) -> bool {
match e.node {
ast::ExprBlock(block) => block.rules == ast::DefaultBlock,
_ => false
}
}
// this statement requires a semicolon after it.
// note that in one case (stmt_semi), we've already
// seen the semicolon, and thus don't need another.
... | {
match e.node {
ast::ExprIf(..)
| ast::ExprMatch(..)
| ast::ExprBlock(_)
| ast::ExprWhile(..)
| ast::ExprLoop(..)
| ast::ExprForLoop(..)
| ast::ExprCall(_, _, ast::DoSugar)
| ast::ExprCall(_, _, ast::ForSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::DoSugar)
... | identifier_body |
classify.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 ... | ast::StmtMac(..) => { false }
}
} | random_line_split | |
classify.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 ... |
}
}
| { false } | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.