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 |
|---|---|---|---|---|
AdminActions.js | import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH',
SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE',
SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE',
SET_ADMIN: 'SET_ADMIN', | };
export function setSearch(search) {
return {
type: ACTIONS.SET_ADMIN_SEARCH,
search
};
}
export function setCurrentPage(page) {
return {
type: ACTIONS.SET_ADMIN_CURRENT_PAGE,
page
};
}
export function setMaxPage(page) {
return {
type: ACTIONS.SET_ADMIN_MAX_PAGE,
page
};
}
export f... | random_line_split | |
AdminActions.js | import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH',
SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE',
SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE',
SET_ADMIN: 'SET_ADMIN',
};
export function setSearch(search) {
return {
type: ACTIONS.S... | (search, page) {
return (dispatch) => {
return callApi(`admin?search=${search}&page=${page}`, 'get', '' ).then(res => {
dispatch(setAdmin(res.admin));
});
};
}
export function deleteAdmin(del) {
return () => {
return callApi('admin/delete', 'post', '', {del}).then(res => {
return res;
... | getAdminSearch | identifier_name |
AdminActions.js | import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH',
SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE',
SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE',
SET_ADMIN: 'SET_ADMIN',
};
export function setSearch(search) |
export function setCurrentPage(page) {
return {
type: ACTIONS.SET_ADMIN_CURRENT_PAGE,
page
};
}
export function setMaxPage(page) {
return {
type: ACTIONS.SET_ADMIN_MAX_PAGE,
page
};
}
export function setAdmin(admin) {
return {
type: ACTIONS.SET_ADMIN,
admin
};
}
export function get... | {
return {
type: ACTIONS.SET_ADMIN_SEARCH,
search
};
} | identifier_body |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='l... | r = requests.get(url, headers=headers, verify=False)
a.remove(current)
a.add(current, r.elapsed.microseconds)
c.timing(endpoint, int(r.elapsed.microseconds)/1000)
iterate = True
elements = []
iterator = a.__iter__()
whil... | def run(self):
endpoints = ['topology', 'remediations']
positions = [30, 50, 99]
api = 'ecepeda-api.route105.net'
token_curl = curl('https://{0}/aims/v1/authenticate'.format(api), '-s', '-k', '-X', 'POST', '-H', 'Accept: application/json', '--user', '2A6B0U16535H6X0D5822:$2a$12$WB8KmRc... | identifier_body |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='l... | (self):
endpoints = ['topology', 'remediations']
positions = [30, 50, 99]
api = 'ecepeda-api.route105.net'
token_curl = curl('https://{0}/aims/v1/authenticate'.format(api), '-s', '-k', '-X', 'POST', '-H', 'Accept: application/json', '--user', '2A6B0U16535H6X0D5822:$2a$12$WB8KmRcUnGpf1M... | run | identifier_name |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='l... | f = FooBarBazMetricJSON() | conditional_block | |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='l... | percentiles[percentile] = elements[int(math.ceil(position))]
percentiles['current'] = int(current) + 1
self.output(str(percentiles))
self.warning(str(endpoints))
if __name__ == "__main__":
f = FooBarBazMetricJSON() | for percentile in positions:
position = (percentile*.01) * len(elements) - 1 | random_line_split |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status', |
if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
else:
subcommand = 'daemon'
parser = OptionParser()
parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true',
help = "Don't daemonize by forking into the background.... | ]
def parse_args(argv): | random_line_split |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status',
]
def parse_args(argv):
if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
... | main() | conditional_block | |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status',
]
def parse_args(argv):
|
def main():
options = parse_args(sys.argv[1:])
import happy
prog = happy.HAppy(options)
getattr(prog, options.subcommand)()
if __name__ == '__main__':
main()
| if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
else:
subcommand = 'daemon'
parser = OptionParser()
parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true',
help = "Don't daemonize by forking into the background.")
... | identifier_body |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status',
]
def | (argv):
if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
else:
subcommand = 'daemon'
parser = OptionParser()
parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true',
help = "Don't daemonize by forking into the bac... | parse_args | identifier_name |
responsive-scripts.js | 's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
... | {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
... | identifier_body | |
responsive-scripts.js | path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In ... | {
return element.value = value;
} | conditional_block | |
responsive-scripts.js | :1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body ... | setPlaceholder | identifier_name | |
responsive-scripts.js | = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing s... |
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docEle... | else {
body.removeChild( div );
} | random_line_split |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
... |
def state_update_dvs(self):
self.module.exit_json(changed=False, msg="Currently not implemented.")
def state_create_dvs(self):
changed = True
result = None
if not self.module.check_mode:
dc = find_datacenter_by_name(self.content, self.datacenter_name)
... | task = self.dvs.Destroy_Task()
changed, result = wait_for_task(task)
self.module.exit_json(changed=changed, result=str(result)) | identifier_body |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
... | (self, module):
self.module = module
self.dvs = None
self.switch_name = self.module.params['switch_name']
self.datacenter_name = self.module.params['datacenter_name']
self.mtu = self.module.params['mtu']
self.uplink_quantity = self.module.params['uplink_quantity']
... | __init__ | identifier_name |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
... |
vmware_dvswitch = VMwareDVSwitch(module)
vmware_dvswitch.process_state()
if __name__ == '__main__':
main()
| module.fail_json(msg='pyvmomi is required for this module') | conditional_block |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
... | find_dvs_by_name,
vmware_argument_spec,
wait_for_task
)
class VMwareDVSwitch(object):
def __init__(self, module):
self.module = module
... | find_datacenter_by_name, | random_line_split |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Ro | ata) {
if (data) {
this.setData(data);
}
};
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url... | utine(d | identifier_name |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Routine(data) {
|
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url + '/GetLastRoutine/').success(function (response) {
if (response && respons... | if (data) {
this.setData(data);
}
};
| identifier_body |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Routine(data) {
if (data) {
| };
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url + '/GetLastRoutine/').success(function (response) {
if (response ... | this.setData(data);
}
| conditional_block |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Routine(data) {
if (data) {
this.setData(data);
}
};
// Methods
Routine.prototype = new DataModel(Config.HostServic... | }
});
};
Routine.prototype.GetByClientId = function (id) {
var $this = this;
return $http.get($this.url + '/GetByClientId/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend... | if (response && response.Status == 0) {
angular.extend($this, response.Result); | random_line_split |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{Thr... |
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
... | {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(heade... | conditional_block |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{Thr... |
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> HttpResult<Response> {
let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
Response::new(raw)
}
}
impl... | { &mut self.headers } | identifier_body |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{Thr... | debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
... | random_line_split | |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{Thr... | (&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConn... | write | identifier_name |
container.js |
import {connect } from 'react-redux'
import React,{Component} from 'react'
import {Nav, Navbar, NavItem} from 'react-bootstrap'
import {pushState} from 'redux-router'
import Alert from '../components/alert'
import Loader from 'react-loader-advanced';
@connect((state) => ( {loading: state.common.loading}))
export defa... | </div>);
}
}
| {
let topRoutes = this.props.route.childRoutes;
let activeRoute = topRoutes.filter(route => this.props.history.isActive(route.path))[0]
return (<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand><a href="#">ToolboxSite</a></Navbar.Brand>
</Navbar.Header>
<Nav pullRigh... | identifier_body |
container.js |
import {connect } from 'react-redux'
import React,{Component} from 'react'
import {Nav, Navbar, NavItem} from 'react-bootstrap'
import {pushState} from 'redux-router'
import Alert from '../components/alert'
import Loader from 'react-loader-advanced';
@connect((state) => ( {loading: state.common.loading}))
export defa... | extends Component {
constructor(props){
super(props);
}
render () {
let topRoutes = this.props.route.childRoutes;
let activeRoute = topRoutes.filter(route => this.props.history.isActive(route.path))[0]
return (<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand><a href="#">T... | App | identifier_name |
container.js | import {connect } from 'react-redux'
import React,{Component} from 'react'
import {Nav, Navbar, NavItem} from 'react-bootstrap'
import {pushState} from 'redux-router'
import Alert from '../components/alert'
import Loader from 'react-loader-advanced';
@connect((state) => ( {loading: state.common.loading}))
export defau... | <Nav pullRight>
{topRoutes.map(route =><NavItem key={route.path} href={'#'+ route.path}>{route.name}</NavItem>)}
<NavItem href="https://github.com/Jishun/ToolboxSite" target="_blank">GitHub</NavItem>
</Nav>
</Navbar>
<div id="content_area" className="container">
... | <Navbar.Brand><a href="#">ToolboxSite</a></Navbar.Brand>
</Navbar.Header> | random_line_split |
compiled_part_6_AbstractAuthView_1.js | window.themingStore.views.AbstractView.prototype.initialize.call(this);
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* creates a base request to send to backend
* @param url
* @param type
* @param data
* @param successf
* @param errorf
* @private
*/
_reqCreator: fu... |
var textValue = $(this).val();
var isValid = false;
if (!(/[^\s]+/.test(textValue))) {
isValid = false;
}
else {
var emailPattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (textValue.match(emailPattern) != null) {
isValid = tru... | random_line_split | |
compiled_part_6_AbstractAuthView_1.js | emingStore.currentRouter.navigate('dashboard');
}
else {
window.themingStore.currentRouter.navigate('browse');
}
}
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* method to react to gp error on load
*/
listenErrorsGPlusError: function () {
var self ... | {
var action = self.lastAction;
switch (action)
{
case 'twitter': self.showFirstForm(500, 500, '.sign_in_twitter_form_container'); break;
case 'email_form': self.showFirstForm(); break;
}
} | conditional_block | |
asha-workers-details.service_20170224103415.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data';
import { AshaWorkerP... | .toPromise()
.then(function(response){
return response.json() as JSONMessageModel
)
.catch(this.handleError)
}
private handleError(error: any):Promise<any>{
console.error('An error occured', erro... | //update the payment rules for rural, urban and help text
updateAshaWorkerPaymentRules(ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<JSONMessageModel>{
let body = JSON.stringify(ashaWorkerPaymentRulesModel);
console.log("body = "+ body);
return this.http.put(this.up... | random_line_split |
asha-workers-details.service_20170224103415.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data';
import { AshaWorkerP... | {
private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details";
private updateURL: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/ashaActivityRules/updateActivity"
constructor(private http: Http){}
getAshaWorkersList(): Promise<Ash... | AshaWorkersDetailsService | identifier_name |
level.js | 'use strict';
function Level(args) {
if(!(this instanceof Level))
return new Level(args);
this.context = args.context;
this.player = args.player;
this.gameplayObjects = args.gameplayObjects;
this.outcomeListeners = [];
this.finalMessageListeners = [];
this.respawnInfoListeners = [];
this.victoryMe... | }
this.isPaused = false;
this.lastFrameTime = performance.now();
window.requestAnimationFrame(gameLoopFrame);
}
Level.prototype.pauseGameLoop = function() {
this.isPaused = true;
}
Level.prototype.addOutcomeListener = function(listener) {
this.outcomeListeners.push(listener);
}
Level.prototype.addFinalM... | random_line_split | |
level.js | 'use strict';
function | (args) {
if(!(this instanceof Level))
return new Level(args);
this.context = args.context;
this.player = args.player;
this.gameplayObjects = args.gameplayObjects;
this.outcomeListeners = [];
this.finalMessageListeners = [];
this.respawnInfoListeners = [];
this.victoryMessages = args.victoryMessages... | Level | identifier_name |
level.js | 'use strict';
function Level(args) |
Level.prototype.draw = function() {
this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height);
this.gameplayObjects.forEach(o => o.draw(this.context));
this.player.draw(this.context);
}
Level.prototype.update = function(dt) {
this.player.update(dt);
}
Level.prototype.frame = functi... | {
if(!(this instanceof Level))
return new Level(args);
this.context = args.context;
this.player = args.player;
this.gameplayObjects = args.gameplayObjects;
this.outcomeListeners = [];
this.finalMessageListeners = [];
this.respawnInfoListeners = [];
this.victoryMessages = args.victoryMessages;
thi... | identifier_body |
init.ts | /// <reference path="application.ts" />
/// <reference path="pages/IndexPageController.ts" />
/// <reference path="pages/DetailsPageController.ts" />
module ft{
declare var Framework7: any;
interface Framework7View{
}
interface Framework7App{
addView(view:String, callback:Framework7ViewOptions):Fr... | ():void {
// Initialize app
this.fw7App = new Framework7({
animateNavBackIcon: true
});
this.fw7ViewOptions = {
dynamicNavbar: true,
domCache: true
}
// Add view
this.mainView = this.fw7App.addView('.view-main', this.fw7ViewOptions);
... | configApp | identifier_name |
init.ts | /// <reference path="application.ts" />
/// <reference path="pages/IndexPageController.ts" />
/// <reference path="pages/DetailsPageController.ts" />
module ft{
declare var Framework7: any;
interface Framework7View{
}
interface Framework7App{
addView(view:String, callback:Framework7ViewOptions):Fr... | this.configApp();
}
private configApp():void {
// Initialize app
this.fw7App = new Framework7({
animateNavBackIcon: true
});
this.fw7ViewOptions = {
dynamicNavbar: true,
domCache: true
}
// Add view
this.mainView = this.fw7... | random_line_split | |
messages.py |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
|
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if messag... | if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded="" | identifier_body |
messages.py | import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
|
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message... | self.type="gc"
self.decoded="" | random_line_split |
messages.py |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
... | ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
d... | get | identifier_name |
messages.py |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
|
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split deco... | self.name=socket.gethostname() | conditional_block |
addImgcom.js | if (typeof exports === 'undefined') {
exports = {}; | }
exports.config = {
"name": "addImgcom",
"desc": "新增图片组件",
// 线上地址
"url": "http://xxx/addImgcom",
// 日常地址
"urlDaily": "http://xxxx/addImgcom",
// 预发地址
"urlPrepub": "http://example.com/addImgcom",
// 支持的 Method 集合
"method": ['POST']
};
exports.request ={
pageId:'1332edf', //... | random_line_split | |
addImgcom.js | if (typeof exports === 'undefined') |
exports.config = {
"name": "addImgcom",
"desc": "新增图片组件",
// 线上地址
"url": "http://xxx/addImgcom",
// 日常地址
"urlDaily": "http://xxxx/addImgcom",
// 预发地址
"urlPrepub": "http://example.com/addImgcom",
// 支持的 Method 集合
"method": ['POST']
};
exports.request ={
pageId:'1332edf', //关... | {
exports = {};
} | conditional_block |
lib.rs | //! Boron is a small and expressive web framework for Rust which aims to give a robust foundation
//! for web applications and APIs.
//!
//! ## Installation
//! Add the following line to your `[dependecies]` section in `Cargo.toml`:
//!
//! ```toml
//! boron = "0.0.2"
//! ```
//!
//! ## Your first app
//!
//! ```rust,n... | pub mod server;
pub mod response;
pub mod request;
pub mod middleware;
pub mod router;
mod matcher; | extern crate regex;
extern crate typemap;
| random_line_split |
fun-call-variants.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 ... | let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
} | pub fn main() {
let a: isize = direct(3); // direct | random_line_split |
fun-call-variants.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let a: isize = direct(3); // direct
let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
}
| { return x + 1; } | identifier_body |
fun-call-variants.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 ... | <F>(f: F) -> isize where F: FnOnce(isize) -> isize { let n: isize = f(3); return n; }
fn direct(x: isize) -> isize { return x + 1; }
pub fn main() {
let a: isize = direct(3); // direct
let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
}
| ho | identifier_name |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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)... |
def summarize(concurrency, canceled):
message = "copied {} scaled {} ".format(results.copied, results.scaled)
difference = results.todo - (results.copied + results.scaled)
if difference:
message += "skipped {} ".format(difference)
message += "using {} coroutines".format(concurrency)
... | f smooth:
scale = min(size / oldImage.width, size / oldImage.height)
newImage = oldImage.scale(scale)
else:
stride = int(math.ceil(max(oldImage.width / size,
oldImage.height / size)))
newImage = oldImage.subsample(strid... | conditional_block |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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)... |
def get_jobs(source, target):
for name in os.listdir(source):
yield os.path.join(source, name), os.path.join(target, name)
@Qtrac.coroutine
def scaler(receiver, sink, size, smooth, me):
while True:
sourceImage, targetImage, who = (yield)
if who == me:
try:
... | ipeline = None
sink = results()
for who in range(concurrency):
pipeline = scaler(pipeline, sink, size, smooth, who)
return pipeline
| identifier_body |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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)... | ):
while True:
result = (yield)
results.todo += result.todo
results.copied += result.copied
results.scaled += result.scaled
Qtrac.report("{} {}".format("copied" if result.copied else "scaled",
os.path.basename(result.name)))
results.todo = results.copi... | esults( | identifier_name |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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)... | "timing) [default: %(default)d]")
parser.add_argument("-s", "--size", default=400, type=int,
help="make a scaled image that fits the given dimension "
"[default: %(default)d]")
parser.add_argument("-S", "--smooth", action="store_true",
help="use smoot... | default=multiprocessing.cpu_count(),
help="specify the concurrency (for debugging and "
| random_line_split |
S11.13.2_A4.7_T1.4.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The production x >>= y is the same as x = x >> y
es5id: 11.13.2_A4.7_T1.4
description: Type(x) and Type(y) vary between Null and Undefined
---*/
//CHECK#1
x = null;
x >>= und... |
//CHECK#3
x = undefined;
x >>= undefined;
if (x !== 0) {
$ERROR('#3: x = undefined; x >>= undefined; x === 0. Actual: ' + (x));
}
//CHECK#4
x = null;
x >>= null;
if (x !== 0) {
$ERROR('#4: x = null; x >>= null; x === 0. Actual: ' + (x));
}
| {
$ERROR('#2: x = undefined; x >>= null; x === 0. Actual: ' + (x));
} | conditional_block |
S11.13.2_A4.7_T1.4.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The production x >>= y is the same as x = x >> y
es5id: 11.13.2_A4.7_T1.4
description: Type(x) and Type(y) vary between Null and Undefined
---*/
//CHECK#1
x = null;
x >>= und... | x = null;
x >>= null;
if (x !== 0) {
$ERROR('#4: x = null; x >>= null; x === 0. Actual: ' + (x));
} | }
//CHECK#4 | random_line_split |
P13nSelectionItem.js | /*
* ! ${copyright}
*/
// Provides control sap.m.P13nSelectionItem.
sap.ui.define([
'jquery.sap.global', './library', 'sap/ui/core/Item'
], function(jQuery, library, Item) {
"use strict";
/**
* Constructor for a new P13nSelectionItem.
*
* @param {string} [sId] ID for the new control, generated automaticall... | }
}
}
});
return P13nSelectionItem;
}, /* bExport= */true); | defaultValue: false | random_line_split |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
| return False, 0
if abs(l_h - r_h) < 2:
return True, max(l_h, r_h) + 1
return False, 0
| """
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
isbalanced, h = self.isBalancedandHeight(root)
return isbalanced
def isBalancedandHeight(self, root):
if root is ... | identifier_body |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# ... |
l, r = root.left, root.right
l_balanced, l_h = self.isBalancedandHeight(l)
if not l_balanced:
return False, 0
r_balanced, r_h = self.isBalancedandHeight(r)
if not r_balanced:
return False, 0
if abs(l_h - r_h) < 2:
return True, max(l... | return True, 0 | conditional_block |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class | :
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
isbalanced, h = self.isBalancedandHeight(root)
return isbalanced
def isBalancedandHeight(self, root):
if ro... | Solution | identifier_name |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
""" | class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
isbalanced, h = self.isBalancedandHeight(root)
return isbalanced
def isBalancedandHeight(self, root):... | random_line_split | |
__init__.py | """Support for MQTT lights."""
import logging
import voluptuous as vol
from homeassistant.components import light
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.helpers.dispatche... |
PLATFORM_SCHEMA = vol.All(
MQTT_LIGHT_SCHEMA_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA), validate_mqtt_light
)
async def async_setup_platform(
hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None
):
"""Set up MQTT light through configuration.yaml."""
await async_setup_... | """Validate MQTT light schema."""
schemas = {
"basic": PLATFORM_SCHEMA_BASIC,
"json": PLATFORM_SCHEMA_JSON,
"template": PLATFORM_SCHEMA_TEMPLATE,
}
return schemas[value[CONF_SCHEMA]](value) | identifier_body |
__init__.py | """Support for MQTT lights."""
import logging
import voluptuous as vol
from homeassistant.components import light
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.helpers.dispatche... | (hass, config_entry, async_add_entities):
"""Set up MQTT light dynamically through MQTT discovery."""
async def async_discover(discovery_payload):
"""Discover and add a MQTT light."""
discovery_data = discovery_payload.discovery_data
try:
config = PLATFORM_SCHEMA(discovery_p... | async_setup_entry | identifier_name |
__init__.py | """Support for MQTT lights."""
import logging
import voluptuous as vol
from homeassistant.components import light
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.helpers.dispatche... | await _async_setup_entity(hass, config, async_add_entities)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up MQTT light dynamically through MQTT discovery."""
async def async_discover(discovery_payload):
"""Discover and add a MQTT light."""
discovery_data = d... | ):
"""Set up MQTT light through configuration.yaml."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS) | random_line_split |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP ad... | base.HeadlessPost.__init__(self)
self.flatmode_tolerance = 256
self.nodesModel = sam.models.nodes.Nodes(common.db, self.page.user.viewing)
def check_flat_tolerance(self):
endpoints = self.nodesModel.get_all_endpoints()
count = len(endpoints)
return count <= self.flat... |
"""
def __init__(self): | random_line_split |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP ad... |
def decode_post_request(self, data):
node = data.get('node')
if not node:
raise errors.RequiredKey('node', 'node')
alias = data.get('alias')
tags = data.get('tags')
env = data.get('env')
request = {'node': node}
if alias is not None:
... | return response | identifier_body |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP ad... | (self):
base.HeadlessPost.__init__(self)
self.flatmode_tolerance = 256
self.nodesModel = sam.models.nodes.Nodes(common.db, self.page.user.viewing)
def check_flat_tolerance(self):
endpoints = self.nodesModel.get_all_endpoints()
count = len(endpoints)
return count <= s... | __init__ | identifier_name |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP ad... |
else:
print("Error in nodeinfo, unrecognized assignment {0} = {1}".format(key, value))
return 0, "Success"
def encode_post_response(self, response):
return {'code': response[0], 'message': response[1]} | self.nodesModel.set_env(node, None) | conditional_block |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display deb... |
def setName(self, name):
if self.debug:
print "Name set to: " + self.textName
| if self.debug:
print self.textName + "'s text set."
self.text = text.lower() | identifier_body |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display deb... | if self.debug:
print "Feature calculation begining on " + self.textName
print "------"
def endCalc(self):
if self.debug:
print "Feature calculation finished on " + self.textName
print "Features Calculated:"
print self.f
print
... | random_line_split | |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display deb... |
def beginCalc(self):
if self.debug:
print "Feature calculation begining on " + self.textName
print "------"
def endCalc(self):
if self.debug:
print "Feature calculation finished on " + self.textName
print "Features Calculated:"
print... | print "--BaseFeatures--" | conditional_block |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display deb... | (self):
return self.f
def setText(self, text):
if self.debug:
print self.textName + "'s text set."
self.text = text.lower()
def setName(self, name):
if self.debug:
print "Name set to: " + self.textName
| getFeatures | identifier_name |
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1... | {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join(""));
} | identifier_body | |
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1... | } | random_line_split | |
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1... | () {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join(""));
}
| main | identifier_name |
const.py | """Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'al... | """Raised when invalid trusted networks config.""" | identifier_body | |
const.py | """Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled' | PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'alexa'
CONF_ALIASES = 'aliases'
CONF_COGNITO_CLIENT_ID = 'cognito_client_id'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_FILTER = 'filter'
CONF_GOOGLE_ACTIONS... | random_line_split | |
const.py | """Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'al... | (Exception):
"""Raised when invalid trusted networks config."""
| InvalidTrustedNetworks | identifier_name |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
sup... |
return rtxt
def get_errorbox_info(self):
rtxt = []
for e in self.find_elements(self.locators['errorbox1']):
if e.is_displayed():
rtxt.append(e.text)
for e in self.find_elements(self.locators['errorbox2']):
if e.is_displayed():
... | if e.is_displayed():
rtxt.append(e.text) | conditional_block |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
sup... | for e in self.find_elements(self.locators['errorbox2']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
class GenericPage_Locators_Base_1(object):
"""
locators for GenericPage object
"""
locators = {
'needhelplink' : "css=#tab",
'debu... | rtxt = []
for e in self.find_elements(self.locators['errorbox1']):
if e.is_displayed():
rtxt.append(e.text) | random_line_split |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
sup... |
def is_logged_in(self):
"""check if user is logged in, returns True or False"""
return self.header.is_logged_in()
def get_account_number(self):
"""return the account number of a logged in user based on urls"""
if not self.is_logged_in():
raise RuntimeError("user... | return self.needhelplink.click() | identifier_body |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
sup... | (self):
"""check if user is logged in, returns True or False"""
return self.header.is_logged_in()
def get_account_number(self):
"""return the account number of a logged in user based on urls"""
if not self.is_logged_in():
raise RuntimeError("user is not logged in")
... | is_logged_in | identifier_name |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds... | () {}
// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) {}
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider... | eh_unwind_resume | identifier_name |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds... | take_range(0..=1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..=1)
take_range(..5);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..5)
take_range(..=42);
//~^ ERROR mismatched types [E0308]... | //~| SUGGESTION &(..)
| random_line_split |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds... |
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(1..)
take_range(..);
//~^ ERROR mismatched typ... | {} | identifier_body |
r.js | "use strict";
const fs = require('fs');
const path = require('path');
module.exports = {
| (opts, runCode) {
const entry = path.join(opts.dir, 'main.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(entry, opts.solution);
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
}
});
... | solutionOnly | identifier_name |
r.js | "use strict";
const fs = require('fs');
const path = require('path');
module.exports = {
solutionOnly(opts, runCode) {
const entry = path.join(opts.dir, 'main.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(entry, opts.solution);
runCode({
na... | `source("solution.R")`,
`test_file("tests.R", reporter=CodewarsReporter$new())`,
].join('\n'));
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
},
});
}
}; | fs.writeFileSync(path.join(opts.dir, 'tests.R'), opts.fixture);
fs.writeFileSync(entry, [
`library(testthat)`,
`source("/runner/frameworks/r/codewars-reporter.R")`, | random_line_split |
r.js | "use strict";
const fs = require('fs');
const path = require('path');
module.exports = {
solutionOnly(opts, runCode) {
const entry = path.join(opts.dir, 'main.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(entry, opts.solution);
runCode({
na... |
};
| {
const entry = path.join(opts.dir, 'run-tests.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(path.join(opts.dir, 'solution.R'), opts.solution);
fs.writeFileSync(path.join(opts.dir, 'tests.R'), opts.fixture);
fs.writeFileSync(entry, [
`libra... | identifier_body |
replication-table-rows-test.js | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
const REPLICATION_DETAILS = {
clusterId: 'b829d963-6835-33eb-a903-57376024b97a',
merkleRoot: 'c21c8428a0a06135cef6ae25bf8e0267ff1592a6'... |
assert
.dom('[data-test-row-value="Merkle root index"]')
.includesText(REPLICATION_DETAILS.merkleRoot, `shows the correct Merkle Root`);
assert.dom('[data-test-row-value="Mode"]').includesText(CLUSTER_MODE, `shows the correct Mode`);
assert
.dom('[data-test-row-value="Replication set"]')
... | random_line_split | |
059_add_consumer_generation.py | # 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
# d... | consumers.create_column(Column("generation", Integer, default=0,
server_default=text("0"), nullable=False)) | conditional_block | |
059_add_consumer_generation.py | # 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
# d... | (migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
# This is adding a column to an existing table, so the server_default
# bit will make existing rows 0 for that column.
co... | upgrade | identifier_name |
059_add_consumer_generation.py | # 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
# d... | meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
# This is adding a column to an existing table, so the server_default
# bit will make existing rows 0 for that column.
consumers.create_column(... | identifier_body | |
059_add_consumer_generation.py | # 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
# d... | from sqlalchemy import text
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
# This is adding a column to an existing table, so the server_default
# bit will make ex... |
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table | random_line_split |
comments.js | var recast = require("../main");
var n = recast.types.namedTypes;
var b = recast.types.builders;
var fromString = require("../lib/lines").fromString;
var util = require("../lib/util");
var annotated = [
"function dup(/* string */ s,",
" /* int */ n) /* string */",
"{",
" // Use an array fu... | var flush = fromString(indented).indent(-2);
assert.strictEqual(
recast.print(retStmt).code,
flush.toString()
);
var join = retStmt.argument;
n.CallExpression.assert(join);
var one = join.callee.object.arguments[0].right;
n.Literal.assert(one);
assert.strictEqual(one.v... |
var indented = annotated.slice(3, 6).join("\n"); | random_line_split |
kendo.culture.zh-SG.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) | /******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
... | {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ ... | identifier_body |
kendo.culture.zh-SG.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function | (moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId... | __webpack_require__ | identifier_name |
kendo.culture.zh-SG.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ ret... |
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_... | random_line_split | |
index.spec.ts | import * as assert from 'power-assert';
import SUSH from 'sush';
import SUSHPluginAddObject from '../';
describe('SUSHPluginAddObject', () => {
let sush: SUSH;
beforeEach(() => {
// Init SUSH
sush = new SUSH();
});
it('dose nothing if argument is none', (done) => {
sush.flow([
SUSHPluginAd... |
const expectedMap = new Map();
for (const key of Object.keys(basedObj)) {
expectedMap.set(key, basedObj[key]);
}
sush.flow([
SUSHPluginAddObject(expectedMap)
])
.then(() => {
for (const [key, expected] of expectedMap.entries()) {
assert.strictEqual(sush.stock.get(key)... | const basedObj: {[key: string]: string} = {
example: 'https://example.com',
test: 'https://test.example'
}; | random_line_split |
Administration.SentEmailsForm.ts | namespace PatientManagement.Administration {
export interface SentEmailsForm {
ToEmail: PatientManagement.LKCodeDescr;
Subject: Serenity.StringEditor;
Body: Serenity.HtmlContentEditor;
EmailSignature: Serenity.HtmlContentEditor;
}
export class SentEmailsForm extends Serenit... | }
}
}
| SentEmailsForm.init = true;
var s = Serenity;
var w0 = PatientManagement.LKCodeDescr;
var w1 = s.StringEditor;
var w2 = s.HtmlContentEditor;
Q.initFormType(SentEmailsForm, [
'ToEmail', w0,
... | conditional_block |
Administration.SentEmailsForm.ts | namespace PatientManagement.Administration {
export interface SentEmailsForm {
ToEmail: PatientManagement.LKCodeDescr;
Subject: Serenity.StringEditor;
Body: Serenity.HtmlContentEditor;
EmailSignature: Serenity.HtmlContentEditor;
}
export class SentEmailsForm extends Serenit... |
Q.initFormType(SentEmailsForm, [
'ToEmail', w0,
'Subject', w1,
'Body', w2,
'EmailSignature', w2
]);
}
}
}
} | random_line_split | |
Administration.SentEmailsForm.ts | namespace PatientManagement.Administration {
export interface SentEmailsForm {
ToEmail: PatientManagement.LKCodeDescr;
Subject: Serenity.StringEditor;
Body: Serenity.HtmlContentEditor;
EmailSignature: Serenity.HtmlContentEditor;
}
export class Se | xtends Serenity.PrefixedContext {
static formKey = 'Administration.SentEmails';
private static init: boolean;
constructor(prefix: string) {
super(prefix);
if (!SentEmailsForm.init) {
SentEmailsForm.init = true;
var s = Serenity;
... | ntEmailsForm e | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.