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
semantic.ts
// // Copyright 2015-21 Volker Sorge // // 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 agree...
return getTree(mml).xml(); } /** * Creates the semantic tree for a given MathML node. * * @param mml The MathML node. * @returns Semantic tree for input node. */ export function getTree(mml: Element): SemanticTree { return new SemanticTree(mml); } /** * Creates the semantic tree for a MathML string. * * @...
random_line_split
ProductImagePage.tsx
import Card from "@material-ui/core/Card"; import CardContent from "@material-ui/core/CardContent"; import { createStyles, Theme, withStyles, WithStyles } from "@material-ui/core/styles"; import TextField from "@material-ui/core/TextField"; import * as React from "react"; import AppHeader from "../../../compon...
images={images} highlighted={image ? image.id : undefined} onRowClick={onRowClick} /> <Card> <CardTitle title={i18n.t("Photo Information")} /> <CardContent> <TextField ...
<PageHeader title={i18n.t("Edit Photo")} /> <Grid variant="inverted"> <div> <ProductImageNavigation disabled={disabled}
random_line_split
hw5.py
from numpy import * from matplotlib.pyplot import * import scipy.constants as sc import copy import scipy.integrate as integ # test sun/earth with hw5(1.989e30,5.972e24,149.6e6,0.0167,1000) def hw5(m1, m2, a, e, tmax, tstep=0.001, tplot=0.025, method='leapfrog'): if method != 'leapfrog' and method != 'odeint': ...
rv_copy = zeros(8) rv_copy[0] = rv[2] rv_copy[1] = rv[3] rv_copy[4] = rv[6] rv_copy[5] = rv[7] # calc velocity deriv r = array([rv[0] - rv[4], rv[1] - rv[5]]) force = ((sc.G*m1*m2)/(np.linalg.norm(r)**2))*(r/np.linalg.norm(r)) rv_copy[2] = - (force[0]/m1) rv_copy[3] = - (...
identifier_body
hw5.py
from numpy import * from matplotlib.pyplot import * import scipy.constants as sc import copy import scipy.integrate as integ # test sun/earth with hw5(1.989e30,5.972e24,149.6e6,0.0167,1000) def hw5(m1, m2, a, e, tmax, tstep=0.001, tplot=0.025, method='leapfrog'): if method != 'leapfrog' and method != 'odeint': ...
rv[3] = rv[3] - (force[1]/m1)*dt rv[6] = rv[6] + (force[0]/m2)*dt rv[7] = rv[7] + (force[1]/m2)*dt # increment counters timeCounter += tstep frameCounter += tstep # plot final position rv_list.append(copy.d...
timeCounter = 0 frameCounter = 0 while timeCounter < tmax: # plot positions if tplot time has passed if frameCounter >= tplot: frameCounter = 0 rv_list.append(copy.deepcopy(rv)) # calc positions rv[0] = rv[0...
conditional_block
hw5.py
from numpy import * from matplotlib.pyplot import * import scipy.constants as sc import copy import scipy.integrate as integ # test sun/earth with hw5(1.989e30,5.972e24,149.6e6,0.0167,1000) def hw5(m1, m2, a, e, tmax, tstep=0.001, tplot=0.025, method='leapfrog'): if method != 'leapfrog' and method != 'odeint': ...
(rv, dt, m1, m2): # calc position deriv rv_copy = zeros(8) rv_copy[0] = rv[2] rv_copy[1] = rv[3] rv_copy[4] = rv[6] rv_copy[5] = rv[7] # calc velocity deriv r = array([rv[0] - rv[4], rv[1] - rv[5]]) force = ((sc.G*m1*m2)/(np.linalg.norm(r)**2))*(r/np.linalg.norm(r)) rv_...
deriv
identifier_name
hw5.py
from numpy import * from matplotlib.pyplot import * import scipy.constants as sc import copy import scipy.integrate as integ # test sun/earth with hw5(1.989e30,5.972e24,149.6e6,0.0167,1000) def hw5(m1, m2, a, e, tmax, tstep=0.001, tplot=0.025, method='leapfrog'): if method != 'leapfrog' and method != 'odeint': ...
return rv_copy
random_line_split
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn
(s: &str) -> i64 { s.parse().unwrap() } fn main() { println!("Collecting updates from weather server..."); let context = zmq::Context::new(); let subscriber = context.socket(zmq::SUB).unwrap(); assert!(subscriber.connect("tcp://localhost:5556").is_ok()); let args: Vec<String> = env::args().co...
atoi
identifier_name
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn atoi(s: &str) -> i64
fn main() { println!("Collecting updates from weather server..."); let context = zmq::Context::new(); let subscriber = context.socket(zmq::SUB).unwrap(); assert!(subscriber.connect("tcp://localhost:5556").is_ok()); let args: Vec<String> = env::args().collect(); let filter = if args.len() > 1...
{ s.parse().unwrap() }
identifier_body
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn atoi(s: &str) -> i64 { s.parse().unwrap() } fn main() { println!("Collecting updates from weather ser...
let string = subscriber.recv_string(0).unwrap().unwrap(); let chks: Vec<i64> = string.split(' ').map(atoi).collect(); let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]); total_temp += temperature; } println!("Average temperature for zipcode '{}' was {}F", fi...
for _ in 0 .. 100 {
random_line_split
main.rs
#![crate_name = "weather_client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; use std::env; fn atoi(s: &str) -> i64 { s.parse().unwrap() } fn main() { println!("Collecting updates from weather ser...
; assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok()); let mut total_temp = 0; for _ in 0 .. 100 { let string = subscriber.recv_string(0).unwrap().unwrap(); let chks: Vec<i64> = string.split(' ').map(atoi).collect(); let (_zipcode, temperature, _relhumidity) = (chks[0], ch...
{ "10001" }
conditional_block
api.module.ts
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { Configuration } from './configuration'; import { BibliographicEntryService } from './api/bibliographicEntry.service'; impo...
} }
{ throw new Error('ApiModule is already loaded. Import your base AppModule only.'); }
conditional_block
api.module.ts
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { Configuration } from './configuration'; import { BibliographicEntryService } from './api/bibliographicEntry.service'; impo...
(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, providers: [ { provide: Configuration, useFactory: configurationFactory } ] } } constructor( @Optional() @SkipSelf() parentModule: ApiModule) { if (parentModule) { ...
forRoot
identifier_name
api.module.ts
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http';
import { ScanService } from './api/scan.service'; import { UserService } from './api/user.service'; import { UtilsService } from './api/utils.service'; @NgModule({ imports: [ CommonModule, HttpClientModule ], declarations: [], exports: [], providers: [ BibliographicEntryService, Bibliographic...
import { Configuration } from './configuration'; import { BibliographicEntryService } from './api/bibliographicEntry.service'; import { BibliographicResourceService } from './api/bibliographicResource.service';
random_line_split
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
impl Font { #[allow(missing_docs)] pub fn new(font: &Path, point_size: u32) -> Font { ensure_init(); let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap(); let ptr = c_path.as_ptr() as *const i8; let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) }; assert!(!p....
{ unsafe { if ffi::TTF_WasInit() == 0 { assert_eq!(ffi::TTF_Init(), 0); } } }
identifier_body
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> { self.render(gl, txt, Color4::of_rgba(0x55, 0x55, 0x55, 0xFF)) } } impl Drop for Font { fn drop(&mut self) { unsafe { ffi::TTF_CloseFont(self.p) } } } //#[test] //fn load_and_unload() { // Font::new(&Path::new("fonts/Open_Sans/OpenSans-Regular...
light
identifier_name
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
ffi::TTF_RenderUTF8_Blended(self.p as *const ffi::c_void, ptr, sdl_color) } }; let tex = unsafe { surface_ptr.as_ref().expect("Cannot render text.") }; unsafe { assert_eq!((*tex.format).format, SDL_PIXELFORMAT_ARGB8888); } let texture = Texture2D::new(gl); unsafe...
let surface_ptr = { let c_str = CString::new(txt.as_bytes()).unwrap(); let ptr = c_str.as_ptr() as *const i8; unsafe {
random_line_split
ttf.rs
//! Module for creating text textures. use std::ffi::CString; use std::path::Path; use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888}; use sdl2_sys::surface::SDL_Surface; use sdl2_sys::surface; use gl; use common::color::Color4; use yaglw::gl_context::GLContext; use yaglw::texture::Texture2D; #[allow(non_ca...
} } impl Font { #[allow(missing_docs)] pub fn new(font: &Path, point_size: u32) -> Font { ensure_init(); let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap(); let ptr = c_path.as_ptr() as *const i8; let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) }; asser...
{ assert_eq!(ffi::TTF_Init(), 0); }
conditional_block
AboutExpects.js
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(true).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equalit...
});
it("should have filled in values", function () { expect(1 + 1).toEqual(2); });
random_line_split
index.js
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react' import { connect } from 'react-redux' import { createSelector } from 'reselect' import { IntlProvider } from 'react-i...
(dispatch) { return { dispatch, } } export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider)
mapDispatchToProps
identifier_name
index.js
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react' import { connect } from 'react-redux' import { createSelector } from 'reselect' import { IntlProvider } from 'react-i...
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} ...
import { makeSelectLocale } from './selectors'
random_line_split
websocket.rs
// https://tools.ietf.org/html/rfc6455#section-4.1 if !is_token(protocol.as_bytes()) { return Err(Error::Syntax); } } let ws = WebSocket::new(global, url_record.clone()); let address = Trusted::new(&*ws); // Create the interface for communicatio...
{ let ws = self.address.root(); // Step 1. ws.ready_state.set(WebSocketRequestState::Open); // Step 2: Extensions. // TODO: Set extensions to extensions in use. // Step 3. if let Some(protocol_name) = self.protocol_in_use { *ws.protocol.borrow_mut()...
identifier_body
websocket.rs
pub const INVALID_PAYLOAD: u16 = 1007; pub const POLICY_VIOLATION: u16 = 1008; pub const TOO_LARGE: u16 = 1009; pub const EXTENSION_MISSING: u16 = 1010; pub const INTERNAL_ERROR: u16 = 1011; pub const TLS_FAILED: u16 = 1015; } pub fn close_the_websocket_connection( address: Trusted<WebSocke...
(&self, data_byte_len: u64) -> Fallible<bool> { let return_after_buffer = match self.ready_state.get() { WebSocketRequestState::Connecting => { return Err(Error::InvalidState); }, WebSocketRequestState::Open => false, WebSocketRequestState::Closing...
send_impl
identifier_name
websocket.rs
16 = 1015; } pub fn close_the_websocket_connection( address: Trusted<WebSocket>, task_source: &NetworkingTaskSource, canceller: &TaskCanceller, code: Option<u16>, reason: String, ) { let close_task = CloseTask { address: address, failed: false, code: code, reason...
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
random_line_split
websocket.rs
} }); // Step 7. Ok(ws) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> { let return_after_buffer = match self.ready_state.get() { WebSocketRequestState::Connecting => { r...
{ return; }
conditional_block
__init__.py
# Copyright (C) 2011-2015 Patrick Totzke <patricktotzke@gmail.com> # This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file from __future__ import absolute_import import re import abc class AddressbookError(Exception): pass class AddressBook(object):...
return res
for name, email in self.get_contacts(): if query.match(name) or query.match(email): res.append((name, email))
random_line_split
__init__.py
# Copyright (C) 2011-2015 Patrick Totzke <patricktotzke@gmail.com> # This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file from __future__ import absolute_import import re import abc class
(Exception): pass class AddressBook(object): """can look up email addresses and realnames for contacts. .. note:: This is an abstract class that leaves :meth:`get_contacts` unspecified. See :class:`AbookAddressBook` and :class:`ExternalAddressbook` for implementations. """ ...
AddressbookError
identifier_name
__init__.py
# Copyright (C) 2011-2015 Patrick Totzke <patricktotzke@gmail.com> # This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file from __future__ import absolute_import import re import abc class AddressbookError(Exception): pass class AddressBook(object):...
return res
res.append((name, email))
conditional_block
__init__.py
# Copyright (C) 2011-2015 Patrick Totzke <patricktotzke@gmail.com> # This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file from __future__ import absolute_import import re import abc class AddressbookError(Exception): pass class AddressBook(object):...
def lookup(self, query=''): """looks up all contacts where name or address match query""" res = [] query = re.compile('.*%s.*' % query, self.reflags) for name, email in self.get_contacts(): if query.match(name) or query.match(email): res.append((name, em...
"""list all contacts tuples in this abook as (name, email) tuples""" return []
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_text_prin...
.map(|def| print_fragment(&TEST_SCHEMA, def)) .collect::<Vec<_>>(); printed.sort(); Ok(printed.join("\n\n")) }
program.fragments().count() ); let mut printed = next_program .fragments()
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_text_prin...
{ let file_key = FileKey::new(fixture.file_name); let ast = parse(fixture.content, file_key).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(&TEST_SCHEMA, ir); let next_program = sort_selections(&program); assert_eq!( next_progr...
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_text_prin...
(fixture: &Fixture) -> Result<String, String> { let file_key = FileKey::new(fixture.file_name); let ast = parse(fixture.content, file_key).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(&TEST_SCHEMA, ir); let next_program = sort_selections(...
transform_fixture
identifier_name
add_binary.py
""" https://leetcode.com/problems/add-binary/ https://leetcode.com/submissions/detail/106524947/ """ class Solution(object):
def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ length = max(len(a), len(b)) remaining = 0 index = 0 result = '' while index < length: bit1 = 0 if len(a) > index: bit1 = i...
random_line_split
add_binary.py
""" https://leetcode.com/problems/add-binary/ https://leetcode.com/submissions/detail/106524947/ """ class
(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ length = max(len(a), len(b)) remaining = 0 index = 0 result = '' while index < length: bit1 = 0 if len(a) > index: ...
Solution
identifier_name
add_binary.py
""" https://leetcode.com/problems/add-binary/ https://leetcode.com/submissions/detail/106524947/ """ class Solution(object): def addBinary(self, a, b):
sum_value = sum_value - 2 result = str(sum_value) + result index += 1 if remaining != 0: result = str(1) + result return result import unittest class Test(unittest.TestCase): def test(self): self.assertEqual(Solution().addBinary('11', ...
""" :type a: str :type b: str :rtype: str """ length = max(len(a), len(b)) remaining = 0 index = 0 result = '' while index < length: bit1 = 0 if len(a) > index: bit1 = int(a[len(a) - index - 1]) b...
identifier_body
add_binary.py
""" https://leetcode.com/problems/add-binary/ https://leetcode.com/submissions/detail/106524947/ """ class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ length = max(len(a), len(b)) remaining = 0 index = ...
return result import unittest class Test(unittest.TestCase): def test(self): self.assertEqual(Solution().addBinary('11', '1'), '100') if __name__ == '__main__': unittest.main()
result = str(1) + result
conditional_block
test_auto_segmentEG_FEMPO.py
import pandas as pd from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.cross_validation import train_test_split from sklearn.metrics import mean_squared_error from .auto_segment_FEMPO import BasicSegmenter_FEMP...
base_estimator = DecisionTreeRegressor(max_depth = 5) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size) print X_train.shape # If you want to compare with BaggingRegressor. # bench = BaggingRegressor(base_estimator = base_estimator, n_estimators = 10, max_s...
random_line_split
test_auto_segmentEG_FEMPO.py
import pandas as pd from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.cross_validation import train_test_split from sklearn.metrics import mean_squared_error from .auto_segment_FEMPO import BasicSegmenter_FEMP...
clf.fit(X_train, y_train) print clf.score(X_test,y_test) y = clf.predict(X_test) print mean_squared_error(y, y_test) print y.shape return clf, X_test, y_test
if X == None: boston = load_boston() X = pd.DataFrame(boston.data) y = pd.DataFrame(boston.target) base_estimator = DecisionTreeRegressor(max_depth = 5) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size) print X_train.shape # If you ...
identifier_body
test_auto_segmentEG_FEMPO.py
import pandas as pd from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.cross_validation import train_test_split from sklearn.metrics import mean_squared_error from .auto_segment_FEMPO import BasicSegmenter_FEMP...
(X = None, y = None, test_size = 0.1): if X == None: boston = load_boston() X = pd.DataFrame(boston.data) y = pd.DataFrame(boston.target) base_estimator = DecisionTreeRegressor(max_depth = 5) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=te...
demo
identifier_name
test_auto_segmentEG_FEMPO.py
import pandas as pd from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.cross_validation import train_test_split from sklearn.metrics import mean_squared_error from .auto_segment_FEMPO import BasicSegmenter_FEMP...
base_estimator = DecisionTreeRegressor(max_depth = 5) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size) print X_train.shape # If you want to compare with BaggingRegressor. # bench = BaggingRegressor(base_estimator = base_estimator, n_estimators = 10, m...
boston = load_boston() X = pd.DataFrame(boston.data) y = pd.DataFrame(boston.target)
conditional_block
MapFull.js
/* name: MapTile.js des: 地图全屏操作 date: 2016-06-02 author: liulin 修改为用js加载 */ ES.MapControl.ESMapFull = ES.Evented.extend({ oOption: { // 加载全屏按钮容器 cSelfDiv: 'ex-map-full', // 父级容器 acParentDivClass: [ 'ex-layout-maptool', ...
}, });
'); $(this).html('<i class="ec-icon-expand"></i>&nbsp;&nbsp;全屏'); } $.AMUI.fullscreen.toggle(); });
conditional_block
MapFull.js
/* name: MapTile.js des: 地图全屏操作 date: 2016-06-02 author: liulin 修改为用js加载 */ ES.MapControl.ESMapFull = ES.Evented.extend({ oOption: { // 加载全屏按钮容器 cSelfDiv: 'ex-map-full', // 父级容器 acParentDivClass: [ 'ex-layout-maptool', ...
});
random_line_split
ui_root.py
''' Implements the targetcli root UI. This file is part of targetcli. Copyright (c) 2011-2013 by Datera, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICE...
self.rtsroot.save_to_file(savefile) self.shell.log.info("Configuration saved to %s" % savefile) def ui_command_restoreconfig(self, savefile=default_save_file, clear_existing=False): ''' Restores configuration from a file. ''' self.assert_root() savefile =...
backup_dir = os.path.dirname(savefile) + "/backup" backup_name = "saveconfig-" + \ datetime.now().strftime("%Y%m%d-%H:%M:%S") + ".json" backupfile = backup_dir + "/" + backup_name with ignored(IOError): shutil.copy(savefile, backupfile) # ...
conditional_block
ui_root.py
''' Implements the targetcli root UI. This file is part of targetcli. Copyright (c) 2011-2013 by Datera, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICE...
(session): acl = session['parent_nodeacl'] indent_print("alias: %(alias)s\tsid: %(id)i type: " \ "%(type)s session-state: %(state)s" % session, base_steps) if action == 'detail': if self.as_root: ...
print_session
identifier_name
ui_root.py
''' Implements the targetcli root UI. This file is part of targetcli. Copyright (c) 2011-2013 by Datera, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICE...
indent_step = 4 base_steps = 0 action_list = ("list", "detail") if action not in action_list: raise ExecutionError("action must be one of: %s" % ", ".join(action_list)) if sid is not None: try: ...
SEE ALSO ======== status '''
random_line_split
ui_root.py
''' Implements the targetcli root UI. This file is part of targetcli. Copyright (c) 2011-2013 by Datera, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICE...
if mlun.write_protect: mode = "r" else: mode = "rw" indent_print("mapped-lun: %d backstore: %s/%s mode: %s" % (mlun.mapped_lun, plugin, name, mode), ...
acl = session['parent_nodeacl'] indent_print("alias: %(alias)s\tsid: %(id)i type: " \ "%(type)s session-state: %(state)s" % session, base_steps) if action == 'detail': if self.as_root: if acl.authenticate_...
identifier_body
11.rs
// SPDX-License-Identifier: MIT use clap::{Arg, App}; static DIRECTIONS : [(i64,i64); 8] = [ (-1,-1), ( 0,-1), ( 1,-1), (-1, 0), ( 1, 0), (-1, 1), ( 0, 1), ( 1, 1), ]; #[derive(Clone)] pub struct Floorplan { pub map: Vec<Vec<char>>, } impl Floorplan { pub fn
() -> Floorplan { Floorplan { map: Vec::new() } } pub fn load(fname: &str) -> Floorplan { let mut plan = Floorplan::new(); let contents = std::fs::read_to_string(fname) .unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err)); for line in contents.trim_end_...
new
identifier_name
11.rs
// SPDX-License-Identifier: MIT use clap::{Arg, App}; static DIRECTIONS : [(i64,i64); 8] = [ (-1,-1), ( 0,-1), ( 1,-1), (-1, 0), ( 1, 0), (-1, 1), ( 0, 1), ( 1, 1), ]; #[derive(Clone)] pub struct Floorplan { pub map: Vec<Vec<char>>, } impl Floorplan { pub fn new() -> Floorplan { ...
for (dx, dy) in DIRECTIONS.iter() { let (mut x, mut y) = (x as i64+dx, y as i64+dy); while x >= 0 && y >= 0 && x < xmax && y < ymax { match self.map[y as usize][x as usize] { '#' => { seated += 1; break; }, 'L' => { break; }, ...
#[inline] pub fn count_visible(&self, x: usize, y: usize) -> u8 { let mut seated = 0; let ymax = self.map.len() as i64; let xmax = self.map[0].len() as i64;
random_line_split
11.rs
// SPDX-License-Identifier: MIT use clap::{Arg, App}; static DIRECTIONS : [(i64,i64); 8] = [ (-1,-1), ( 0,-1), ( 1,-1), (-1, 0), ( 1, 0), (-1, 1), ( 0, 1), ( 1, 1), ]; #[derive(Clone)] pub struct Floorplan { pub map: Vec<Vec<char>>, } impl Floorplan { pub fn new() -> Floorplan { ...
#[test] fn test2() { let mut plan = Floorplan::load("11.in"); while plan.step2() { } assert_eq!(plan.count(&'#'), 2257); } }
{ let mut plan = Floorplan::load("11.in"); while plan.step1() { } assert_eq!(plan.count(&'#'), 2476); }
identifier_body
redis.py
""" Redis Blueprint =============== **Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ import re from fabric.decorators import task from fabric.utils import abort from ref...
(): """ Install and configure Redis """ install() configure() def install(): with sudo(): debian.apt_get('install', 'redis-server') def get_installed_version(): """ Get installed version as tuple. Parsed output format: Redis server v=2.8.4 sha=00000000:0 malloc=jemal...
setup
identifier_name
redis.py
""" Redis Blueprint =============== **Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ import re from fabric.decorators import task from fabric.utils import abort from ref...
stop = debian.service_task('redis-server', 'stop') restart = debian.service_task('redis-server', 'restart') @task def setup(): """ Install and configure Redis """ install() configure() def install(): with sudo(): debian.apt_get('install', 'redis-server') def get_installed_version()...
blueprint = blueprints.get(__name__) start = debian.service_task('redis-server', 'start')
random_line_split
redis.py
""" Redis Blueprint =============== **Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ import re from fabric.decorators import task from fabric.utils import abort from ref...
def install(): with sudo(): debian.apt_get('install', 'redis-server') def get_installed_version(): """ Get installed version as tuple. Parsed output format: Redis server v=2.8.4 sha=00000000:0 malloc=jemalloc-3.4.1 bits=64 build=a... """ retval = run('redis-server --version') ...
""" Install and configure Redis """ install() configure()
identifier_body
redis.py
""" Redis Blueprint =============== **Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ import re from fabric.decorators import task from fabric.utils import abort from ref...
if debian.lbs_release() >= '16.04': debian.chown(location='/etc/redis/redis.conf', owner='redis', group='root') restart()
conditional_block
FollowProfileButton_profile.graphql.ts
/* tslint:disable */ import { ConcreteFragment } from "relay-runtime"; declare const _FollowProfileButton_profile$ref: unique symbol; export type FollowProfileButton_profile$ref = typeof _FollowProfileButton_profile$ref; export type FollowProfileButton_profile = { readonly __id: string; readonly id: string; ...
const node: ConcreteFragment = { "kind": "Fragment", "name": "FollowProfileButton_profile", "type": "Profile", "metadata": null, "argumentDefinitions": [], "selections": [ { "kind": "ScalarField", "alias": null, "name": "__id", "args": null, "storageKey": null }, {...
readonly " $refType": FollowProfileButton_profile$ref; };
random_line_split
context.rs
context from a shared one. pub struct ThreadLocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl ThreadLocalStyleContextCreationInfo { /// Trivially constructs a `ThreadLocalStyleContextCreationInfo`. pub fn new(animations_sender: Sender<Animation>) -> Self { ThreadLoca...
} } /// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*; SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } /// Creates a task to update CSS Animations on a ...
{ unsafe { el.update_animations(pseudo.as_ref()) }; }
conditional_block
context.rs
context from a shared one. pub struct ThreadLocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl ThreadLocalStyleContextCreationInfo { /// Trivially constructs a `ThreadLocalStyleContextCreationInfo`. pub fn new(animations_sender: Sender<Animation>) -> Self { ThreadLoca...
SetSelectorFlags(unsafe { SendElement::new(el) }, flags) } /// Creates a task to update CSS Animations on a given (pseudo-)element. pub fn update_animations(el: E, pseudo: Option<PseudoElement>) -> Self { use self::SequentialTask::*; UpdateAnimations(unsafe { SendElement::new(el) },...
/// Creates a task to set the selector flags on an element. pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self { use self::SequentialTask::*;
random_line_split
context.rs
context from a shared one. pub struct ThreadLocalStyleContextCreationInfo { new_animations_sender: Sender<Animation>, } impl ThreadLocalStyleContextCreationInfo { /// Trivially constructs a `ThreadLocalStyleContextCreationInfo`. pub fn new(animations_sender: Sender<Animation>) -> Self { ThreadLoca...
{ /// The total number of elements traversed. pub elements_traversed: u32, /// The number of elements where has_styles() went from false to true. pub elements_styled: u32, /// The number of elements for which we performed selector matching. pub elements_matched: u32, /// The number of cache...
TraversalStatistics
identifier_name
context.rs
, } /// A shared style context. /// /// There's exactly one of these during a given restyle traversal, and it's /// shared among the worker threads. pub struct SharedStyleContext { /// The CSS selector stylist. pub stylist: Arc<Stylist>, /// The animations that are currently running. pub running_anima...
{ debug_assert!(self.current_element_info.is_none()); self.current_element_info = Some(CurrentElementInfo { element: element.as_node().opaque(), is_initial_style: !data.has_styles(), }); }
identifier_body
res_partner.py
# -*- encoding: utf-8 -*- ############################################################################## # # Romanian accounting localization for OpenERP V7 # @author - Fekete Mihai, Tatár Attila <atta@nvm.ro> # Copyright (C) 2011-2013 TOTAL PC SYSTEMS (http://www.www.erpsystems.ro). # Copyright (C)...
od): headers = { "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)", "Content-Type": "multipart/form-data;" } params = {'cod': cod} res = requests.get( 'http://www.mfinante.ro/infocodfiscal.html', params=params, headers=headers ) res.raise_...
tMfinante(c
identifier_name
res_partner.py
# -*- encoding: utf-8 -*- ############################################################################## # # Romanian accounting localization for OpenERP V7 # @author - Fekete Mihai, Tatár Attila <atta@nvm.ro> # Copyright (C) 2011-2013 TOTAL PC SYSTEMS (http://www.www.erpsystems.ro). # Copyright (C)...
val = ' '.join([x.strip() for x in tr.getchildren()[ 1].text_content().split('\n') if x.strip() != '']) result[key] = val.encode('utf8').translate(CEDILLATRANS).decode('utf8') return result class res_partner(models.Model): _name = "res.partner" _inherit = "res.partne...
random_line_split
res_partner.py
# -*- encoding: utf-8 -*- ############################################################################## # # Romanian accounting localization for OpenERP V7 # @author - Fekete Mihai, Tatár Attila <atta@nvm.ro> # Copyright (C) 2011-2013 TOTAL PC SYSTEMS (http://www.www.erpsystems.ro). # Copyright (C)...
if res['found'] and res['found'][0]: datas = res['found'][0] if res['notfound'] and res['notfound'][0]: datas = res['notfound'][0] if datas['data_sfa...
s = requests.post( 'https://webservicesp.anaf.ro:/PlatitorTvaRest/api/v1/ws/tva', json=[{'cui': vat_number, 'data': datas['data_sfarsit']}], headers = headers) if res.status_code ==...
conditional_block
res_partner.py
# -*- encoding: utf-8 -*- ############################################################################## # # Romanian accounting localization for OpenERP V7 # @author - Fekete Mihai, Tatár Attila <atta@nvm.ro> # Copyright (C) 2011-2013 TOTAL PC SYSTEMS (http://www.www.erpsystems.ro). # Copyright (C)...
vat_country, vat_number = self._split_vat(part.vat) if part.vat_subjected: self.write({'vat_subjected': False}) if vat_number and vat_country: self.write({ 'is_company': True, 'country_id': self.env['res.country'].search( ...
f _check_vat_ro(vat): return bool(len(part.name.strip()) > 2 and part.name.strip().upper()[:2] == 'RO' and part.name.strip()[2:].isdigit()) part = self[0] vat = part.vat if vat: self.write({'vat': part.vat.upper().replace("...
identifier_body
seed.js
/* * Populate DB with sample data on server start * to disable, edit config/environment/index.js, and set `seedDB: false` */ 'use strict'; var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; var env = process.env.NODE_ENV || 'development'; var User = require('../api/user/user.model'...
password: 'password', active: true }]; exports.shipments = [ { // _id: '57b4bcf47a18a5b400923d78', orderId:"DKcRNc7XN", creationDate:"Aug 6, 2016", shipByDate:"Aug 12, 2016", status:"Shipment confirmed", units:1, payments:"$3.92", sku: "06F", // product: ObjectId('57b4bcf37a18a5b400923d75'), //...
name: 'Root',
random_line_split
seed.js
/* * Populate DB with sample data on server start * to disable, edit config/environment/index.js, and set `seedDB: false` */ 'use strict'; var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; var env = process.env.NODE_ENV || 'development'; var User = require('../api/user/user.model'...
() { Shipment.find({}).remove(function () { Customer.find({}).exec().then(function(customers) { exports.shipments.forEach(function (shipment, i) { shipment.customer = customers[i%2]['_id']; }) Product.find({}).exec().then(function(products) { exports.shipments.forEa...
popShipments
identifier_name
seed.js
/* * Populate DB with sample data on server start * to disable, edit config/environment/index.js, and set `seedDB: false` */ 'use strict'; var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; var env = process.env.NODE_ENV || 'development'; var User = require('../api/user/user.model'...
else { console.log('finished populating products'); popShipments(); } }); }); } function popShipments() { Shipment.find({}).remove(function () { Customer.find({}).exec().then(function(customers) { exports.shipments.forEach(function (shipment, i) { ...
{ console.error('Error while populating products: %s', err); }
conditional_block
seed.js
/* * Populate DB with sample data on server start * to disable, edit config/environment/index.js, and set `seedDB: false` */ 'use strict'; var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; var env = process.env.NODE_ENV || 'development'; var User = require('../api/user/user.model'...
}); } function popLots() { Lot.find({}).remove(function () { Shipment.find({}).exec().then(function(shipments) { // console.log('in popLots, shipments: ' + JSON.stringify(shipments)) exports.lots.forEach(function (lot, i) { lot.shipments.push(shipments[0]['_id']); ...
{ Shipment.find({}).remove(function () { Customer.find({}).exec().then(function(customers) { exports.shipments.forEach(function (shipment, i) { shipment.customer = customers[i%2]['_id']; }) Product.find({}).exec().then(function(products) { exports.shipments.forEach(...
identifier_body
throttle.ts
import { Operator } from '../Operator'; import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { Subscription } from '../Subscription'; import { OuterSubscriber } from '../OuterSubscriber'; import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeToResult } from '...
() { const { _hasValue, _sendValue } = this; if (_hasValue) { this.destination.next(_sendValue!); this.throttle(_sendValue!); } this._hasValue = false; this._sendValue = null; } private throttle(value: T): void { const duration = this.tryDurationSelector(value); if (!!durati...
send
identifier_name
throttle.ts
import { Operator } from '../Operator'; import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { Subscription } from '../Subscription'; import { OuterSubscriber } from '../OuterSubscriber'; import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeToResult } from '...
notifyComplete(): void { this.throttlingDone(); } }
{ this.throttlingDone(); }
identifier_body
throttle.ts
import { Operator } from '../Operator'; import { Observable } from '../Observable';
import { Subscription } from '../Subscription'; import { OuterSubscriber } from '../OuterSubscriber'; import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeToResult } from '../util/subscribeToResult'; import { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types'; export ...
import { Subscriber } from '../Subscriber';
random_line_split
throttle.ts
import { Operator } from '../Operator'; import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { Subscription } from '../Subscription'; import { OuterSubscriber } from '../OuterSubscriber'; import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeToResult } from '...
} private tryDurationSelector(value: T): SubscribableOrPromise<any> | null { try { return this.durationSelector(value); } catch (err) { this.destination.error(err); return null; } } private throttlingDone() { const { _throttled, _trailing } = this; if (_throttled) { ...
{ this.add(this._throttled = subscribeToResult(this, duration)); }
conditional_block
add_swift_support.js
var child_process = require('child_process'), fs = require('fs'), path = require('path'); module.exports = function(context) { var IOS_DEPLOYMENT_TARGET = '8.0', SWIFT_VERSION = '3.0', COMMENT_KEY = /_comment$/, CORDOVA_VERSION = process.env.CORDOVA_VERSION; run(); functio...
} return newObj; } function unquote(str) { if (str) return str.replace(/^"(.*)"$/, "$1"); } }
{ newObj[keys[i]] = obj[keys[i]]; }
conditional_block
add_swift_support.js
var child_process = require('child_process'), fs = require('fs'), path = require('path'); module.exports = function(context) { var IOS_DEPLOYMENT_TARGET = '8.0', SWIFT_VERSION = '3.0', COMMENT_KEY = /_comment$/, CORDOVA_VERSION = process.env.CORDOVA_VERSION; run(); functio...
var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()), config, buildSettings; for (config in configurations) { buildSettings = configurations[config].buildSettings; buildSettings['IPHONEOS_DEPLOYMENT_TARGET'] = IOS_DEPLOY...
random_line_split
add_swift_support.js
var child_process = require('child_process'), fs = require('fs'), path = require('path'); module.exports = function(context) { var IOS_DEPLOYMENT_TARGET = '8.0', SWIFT_VERSION = '3.0', COMMENT_KEY = /_comment$/, CORDOVA_VERSION = process.env.CORDOVA_VERSION; run(); functio...
(str) { if (str) return str.replace(/^"(.*)"$/, "$1"); } }
unquote
identifier_name
add_swift_support.js
var child_process = require('child_process'), fs = require('fs'), path = require('path'); module.exports = function(context) { var IOS_DEPLOYMENT_TARGET = '8.0', SWIFT_VERSION = '3.0', COMMENT_KEY = /_comment$/, CORDOVA_VERSION = process.env.CORDOVA_VERSION; run(); functio...
function setBridgingHeader(xcodeProject, headerPath) { var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()), config, buildSettings, bridgingHeader; for (config in configurations) { buildSettings = configurations[config].buildSettings; ...
{ var newBHPath = path.join(xcodeProjectRootPath, "Plugins", "Bridging-Header.h"), content = ["//", "// Use this file to import your target's public headers that you would like to expose to Swift.", "//", "#import <Cordova/CDV.h>"...
identifier_body
mod.rs
mod bunser; mod map; mod read; mod reentrant; mod seq; mod template; #[cfg(test)] mod test; mod variant; use std::io; use std::str; use serde::de; use crate::errors::*; use crate::header::*; use self::bunser::{Bunser, PduInfo}; use self::read::{DeRead, Reference, SliceRead}; use self::reentrant::ReentrantLimit; pu...
(read: R) -> Result<Self> { let mut bunser = Bunser::new(read); let pdu_info = bunser.read_pdu()?; Ok(Deserializer { bunser, pdu_info, remaining_depth: ReentrantLimit::new(128), }) } /// This method must be called after a value has been fully ...
new
identifier_name
mod.rs
mod bunser; mod map; mod read; mod reentrant; mod seq; mod template; #[cfg(test)] mod test; mod variant; use std::io; use std::str; use serde::de; use crate::errors::*; use crate::header::*; use self::bunser::{Bunser, PduInfo}; use self::read::{DeRead, Reference, SliceRead}; use self::reentrant::ReentrantLimit; pu...
pub fn from_reader<R, T>(rdr: R) -> Result<T> where R: io::Read, T: de::DeserializeOwned, { from_trait(read::IoRead::new(rdr)) } impl<'de, R> Deserializer<R> where R: DeRead<'de>, { pub fn new(read: R) -> Result<Self> { let mut bunser = Bunser::new(read); let pdu_info = bunser.rea...
{ from_trait(SliceRead::new(slice)) }
identifier_body
mod.rs
mod bunser; mod map; mod read; mod reentrant; mod seq; mod template; #[cfg(test)] mod test; mod variant; use std::io; use std::str; use serde::de; use crate::errors::*; use crate::header::*; use self::bunser::{Bunser, PduInfo}; use self::read::{DeRead, Reference, SliceRead}; use self::reentrant::ReentrantLimit; pu...
} /// This method must be called after a value has been fully deserialized. pub fn end(&self) -> Result<()> { self.bunser.end(&self.pdu_info) } #[inline] pub fn capabilities(&self) -> u32 { self.pdu_info.bser_capabilities } fn parse_value<V>(&mut self, visitor: V) -> R...
pdu_info, remaining_depth: ReentrantLimit::new(128), })
random_line_split
app.component.ts
import {Component, ViewChild} from '@angular/core'; import {NgxSlideshowComponent} from '../../projects/ngx-slideshow/src/public-api'; @Component({ selector: 'app-root', template: ` <div class="getting-started"> <div class="slideshow"> <div class="arrow left"> <button mat-icon-button (c...
{ @ViewChild('slideshow', {static: false}) slideshow: NgxSlideshowComponent; numList = Array.from(Array(10).keys()); right() { this.slideshow.right(); } left() { this.slideshow.left(); } }
AppComponent
identifier_name
app.component.ts
import {Component, ViewChild} from '@angular/core'; import {NgxSlideshowComponent} from '../../projects/ngx-slideshow/src/public-api'; @Component({ selector: 'app-root', template: ` <div class="getting-started"> <div class="slideshow"> <div class="arrow left"> <button mat-icon-button (c...
}) export class AppComponent { @ViewChild('slideshow', {static: false}) slideshow: NgxSlideshowComponent; numList = Array.from(Array(10).keys()); right() { this.slideshow.right(); } left() { this.slideshow.left(); } }
random_line_split
paged-list-controller-scope.js
(function () { 'use strict'; PN.namespace('PN.AngularDashboard.List'); PN.AngularDashboard.List.PagedListControllerScope = PN.AngularDashboard.List.ListControllerScope.extend({ _$timeout: null, pageSize: 30, pageNumber: 1, pageCount: 1, maxPageLength: 11, ...
if (that.totalCount === 0) { that.showAddForm = true; that.focusAddFormInput = true; } }); }, _createQueryData: function () { var token = new Date().valueOf().toString(); this._factory.latestToke...
that.showLoading = false; that.models = models; that.totalCount = Number(responseHeaders('total-count')); that.filteredCount = Number(responseHeaders('filtered-count')); that.pageCount = Math.max(Math.ceil(that.filteredCount / that.pageSize...
random_line_split
paged-list-controller-scope.js
(function () { 'use strict'; PN.namespace('PN.AngularDashboard.List'); PN.AngularDashboard.List.PagedListControllerScope = PN.AngularDashboard.List.ListControllerScope.extend({ _$timeout: null, pageSize: 30, pageNumber: 1, pageCount: 1, maxPageLength: 11, ...
}); }, __sort: function (expression, reverse) { this.sortExpression = expression; this.sortReverse = reverse; this.pageNumber = 1; this.showLoading = true; this._loadModels(); }, _loadModels: function () { ...
{ $scope.showLoading = true; $scope._loadModels(); window.scrollTo(0, 0); }
conditional_block
user.ts
rustration = profile.frustrations?.some( (frustration): boolean => personalisations.includes(frustration)) if (isFrustration) { return true } return personalisations. map((p: string): PersonalizationPredicate|undefined => personalizationsPredicates[p as Personalization]). some(predicate => ...
useTranslation
identifier_name
user.ts
// Returns a list of all frustrations of a user, as tags. // TODO(guillaume): Pull directly from Airtable when we know for sure the shape. function getUserFrustrationTags(profile: bayes.bob.UserProfile, t: TFunction): readonly string[] { const frustrationsToTag: {[f: string]: string} = { AGE_DISCRIMINATION: t(...
{ const todayYear = (new Date()).getFullYear() return todayYear - yearOfBirth }
identifier_body
user.ts
"), value: 'EXPERIENCE', }, { isCountryDependent: true, // i18next-extract-mark-context-next-line ["fr", "uk", "us"] name: prepareT('Mon niveau en **français**'), value: 'LANGUAGE', }, { isCountryDependent: true, // i18next-extract-mark-context-next-line ["fr", "uk", "us"] name: ...
tchUserFromUrl(window.location.search)
conditional_block
user.ts
0 } const createdAtTime = createdAt ? new Date(createdAt).getTime() : Date.now() const duration = createdAtTime - new Date(jobSearchStartedAt).getTime() return Math.round(duration / MILLIS_IN_MONTH) } const FAMILY_SITUATION_OPTIONS: readonly LocalizedSelectOption<bayes.bob.FamilySituation>[] = [ {name: prep...
// eslint-disable-next-line no-console console.log(
random_line_split
index.d.ts
// Type definitions for react-grid-layout 0.16 // Project: https://github.com/STRML/react-grid-layout // Definitions by: Andrew Birkholz <https://github.com/abirkholz>, // Ali Taheri <https://github.com/alitaheri>, // Zheyang Song <https://github.com/ZheyangSong>, // Andr...
className?: string; /** * Inline-style object to pass to the root element. */ style?: React.CSSProperties; /** * If true, the container height swells and contracts to fit contents. */ autoSize?: boolean; /** * A CSS selector...
random_line_split
index.d.ts
// Type definitions for react-grid-layout 0.16 // Project: https://github.com/STRML/react-grid-layout // Definitions by: Andrew Birkholz <https://github.com/abirkholz>, // Ali Taheri <https://github.com/alitaheri>, // Zheyang Song <https://github.com/ZheyangSong>, // Andr...
extends React.Component< ReactGridLayout.ReactGridLayoutProps > {} declare namespace ReactGridLayout { interface Layout { /** * A string corresponding to the component key. * Uses the index of components instead if not provided. */ i?: string; /** *...
ReactGridLayout
identifier_name
api.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import json...
(self): try: return json.loads(self.request.body) except ValueError: raise JSONDecodeError def get_permissions(self): """Returns permission handler instances required for a particular view.""" return [permission() for permission in self.permission_classes] ...
request_data
identifier_name
api.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import json...
def form_invalid(self, form): return JsonResponse({'errors': form.errors}, status=400)
return JsonResponse({'msg': msg}, status=status)
identifier_body
api.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import json...
def handle_exception(self, exc): """Handles response exceptions.""" if isinstance(exc, Http404): return JsonResponseNotFound({ 'msg': 'Not found', }) if isinstance(exc, PermissionDenied): return JsonResponseForbidden({ 'm...
if not permission.has_object_permission(request, self, obj): raise PermissionDenied
conditional_block
api.py
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import json...
def get_search_filter(self, keyword): search_fields = getattr(self, 'search_fields', None) if search_fields is None: search_fields = self.fields # Assume all fields field_queries = list( zip(map(lambda x: '%s__icontains' % x, search_fields), (keyword...
} return return_values
random_line_split
en.js
{ "CMSMAIN.WARNINGSAVEPAGESBEFOREADDING" : "You have to save a page before adding children underneath it", "CMSMAIN.CANTADDCHILDREN" : "You can't add children to the selected node", "CMSMAIN.ERRORADDINGPAGE" : "Error adding page", "CMSMAIN.FILTEREDTREE" : "Filtered tree to only show changed pages", "CMSMAIN.ERRORF...
"AssetAdmin.BATCHACTIONSDELETECONFIRM": "Do you really want to delete %s folders?", "AssetTableField.REALLYDELETE": "Do you really want to delete the marked files?", "AssetTableField.MOVING": "Moving %s file(s)", "CMSMAIN.AddSearchCriteria": "Add Criteria", "WidgetAreaEditor.TOOMANY": "Sorry, you have reached the ...
"CMSMAIN.ALERTCLASSNAME": "The page type will be updated after the page is saved", "CMSMAIN.URLSEGMENTVALIDATION": "URLs can only be made up of letters, digits and hyphens.",
random_line_split
shell.rs
use std::env; use std::io::stdin; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; struct Shell { cmd_prompt: String, cwd: PathBuf } impl Shell { fn
(prompt_str: &str, cwd: PathBuf) -> Shell { Shell { cmd_prompt: prompt_str.to_owned(), cwd: cwd } } fn start(&mut self) { let stdin = stdin(); loop { println!("{}", self.cmd_prompt); let mut line = String::new(); stdin...
new
identifier_name
shell.rs
use std::env; use std::io::stdin; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; struct Shell { cmd_prompt: String, cwd: PathBuf } impl Shell { fn new(prompt_str: &str, cwd: PathBuf) -> Shell { Shell { cmd_prompt: prompt_str.to_owned(), cwd: cwd ...
fn run_cmd(&mut self, cmd: String, argv: Vec<String>) { match &*cmd { "\u{1F697}" => self.cd(argv), "\u{1F4CD}" => self.pwd(), "\u{1F50D}" => self.execute_program("ls".to_string(), argv), "\u{1F431}" => self.execute_program("cat".to_string(), argv), ...
{ let mut arg_vec = Vec::new(); let mut cmd = String::new(); for (index, raw_s) in cmd_line.split("\u{1F345}").enumerate() { let s = raw_s.trim(); if s == "" { continue; } if index == 0 { cmd = s.to_owned(); } else { arg_vec.push(s.to_owned()); } } ...
identifier_body
shell.rs
use std::env; use std::io::stdin; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; struct Shell { cmd_prompt: String, cwd: PathBuf } impl Shell { fn new(prompt_str: &str, cwd: PathBuf) -> Shell { Shell { cmd_prompt: prompt_str.to_owned(), cwd: cwd ...
Shell::new("\u{1f41a} ", path).start(); }
random_line_split
main.spec.js
/* * Copyright (c) 2013, IT Services, Stockholm University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this *...
});
});
random_line_split
CreateFileDialogContainer.tsx
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope tha...
/> </form> </DialogBody> <DialogFooter> <FormControlLabel style={{ marginRight: 'auto' }} label={formatMessage(translations.openOnSuccess)} title={formatMessage(translations.openOnSuccessTitle)} control={ <Checkbox checked={openOn...
event.target.value .replace(allowBraces ? /[^a-zA-Z0-9-_{}.]/g : /[^a-zA-Z0-9-_.]/g, '') .replace(/\.{1,}/g, '.') ) }
random_line_split
CreateFileDialogContainer.tsx
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope tha...
else { setConfirm({ error: true, body: formatMessage(translations.policyError) }); dispatch( updateCreateFolderDialog({ isSubmitting: false }) ); } }); } }; const onConfirm = () => { const f...
{ if (modifiedValue) { setConfirm({ body: formatMessage(translations.createPolicy, { name: modifiedValue.replace(`${path}/`, '') }) }); } else { const fileName = getName(type, name); onCreateFile(site, path, fileName); } ...
conditional_block
memvis.rs
((color as f32 * (scale as f32 / 255f32)) as i16) } /// Draw all memory values represented by pixels. Width is determined /// by `MEM_DISP_WIDTH`. pub fn draw_memory_values<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu) where T: sdl2::render::RenderTarget, { let mut x = 0; let mut y = 0; fo...
{ let pc = pc as usize; let ref mem = cpu.mem; let b1 = mem[pc + 1]; let b2 = mem[pc + 2]; let (mnem, _) = disasm::pp_opcode(mem[pc] as u8, b1 as u8, b2 as u8, pc as u16); let nn = byte_to_u16(b1, b2); println!( "${:04X} {:16} 0x{:02X} 0x{:02X} 0x{:02X} 0x{:04X}", pc, mnem, m...
identifier_body
memvis.rs
_mem_addr(position) { info!("Jumping to ${:04X}", pc); cpu.pc = pc; if cpu.state != CpuState::Normal { info!("CPU state was '{:?}', forcing run.", cpu.state); cpu.state = CpuState::Normal; } ...
let (r, g, b) = mix_color(colval, colval, scale_col(colval, val), 0, 0, 0); renderer.set_draw_color(Color::RGB(r, g, b)); match renderer.draw_point(addr_to_point(addr)) { Ok(_) => (),
random_line_split
memvis.rs
32, txt_format, ) .unwrap(); // This determines how fast access fades (actual speed // will depend on the frame rate). const ACCESS_FADE_ALPHA: u8 = 100; // Create texture with alpha to do fading effect let mut blend =...
draw_memory_events
identifier_name