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
borrowck-move-subcomponent.rs
// Copyright 2012-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-MI...
let S { x: ax } = a; //~ ERROR cannot move out f(pb); }
let a : S = S { x : box 1 }; let pb = &a;
random_line_split
borrowck-move-subcomponent.rs
// Copyright 2012-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-MI...
() { let a : S = S { x : box 1 }; let pb = &a; let S { x: ax } = a; //~ ERROR cannot move out f(pb); }
main
identifier_name
utils.py
= db def resetSession(self): """ Resetea los datos de la session """ session = current.session session.empresa = None session.predio = None session.datosfuncId = None session.genera = None def cargarResiduos(self,decid): s = current.session s.g...
self.db
identifier_name
utils.py
(self,data): import json semana = {0: 'Domingo', 1: 'Lunes', 2: 'Martes', 3: 'Miércoles', 4: 'Jueves', 5: 'Viernes', 6: 'Sábado'} #Codificado data_string = json.dumps(data) #Decodificado decoded = json.loads(data_string) horario = {} resultado ...
n [
conditional_block
utils.py
Args: db: La base de datos. """ def __init__(self, db): self.db = db def resetSession(self): """ Resetea los datos de la session """ session = current.session session.empresa = None session.predio = None session.datosfuncId = None sessio...
class Utils(object): """ Esta clase provee funciones para el manejo de la sesión, validaciones y para exportar los datos en formato PDF.
random_line_split
utils.py
son menores a 10, se agrega un cero delante para alinear las posiciones con las validaciones if rut_tam in range(10,12) and int(rut[8:10]) != 0: rut = "0" + rut rut_tam +=1 if rut_tam == 11 or rut_tam == 12: val1 = int(rut[:2]) in range(1, 22) val2 = int(...
lf,omitidos=[]): campos=['password','registration_id','registration_key','reset_password_key','is_active', 'created_on', 'created_by', 'modified_on', 'modified_by'] campos+=['centro','id','declaracion','empresa','predio'] campos+=omitidos return campos def traducirlista(self,lista,t...
ent.session listo = False for tipo in session.genera: if (session.genera[tipo] is not None): listo = True break if listo: session.residuosCargados = True else: session.residuosCargados = None def ob...
identifier_body
qmp_basic.py
# - Valid, but not obvious syntax, like zillion of spaces or # strings with unicode chars (different suite maybe?) bad_json = [] # A JSON value MUST be an object, array, number, string, true, false, # or null # # NOTE: QMP seems to ignore a number of chars...
greeting_suite(qmp_monitor) input_object_suite(qmp_monitor)
random_line_split
qmp_basic.py
, key) if not isinstance(qmp_dict[key], keytype): raise error.TestFail("'%s' key is not of type '%s', it's '%s'" % (key, keytype, type(qmp_dict[key]))) def check_key_is_dict(qmp_dict, key):
def check_key_is_list(qmp_dict, key): check_dict_key(qmp_dict, key, list) def check_key_is_str(qmp_dict, key): check_dict_key(qmp_dict, key, unicode) def check_str_key(qmp_dict, keyname, value=None): check_dict_key(qmp_dict, keyname, unicode) if value and value != qmp_dic...
check_dict_key(qmp_dict, key, dict)
identifier_body
qmp_basic.py
""" Check that QMP's parser is able to recover from parsing errors, please check the JSON spec for more info on the JSON syntax (RFC 4627). """ # We're quite simple right now and the focus is on parsing errors that # have already biten us in the past. # # ...
resp = monitor.cmd_qmp(cmd) check_error_resp(resp, "CommandNotFound", {"name": cmd})
conditional_block
qmp_basic.py
message format, as described in the QMP specfication section '2.2 Server Greeting'. { "QMP": { "version": json-object, "capabilities": json-array } } """ greeting = monitor.get_greeting() test_greeting(greeting) test_version(greeting["QMP"]["version"]) def json_par...
unknown_commands_suite
identifier_name
actions.js
import { createAction, createThunkAction } from 'redux/actions'; import { getShortenUrl } from 'services/bitly'; import { saveAreaOfInterest } from 'components/forms/area-of-interest/actions'; export const setShareData = createAction('setShareData'); export const setShareUrl = createAction('setShareUrl'); export con...
dispatch(setShareLoading(false)); } }) .catch(() => { dispatch(setShareLoading(false)); }); } ); export const setShareAoi = createThunkAction('shareModalSaveAoi', (params) => (dispatch) => { dispatch(saveAreaOfInterest({ ...params })) });
} else {
random_line_split
actions.js
import { createAction, createThunkAction } from 'redux/actions'; import { getShortenUrl } from 'services/bitly'; import { saveAreaOfInterest } from 'components/forms/area-of-interest/actions'; export const setShareData = createAction('setShareData'); export const setShareUrl = createAction('setShareUrl'); export con...
else { dispatch(setShareLoading(false)); } }) .catch(() => { dispatch(setShareLoading(false)); }); } ); export const setShareAoi = createThunkAction('shareModalSaveAoi', (params) => (dispatch) => { dispatch(saveAreaOfInterest({ ...params })) });
{ shortShareUrl = response.data.link; dispatch(setShareUrl(shortShareUrl)); }
conditional_block
vlayout.rs
use core::position::{Size, Pos, HasSize, HasPosition}; use core::cellbuffer::CellAccessor; use std::boxed::Box; use std::collections::HashMap; use ui::core::{ Layout, Alignable, HorizontalAlign, VerticalAlign, Widget, Frame, Button, Painter, ButtonResult }; /// Hold buttons an...
/// /// let buttons = vec![b1, b2, b3].into_iter().map(Box::new); /// let buttons = buttons.map(|x| x as Box<Button>).collect(); /// /// let mut vlayout = VerticalLayout::from_vec(buttons, 1); /// vlayout.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Bottom, (0,1)); /// /// maindlg.add_layout(vlayout); //...
/// let mut maindlg = Dialog::new(60, 10); /// /// let b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); /// let b2 = StdButton::new("Foo!", 'f', ButtonResult::Custom(1)); /// let b3 = StdButton::new("Bar!", 'b', ButtonResult::Custom(2));
random_line_split
vlayout.rs
use core::position::{Size, Pos, HasSize, HasPosition}; use core::cellbuffer::CellAccessor; use std::boxed::Box; use std::collections::HashMap; use ui::core::{ Layout, Alignable, HorizontalAlign, VerticalAlign, Widget, Frame, Button, Painter, ButtonResult }; /// Hold buttons an...
fn frame(&self) -> &Frame { &self.frame } fn frame_mut(&mut self) -> &mut Frame { &mut self.frame } } impl Layout for VerticalLayout { fn align_elems(&mut self) { let (x, y) = self.origin; let mut current_y = y; for widget in self.widgets.iter_mut() { ...
{ self.frame.resize(new_size); }
identifier_body
vlayout.rs
use core::position::{Size, Pos, HasSize, HasPosition}; use core::cellbuffer::CellAccessor; use std::boxed::Box; use std::collections::HashMap; use ui::core::{ Layout, Alignable, HorizontalAlign, VerticalAlign, Widget, Frame, Button, Painter, ButtonResult }; /// Hold buttons an...
(widgets: Vec<Box<Button>>, inner_margin: usize) -> VerticalLayout { let first_origin = widgets.first().unwrap().frame().origin(); let height = widgets.len() + widgets.len() * inner_margin; let width = widgets.iter().map(|s| s.frame().size().0).max().unwrap(); VerticalLayout { ...
from_vec
identifier_name
l10n-number.pipe.ts
import { Pipe, PipeTransform, ChangeDetectorRef } from '@angular/core'; import { L10nNumberFormatOptions } from '../models/types'; import { L10nAsyncPipe } from '../models/l10n-async-pipe'; import { L10nIntlService } from '../services/l10n-intl.service'; import { L10nTranslationService } from '../services/l10n-transla...
}) export class L10nNumberPipe implements PipeTransform { constructor(protected intl: L10nIntlService) { } public transform(value: any, language: string, options?: L10nNumberFormatOptions, currency?: string): string | null { if (value == null || value === '') return null; return this.intl.for...
pure: true
random_line_split
l10n-number.pipe.ts
import { Pipe, PipeTransform, ChangeDetectorRef } from '@angular/core'; import { L10nNumberFormatOptions } from '../models/types'; import { L10nAsyncPipe } from '../models/l10n-async-pipe'; import { L10nIntlService } from '../services/l10n-intl.service'; import { L10nTranslationService } from '../services/l10n-transla...
public transform(value: any, language: string, options?: L10nNumberFormatOptions, currency?: string): string | null { if (value == null || value === '') return null; return this.intl.formatNumber(value, options, language, currency); } } @Pipe({ name: 'l10nNumberAsync', pure: false }...
{ }
identifier_body
l10n-number.pipe.ts
import { Pipe, PipeTransform, ChangeDetectorRef } from '@angular/core'; import { L10nNumberFormatOptions } from '../models/types'; import { L10nAsyncPipe } from '../models/l10n-async-pipe'; import { L10nIntlService } from '../services/l10n-intl.service'; import { L10nTranslationService } from '../services/l10n-transla...
(value: any, options?: L10nNumberFormatOptions, language?: string, currency?: string): string | null { if (value == null || value === '') return null; return this.intl.formatNumber(value, options, language, currency); } }
transform
identifier_name
repo_info.py
""" Methods to get certain kinds of data from the Github API. Writes each repo's data to a separate file in a given directory """ import json from mimetools import Message from StringIO import StringIO from github_util import * import time import sys, os ##### # CONSTANTS ##### #constants to specify parameters when ...
(repo): URLstr = "https://api.github.com/repos/{}/{}/pulls".format(repo["user"], repo["name"]) page = 1 pulls = [] while page>0: response = api_get(baseURL=URLstr, parameters={'page':page, 'per_page':100, "state":"all"}) if not is_successful_response(response): print "{}\n{}\...
get_pulls
identifier_name
repo_info.py
""" Methods to get certain kinds of data from the Github API. Writes each repo's data to a separate file in a given directory """ import json from mimetools import Message from StringIO import StringIO from github_util import * import time import sys, os ##### # CONSTANTS ##### #constants to specify parameters when ...
#read the data of the current page try: repo_data = json.loads(response.text) except: error_dump("{}\n{}\n{}".format(response, URLstr, response.text)) raise e for repo in repo_data: #get name of the repo ...
all_repos = {} for u in users: repos = [] forked = [] page = 1 while page>0: #api has multiple pages URLstr = 'https://api.github.com/users/{}/repos'.format(u) response = api_get(URLstr, parameters={'page':page, 'per_page':100}) if not is_suc...
identifier_body
repo_info.py
""" Methods to get certain kinds of data from the Github API. Writes each repo's data to a separate file in a given directory """ import json from mimetools import Message from StringIO import StringIO from github_util import * import time import sys, os ##### # CONSTANTS ##### #constants to specify parameters when ...
else: repos.append(repoName) #add to the allRepos dictionary if forks: all_repos[u] = (repos,forked) else: all_repos[u] = repos return all_repos """ grabs a list of all (contributors|collaborators|forkers) of all the repos return...
forked.append(repoName)
conditional_block
repo_info.py
""" Methods to get certain kinds of data from the Github API. Writes each repo's data to a separate file in a given directory """ import json from mimetools import Message from StringIO import StringIO from github_util import * import time import sys, os ##### # CONSTANTS ##### #constants to specify parameters when ...
return parentRepo """ Returns all the commits of a given repo """ def get_all_commits(repo): URLstr = "https://api.github.com/repos/{}/{}/commits".format(repo["user"], repo["name"]) commits = [] page = 1 while page>0: response = api_get(baseURL=URLstr, parameters={'page':page,'per_page':100...
name = JSON_access(page,('parent','name')) owner = JSON_access(page, ('parent','owner','login')) if name != None and owner != None: parentRepo = (name, owner)
random_line_split
s7_client.js
"use strict"; var logger = require('./misc/debug.js'); var TPDU_Client = require('./tpdu_client.js'); var PDU_TYPE = require('./types.js').PDU_TYPE; var S7_Req_Header = require('./types.js').S7_Req_Header; var S7_ReqFun_PlcStop = require('./types.js').S7_ReqFun_PlcStop; var S7_Client = function(host, rack, slot...
}; S7_Client.prototype.DBWrite = function() { }; S7_Client.prototype.MBRead = function() { }; S7_Client.prototype.MBWrite = function() { }; S7_Client.prototype.IBRead = function() { }; S7_Client.prototype.IBWrite = function() { }; S7_Client.prototype.QBRead = function() { }; S7_Client.prototype.QBWri...
random_line_split
watcher.py
import cPickle import logging import numpy import os import time from collections import deque from copy import deepcopy from datetime import datetime from pytz import timezone from threading import Event, Thread from coinbase.wallet.client import Client from jarvis.utils.messaging.client import TwilioMessenger from ...
except Exception: logging.exception("Exception in main loop") time.sleep(self.POLL_PERIOD) store_to_file(self.MSGPATH,self.sent_messages) store_to_file(self.BTCTICKERPATH,self.btc_timeseries.timeseries) store_to_file(self.ETHTICKERPATH,self.eth_timeserie...
msg = self.btc_timeseries.is_large_movement() if msg: self.twilio_client.send_message(msg) self.sent_messages.append((msg, time.time())) self.initiate_cooldown() msg = self.eth_timeseries.is_large_movement() ...
conditional_block
watcher.py
import cPickle import logging import numpy import os import time from collections import deque from copy import deepcopy from datetime import datetime from pytz import timezone from threading import Event, Thread from coinbase.wallet.client import Client from jarvis.utils.messaging.client import TwilioMessenger from ...
watcher.start()
random_line_split
watcher.py
import cPickle import logging import numpy import os import time from collections import deque from copy import deepcopy from datetime import datetime from pytz import timezone from threading import Event, Thread from coinbase.wallet.client import Client from jarvis.utils.messaging.client import TwilioMessenger from ...
(self): self.api_key, self.api_secret = load_coinbase_config() self.client = Client(self.api_key, self.api_secret) def do(self, func, *args, **kwargs): return getattr(self.client,func)(*args, **kwargs) class TickerTimeseries(object): def __init__(self, max_length, recent_cutoff, ...
__init__
identifier_name
watcher.py
import cPickle import logging import numpy import os import time from collections import deque from copy import deepcopy from datetime import datetime from pytz import timezone from threading import Event, Thread from coinbase.wallet.client import Client from jarvis.utils.messaging.client import TwilioMessenger from ...
def initiate_cooldown(self): self.cooldown = self.COOLDOWN_TICKS def start(self): while not self.stop.is_set(): try: spot_price = self.coinbase_client.do( 'get_spot_price',currency_pair='BTC-USD') self.btc_timeseries.append(f...
self.cooldown = max(0,self.cooldown - 1) if self.cooldown <= 0: return False return True
identifier_body
image_warp.py
# Copyright 2007 Zachary Pincus # This file is part of CellTool. # # CellTool is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. from scipy import ndimage import numpy def warp_images(from_points, ...
_small = 1e-100 def _U(x): return (x**2) * numpy.where(x<_small, 0, numpy.log(x)) def _interpoint_distances(points): xd = numpy.subtract.outer(points[:,0], points[:,0]) yd = numpy.subtract.outer(points[:,1], points[:,1]) return numpy.sqrt(xd**2 + yd**2) def _make_L_matrix(points): n = len(points) ...
transform = [transform_x, transform_y] return transform
random_line_split
image_warp.py
# Copyright 2007 Zachary Pincus # This file is part of CellTool. # # CellTool is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. from scipy import ndimage import numpy def warp_images(from_points, ...
def _interpoint_distances(points): xd = numpy.subtract.outer(points[:,0], points[:,0]) yd = numpy.subtract.outer(points[:,1], points[:,1]) return numpy.sqrt(xd**2 + yd**2) def _make_L_matrix(points): n = len(points) K = _U(_interpoint_distances(points)) P = numpy.ones((n, 3)) P[:,1:] = po...
return (x**2) * numpy.where(x<_small, 0, numpy.log(x))
identifier_body
image_warp.py
# Copyright 2007 Zachary Pincus # This file is part of CellTool. # # CellTool is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. from scipy import ndimage import numpy def warp_images(from_points, ...
(x): return (x**2) * numpy.where(x<_small, 0, numpy.log(x)) def _interpoint_distances(points): xd = numpy.subtract.outer(points[:,0], points[:,0]) yd = numpy.subtract.outer(points[:,1], points[:,1]) return numpy.sqrt(xd**2 + yd**2) def _make_L_matrix(points): n = len(points) K = _U(_interpoint...
_U
identifier_name
image_warp.py
# Copyright 2007 Zachary Pincus # This file is part of CellTool. # # CellTool is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. from scipy import ndimage import numpy def warp_images(from_points, ...
return a1 + ax*x + ay*y + summation def _make_warp(from_points, to_points, x_vals, y_vals): from_points, to_points = numpy.asarray(from_points), numpy.asarray(to_points) err = numpy.seterr(divide='ignore') L = _make_L_matrix(from_points) V = numpy.resize(to_points, (len(to_points)+3, 2)) V[-3:...
summation += wi * _U(numpy.sqrt((x-Pi[0])**2 + (y-Pi[1])**2))
conditional_block
test_plugins_input.py
import os.path import unittest from contextlib import contextmanager from unittest.mock import MagicMock, patch from streamlink import PluginError, Streamlink from streamlink.plugin.plugin import UserInputRequester from streamlink_cli.console import ConsoleUserInputRequester from tests.plugin.testplugin import TestPlu...
console_input.console.askpass.assert_called_with("password: ") def test_user_input_console_no_tty(self): p = _TestPlugin("http://example.com/stream") with self._mock_console_input(isatty=False) as console_input: p.bind(self.session, 'test_plugin', console_input) ...
self.assertEqual("password", p.input_ask_password("password")) console_input.console.ask.assert_called_with("username: ")
random_line_split
test_plugins_input.py
import os.path import unittest from contextlib import contextmanager from unittest.mock import MagicMock, patch from streamlink import PluginError, Streamlink from streamlink.plugin.plugin import UserInputRequester from streamlink_cli.console import ConsoleUserInputRequester from tests.plugin.testplugin import TestPlu...
(self): p = _TestPlugin("http://example.com/stream") p.bind(self.session, 'test_plugin', UserInputRequester()) self.assertRaises(PluginError, p.input_ask, 'test') self.assertRaises(PluginError, p.input_ask_password, 'test') def test_user_input_console(self): p = _TestPlugin(...
test_user_input_not_implemented
identifier_name
test_plugins_input.py
import os.path import unittest from contextlib import contextmanager from unittest.mock import MagicMock, patch from streamlink import PluginError, Streamlink from streamlink.plugin.plugin import UserInputRequester from streamlink_cli.console import ConsoleUserInputRequester from tests.plugin.testplugin import TestPlu...
@contextmanager def _mock_console_input(self, isatty=True): with patch('streamlink_cli.console.sys.stdin.isatty', return_value=isatty): mock_console = MagicMock() mock_console.ask.return_value = "username" mock_console.askpass.return_value = "password" y...
self.session = Streamlink()
identifier_body
urls.py
from django.conf.urls import url
from fir_artifacts import views app_name='fir_artifacts' urlpatterns = [ url(r'^(?P<artifact_id>\d+)/detach/(?P<relation_name>\w+)/(?P<relation_id>\d+)/$', views.detach_artifact, name='detach'), url(r'^(?P<artifact_id>\d+)/correlations/$', views.artifacts_correlations, name='correlations'), url(r'^files/(...
random_line_split
inspector.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; /* import-globals-from ../includes.js */ const MIN_INSPECTOR_WIDTH = 300; // Strings for rendering...
if (!bypassable) { button.setAttribute("disabled", true); } else { button.removeAttribute("disabled"); } if (!bypassable || bypassed) { button.removeAttribute("checked"); } else { button.setAttribute("checked", true); } }, /** * Event handlers */ /** * ...
let bypassable = node.bypassable; let bypassed = node.isBypassed(); let button = $("#audio-node-toolbar .bypass");
random_line_split
inspector.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; /* import-globals-from ../includes.js */ const MIN_INSPECTOR_WIDTH = 300; // Strings for rendering...
}), /** * Returns the current AudioNodeView. */ getCurrentAudioNode: function () { return this._currentNode; }, /** * Empties out the props view. */ resetUI: function () { // Set current node to empty to load empty view this.setCurrentAudioNode(); // Reset AudioNode inspector...
{ $("#web-audio-editor-details-pane-empty").setAttribute("hidden", "true"); $("#web-audio-editor-tabs").removeAttribute("hidden"); this._buildToolbar(); window.emit(EVENTS.UI_INSPECTOR_NODE_SET, this._currentNode.id); }
conditional_block
Router.tsx
import React from 'react'; import { BrowserRouter, Route, Redirect } from 'react-router-dom'; import { CssBaseline } from '@material-ui/core'; import { AuthProvider, useAuth } from './components/AuthContext'; import Signup from './Signup'; import Login from './Login'; import Home from './Home'; import ResetPassword fro...
export default Router;
random_line_split
cssstylevalue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods; use crate::dom::bindings...
{ reflector: Reflector, value: String, } impl CSSStyleValue { fn new_inherited(value: String) -> CSSStyleValue { CSSStyleValue { reflector: Reflector::new(), value: value, } } pub fn new(global: &GlobalScope, value: String) -> DomRoot<CSSStyleValue> { ...
CSSStyleValue
identifier_name
cssstylevalue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods; use crate::dom::bindings...
value: value, } } pub fn new(global: &GlobalScope, value: String) -> DomRoot<CSSStyleValue> { reflect_dom_object(Box::new(CSSStyleValue::new_inherited(value)), global, Wrap) } } impl CSSStyleValueMethods for CSSStyleValue { /// <https://drafts.css-houdini.org/css-typed-om-1...
reflector: Reflector::new(),
random_line_split
windows.js
import WindowController from "@/modv/window-controller"; import getLargestWindow from "@/modv/get-largest-window"; const state = { windows: [], size: { width: 0, height: 0 } }; // We can't store Window Objects in Vuex because the Observer traversal exceeds the stack size const externalState = []; // getters cons...
() { return () => getLargestWindow(state.windows).controller; }, getWindowById: state => id => state.windows.find(windowController => windowController.id === id), windowIds: state => state.windows.map(windowController => windowController.id) }; // actions const actions = { createWindow({ commit }, { Vu...
largestWindowController
identifier_name
windows.js
import WindowController from "@/modv/window-controller"; import getLargestWindow from "@/modv/get-largest-window"; const state = { windows: [], size: { width: 0, height: 0 } }; // We can't store Window Objects in Vuex because the Observer traversal exceeds the stack size const externalState = []; // getters cons...
}; // actions const actions = { createWindow({ commit }, { Vue }) { const number = state.windows.length; return new WindowController(Vue, number).then(windowController => { const windowRef = windowController.window; delete windowController.window; commit("addWindow", { windowController, win...
state.windows.find(windowController => windowController.id === id), windowIds: state => state.windows.map(windowController => windowController.id)
random_line_split
windows.js
import WindowController from "@/modv/window-controller"; import getLargestWindow from "@/modv/get-largest-window"; const state = { windows: [], size: { width: 0, height: 0 } }; // We can't store Window Objects in Vuex because the Observer traversal exceeds the stack size const externalState = []; // getters cons...
, largestWindowController() { return () => getLargestWindow(state.windows).controller; }, getWindowById: state => id => state.windows.find(windowController => windowController.id === id), windowIds: state => state.windows.map(windowController => windowController.id) }; // actions const actions = { cr...
{ return () => getLargestWindow(state.windows).window || externalState[0]; }
identifier_body
constants.d.ts
export declare const enum Service { ConnectRequest = 517, ConnectResponse = 518, ConnectionStateRequest = 519, ConnectStateResponse = 520, DisconnectRequest = 521, DisconnectResponse = 522, TunnelingAck = 1057, TunnelingRequest = 1056, } export declare const enum Protocol { Udp4 = 1,...
Tunnel = 4, } export declare const enum Status { ConnectionId = 33, ConnectionOption = 35, ConnectionType = 34, DataConnection = 38, HostProtocolType = 1, KnxConnection = 39, NoError = 0, NoMoreConnections = 36, SequenceNumber = 4, TunnelingLayer = 41, VersionNotSupported...
export declare const enum Connection {
random_line_split
index.js
/** * The routes worker process * * This worker process gets the app routes by running the application dynamically * on the server, then stores the publicly exposed routes in an intermediate format * (just the url paths) in Redis. * From there, the paths are used by the live app for serving /sitemap.xml and ...
(urlPath, timeout) { var url = urlm.format({ protocol: "http", hostname: config.app.hostname, port: config.app.port || 80, pathname: urlPath }); phantom.create(function(err, ph) { return ph.createPage(function(err, page) { return page.open(url, function(err, status) { if (statu...
routes
identifier_name
index.js
/** * The routes worker process * * This worker process gets the app routes by running the application dynamically * on the server, then stores the publicly exposed routes in an intermediate format * (just the url paths) in Redis. * From there, the paths are used by the live app for serving /sitemap.xml and ...
if (err) { console.error("failed to get appRoutes"); } else { writeAppRoutes(Object.keys(result)); } ph.exit(); }); }, timeout); } }); }); }); } module.exports = { routes: routes };
{ var url = urlm.format({ protocol: "http", hostname: config.app.hostname, port: config.app.port || 80, pathname: urlPath }); phantom.create(function(err, ph) { return ph.createPage(function(err, page) { return page.open(url, function(err, status) { if (status !== "success") { ...
identifier_body
index.js
/** * The routes worker process * * This worker process gets the app routes by running the application dynamically * on the server, then stores the publicly exposed routes in an intermediate format * (just the url paths) in Redis. * From there, the paths are used by the live app for serving /sitemap.xml and ...
ph.exit(); }); }, timeout); } }); }); }); } module.exports = { routes: routes };
{ writeAppRoutes(Object.keys(result)); }
conditional_block
index.js
/** * The routes worker process * * This worker process gets the app routes by running the application dynamically * on the server, then stores the publicly exposed routes in an intermediate format * (just the url paths) in Redis. * From there, the paths are used by the live app for serving /sitemap.xml and ...
if (err) { console.error("failed to store the routes for "+config.keys.routes); } else { console.log("successfully stored "+appRoutes.length+" routes in "+config.keys.routes); } redisClient.quit(); }); } else { console.error("no routes found for "+config.app.hostname); ...
redisClient.set(config.keys.routes, appRoutes, function(err) {
random_line_split
musepack.py
c = fileobj.read(1) if len(c) != 1: raise EOFError c = bytearray(c) num = (num << 7) | (c[0] & 0x7F) if not c[0] & 0x80: return num, i + 1 if limit > 0: raise ValueError return 0, 0 def _calc_sv8_gain(gain): # 64.82 taken from mpcdec ...
score
identifier_name
musepack.py
algorithms. Stream versions 4 through 7 are supported. For more information, see http://www.musepack.net/. """ __all__ = ["Musepack", "Open", "delete"] import struct from ._compat import endswith, xrange from mutagen import StreamInfo from mutagen.apev2 import APEv2File, error, delete from mutagen.id3._util import...
self.sample_rate = RATES[bytearray(data)[0] >> 5] self.channels = (bytearray(data)[1] >> 4) + 1 def __parse_replaygain_packet(self, fileobj, data_size): data = fileobj.read(data_size) if data_size < 9: raise MusepackHeaderError("Invalid RG packet size.") if len(...
raise MusepackHeaderError("SH packet ended unexpectedly.")
conditional_block
musepack.py
2 algorithms. Stream versions 4 through 7 are supported. For more information, see http://www.musepack.net/. """ __all__ = ["Musepack", "Open", "delete"] import struct from ._compat import endswith, xrange from mutagen import StreamInfo from mutagen.apev2 import APEv2File, error, delete from mutagen.id3._util impor...
remaining_size -= 1 try: samples, l1 = _parse_sv8_int(fileobj) samples_skip, l2 = _parse_sv8_int(fileobj) except (EOFError, ValueError): raise MusepackHeaderError( "SH packet: Invalid sample counts.") self.samples = samples - samples...
random_line_split
musepack.py
2 algorithms. Stream versions 4 through 7 are supported. For more information, see http://www.musepack.net/. """ __all__ = ["Musepack", "Open", "delete"] import struct from ._compat import endswith, xrange from mutagen import StreamInfo from mutagen.apev2 import APEv2File, error, delete from mutagen.id3._util impor...
return 0, 0 def _calc_sv8_gain(gain): # 64.82 taken from mpcdec return 64.82 - gain / 256.0 def _calc_sv8_peak(peak): return (10 ** (peak / (256.0 * 20.0)) / 65535.0) class MusepackInfo(StreamInfo): """MusepackInfo() Musepack stream information. Attributes: channels (`int`):...
"""Reads (max limit) bytes from fileobj until the MSB is zero. All 7 LSB will be merged to a big endian uint. Raises ValueError in case not MSB is zero, or EOFError in case the file ended before limit is reached. Returns (parsed number, number of bytes read) """ num = 0 for i in xrange(li...
identifier_body
send-email.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message}; use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::...
println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("From address: {}", &from_address); println!("Contact list: {}", &contact_list); println!("Subject: {}", &subject); println!("Me...
{ tracing_subscriber::fmt::init(); let Opt { contact_list, region, from_address, message, subject, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_els...
identifier_body
send-email.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message}; use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::...
let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); send_message(&client, &contact_list, &from_address, &subject, &message).await }
{ println!("SES client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("From address: {}", &from_address); println!("Contact list: {}", &contact_list); println...
conditional_block
send-email.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message}; use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::...
() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { contact_list, region, from_address, message, subject, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_pr...
main
identifier_name
send-email.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message}; use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::...
/// The email address of the sender. #[structopt(short, long)] from_address: String, /// The message of the email. #[structopt(short, long)] message: String, /// The subject of the email. #[structopt(short, long)] subject: String, /// Whether to display additional information....
random_line_split
replicationcontrollerinfo_controller_test.js
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
ctrl.details = { namespace: 'foo-namespace', name: 'foo-name', podInfo: { current: 3, desired: 3, }, }; spyOn(kdReplicationControllerService, 'showUpdateReplicasDialog'); // when ctrl.handleUpdateReplicasDialog(); // then expect(kdReplicationControll...
}); }); it('should show edit replicas dialog', () => { // given
random_line_split
register.js
var router = require('express').Router(); var Q = require('q'); var KEY = require('./key'); var User = require('../models/user.js'); var Comm = require('../comm'); var ERR = Comm.ERR; var FailProcess = Comm.FailProcess; /* * get: 注册页面 * post: 提交注册 */
router.route('/') .get(function(req, res){ return res.render('register', { title: 'Register', key: KEY.REGISTER }); }) .post(function(req, res){ var name = Comm.clearSpace(req.body.username); var nick = Comm.clearSpace(req.body.nick); var password = req.body.password; var vcode = Comm.clearSpace(req...
random_line_split
register.js
var router = require('express').Router(); var Q = require('q'); var KEY = require('./key'); var User = require('../models/user.js'); var Comm = require('../comm'); var ERR = Comm.ERR; var FailProcess = Comm.FailProcess; /* * get: 注册页面 * post: 提交注册 */ router.route('/') .get(function(req, res){ return res.render...
oLowerCase() !== req.session.verifycode) { ret = ERR.ARGS; throw new Error('wrong verify code.'); } return User.watch(name); }) .then(function(user){ if (user) { ret = ERR.ARGS; throw new Error('the user name has already been registered.'); } return (new User({ name...
R.ARGS; throw new Error('invalid args.'); } if (vcode.t
conditional_block
todo.service.ts
/** use this class to manipulate data if you do not have server using this will not save any data, hense refresing the page will reload everything. */ import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; let todos = []; @Injectable() export class TodoService { constructor() { } /...
() { return new Promise(resolve => { todos = todos.filter(todo => !todo.isDone); resolve(todos); }); } }
deleteCompleted
identifier_name
todo.service.ts
/** use this class to manipulate data if you do not have server using this will not save any data, hense refresing the page will reload everything. */ import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; let todos = []; @Injectable() export class TodoService { constructor() { } /...
resolve(data); }); } // add data add(data) { return new Promise(resolve => { todos.push(data); resolve(data); }); } // put data put(data) { return new Promise(resolve => { const index = todos.findIndex(todo => todo._id === data._id); todos[index].title = data.tit...
{ data = todos; }
conditional_block
todo.service.ts
/** use this class to manipulate data if you do not have server using this will not save any data, hense refresing the page will reload everything. */
let todos = []; @Injectable() export class TodoService { constructor() { } // get data get(query = '') { return new Promise(resolve => { let data; if (query === 'completed' || query === 'active') { const isCompleted = query === 'completed'; data = todos.filter(todo => todo.isDon...
import { Injectable } from '@angular/core'; import { Http } from '@angular/http';
random_line_split
ssh_connection.py
# Copyright 2016 Isotoma Limited # # 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...
(self, username, password): return paramiko.AUTH_SUCCESSFUL def check_auth_publickey(self, username, key): return paramiko.AUTH_SUCCESSFUL def check_channel_request(self, kind, chanid): return paramiko.OPEN_SUCCEEDED def check_channel_exec_request(self, channel, command): ...
check_auth_password
identifier_name
ssh_connection.py
# Copyright 2016 Isotoma Limited # # 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...
): return True class SshConnectionFixture(Fixture): def __enter__(self): self.listen_socket = socket.socket() self.listen_socket.bind(("0.0.0.0", 0)) self.listen_socket.listen(1) self.address, self.port = self.listen_socket.getsockname() self.fixtures.push(lamb...
def get_allowed_auths(self, username): return "publickey,password" def check_auth_password(self, username, password): return paramiko.AUTH_SUCCESSFUL def check_auth_publickey(self, username, key): return paramiko.AUTH_SUCCESSFUL def check_channel_request(self, kind, chanid): ...
identifier_body
ssh_connection.py
# Copyright 2016 Isotoma Limited # # 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...
def check_auth_publickey(self, username, key): return paramiko.AUTH_SUCCESSFUL def check_channel_request(self, kind, chanid): return paramiko.OPEN_SUCCEEDED def check_channel_exec_request(self, channel, command): return True def check_channel_shell_request(self, channel): ...
def check_auth_password(self, username, password): return paramiko.AUTH_SUCCESSFUL
random_line_split
regions.test.ts
import {expect, test} from '../test' const withRegions = test .nock('https://api.heroku.com', api => api .get('/regions') .reply(200, [ {name: 'eu', description: 'Europe', private_capable: false}, {name: 'us', description: 'United States', private_capable: false}, {name: 'oregon', description: 'Oregon, United St...
.it('list regions', async ({stdout}) => { expect(stdout).to.equal(`ID Location Runtime ────── ───────────────────── ────────────── eu Europe Common Runtime us United States Common Runtime oregon Oregon, United States Private Spaces `) }) withRegions ...
describe('regions', () => { withRegions .stdout() .command(['regions'])
random_line_split
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::WorkunitStore; use crate::{ CommandRunner as CommandRunnerTrait, Contex...
.as_ref() .unwrap() .try_into() .unwrap(); let removed = store.remove_file(output_child_digest).await.unwrap(); assert!(removed); assert!(store .contents_for_directory(output_dir_digest) .await .err() .is_some()) } // Ensure that we don't fail if we re-ru...
random_line_split
cache_tests.rs
use std::convert::TryInto; use std::io::Write; use std::path::PathBuf; use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME}; use store::Store; use tempfile::TempDir; use testutil::data::TestData; use testutil::relative_paths; use workunit_store::WorkunitStore; use crate::{ CommandRunner as CommandRunnerTrait, Contex...
() { WorkunitStore::setup_for_tests(); let results = run_roundtrip(1).await; assert_ne!(results.uncached, results.maybe_cached); assert_eq!(results.uncached.unwrap().exit_code, 1); assert_eq!(results.maybe_cached.unwrap().exit_code, 127); // aka the return code for file not found } #[tokio::test] async fn re...
failures_not_cached
identifier_name
db.py
import sqlite3 class Database: def __init__(self, dbfile, page_rows=100): self.dbfile = dbfile self.page_rows = page_rows self.conn = sqlite3.connect(self.dbfile) self.conn.row_factory = sqlite3.Row cursor = self.conn.cursor() cursor.execute( "CREATE TAB...
[self.page_rows, offset] ).fetchall() return [ dict(row) for row in rows ] def save(self, item): saved = False if item.item_type == 'message': timestamp = item.content['timestamp'] message = item.asJson() cursor = self.conn.cursor() ...
random_line_split
db.py
import sqlite3 class Database: def __init__(self, dbfile, page_rows=100): self.dbfile = dbfile self.page_rows = page_rows self.conn = sqlite3.connect(self.dbfile) self.conn.row_factory = sqlite3.Row cursor = self.conn.cursor() cursor.execute( "CREATE TAB...
return saved
timestamp = item.content['timestamp'] message = item.asJson() cursor = self.conn.cursor() cursor.execute( "INSERT INTO messages VALUES (?,?)", [timestamp, message] ) self.conn.commit() saved = True
conditional_block
db.py
import sqlite3 class Database: def __init__(self, dbfile, page_rows=100): self.dbfile = dbfile self.page_rows = page_rows self.conn = sqlite3.connect(self.dbfile) self.conn.row_factory = sqlite3.Row cursor = self.conn.cursor() cursor.execute( "CREATE TAB...
(self, item): saved = False if item.item_type == 'message': timestamp = item.content['timestamp'] message = item.asJson() cursor = self.conn.cursor() cursor.execute( "INSERT INTO messages VALUES (?,?)", [timestamp, message...
save
identifier_name
db.py
import sqlite3 class Database: def __init__(self, dbfile, page_rows=100): self.dbfile = dbfile self.page_rows = page_rows self.conn = sqlite3.connect(self.dbfile) self.conn.row_factory = sqlite3.Row cursor = self.conn.cursor() cursor.execute( "CREATE TAB...
def count(self): cursor = self.conn.cursor() n = cursor.execute("SELECT COUNT(*) FROM messages").fetchone()[0] return n def messages(self, offset=0): cursor = self.conn.cursor() rows = cursor.execute( "SELECT * FROM messages " "ORDER BY timestam...
if self.conn: self.conn.close() self.conn = None
identifier_body
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # sans titre.py # # Copyright 2013 Florent Mercier <contact@florentmercier.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either ...
(): # MAN if (len(sys.argv)<3): print BTOVLE_MAN sys.exit(0); # Opening project: cwd = os.path.split(sys.argv[0])[0] projectName = os.path.basename(sys.argv[1]) path = os.path.join(os.path.expanduser("~/.vle/pkgs"),projectName) distutils.dir_util.copy_tree(os.path.join(cwd,"..","template"),path) ...
main
identifier_name
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # sans titre.py # # Copyright 2013 Florent Mercier <contact@florentmercier.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either ...
# Opening project: cwd = os.path.split(sys.argv[0])[0] projectName = os.path.basename(sys.argv[1]) path = os.path.join(os.path.expanduser("~/.vle/pkgs"),projectName) distutils.dir_util.copy_tree(os.path.join(cwd,"..","template"),path) os.chdir(path) Namespace(sys.argv[1], sys.argv[2]).write() if ...
print BTOVLE_MAN sys.exit(0);
conditional_block
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # sans titre.py # # Copyright 2013 Florent Mercier <contact@florentmercier.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either ...
def main(): # MAN if (len(sys.argv)<3): print BTOVLE_MAN sys.exit(0); # Opening project: cwd = os.path.split(sys.argv[0])[0] projectName = os.path.basename(sys.argv[1]) path = os.path.join(os.path.expanduser("~/.vle/pkgs"),projectName) distutils.dir_util.copy_tree(os.path.join(cwd,"..","template")...
from strings import *
random_line_split
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # sans titre.py # # Copyright 2013 Florent Mercier <contact@florentmercier.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either ...
if __name__ == '__main__': main()
if (len(sys.argv)<3): print BTOVLE_MAN sys.exit(0); # Opening project: cwd = os.path.split(sys.argv[0])[0] projectName = os.path.basename(sys.argv[1]) path = os.path.join(os.path.expanduser("~/.vle/pkgs"),projectName) distutils.dir_util.copy_tree(os.path.join(cwd,"..","template"),path) os.chdir(path...
identifier_body
aaspi_file.py
#!/bin/env python #========================================================================== # (c) 2004 Total Phase, Inc. #-------------------------------------------------------------------------- # Project : Aardvark Sample Code # File : aaspi_file.c #-------------------------------------------------------------...
print " mode 3 : pol = 1, phase = 1" print "" print " 'filename' should contain data to be sent" print " to the downstream spi device" sys.exit() port = int(sys.argv[1]) mode = int(sys.argv[2]) filename = sys.argv[3] handle = aa_open(port) if (handle <= 0): print "Unable to open Aar...
print " mode 2 : pol = 1, phase = 0"
random_line_split
aaspi_file.py
#!/bin/env python #========================================================================== # (c) 2004 Total Phase, Inc. #-------------------------------------------------------------------------- # Project : Aardvark Sample Code # File : aaspi_file.c #-------------------------------------------------------------...
sys.stdout.write("*** Transaction #%02d\n" % trans_num) sys.stdout.write("Data written to device:") for i in range(count): if ((i&0x0f) == 0): sys.stdout.write("\n%04x: " % i) sys.stdout.write("%02x " % (data_out[i] & 0xff)) if (((i+1)&0x07...
print "error: only a partial number of bytes written" print " (%d) instead of full (%d)" % (count, num_write)
conditional_block
aaspi_file.py
#!/bin/env python #========================================================================== # (c) 2004 Total Phase, Inc. #-------------------------------------------------------------------------- # Project : Aardvark Sample Code # File : aaspi_file.c #-------------------------------------------------------------...
break elif (count != len(data_out)): print "error: only a partial number of bytes written" print " (%d) instead of full (%d)" % (count, num_write) sys.stdout.write("*** Transaction #%02d\n" % trans_num) sys.stdout.write("Data written to device:") for...
try: f=open(filename, 'rb') except: print "Unable to open file '" + filename + "'" return trans_num = 0 while 1: # Read from the file filedata = f.read(BUFFER_SIZE) if (len(filedata) == 0): break # Write the data to the bus data_o...
identifier_body
aaspi_file.py
#!/bin/env python #========================================================================== # (c) 2004 Total Phase, Inc. #-------------------------------------------------------------------------- # Project : Aardvark Sample Code # File : aaspi_file.c #-------------------------------------------------------------...
(handle, filename): # Open the file try: f=open(filename, 'rb') except: print "Unable to open file '" + filename + "'" return trans_num = 0 while 1: # Read from the file filedata = f.read(BUFFER_SIZE) if (len(filedata) == 0): break ...
blast_bytes
identifier_name
Row.js
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key))
} } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _classnames = requi...
{ target[key] = source[key]; }
conditional_block
Row.js
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj)
var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _constants = require('../constants'); va...
{ return obj && obj.__esModule ? obj : { 'default': obj }; }
identifier_body
Row.js
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return ...
});
return _react2['default'].createElement('div', _extends({}, props, { style: _extends(rowStyle, this.props.style), className: className })); }
random_line_split
Row.js
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function
(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _blacklist = require('blacklist'); var _blacklist2 = _interopRequireDefault(_blacklist); var _classnames = require('classnames'); var _classnames2 = _interopRequireDe...
_interopRequireDefault
identifier_name
main.rs
extern crate glob; extern crate rustc_serialize; extern crate rustache; use std::error::Error; use std::process; use std::fs::File; use std::path::Path; use std::io::prelude::*; use glob::glob; use rustc_serialize::json::Json; use std::env; fn load(path: &Path) -> String { let display = path.display(); let mu...
(path: &Path, tmpl: &String) { let s = load(path); let data = Json::from_str(&s).unwrap(); let rv = rustache::render_text(tmpl, data).unwrap().unwrap(); let output = String::from_utf8(rv).unwrap(); println!("{}", output); } fn main() { let args: Vec<String> = env::args().collect(); if args....
read
identifier_name
main.rs
extern crate glob; extern crate rustc_serialize; extern crate rustache; use std::error::Error; use std::process; use std::fs::File; use std::path::Path; use std::io::prelude::*; use glob::glob; use rustc_serialize::json::Json; use std::env; fn load(path: &Path) -> String { let display = path.display(); let mu...
} }
Err(e) => println!("{:?}", e) }
random_line_split
main.rs
extern crate glob; extern crate rustc_serialize; extern crate rustache; use std::error::Error; use std::process; use std::fs::File; use std::path::Path; use std::io::prelude::*; use glob::glob; use rustc_serialize::json::Json; use std::env; fn load(path: &Path) -> String { let display = path.display(); let mu...
fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 3 { println!("Usage: {} template dataPath", args[0]); process::exit(1); } let tmpl = load(Path::new(&args[1])); let mut data_path = args[2].clone(); if !data_path.ends_with("/") { data_path.push...
{ let s = load(path); let data = Json::from_str(&s).unwrap(); let rv = rustache::render_text(tmpl, data).unwrap().unwrap(); let output = String::from_utf8(rv).unwrap(); println!("{}", output); }
identifier_body
setup.py
#!/usr/bin/env python # coding=utf-8 """ The full documentation is at https://python_hangman.readthedocs.org. """ try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand):
with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = ['click', 'future'] test_requirements = ['pytest', 'mock'] setup( # :off name='python_hangman', version='2.2.2', description='Python Hang...
def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest import sys errno = pytest.main(self.test_args) sys.exit(errno)
identifier_body
setup.py
#!/usr/bin/env python # coding=utf-8 """ The full documentation is at https://python_hangman.readthedocs.org. """ try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools.command.test import test as TestCommand class
(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest import sys errno = pytest.main(self.test_args) sys.exit(errno) with open('README.rst') as readme...
PyTest
identifier_name
setup.py
#!/usr/bin/env python # coding=utf-8 """ The full documentation is at https://python_hangman.readthedocs.org. """
from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest import sys errno = pytest.main(self...
try: from setuptools import setup except ImportError: from distutils.core import setup
random_line_split
sitemap_generator.js
const massive = require("massive"); const aws = require('aws-sdk'); const spawn = require('lib/spawn'); const log = require('log-colors'); const sm = require('sitemap'); const get_slug = require('speakingurl'); const AWS_ACCESS_KEY_ID = process.env['AWS_ACCESS_KEY_ID']; const AWS_SECRET_ACCESS_KEY = process.env['AWS_S...
const s3 = new aws.S3(); spawn(function*(){ var db = yield new Promise((resolve) => { log.info('connecting to db'); massive.connect({ connectionString: `postgres://${DB_USER}:${DB_PASSWD}@${DB_HOST}/${DB_NAME}` }, (err, _db) => { log.info('connected to db'); resolve(_db); }); })...
const DB_USER = process.env['DB_USER']; const DB_PASSWD = process.env['DB_PASSWD']; const DB_NAME = process.env['DB_NAME'];
random_line_split
sitemap_generator.js
const massive = require("massive"); const aws = require('aws-sdk'); const spawn = require('lib/spawn'); const log = require('log-colors'); const sm = require('sitemap'); const get_slug = require('speakingurl'); const AWS_ACCESS_KEY_ID = process.env['AWS_ACCESS_KEY_ID']; const AWS_SECRET_ACCESS_KEY = process.env['AWS_S...
resolve(items); }); }); log.info(`got ${items.length} items`); log.info(`processing items`); var files_count = Math.ceil(items.length / 50000); for(var counter = 0; counter < files_count; counter++){ var sitemap = sm.createSitemap ({ hostname: 'http://mightygoose.com', cacheTime: ...
{ log.error(err); }
conditional_block
index.d.ts
// Type definitions for Registry Auth Token 4.2 // Project: https://github.com/rexxars/registry-auth-token // Definitions by: Maurice de Beijer <https://github.com/mauricedb> // James Liang <https://github.com/LiangZugeng> // Piotr Błażejewicz <https://github.com/peterblazejewicz> // Def...
* The type of token */ type: 'Basic' | 'Bearer'; /** * The username used in `Basic` */ username?: string; /** * The password used in `Basic` */ password?: string; } } /** * * @param registryUrl - Either the registry url...
/**
random_line_split
lc0796_rotate_string.py
"""Leetcode 796. Rotate String Easy URL: https://leetcode.com/problems/rotate-string/ We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and ...
class SolutionStringConcatSubstring(object): def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool Time complexity: O(2n+2n*n)=O(n^2). Space complexity:O(n). """ # Check if lengths are not equal. if len(A) != len(B): ...
"""
random_line_split
lc0796_rotate_string.py
"""Leetcode 796. Rotate String Easy URL: https://leetcode.com/problems/rotate-string/ We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and ...
(object): def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool Time complexity: O(2n+2n*n)=O(n^2). Space complexity:O(n). """ # Check if lengths are not equal. if len(A) != len(B): return False # If rot...
SolutionStringConcatSubstring
identifier_name
lc0796_rotate_string.py
"""Leetcode 796. Rotate String Easy URL: https://leetcode.com/problems/rotate-string/ We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and ...
main()
conditional_block
lc0796_rotate_string.py
"""Leetcode 796. Rotate String Easy URL: https://leetcode.com/problems/rotate-string/ We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and ...
def main(): # Input: A = 'abcde', B = 'cdeab' # Output: true A = 'abcde' B = 'cdeab' print SolutionStringConcatSubstring().rotateString(A, B) # Input: A = 'abcde', B = 'abced' # Output: false A = 'abcde' B = 'abced' print SolutionStringConcatSubstring().rotateString(A, B) i...
""" :type A: str :type B: str :rtype: bool Time complexity: O(2n+2n*n)=O(n^2). Space complexity:O(n). """ # Check if lengths are not equal. if len(A) != len(B): return False # If rotate string, B is substring of concated string A + A....
identifier_body
.createFiles.ts
import { TestCallback, TestInfo } from '../Type' import { v2 } from '../../../../lib/index.js' import { XMLElementUtil } from 'xml-js-builder' export function proppatch(server : v2.WebDAVServer, info : TestInfo, path : string, expectedStatusCode : number, bodySet : string[], bodyRemove : string[], callback : (xml : XM...
export function propfind(server : v2.WebDAVServer, info : TestInfo, path : string, expectedStatusCode : number, depth : number, body : string, callback : (xml : XMLElementUtil) => void) { info.reqXML({ url: 'http://localhost:' + server.options.port + '/' + path, method: 'PROPFIND', headers...
{ let body = '<D:propertyupdate xmlns:D="DAV:" xmlns:Z="http://ns.example.com/standards/z39.50/">'; if(bodySet && bodySet.length > 0) body += '<D:set><D:prop>' + bodySet.join() + '</D:prop></D:set>'; if(bodyRemove && bodyRemove.length > 0) body += '<D:remove><D:prop>' + bodyRemove.join() + '...
identifier_body
.createFiles.ts
import { TestCallback, TestInfo } from '../Type' import { v2 } from '../../../../lib/index.js' import { XMLElementUtil } from 'xml-js-builder' export function proppatch(server : v2.WebDAVServer, info : TestInfo, path : string, expectedStatusCode : number, bodySet : string[], bodyRemove : string[], callback : (xml : XM...
(info : TestInfo, isValid : TestCallback, callback : (server : v2.WebDAVServer) => void) : void { const server = info.startServer(); server.rootFileSystem().addSubTree(v2.ExternalRequestContext.create(server), { 'folder': v2.ResourceType.Directory, 'file': v2.ResourceType.File }, (e) => { ...
starter
identifier_name
.createFiles.ts
import { TestCallback, TestInfo } from '../Type' import { v2 } from '../../../../lib/index.js' import { XMLElementUtil } from 'xml-js-builder' export function proppatch(server : v2.WebDAVServer, info : TestInfo, path : string, expectedStatusCode : number, bodySet : string[], bodyRemove : string[], callback : (xml : XM...
callback(xml); }) } export function propfind(server : v2.WebDAVServer, info : TestInfo, path : string, expectedStatusCode : number, depth : number, body : string, callback : (xml : XMLElementUtil) => void) { info.reqXML({ url: 'http://localhost:' + server.options.port + '/' + path, meth...
info.reqXML({ url: 'http://localhost:' + server.options.port + '/' + path, method: 'PROPPATCH', body }, expectedStatusCode, (res, xml) => {
random_line_split