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
vtable_writer.rs
/* * Copyright 2018 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 applica...
(&mut self, n: VOffsetT) { emplace_scalar::<VOffsetT>(&mut self.buf[SIZE_VOFFSET..2 * SIZE_VOFFSET], n); } /// Gets an object field offset from the vtable. Only used for debugging. /// /// Note that this expects field offsets (which are like pointers), not /// field ids (which are like arra...
write_object_inline_size
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Package' db.create_table(u'api_package', ( (u'id', self.gf('django.db.models.fie...
(self, orm): # Removing unique constraint on 'Package', fields ['name', 'url'] db.delete_unique(u'api_package', ['name', 'url']) # Deleting model 'Package' db.delete_table(u'api_package') models = { u'api.package': { 'Meta': {'unique_together': "(('name', 'url'...
backwards
identifier_name
0001_initial.py
from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Package' db.create_table(u'api_package', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ...
# -*- coding: utf-8 -*- import datetime
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration):
models = { u'api.package': { 'Meta': {'unique_together': "(('name', 'url'),)", 'object_name': 'Package'}, 'created_at': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key':...
def forwards(self, orm): # Adding model 'Package' db.create_table(u'api_package', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=500, db_index=True)), ('url', sel...
identifier_body
string.js
/** @module ember @submodule ember-htmlbars */ import Ember from 'ember-metal/core'; import EmberStringUtils from 'ember-runtime/system/string'; import { SafeString, escapeExpression } from 'htmlbars-util'; /** Mark a string as safe for unescaped output with Ember templates. If you return HTML from a helper, use ...
return new SafeString(str); } EmberStringUtils.htmlSafe = htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function() { return htmlSafe(this); }; } export { SafeString, htmlSafe, escapeExpression };
{ str = '' + str; }
conditional_block
string.js
/** @module ember @submodule ember-htmlbars */ import Ember from 'ember-metal/core'; import EmberStringUtils from 'ember-runtime/system/string'; import { SafeString, escapeExpression } from 'htmlbars-util'; /** Mark a string as safe for unescaped output with Ember templates. If you return HTML from a helper, use ...
export { SafeString, htmlSafe, escapeExpression };
random_line_split
string.js
/** @module ember @submodule ember-htmlbars */ import Ember from 'ember-metal/core'; import EmberStringUtils from 'ember-runtime/system/string'; import { SafeString, escapeExpression } from 'htmlbars-util'; /** Mark a string as safe for unescaped output with Ember templates. If you return HTML from a helper, use ...
EmberStringUtils.htmlSafe = htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function() { return htmlSafe(this); }; } export { SafeString, htmlSafe, escapeExpression };
{ if (str === null || str === undefined) { return ''; } if (typeof str !== 'string') { str = '' + str; } return new SafeString(str); }
identifier_body
string.js
/** @module ember @submodule ember-htmlbars */ import Ember from 'ember-metal/core'; import EmberStringUtils from 'ember-runtime/system/string'; import { SafeString, escapeExpression } from 'htmlbars-util'; /** Mark a string as safe for unescaped output with Ember templates. If you return HTML from a helper, use ...
(str) { if (str === null || str === undefined) { return ''; } if (typeof str !== 'string') { str = '' + str; } return new SafeString(str); } EmberStringUtils.htmlSafe = htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function() { ...
htmlSafe
identifier_name
resolveExportDeclaration.ts
import { namedTypes as t } from 'ast-types'; import resolveToValue from './resolveToValue'; import type { Importer } from '../parse'; import type { NodePath } from 'ast-types/lib/node-path'; export default function resolveExportDeclaration( path: NodePath, importer: Importer, ): NodePath[]
{ const definitions: NodePath[] = []; if (path.node.default) { definitions.push(path.get('declaration')); } else if (path.node.declaration) { if (t.VariableDeclaration.check(path.node.declaration)) { path .get('declaration', 'declarations') .each(declarator => definitions.push(declar...
identifier_body
resolveExportDeclaration.ts
import { namedTypes as t } from 'ast-types'; import resolveToValue from './resolveToValue'; import type { Importer } from '../parse'; import type { NodePath } from 'ast-types/lib/node-path'; export default function resolveExportDeclaration( path: NodePath, importer: Importer, ): NodePath[] { const definitions: N...
} } else if (path.node.specifiers) { path .get('specifiers') .each(specifier => definitions.push(specifier.get('local'))); } return definitions.map(definition => resolveToValue(definition, importer)); }
.get('declaration', 'declarations') .each(declarator => definitions.push(declarator)); } else { definitions.push(path.get('declaration'));
random_line_split
resolveExportDeclaration.ts
import { namedTypes as t } from 'ast-types'; import resolveToValue from './resolveToValue'; import type { Importer } from '../parse'; import type { NodePath } from 'ast-types/lib/node-path'; export default function
( path: NodePath, importer: Importer, ): NodePath[] { const definitions: NodePath[] = []; if (path.node.default) { definitions.push(path.get('declaration')); } else if (path.node.declaration) { if (t.VariableDeclaration.check(path.node.declaration)) { path .get('declaration', 'declaratio...
resolveExportDeclaration
identifier_name
priceDB_test.py
#!/usr/bin/env python3 # Test file for price database stuff # To update the price database call # $PATH/gnucash --add-price-quotes $PATHTOFILE # before running this. # Adding to a calling bash script would be better # Although calling it from here would be even better! # OR: export PYTHONPATH=<path-to-gnucash-inst-d...
comm_table = book.get_table() gbp = comm_table.lookup("CURRENCY", "SOME_CURRENCY") arm = comm_table.lookup("NASDAQ", "SOME_STOCK") latest = pdb.lookup_latest(arm,gbp) # from the table, NOT live data value = latest.get_value() pl = pdb.get_prices(arm,gbp) for pr in pl: source = pr.get_source() time = pr.get_time64...
root = session.book.get_root_account() book = session.book pdb = book.get_price_db()
random_line_split
priceDB_test.py
#!/usr/bin/env python3 # Test file for price database stuff # To update the price database call # $PATH/gnucash --add-price-quotes $PATHTOFILE # before running this. # Adding to a calling bash script would be better # Although calling it from here would be even better! # OR: export PYTHONPATH=<path-to-gnucash-inst-d...
if len(pl) > 0: v0 = pl[0].get_value() print(arm.get_fullname(), float(v0.num) / float(v0.denom )) session.end() session.destroy() quit()
source = pr.get_source() time = pr.get_time64() v=pr.get_value() price = float(v.num)/v.denom print(time, source, price)
conditional_block
check_mrz_ocr.py
import logging def same_ocr_mrz(mrz_data, zones): last_name_is_valid = mrz_data["last_name"][:25] == zones["last_name"]["value"][:25] logging.debug( "MRZ last name: {}; OCR last name: {}; matching {}".format( mrz_data["last_name"], zones["last_name"]["value"], last_name_is_valid )...
first_name_is_valid = first_names_mrz_joined[:length_checked] == first_names_ocr_joined[:length_checked] logging.debug( "MRZ first names: {}; OCR first names: {}; matching {}".format( first_names_mrz, first_names_ocr, first_name_is_valid ) ) return last_name_is_valid and fi...
len(first_names_mrz_joined), 12 ])
random_line_split
check_mrz_ocr.py
import logging def same_ocr_mrz(mrz_data, zones):
first_names_mrz, first_names_ocr, first_name_is_valid ) ) return last_name_is_valid and first_name_is_valid
last_name_is_valid = mrz_data["last_name"][:25] == zones["last_name"]["value"][:25] logging.debug( "MRZ last name: {}; OCR last name: {}; matching {}".format( mrz_data["last_name"], zones["last_name"]["value"], last_name_is_valid ) ) first_names_ocr = zones["first_name"]["value...
identifier_body
check_mrz_ocr.py
import logging def
(mrz_data, zones): last_name_is_valid = mrz_data["last_name"][:25] == zones["last_name"]["value"][:25] logging.debug( "MRZ last name: {}; OCR last name: {}; matching {}".format( mrz_data["last_name"], zones["last_name"]["value"], last_name_is_valid ) ) first_names_ocr = zon...
same_ocr_mrz
identifier_name
urls.py
from django.conf.urls import * from . import views from . import z_queries from rockletonfortune import settings from django.contrib.auth.views import login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth import views as auth_views from django.views.static import serve from ...
# Edit the weekly/monthly allocation per secondary transaction url(r'budget/edit/$', login_required(views.budget_edit), name = 'budget_edit'), #Fetch the weekly spend summary per secondary and primary categories url('ajax/budget/$', login_required(z_queries.q_budget_view_json), name='q_budget_view_...
# Export transactions to csv for Google Sheets url(r'transactions/csv/$', login_required(views.export_csv), name = 'export_csv'),
random_line_split
__init__.py
from flask import Flask, render_template, flash from flask_material_lite import Material_Lite from flask_appconfig import AppConfig from flask_wtf import Form, RecaptchaField from flask_wtf.file import FileField from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField, Int...
class ExampleForm(Form): field1 = TextField('First Field', description='This is field one.') field2 = TextField('Second Field', description='This is field two.', validators=[Required()]) hidden_field = HiddenField('You cannot see this', description='Nope') recaptcha = Recaptcha...
country_code = IntegerField('Country Code', [validators.required()]) area_code = IntegerField('Area Code/Exchange', [validators.required()]) number = TextField('Number')
identifier_body
__init__.py
from flask import Flask, render_template, flash from flask_material_lite import Material_Lite from flask_appconfig import AppConfig from flask_wtf import Form, RecaptchaField from flask_wtf.file import FileField from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField, Int...
(Form): field1 = TextField('First Field', description='This is field one.') field2 = TextField('Second Field', description='This is field two.', validators=[Required()]) hidden_field = HiddenField('You cannot see this', description='Nope') recaptcha = RecaptchaField('A sample reca...
ExampleForm
identifier_name
__init__.py
from flask import Flask, render_template, flash from flask_material_lite import Material_Lite from flask_appconfig import AppConfig from flask_wtf import Form, RecaptchaField from flask_wtf.file import FileField from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField, Int...
app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/', methods=('GET', 'POST')) def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser flash('criti...
random_line_split
__init__.py
from flask import Flask, render_template, flash from flask_material_lite import Material_Lite from flask_appconfig import AppConfig from flask_wtf import Form, RecaptchaField from flask_wtf.file import FileField from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField, Int...
create_app().run(debug=True)
conditional_block
ResourceHandlerHttpClient.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams, HttpRequest, HttpResponse } from '@angular/common/http'; import { catchError, last, map } from 'rxjs/operators'; import { IResourceHandlerResponse, IResourceRequest, IResourceResponse, ResourceHandler, ...
(req: IResourceRequest): HttpRequest<any> { let method = 'GET'; switch (req.method) { case ResourceRequestMethod.Get: method = 'GET'; break; case ResourceRequestMethod.Post: method = 'POST'; break; case ResourceRequestMethod.Put: method = 'PUT'; ...
prepareRequest
identifier_name
ResourceHandlerHttpClient.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams, HttpRequest, HttpResponse } from '@angular/common/http'; import { catchError, last, map } from 'rxjs/operators'; import { IResourceHandlerResponse, IResourceRequest, IResourceResponse, ResourceHandler, ...
params?: HttpParams; responseType?: THttpRequestInitResponseType; withCredentials?: boolean; }
export type THttpRequestInitResponseType = 'arraybuffer' | 'blob' | 'json' | 'text'; export interface IHttpRequestInit { headers?: HttpHeaders;
random_line_split
test_views.py
from __future__ import unicode_literals import copy import sys from django.test import TestCase from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.test import APIRequestFact...
request = factory.post('/', 'f00bar', content_type='application/json') response = self.view(request) expected = { 'detail': JSON_ERROR } self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(sanitise_json_error(response.data), ex...
def setUp(self): self.view = basic_view def test_400_parse_error(self):
random_line_split
test_views.py
from __future__ import unicode_literals import copy import sys from django.test import TestCase from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.test import APIRequestFact...
elif request.method == 'POST': return {'method': 'POST', 'data': request.data} elif request.method == 'PUT': return {'method': 'PUT', 'data': request.data} elif request.method == 'PATCH': return {'method': 'PATCH', 'data': request.data} class ErrorView(APIView): def get(self, ...
return {'method': 'GET'}
conditional_block
test_views.py
from __future__ import unicode_literals import copy import sys from django.test import TestCase from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.test import APIRequestFact...
(error_dict): """ Exact contents of JSON error messages depend on the installed version of json. """ ret = copy.copy(error_dict) chop = len(JSON_ERROR) ret['detail'] = ret['detail'][:chop] return ret class ClassBasedViewIntegrationTests(TestCase): def setUp(self): self.view...
sanitise_json_error
identifier_name
test_views.py
from __future__ import unicode_literals import copy import sys from django.test import TestCase from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.test import APIRequestFact...
def test_function_based_view_exception_handler(self): view = error_view request = factory.get('/', content_type='application/json') response = view(request) expected = 'Error!' self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(res...
view = ErrorView.as_view() request = factory.get('/', content_type='application/json') response = view(request) expected = 'Error!' self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data, expected)
identifier_body
LPS.rs
pub fn longest_palindrome(s: String) -> String { let mut s = s.as_bytes().to_vec(); let mut d = s.clone(); d.reverse(); let mut largest_len = 0; let mut result = String::new(); loop { if s.len() == 0 || s.len() < largest_len { break; } let (a, b) = inner_loo...
let (b, size) = inner_loop2(ss, start, end); if b { if size.unwrap() > largest_size { largest_size = size.unwrap(); record_start = start; } } } } //println!("{}, {}", record_start, largest_size...
{ break; }
conditional_block
LPS.rs
pub fn longest_palindrome(s: String) -> String
} result } /// find palindrome, return length, start index fn inner_loop(s: &Vec<u8>, d: &Vec<u8>) -> (usize, String) { //println!("here: {:?}, {:?}", s, d); let mut length = s.len(); let mut offset = 0; let mut flag = true; loop { flag = true; if length == 0 { ...
{ let mut s = s.as_bytes().to_vec(); let mut d = s.clone(); d.reverse(); let mut largest_len = 0; let mut result = String::new(); loop { if s.len() == 0 || s.len() < largest_len { break; } let (a, b) = inner_loop(&s, &d); if a > largest_len { ...
identifier_body
LPS.rs
pub fn
(s: String) -> String { let mut s = s.as_bytes().to_vec(); let mut d = s.clone(); d.reverse(); let mut largest_len = 0; let mut result = String::new(); loop { if s.len() == 0 || s.len() < largest_len { break; } let (a, b) = inner_loop(&s, &d); if a >...
longest_palindrome
identifier_name
LPS.rs
pub fn longest_palindrome(s: String) -> String { let mut s = s.as_bytes().to_vec(); let mut d = s.clone(); d.reverse(); let mut largest_len = 0; let mut result = String::new(); loop { if s.len() == 0 || s.len() < largest_len { break; } let (a, b) = inner_loo...
assert_eq!("bab", longest_palindrome("babad".to_string())); assert_eq!("bb", longest_palindrome("cbbd".to_string())); assert_eq!("", longest_palindrome("".to_string())); assert_eq!("bab", longest_palindrome2("babad".to_string())); assert_eq!("bb", longest_palindrome2("cbbd".to_string())); asser...
fn main() {
random_line_split
testMoveToElement.js
var MockServer = require('mockserver'); module.exports = { setUp: function (callback) { this.client = require('../../nightwatch.js').init(); callback(); }, testCommand : function(test) { var client = this.client;
postdata: '{"element":"0"}', response : JSON.stringify({ sessionId: "1352110219202", status: 0 }) }); client.moveTo('css selector', '#weblogin', null, null, function callback(result) { test.equals(result.status, 0) }).moveToElement('#weblogin', null, null, functi...
MockServer.addMock({ url : "/wd/hub/session/1352110219202/moveto", method:'POST',
random_line_split
mod.rs
pub mod display; pub mod device; pub mod state; pub mod termios; mod err; use std::os::unix::io::AsRawFd; use std::io::{self, Write}; use std::mem; use std::fmt; use ::libc; use ::child::exec; use ::pty::prelude as pty; use self::device::Device; use self::termios::Termios; pub use self::state::ShellState; pub use se...
, #[cfg(not(feature = "auto-resize"))] () => { self.state.update_from(&mut self.screen, event); self.state }, } } } impl Iterator for Shell { type Item = ShellState; fn next(&mut self) -> Option<ShellState> { match self.de...
{ self.state.update_from(&mut self.screen, event); if let Some(size) = self.state.is_resized() { self.set_window_size_with(&size); } self.state }
conditional_block
mod.rs
pub mod display; pub mod device; pub mod state; pub mod termios; mod err; use std::os::unix::io::AsRawFd; use std::io::{self, Write}; use std::mem; use std::fmt; use ::libc; use ::child::exec; use ::pty::prelude as pty; use self::device::Device; use self::termios::Termios; pub use self::state::ShellState; pub use se...
}
} }
random_line_split
mod.rs
pub mod display; pub mod device; pub mod state; pub mod termios; mod err; use std::os::unix::io::AsRawFd; use std::io::{self, Write}; use std::mem; use std::fmt; use ::libc; use ::child::exec; use ::pty::prelude as pty; use self::device::Device; use self::termios::Termios; pub use self::state::ShellState; pub use se...
(&mut self) { if let Ok(size) = Winszed::new(libc::STDOUT_FILENO) { self.set_window_size_with(&size); } } /// The mutator method `set_window_size` redimentionnes the window /// with a argument size. fn set_window_size_with(&mut self, size: &Winszed) { self.screen.set...
set_window_size
identifier_name
mod.rs
pub mod display; pub mod device; pub mod state; pub mod termios; mod err; use std::os::unix::io::AsRawFd; use std::io::{self, Write}; use std::mem; use std::fmt; use ::libc; use ::child::exec; use ::pty::prelude as pty; use self::device::Device; use self::termios::Termios; pub use self::state::ShellState; pub use se...
/// The mutator method `write` set a buffer to the display /// without needing to print it fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.screen.write(buf) } /// The mutator method `next` updates the event and returns /// the new state. fn next(&mut self, event: state...
{ self.screen.set_window_size(size); unsafe { libc::ioctl(self.speudo.as_raw_fd(), libc::TIOCSWINSZ, size); libc::kill(self.pid, libc::SIGWINCH); } }
identifier_body
storage.rs
//! Abstract definition of a matrix data storage. use std::fmt::Debug; use std::mem; use crate::base::allocator::{Allocator, SameShapeC, SameShapeR}; use crate::base::default_allocator::DefaultAllocator; use crate::base::dimension::{Dim, U1}; use crate::base::Scalar; /* * Aliases for allocation results. */ /// The...
/// Retrieves the mutable data buffer as a contiguous slice. /// /// Matrix components may not be contiguous, depending on its strides. fn as_mut_slice(&mut self) -> &mut [N]; } /// A matrix storage that is stored contiguously in memory. /// /// The storage requirement means that for any value of `i`...
{ let lid1 = self.linear_index(row_col1.0, row_col1.1); let lid2 = self.linear_index(row_col2.0, row_col2.1); self.swap_unchecked_linear(lid1, lid2) }
identifier_body
storage.rs
//! Abstract definition of a matrix data storage. use std::fmt::Debug; use std::mem; use crate::base::allocator::{Allocator, SameShapeC, SameShapeR}; use crate::base::default_allocator::DefaultAllocator; use crate::base::dimension::{Dim, U1}; use crate::base::Scalar; /* * Aliases for allocation results. */ /// The...
(&mut self, i1: usize, i2: usize) { let a = self.get_address_unchecked_linear_mut(i1); let b = self.get_address_unchecked_linear_mut(i2); mem::swap(&mut *a, &mut *b); } /// Swaps two elements without bound-checking. #[inline] unsafe fn swap_unchecked(&mut self, row_col1: (usize...
swap_unchecked_linear
identifier_name
storage.rs
//! Abstract definition of a matrix data storage. use std::fmt::Debug; use std::mem; use crate::base::allocator::{Allocator, SameShapeC, SameShapeR}; use crate::base::default_allocator::DefaultAllocator; use crate::base::dimension::{Dim, U1}; use crate::base::Scalar; /* * Aliases for allocation results. */ /// The...
/// failing to comply to this may cause Undefined Behaviors. pub unsafe trait ContiguousStorage<N: Scalar, R: Dim, C: Dim = U1>: Storage<N, R, C> { } /// A mutable matrix storage that is stored contiguously in memory. /// /// The storage requirement means that for any value of `i` in `[0, nrows * ncols[`, the valu...
/// `.get_unchecked_linear` returns one of the matrix component. This trait is unsafe because
random_line_split
validation.service.ts
export class ValidationService { static getValidatorErrorMessage(validatorName: string, validatorValue?: any) { let validatorValueLength = validatorValue ? validatorValue.requiredLength : -1; let config = { 'required': 'Required', 'maxlength': 'Should have a length less than ' + validatorValueLe...
return null; } else { return { 'invalidBookingCode': true }; } } static familyNameValidator(control) { if (control.value.match(/^[a-zA-Z]+$/)) { return null; } else { return { 'invalidFamilyName': true }; } } }
static bookingCodeValidator(control) { if (control.value.match(/^[2-9a-zA-Z]+$/)) {
random_line_split
validation.service.ts
export class ValidationService { static getValidatorErrorMessage(validatorName: string, validatorValue?: any) { let validatorValueLength = validatorValue ? validatorValue.requiredLength : -1; let config = { 'required': 'Required', 'maxlength': 'Should have a length less than ' + validatorValueLe...
(control) { if (control.value.match(/^[2-9a-zA-Z]+$/)) { return null; } else { return { 'invalidBookingCode': true }; } } static familyNameValidator(control) { if (control.value.match(/^[a-zA-Z]+$/)) { return null; } else { return { 'invalidFamilyName': true }; } }...
bookingCodeValidator
identifier_name
validation.service.ts
export class ValidationService { static getValidatorErrorMessage(validatorName: string, validatorValue?: any) { let validatorValueLength = validatorValue ? validatorValue.requiredLength : -1; let config = { 'required': 'Required', 'maxlength': 'Should have a length less than ' + validatorValueLe...
} static familyNameValidator(control) { if (control.value.match(/^[a-zA-Z]+$/)) { return null; } else { return { 'invalidFamilyName': true }; } } }
{ return { 'invalidBookingCode': true }; }
conditional_block
validation.service.ts
export class ValidationService { static getValidatorErrorMessage(validatorName: string, validatorValue?: any) { let validatorValueLength = validatorValue ? validatorValue.requiredLength : -1; let config = { 'required': 'Required', 'maxlength': 'Should have a length less than ' + validatorValueLe...
}
{ if (control.value.match(/^[a-zA-Z]+$/)) { return null; } else { return { 'invalidFamilyName': true }; } }
identifier_body
mudserver.js
/* * Include everything. */ var net = require('net'); var MudClient = require("./mudclient.js"); var MudRooms = require("./mudrooms.js"); /* * I wanted to make this a field on a MudServer class and node decided it wanted to monkeypatch my scope and break that idea. */ var clients = [] /* * As much as I feel thi...
; /* * Send text to all fully logged in clients except the one. * * I envisioned this as being a method on a server class but nodejs didnt co-operate in the limited time I had. */ function sendToAllOtherClients(socket, data) { for(var i = 0; i< clients.length; i++) { if( clients[i].socket !== socket && clients...
{ for(var i = 0; i < clients.length; i++) { clients[i].writeline(data); clients[i].prompt(); } }
identifier_body
mudserver.js
/* * Include everything. */ var net = require('net'); var MudClient = require("./mudclient.js"); var MudRooms = require("./mudrooms.js"); /* * I wanted to make this a field on a MudServer class and node decided it wanted to monkeypatch my scope and break that idea. */ var clients = [] /* * As much as I feel thi...
} var roomDestination = rooms[client.location].exits[words[1]]; for(var i = 0; i < clients.length; i++) { if(roomDestination == clients[i].location && clients[i].socket !== client.socket){ clients[i].writeline(client.name + " arrived from " + client.location ); clients[i].prompt() } } ...
{ clients[i].writeline(client.name + " went " + words[1] ); clients[i].prompt() }
conditional_block
mudserver.js
/* * Include everything. */ var net = require('net'); var MudClient = require("./mudclient.js"); var MudRooms = require("./mudrooms.js"); /* * I wanted to make this a field on a MudServer class and node decided it wanted to monkeypatch my scope and break that idea. */ var clients = [] /* * As much as I feel thi...
(socket, data) { for(var i = 0; i< clients.length; i++) { if( clients[i].socket !== socket && clients[i].name !== '') { clients[i].writeline(data); clients[i].prompt(); } } }; /* * Send text and client sending it to the command system. * * I envisioned this as being a method on a dedicated command contr...
sendToAllOtherClients
identifier_name
mudserver.js
/* * Include everything. */ var net = require('net'); var MudClient = require("./mudclient.js"); var MudRooms = require("./mudrooms.js"); /* * I wanted to make this a field on a MudServer class and node decided it wanted to monkeypatch my scope and break that idea. */ var clients = [] /* * As much as I feel thi...
Create: function(port) { var server = net.createServer(newClientConnection); server.listen(port); return server; } };
random_line_split
google-docs.js
import Component from '@ember/component'; import layout from '../templates/components/google-docs'; import { computed, get } from '@ember/object';
tagName: 'a', attributeBindings: ['href', 'rel', 'target'], type: 'reference', referenceUrl: 'https://developers.google.com/maps/documentation/javascript/reference#', guideUrl: 'https://developers.google.com/maps/documentation/javascript/', rel: 'noopener', target: '_blank', baseUrl: computed('type', ...
import { capitalize } from '@ember/string'; const GoogleDocs = Component.extend({ layout,
random_line_split
revertable.py
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pr...
""" Initialize a :class:`RevertableAction` instance. `kwargs` can contain any of the names of public instance variables, of which :attr:`actions` and :attr:`description` are required to be set eventually, either with `kwargs` or direct assignment later. """ self.actions ...
identifier_body
revertable.py
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pr...
(self): """Return the :attr:`aeidon.registers` item for reversion.""" if self.register.shift == 1: return aeidon.registers.UNDO if self.register.shift == -1: return aeidon.registers.REDO raise ValueError("Invalid register: {!r}" .format(se...
_get_reversion_register
identifier_name
revertable.py
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pr...
:ivar actions: Sequence of :class:`RevertableAction` in group :ivar description: Short one line description """ def __init__(self, **kwargs): """ Initialize a :class:`RevertableAction` instance. `kwargs` can contain any of the names of public instance variables, of whic...
Group of :class:`RevertableAction`.
random_line_split
revertable.py
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pr...
if self.register.shift == -1: return aeidon.registers.REDO raise ValueError("Invalid register: {!r}" .format(self.register)) def revert(self): """Call the reversion function.""" kwargs = self.revert_kwargs.copy() kwargs["register"] = sel...
return aeidon.registers.UNDO
conditional_block
core.py
"модуль із класом Core що включає в собі деякі методи комбінаторики, які використовуються в програмі" import itertools from math import factorial as fact class Core: # Методи-генератори комбінацій/перестановок #perm = itertools.permutations # перестановки comb = ite...
else: for res in Core.place_w_repl(seq, depth, prev=res): yield res @staticmethod def perm(seq, uselessK): # перестановки for res in itertools.permutations(seq): yield res # # Мет...
РАХОВУЄТЬСЯ) for char in tuple(seq): res = prev + (char,) if len(res) == depth: yield res
conditional_block
core.py
"модуль із класом Core що включає в собі деякі методи комбінаторики, які використовуються в програмі" import itertools from math import factorial as fact class Core: # Методи-генератори комбінацій/перестановок #perm = itertools.permutations # перестановки comb = ite...
else: for res in Core.place_w_repl(seq, depth, prev=res): yield res @staticmethod def perm(seq, uselessK): # перестановки for res in itertools.permutations(seq): yield res # # Мет...
ev=res): yield res @staticmethod def place_w_repl(seq, depth, prev=()): # розміщення із повторенями (порядок ВРАХОВУЄТЬСЯ) for char in tuple(seq): res = prev + (char,) if len(res) == depth: yield res
identifier_body
core.py
"модуль із класом Core що включає в собі деякі методи комбінаторики, які використовуються в програмі" import itertools from math import factorial as fact class Core: # Методи-генератори комбінацій/перестановок #perm = itertools.permutations # перестановки comb = ite...
Core.place("abcdef", 3): print(i, end=" ") print(Core.place_number("abcdef", 3)) print(len(list(Core.perm(range(10), None))), Core.perm_number(range(10), None)) l=[] for i in Core.comb(range(15545), 15): l.append(i) if len(l)>50: break print(l) ...
for i in
identifier_name
core.py
"модуль із класом Core що включає в собі деякі методи комбінаторики, які використовуються в програмі" import itertools from math import factorial as fact class Core: # Методи-генератори комбінацій/перестановок #perm = itertools.permutations # перестановки comb = ite...
@staticmethod def perm(seq, uselessK): # перестановки for res in itertools.permutations(seq): yield res # # Методи для обчислення кількості комбінацій/перестановок @staticmethod def comb_number(seq, k): N...
yield res
random_line_split
contextmenu.js
() { var top = menustack.pop(); hideMenu(top); return top; } // Context menu operation complete. Triggered by multiple things. function mouseend() { overlay.style.opacity = "0.0"; mousedown_timeout = setTimeout(function () { while (menustack.length) { ...
//Left 1px border shouldn't be included. //Close the menu: (bubble event) return; } } e.stopPropagation(); e.preventDefault(); return false; } function onsubcontextmenuout(e) { // Cancel any other previews ...
// menu.onmousedown function onmousedown(e) { if (e.target.nodeName === menuNodeName) { if (e.offsetX === 0) {
random_line_split
contextmenu.js
menu() { var top = menustack.pop(); hideMenu(top); return top; } // Context menu operation complete. Triggered by multiple things. function mouseend() { overlay.style.opacity = "0.0"; mousedown_timeout = setTimeout(function () { while (menustack.length) {...
(menu) { if (overlay) { overlay.appendChild(menu); } else { toAppend.push(menu); } } // Adds javascript code, so it works without native html5 contextmenu support function prepareMenu(menu) { var p = menu.parentNode, clone; ...
appendToOverlay
identifier_name
contextmenu.js
() { var top = menustack.pop(); hideMenu(top); return top; } // Context menu operation complete. Triggered by multiple things. function mouseend() { overlay.style.opacity = "0.0"; mousedown_timeout = setTimeout(function () { while (menustack.length) { ...
} function initContextMenu(menu, x, y) { t = new Date(); menustack.push(menu); menu.style.top = Math.max(y - 5, 0) + "px"; menu.style.left = x + "px"; showMenu(menu); overlay.style.display = "block"; holding = false; // Make sure contextmenu stay...
{ p.removeChild(menu); appendToOverlay(menu); }
conditional_block
contextmenu.js
() { var top = menustack.pop(); hideMenu(top); return top; } // Context menu operation complete. Triggered by multiple things. function mouseend() { overlay.style.opacity = "0.0"; mousedown_timeout = setTimeout(function () { while (menustack.length) { ...
function inititalize() { menustack = []; overlay = d.createElement("div"); // Style: var os_code = "osx10_7", mouseup_wait_for_me = 0; if (/Mac/.test(navigator.userAgent)) { os_code = "osx10_7"; } else if (/Win/.test(navigator.userAge...
{ doneEvents.forEach(function (f) { try{ f(); } catch(ex) { setTimeout(function (){ throw ex; }, 0); } }); doneEvents = []; }
identifier_body
Cartridge2k.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
const paddedBuffer = new Uint8Array(paddedLength); for (let i = 0; i < paddedLength; i++) { paddedBuffer[paddedLength - i - 1] = i < buffer.length ? buffer[buffer.length - i - 1] : 0; } return paddedBuffer; } class Cartridge2k extends AbstractCartridge { constructor(buffer: { [i: number...
{ return buffer; }
conditional_block
Cartridge2k.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
function padBuffer(buffer: ArrayLike<number>): ArrayLike<number> { const paddedLength = nextPowerOfTwo(buffer.length); if (paddedLength === buffer.length) { return buffer; } const paddedBuffer = new Uint8Array(paddedLength); for (let i = 0; i < paddedLength; i++) { paddedBuffer[pa...
} return v; }
random_line_split
Cartridge2k.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
extends AbstractCartridge { constructor(buffer: { [i: number]: number; length: number }) { super(); if (buffer.length > 0x0800) { throw new Error(`buffer is not a 2k cartridge image: wrong length ${buffer.length}`); } const paddedBuffer = padBuffer(buffer); fo...
Cartridge2k
identifier_name
Cartridge2k.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
// A11 - A15 masked out -> 0x0800 bytes of ROM protected _rom = new Uint8Array(0x0800); } export { Cartridge2k as default };
{ return CartridgeInfo.CartridgeType.vanilla_2k; }
identifier_body
lib.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License....
//
random_line_split
staffing_plan.js
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on('Staffing Plan', { setup: function(frm) { frm.set_query("designation", "staffing_details", function() { let designations = []; $.each(frm.doc.staffing_details, function(in...
}); frappe.ui.form.on('Staffing Plan Detail', { designation: function(frm, cdt, cdn) { let child = locals[cdt][cdn] if(frm.doc.company && child.designation){ frappe.call({ "method": "erpnext.hr.doctype.staffing_plan.staffing_plan.get_designation_counts", args: { designation: child.designation, ...
}; }); }
random_line_split
staffing_plan.js
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on('Staffing Plan', { setup: function(frm) { frm.set_query("designation", "staffing_details", function() { let designations = []; $.each(frm.doc.staffing_details, function(in...
}); } }, number_of_positions: function(frm, cdt, cdn) { set_vacancies(frm, cdt, cdn); }, current_count: function(frm, cdt, cdn) { set_vacancies(frm, cdt, cdn); }, estimated_cost_per_position: function(frm, cdt, cdn) { let child = locals[cdt][cdn]; set_total_estimated_cost(frm, cdt, cdn); } }); ...
{ frappe.call({ "method": "erpnext.hr.doctype.staffing_plan.staffing_plan.get_designation_counts", args: { designation: child.designation, company: frm.doc.company }, callback: function (data) { if(data.message){ frappe.model.set_value(cdt, cdn, 'current_count', data.message.empl...
conditional_block
TardisGallery.server.js
var mach = require("mach"); var Ambidex = require("../../Ambidex.server.js"); var utilities = require("../utilities.js"); function
( { ambidexPromises, settings } ) { var customSettings = settings; settings = utilities.recursiveCloneWithDefaults( customSettings, require("./settings.default.js") ); // Introspect URLS from ambidexes, if they aren't already set if (settings.URLS) { settings.APPEND_PATH_TO_URLS = cu...
TardisGallery
identifier_name
TardisGallery.server.js
var mach = require("mach"); var Ambidex = require("../../Ambidex.server.js"); var utilities = require("../utilities.js"); function TardisGallery( { ambidexPromises, settings } )
} } else { settings.URLS = ambidexPromises.map( promise => { var { HOST, PORT } = promise.ambidexInProgress._get("settings"); return `//${ HOST }:${ PORT }` } ); } var self = new Ambidex({ settings }); self.mapper = mach.mapper(); ambidexPromises = ambidexPromises.co...
{ var customSettings = settings; settings = utilities.recursiveCloneWithDefaults( customSettings, require("./settings.default.js") ); // Introspect URLS from ambidexes, if they aren't already set if (settings.URLS) { settings.APPEND_PATH_TO_URLS = customSettings.APPEND_PATH_TO_URLS || false; ...
identifier_body
TardisGallery.server.js
var mach = require("mach"); var Ambidex = require("../../Ambidex.server.js"); var utilities = require("../utilities.js"); function TardisGallery( { ambidexPromises, settings } ) { var customSettings = settings;
settings = utilities.recursiveCloneWithDefaults( customSettings, require("./settings.default.js") ); // Introspect URLS from ambidexes, if they aren't already set if (settings.URLS) { settings.APPEND_PATH_TO_URLS = customSettings.APPEND_PATH_TO_URLS || false; if (ambidexPromises) { var {...
random_line_split
helpers.py
from collections import OrderedDict from django.core.cache import cache from django.conf import settings import jingo import jinja2 from bedrock.firefox.models import FirefoxOSFeedLink from bedrock.firefox.firefox_details import firefox_desktop, firefox_android from bedrock.base.urlresolvers import reverse from lib....
try: return settings.FXOS_PRESS_BLOG_LINKS[locale] except KeyError: if '-' in locale: return firefox_os_blog_link(locale.split('-')[0]) else: return None
identifier_body
helpers.py
from collections import OrderedDict from django.core.cache import cache from django.conf import settings import jingo import jinja2 from bedrock.firefox.models import FirefoxOSFeedLink from bedrock.firefox.firefox_details import firefox_desktop, firefox_android from bedrock.base.urlresolvers import reverse from lib....
(channel, builds=None): builds = builds or [] variations = OrderedDict([ ('api-9', 'Gingerbread'), ('api-11', 'Honeycomb+ ARMv7+'), ('x86', 'x86'), ]) if channel == 'alpha': for type, arch_pretty in variations.iteritems(): link = firefox_android.get_download_...
android_builds
identifier_name
helpers.py
from collections import OrderedDict from django.core.cache import cache from django.conf import settings import jingo import jinja2 from bedrock.firefox.models import FirefoxOSFeedLink from bedrock.firefox.firefox_details import firefox_desktop, firefox_android from bedrock.base.urlresolvers import reverse from lib....
'-id').values_list('link', 'title')[:10]) cache.set(cache_key, links) return links elif '-' in locale: return firefox_os_feed_links(locale.split('-')[0]) @jingo.register.function def firefox_os_blog_link(locale): try: return settings.FXOS_PRESS_BLOG_LINKS[locale...
if links: return links links = list( FirefoxOSFeedLink.objects.filter(locale=locale).order_by(
random_line_split
helpers.py
from collections import OrderedDict from django.core.cache import cache from django.conf import settings import jingo import jinja2 from bedrock.firefox.models import FirefoxOSFeedLink from bedrock.firefox.firefox_details import firefox_desktop, firefox_android from bedrock.base.urlresolvers import reverse from lib....
# will not be output, and the JS won't attempt the IE popup. if force_direct: # no need to run get_download_url again with the same args download_link_direct = False else: download_link_direct = firefox_desktop.get_download_url( ...
for plat_os, plat_os_pretty in firefox_desktop.platform_labels.iteritems(): # Windows 64-bit builds are currently available only on the Aurora # and Beta channel if plat_os == 'win64' and channel not in ['alpha', 'beta']: continue # Fallback to en-US if t...
conditional_block
analyticsadmin_v1alpha_generated_analytics_admin_service_approve_display_video360_advertiser_link_proposal_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_ApproveDisplayVideo360AdvertiserLinkProposal_sync]
client = admin_v1alpha.AnalyticsAdminServiceClient() # Initialize request argument(s) request = admin_v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) # Make the request response = client.approve_display_video360_advertiser_link_proposal(request=request) ...
identifier_body
analyticsadmin_v1alpha_generated_analytics_admin_service_approve_display_video360_advertiser_link_proposal_sync.py
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under ...
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC
random_line_split
analyticsadmin_v1alpha_generated_analytics_admin_service_approve_display_video360_advertiser_link_proposal_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): # Create a client client = admin_v1alpha.AnalyticsAdminServiceClient() # Initialize request argument(s) request = admin_v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) # Make the request response = client.approve_display_video360_advertiser_lin...
sample_approve_display_video360_advertiser_link_proposal
identifier_name
mapSequence.js
'use strict'; import isPlainObject from 'lodash/lang/isPlainObject'; import mapValues from 'lodash/object/mapValues'; import isArrayLike from './isArrayLike'; import isIterable from './isIterable'; import isIterator from './isIterator'; import mapIterator from './mapIterator'; var nativeMap = Array.prototype.map; /...
else { throw new TypeError( "Can't map value of type %s", typeof sequence ); } }
} else if(isPlainObject(sequence)) { return mapValues(sequence, callback, thisObj); }
random_line_split
mapSequence.js
'use strict'; import isPlainObject from 'lodash/lang/isPlainObject'; import mapValues from 'lodash/object/mapValues'; import isArrayLike from './isArrayLike'; import isIterable from './isIterable'; import isIterator from './isIterator'; import mapIterator from './mapIterator'; var nativeMap = Array.prototype.map; /...
{ if (isArrayLike(sequence)) { return nativeMap.call(sequence, callback, thisObj); } else if (isIterable(sequence)) { sequence = sequence[Symbol.iterator](); } if (isIterator(sequence)) { return mapIterator(sequence, callback, thisObj); } else if(isPlainObject(sequence)) { return mapValues...
identifier_body
mapSequence.js
'use strict'; import isPlainObject from 'lodash/lang/isPlainObject'; import mapValues from 'lodash/object/mapValues'; import isArrayLike from './isArrayLike'; import isIterable from './isIterable'; import isIterator from './isIterator'; import mapIterator from './mapIterator'; var nativeMap = Array.prototype.map; /...
(sequence, callback, thisObj) { if (isArrayLike(sequence)) { return nativeMap.call(sequence, callback, thisObj); } else if (isIterable(sequence)) { sequence = sequence[Symbol.iterator](); } if (isIterator(sequence)) { return mapIterator(sequence, callback, thisObj); } else if(isPlainObject(seq...
mapSequence
identifier_name
index.js
var decode = require('base64-decode'); var crypto = require('crypto'); var ANTI_CHEAT_CODE = 'Fe12NAfA3R6z4k0z'; var SALT = 'af0ik392jrmt0nsfdghy0'; function
(save) { if (save.indexOf(ANTI_CHEAT_CODE) > -1) { var result = save.split(ANTI_CHEAT_CODE); save = ''; for (var i = 0; i < result[0].length; i += 2) { save += result[0].charAt(i); } var md5 = crypto.createHash('md5'); md5.update(save + SALT, 'ascii'); if (md5.digest('hex') !== resu...
parse
identifier_name
index.js
var decode = require('base64-decode'); var crypto = require('crypto'); var ANTI_CHEAT_CODE = 'Fe12NAfA3R6z4k0z'; var SALT = 'af0ik392jrmt0nsfdghy0'; function parse(save) { if (save.indexOf(ANTI_CHEAT_CODE) > -1) { var result = save.split(ANTI_CHEAT_CODE); save = ''; for (var i = 0; i < result[0].length;...
throw new Error('Anti-cheat code not found'); } var data = JSON.parse(decode(save)); return data; } module.exports = parse;
else {
random_line_split
index.js
var decode = require('base64-decode'); var crypto = require('crypto'); var ANTI_CHEAT_CODE = 'Fe12NAfA3R6z4k0z'; var SALT = 'af0ik392jrmt0nsfdghy0'; function parse(save) { if (save.indexOf(ANTI_CHEAT_CODE) > -1) { var result = save.split(ANTI_CHEAT_CODE); save = ''; for (var i = 0; i < result[0].length;...
} else { throw new Error('Anti-cheat code not found'); } var data = JSON.parse(decode(save)); return data; } module.exports = parse;
{ throw new Error('Bad hash'); }
conditional_block
index.js
var decode = require('base64-decode'); var crypto = require('crypto'); var ANTI_CHEAT_CODE = 'Fe12NAfA3R6z4k0z'; var SALT = 'af0ik392jrmt0nsfdghy0'; function parse(save)
} module.exports = parse;
{ if (save.indexOf(ANTI_CHEAT_CODE) > -1) { var result = save.split(ANTI_CHEAT_CODE); save = ''; for (var i = 0; i < result[0].length; i += 2) { save += result[0].charAt(i); } var md5 = crypto.createHash('md5'); md5.update(save + SALT, 'ascii'); if (md5.digest('hex') !== result[1]) ...
identifier_body
id_type.rs
found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied...
() -> IdType { IdType::new(&RevocationIdType::new::<MaidTypeTags>()) } } #[test] fn serialisation_maid() { use helper::*; let obj_before = IdType::generate_random(); let mut e = cbor::Encoder::from_memory(); e.encode(&[&obj_before]).unwrap(); let mu...
generate_random
identifier_name
id_type.rs
in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // /...
let type_tag: u64 = match String::from_utf8(tag_type_vec) { Ok(string) => { match string.parse::<u64>() { Ok(type_tag) => type_tag, Err(_) => return Err(d.error("Bad Tag Type")) } }, Err(_) => return E...
{ return Err(d.error("Bad IdType size")); }
conditional_block
id_type.rs
// // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions...
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
random_line_split
id_type.rs
in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // /...
/// Returns the PublicKeys pub fn public_keys(&self) -> &(crypto::sign::PublicKey, crypto::asymmetricbox::PublicKey){ &self.public_keys } /// Returns the PublicKeys pub fn secret_keys(&self) -> &(crypto::sign::SecretKey, crypto::asymmetricbox::SecretKey) { &self.secret_keys } ...
{ let combined_iter = (&self.public_keys.0).0.into_iter().chain((&self.public_keys.1).0.into_iter()); let mut combined: Vec<u8> = Vec::new(); for iter in combined_iter { combined.push(*iter); } for i in self.type_tag.to_string().into_bytes().into_iter() { ...
identifier_body
tasks_widget_spec.tsx
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
});
helper.clickByTestId("Delete-icon"); expect(helper.textByTestId("selected-task")).toBe(sleepTask.represent()); expect(helper.text("pre")).toBe(sleepTask.represent()); });
random_line_split
scrapeAndSaver.ts
import models = require('../data/models'); import database = require('../data/database'); import scraper = require('./realEstateScraper'); /* Loop through search results Insert / Update result in database Loop through non-archived properties in database matching search with update time != 'TODAY' Rescrape an...
/* function rescrapeExistingPropertiesMatchingSearch( search: models.ISearch, options: { progress: () => any, done: () => any }) { var url = scraper.getSearchUrl(search); scraper.scrapeRentalPropertyPage(url, (err, property) => { }); } */
{ database.properties.insert(property, done); }
identifier_body
scrapeAndSaver.ts
import models = require('../data/models'); import database = require('../data/database'); import scraper = require('./realEstateScraper'); /* Loop through search results Insert / Update result in database Loop through non-archived properties in database matching search with update time != 'TODAY' Rescrape an...
( search: models.ISearch, options?: { progress?: (operations: { message: string }) => any, done?: (operations: { inserts: number, updates: number, errors: number }) => any }) { var url = scraper.getSearchUrl(search); var operations = { inserts: 0, updates: 0, errors: 0 }; // Defa...
scrapeAndSaveListings
identifier_name
scrapeAndSaver.ts
import models = require('../data/models'); import database = require('../data/database'); import scraper = require('./realEstateScraper'); /* Loop through search results Insert / Update result in database Loop through non-archived properties in database matching search with update time != 'TODAY' Rescrape an...
vendorId: listing.vendorId }, (err, existing) => { if (err) { done(err); } else if (existing) { updateProperty(existing, property, err => { if (err) { done(err); } else { done(null, SaveOperation.Update); } }); } else { insertProper...
database.properties.findOne({ vendor: listing.vendor,
random_line_split
TestSerializationSorted.py
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
] }}""" ) .format('",\n "'.join(sorted(unsorted_set))) .encode() ) sorted_struct = readStructFromJSON(unsorted_blob, SortedSetStruct) blob = writeToJSON(sorted_struct) self.assertNotEqual(blob, unsorted_blob) self.a...
unsorted_set = set(["5", "4", "3", "2", "1", "0"]) static_struct = SortedSetStruct(aSet=unsorted_set) unsorted_blob = ( textwrap.dedent( """\ {{ "aSet": [ "{}" ] }}""" ) .format('",\n ...
identifier_body
TestSerializationSorted.py
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
def testNegativeId(self): obj = NegativeId() self.assertEqual(obj.field1, 1) self.assertEqual(obj.field2, 2) self.assertEqual(obj.field3, 3)
self.assertEqual(static_struct, sorted_struct)
random_line_split
TestSerializationSorted.py
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
(unittest.TestCase): def testSorted(self): static_struct = SortedStruct(aMap={"b": 1.0, "a": 1.0}) unsorted_blob = b'{\n "aMap": {\n "b": 1.0,\n "a": 1.0\n }\n}' sorted_blob = b'{\n "aMap": {\n "a": 1.0,\n "b": 1.0\n }\n}' sorted_struct = readStructFromJSON(unsorted_b...
TestSortKeys
identifier_name
schema2.rs
use types::{ColumnType}; pub trait Schema { fn len(&self) -> usize; fn name(&self, index: usize) -> &str; fn ctype(&self, index: usize) -> ColumnType; fn nullable(&self, index: usize) -> bool;
pub names: Vec<String>, pub types: Vec<ColumnType>, pub nullable: Vec<bool>, } impl Schema2 { pub fn new() -> Self { Schema2 { names: Vec::new(), types: Vec::new(), nullable: Vec::new(), } } pub fn add(&mut self, name: &str, ...
} #[derive(Clone)] pub struct Schema2 {
random_line_split
schema2.rs
use types::{ColumnType}; pub trait Schema { fn len(&self) -> usize; fn name(&self, index: usize) -> &str; fn ctype(&self, index: usize) -> ColumnType; fn nullable(&self, index: usize) -> bool; } #[derive(Clone)] pub struct
{ pub names: Vec<String>, pub types: Vec<ColumnType>, pub nullable: Vec<bool>, } impl Schema2 { pub fn new() -> Self { Schema2 { names: Vec::new(), types: Vec::new(), nullable: Vec::new(), } } pub fn add(&mut self, name: &str,...
Schema2
identifier_name
schema2.rs
use types::{ColumnType}; pub trait Schema { fn len(&self) -> usize; fn name(&self, index: usize) -> &str; fn ctype(&self, index: usize) -> ColumnType; fn nullable(&self, index: usize) -> bool; } #[derive(Clone)] pub struct Schema2 { pub names: Vec<String>, pub types: Vec<ColumnType>, pub n...
pub fn set_nullable(&mut self, index: usize, nullability: bool) { self.nullable[index] = nullability; } } impl Schema for Schema2 { fn len(&self) -> usize { self.names.len() } fn name(&self, index: usize) -> &str { self.names[index].as_str() } fn ctype(&self, ind...
{ self.names.push(name.to_string()); self.types.push(ctype); self.nullable.push(nullable); }
identifier_body
lib.rs
self.name, self.value_string(), self.value_binary_string(), ) } } } /// An error decoding an ESR value. #[derive(Debug, Error)] pub enum DecodeError { /// A RES0 field was not 0. #[error("Invalid ESR, res0 is {res0:#x}")] InvalidRes0 { res0: u64 }, ...
describe_il
identifier_name
lib.rs
, Eq, PartialEq)] pub struct FieldInfo { /// The short name of the field, e.g. "ISS". pub name: &'static str, /// The long name of the field, e.g. "Instruction Specific Syndrome". pub long_name: Option<&'static str>, /// The index of the lowest bit of the field. pub start: usize, /// The num...
fn check_res0(self) -> Result<Self, DecodeError> { if self.value != 0 { Err(DecodeError::InvalidRes0 { res0: self.value }) } else { Ok(self) } } /// Returns the value as a hexadecimal string, or "true" or "false" if it is a single bit. pub fn value_stri...
{ let description = describer(self.value)?.to_string(); Ok(self.with_description(description)) }
identifier_body