file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
views.py
from django.views import generic from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import tabs from horizon import tables from billingdashboard.co...
class IndexView(tables.DataTableView): table_class = invoice_table.UserInvoiceListingTable template_name = 'project/cust_invoice/index.html' page_title = _("Invoices") def get_data(self): return get_user_invoices(self.request, verbose=True) class UserInvoiceDetailsView(generic.Templa...
random_line_split
views.py
from django.views import generic from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import tabs from horizon import tables from billingdashboard.co...
(self): return get_user_invoices(self.request, verbose=True) class UserInvoiceDetailsView(generic.TemplateView): template_name = 'project/cust_invoice/invoice.html' def get_context_data(self, **kwargs): context = super(UserInvoiceDetailsView, self).get_context_data(**kwargs) id = s...
get_data
identifier_name
views.py
from django.views import generic from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import tabs from horizon import tables from billingdashboard.co...
template_name = 'project/cust_invoice/invoice.html' def get_context_data(self, **kwargs): context = super(UserInvoiceDetailsView, self).get_context_data(**kwargs) id = self.kwargs['invoice_id'] context['invoice'] = get_invoice(self.request, id, verbose=True) return context
identifier_body
test.py
import os import gc import platform import sys import time import tempfile import warnings from optparse import OptionParser import gpaw.mpi as mpi from gpaw.hooks import hooks from gpaw import debug from gpaw.version import version def run(): description = ('Run the GPAW test suite. The test suite can be run i...
help='Show standard output from tests.') opt, tests = parser.parse_args() if len(tests) == 0: from gpaw.test import tests if opt.reverse: tests.reverse() if opt.run_failed_tests_only: tests = [line.strip() for line in open('failed-tests.txt')] excl...
parser.add_option('-d', '--directory', help='Run test in this directory') parser.add_option('-s', '--show-output', action='store_true',
random_line_split
test.py
import os import gc import platform import sys import time import tempfile import warnings from optparse import OptionParser import gpaw.mpi as mpi from gpaw.hooks import hooks from gpaw import debug from gpaw.version import version def run():
if __name__ == '__main__': run()
description = ('Run the GPAW test suite. The test suite can be run in ' 'parallel with MPI through gpaw-python. The test suite ' 'supports 1, 2, 4 or 8 CPUs although some tests are ' 'skipped for some parallelizations. If no TESTs are ' 'giv...
identifier_body
test.py
import os import gc import platform import sys import time import tempfile import warnings from optparse import OptionParser import gpaw.mpi as mpi from gpaw.hooks import hooks from gpaw import debug from gpaw.version import version def
(): description = ('Run the GPAW test suite. The test suite can be run in ' 'parallel with MPI through gpaw-python. The test suite ' 'supports 1, 2, 4 or 8 CPUs although some tests are ' 'skipped for some parallelizations. If no TESTs are ' ...
run
identifier_name
test.py
import os import gc import platform import sys import time import tempfile import warnings from optparse import OptionParser import gpaw.mpi as mpi from gpaw.hooks import hooks from gpaw import debug from gpaw.version import version def run(): description = ('Run the GPAW test suite. The test suite can be run i...
elif not opt.keep_tmpdir: os.system('rm -rf ' + tmpdir) hooks.update(old_hooks.items()) return len(failed) if __name__ == '__main__': run()
open('failed-tests.txt', 'w').write('\n'.join(failed) + '\n')
conditional_block
cardlist_component_test.js
// Copyright 2017 The Kubernetes Dashboard Authors. // // 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
// 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....
// // http://www.apache.org/licenses/LICENSE-2.0 //
random_line_split
parser.rs
#![plugin(peg_syntax_ext)] use std::fmt; use std::collections::HashMap; peg_file! gremlin("gremlin.rustpeg"); pub fn parse(g: &str) -> Result<ParsedGraphQuery, gremlin::ParseError> { let parsed = pre_parse(g); // verify all the steps actually make sense // is it a query to a single vertex or a global que...
} /* generic step used in ParsedGraphQuery will be turned into specific steps */ #[derive(Debug)] pub struct RawStep { pub name: String, pub args: Vec<Arg>, } #[derive(Debug, Display)] pub enum Arg { Integer(i64), Float(f64), String(String), } impl RawStep { pub fn new(name: String, args: Vec...
*/ pub enum Scope { Global, Vertex(Vec<i64>),
random_line_split
parser.rs
#![plugin(peg_syntax_ext)] use std::fmt; use std::collections::HashMap; peg_file! gremlin("gremlin.rustpeg"); pub fn parse(g: &str) -> Result<ParsedGraphQuery, gremlin::ParseError> { let parsed = pre_parse(g); // verify all the steps actually make sense // is it a query to a single vertex or a global que...
{ pub name: String, pub args: Vec<Arg>, } #[derive(Debug, Display)] pub enum Arg { Integer(i64), Float(f64), String(String), } impl RawStep { pub fn new(name: String, args: Vec<Arg>) -> RawStep { RawStep{name:name, args:args} } } impl fmt::Display for RawStep { fn fmt(&self, ...
RawStep
identifier_name
parser.rs
#![plugin(peg_syntax_ext)] use std::fmt; use std::collections::HashMap; peg_file! gremlin("gremlin.rustpeg"); pub fn parse(g: &str) -> Result<ParsedGraphQuery, gremlin::ParseError> { let parsed = pre_parse(g); // verify all the steps actually make sense // is it a query to a single vertex or a global que...
}
{ write!(f, "RawStep {}", self.name) }
identifier_body
ApolloContext.ts
import React from 'react'; import { ApolloClient } from '../../core'; export interface ApolloContextValue { client?: ApolloClient<object>; renderPromises?: Record<any, any>; } // To make sure Apollo Client doesn't create more than one React context // (which can lead to problems like having an Apollo Client insta...
export function getApolloContext() { if (!(React as any)[contextSymbol]) { resetApolloContext(); } return (React as any)[contextSymbol] as React.Context<ApolloContextValue>; }
{ Object.defineProperty(React, contextSymbol, { value: React.createContext<ApolloContextValue>({}), enumerable: false, configurable: true, writable: false, }); }
identifier_body
ApolloContext.ts
import React from 'react'; import { ApolloClient } from '../../core'; export interface ApolloContextValue { client?: ApolloClient<object>; renderPromises?: Record<any, any>; } // To make sure Apollo Client doesn't create more than one React context // (which can lead to problems like having an Apollo Client insta...
() { Object.defineProperty(React, contextSymbol, { value: React.createContext<ApolloContextValue>({}), enumerable: false, configurable: true, writable: false, }); } export function getApolloContext() { if (!(React as any)[contextSymbol]) { resetApolloContext(); } return (React as any)[con...
resetApolloContext
identifier_name
ApolloContext.ts
import React from 'react'; import { ApolloClient } from '../../core'; export interface ApolloContextValue { client?: ApolloClient<object>; renderPromises?: Record<any, any>; } // To make sure Apollo Client doesn't create more than one React context // (which can lead to problems like having an Apollo Client insta...
return (React as any)[contextSymbol] as React.Context<ApolloContextValue>; }
{ resetApolloContext(); }
conditional_block
ApolloContext.ts
import React from 'react'; import { ApolloClient } from '../../core'; export interface ApolloContextValue { client?: ApolloClient<object>; renderPromises?: Record<any, any>; } // To make sure Apollo Client doesn't create more than one React context // (which can lead to problems like having an Apollo Client insta...
resetApolloContext(); } return (React as any)[contextSymbol] as React.Context<ApolloContextValue>; }
} export function getApolloContext() { if (!(React as any)[contextSymbol]) {
random_line_split
setup_wizard.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, json, copy from frappe.utils import cstr, flt, getdate from frappe import _ from frappe.utils.file_manager import save_file from frappe....
"""update Activity feed and create todo for creation of item, customer, vendor""" frappe.get_doc({ "doctype": "Feed", "feed_type": "Comment", "subject": "ERPNext Setup Complete!" }).insert(ignore_permissions=True) def create_email_digest(): from frappe.utils.user import get_system_managers system_managers =...
def create_feed_and_todo():
random_line_split
setup_wizard.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, json, copy from frappe.utils import cstr, flt, getdate from frappe import _ from frappe.utils.file_manager import save_file from frappe....
def get_fy_details(fy_start_date, fy_end_date): start_year = getdate(fy_start_date).year if start_year == getdate(fy_end_date).year: fy = cstr(start_year) else: fy = cstr(start_year) + '-' + cstr(start_year + 1) return fy def create_taxes(args): for i in xrange(1,6): if args.get("tax_" + str(i)): # rep...
edigest = frappe.new_doc("Email Digest") edigest.update({ "name": "Scheduler Errors", "company": companies[0], "frequency": "Daily", "recipient_list": "\n".join(system_managers), "scheduler_errors": 1, "enabled": 1 }) edigest.insert()
conditional_block
setup_wizard.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, json, copy from frappe.utils import cstr, flt, getdate from frappe import _ from frappe.utils.file_manager import save_file from frappe....
(): return { "default_language": get_language_from_code(frappe.local.lang), "languages": sorted(get_lang_dict().keys()) }
load_languages
identifier_name
setup_wizard.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, json, copy from frappe.utils import cstr, flt, getdate from frappe import _ from frappe.utils.file_manager import save_file from frappe....
def create_logo(args): if args.get("attach_logo"): attach_logo = args.get("attach_logo").split(",") if len(attach_logo)==3: filename, filetype, content = attach_logo fileurl = save_file(filename, content, "Website Settings", "Website Settings", decode=True).file_url frappe.db.set_value("Website Sett...
if args.get("attach_letterhead"): frappe.get_doc({ "doctype":"Letter Head", "letter_head_name": _("Standard"), "is_default": 1 }).insert() attach_letterhead = args.get("attach_letterhead").split(",") if len(attach_letterhead)==3: filename, filetype, content = attach_letterhead fileurl = save_fil...
identifier_body
inputcontainer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # Copyright (c) 2014 Kevin B. Hendricks, John Schember, and Doug Massay # All rights reserved. #
# Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # # 2. Redistributions in binary form m...
random_line_split
inputcontainer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # Copyright (c) 2014 Kevin B. Hendricks, John Schember, and Doug Massay # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following ...
self._w.addotherfile(book_href, data)
identifier_body
inputcontainer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # Copyright (c) 2014 Kevin B. Hendricks, John Schember, and Doug Massay # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following ...
(self, book_href, data): # creates a new file not in manifest with desired ebook root relative href self._w.addotherfile(book_href, data)
addotherfile
identifier_name
generate_projects.py
import os, sys, multiprocessing, subprocess from build_util import * if __name__ == "__main__": cfg = cfg_from_argv(sys.argv) bi = build_info(cfg.compiler, cfg.archs, cfg.cfg) print("Starting build project: " + build_cfg.project_name + " ...") additional_options = "-DCFG_PROJECT_NAME:STRING=\"%s\"" % build_cfg.pr...
print("Generating %s..." % (build_cfg.project_name)) for info in bi.compilers: build_project(build_cfg.project_name, build_cfg.build_path, bi, "../cmake", info, False, False, additional_options)
random_line_split
generate_projects.py
import os, sys, multiprocessing, subprocess from build_util import * if __name__ == "__main__": cfg = cfg_from_argv(sys.argv) bi = build_info(cfg.compiler, cfg.archs, cfg.cfg) print("Starting build project: " + build_cfg.project_name + " ...") additional_options = "-DCFG_PROJECT_NAME:STRING=\"%s\"" % build_cfg.pr...
build_project(build_cfg.project_name, build_cfg.build_path, bi, "../cmake", info, False, False, additional_options)
conditional_block
CdaQuery.ext.js
/*! * Copyright 2002 - 2017 Webdetails, a Hitachi Vantara company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a ...
*/ define('cdf/queries/CdaQuery.ext', [], function() { var CdaQueryExt = { getDoQuery: function() { return ""; }, getWebsocketQuery: function() { return ""; }, getUnwrapQuery: function(parameters) { return ""; } }; return CdaQueryExt; });
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and...
random_line_split
week2-01-Keras-Tutorial.py
import numpy as np from keras import layers from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D from keras.models import Model from keras.preprocessing import im...
""" Implementation of the HappyModel. Arguments: input_shape -- shape of the images of the dataset Returns: model -- a Model() instance in Keras """ ### START CODE HERE ### # Feel free to use the suggested outline in the text above to get started, and run through the whole...
def HappyModel(input_shape):
random_line_split
week2-01-Keras-Tutorial.py
import numpy as np from keras import layers from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D from keras.models import Model from keras.preprocessing import im...
#https://keras.io/models/model/ happyModel = HappyModel((64,64,3,)) happyModel.compile(loss='mean_squared_error', optimizer='sgd') happyModel.fit(x=X_train, y=Y_train, epochs=1) ### START CODE HERE ### (1 line) preds = happyModel.predict(x=X_test) #happyModel.evaluate(x=X_test, y=Y_test) #print(preds,happyModel.metr...
""" Implementation of the HappyModel. Arguments: input_shape -- shape of the images of the dataset Returns: model -- a Model() instance in Keras """ ### START CODE HERE ### # Feel free to use the suggested outline in the text above to get started, and run through the whole ...
identifier_body
week2-01-Keras-Tutorial.py
import numpy as np from keras import layers from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D from keras.models import Model from keras.preprocessing import im...
(input_shape): """ Implementation of the HappyModel. Arguments: input_shape -- shape of the images of the dataset Returns: model -- a Model() instance in Keras """ ### START CODE HERE ### # Feel free to use the suggested outline in the text above to get started, and run th...
HappyModel
identifier_name
config.rs
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr}; use std::str::FromStr; use std::any::TypeId; use std::mem::swap; use std::time::Duration; use anymap::Map; use anymap::any::{Any, UncheckedAnyExt}; ///HTTP or HTTPS. pub enum Scheme { ///Standard HTTP. Http, ///HTTP with SSL encryption. ...
///Settings for `keep-alive` connections to the server. pub struct KeepAlive { ///How long a `keep-alive` connection may idle before it's forced close. pub timeout: Duration, ///The number of threads in the thread pool that should be kept free from ///idling threads. Connections will be closed if the ...
}
random_line_split
config.rs
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr}; use std::str::FromStr; use std::any::TypeId; use std::mem::swap; use std::time::Duration; use anymap::Map; use anymap::any::{Any, UncheckedAnyExt}; ///HTTP or HTTPS. pub enum Scheme { ///Standard HTTP. Http, ///HTTP with SSL encryption. ...
() -> Global { Global(GlobalState::None) } } enum GlobalState { None, One(TypeId, Box<Any + Send + Sync>), Many(Map<Any + Send + Sync>), } ///Settings for `keep-alive` connections to the server. pub struct KeepAlive { ///How long a `keep-alive` connection may idle before it's forced close....
default
identifier_name
config.rs
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr}; use std::str::FromStr; use std::any::TypeId; use std::mem::swap; use std::time::Duration; use anymap::Map; use anymap::any::{Any, UncheckedAnyExt}; ///HTTP or HTTPS. pub enum Scheme { ///Standard HTTP. Http, ///HTTP with SSL encryption. ...
} impl<T: Any + Send + Sync> From<Box<T>> for Global { fn from(data: Box<T>) -> Global { Global(GlobalState::One(TypeId::of::<T>(), data)) } } macro_rules! from_tuple { ($first: ident, $($t: ident),+) => ( impl<$first: Any + Send + Sync, $($t: Any + Send + Sync),+> From<($first, $($t),+)>...
{ match self.0 { GlobalState::None => { *self = Box::new(value).into(); None }, GlobalState::One(id, _) => if id == TypeId::of::<T>() { if let GlobalState::One(_, ref mut previous_value) = self.0 { let mut v ...
identifier_body
Admin.py
# -*- coding: utf-8 -*- """ Created on Feb 09, 2018 @author: Tyranic-Moron """ from twisted.plugin import IPlugin from pymoronbot.moduleinterface import IModule from pymoronbot.modules.commandinterface import BotCommand, admin from zope.interface import implementer import re from collections import OrderedDict from ...
(BotCommand): def triggers(self): return ['admin'] @admin("Only my admins may add new admins!") def _add(self, message): """add <nick/full hostmask> - adds the specified user to the bot admins list. You can list multiple users to add them all at once. Nick alone will be conv...
Admin
identifier_name
Admin.py
# -*- coding: utf-8 -*- """ Created on Feb 09, 2018 @author: Tyranic-Moron """ from twisted.plugin import IPlugin from pymoronbot.moduleinterface import IModule from pymoronbot.modules.commandinterface import BotCommand, admin from zope.interface import implementer import re from collections import OrderedDict from ...
self.bot.config.writeConfig() return IRCResponse(ResponseType.Say, u"Added specified users as bot admins!", message.ReplyTo) @admin("Only my admins may remove admins!") def _del(self, message): """del <full hostmask> - removes the ...
if message.ReplyTo in self.bot.channels: if admin in self.bot.channels[message.ReplyTo].Users: user = self.bot.channels[message.ReplyTo].Users[admin] admin = u'*!{}@{}'.format(user.User, user.Hostmask) admins = self.bot.config.getWithDefault('admins',...
conditional_block
Admin.py
# -*- coding: utf-8 -*- """ Created on Feb 09, 2018 @author: Tyranic-Moron """ from twisted.plugin import IPlugin from pymoronbot.moduleinterface import IModule from pymoronbot.modules.commandinterface import BotCommand, admin from zope.interface import implementer import re from collections import OrderedDict from ...
def _add(self, message): """add <nick/full hostmask> - adds the specified user to the bot admins list. You can list multiple users to add them all at once. Nick alone will be converted to a glob hostmask, eg: *!user@host""" if len(message.ParameterList) < 2: return IRCRe...
@admin("Only my admins may add new admins!")
random_line_split
Admin.py
# -*- coding: utf-8 -*- """ Created on Feb 09, 2018 @author: Tyranic-Moron """ from twisted.plugin import IPlugin from pymoronbot.moduleinterface import IModule from pymoronbot.modules.commandinterface import BotCommand, admin from zope.interface import implementer import re from collections import OrderedDict from ...
adminCommand = Admin()
def triggers(self): return ['admin'] @admin("Only my admins may add new admins!") def _add(self, message): """add <nick/full hostmask> - adds the specified user to the bot admins list. You can list multiple users to add them all at once. Nick alone will be converted to a glob ho...
identifier_body
parse.py
#!/usr/bin/env python import re import string import sys import os USAGE = 'USAGE: parse.y <player.h> <playercore_casts.i> <playercore_arraysofclasses.i> <Jplayercore> <playercore> <player.java>' if __name__ == '__main__': if len(sys.argv) != 7: print USAGE sys.exit(-1) infilename = sys.argv[1] outfi...
pcjfile.write(' public static ' + jclass + ' ' + buf_to_Jname + '(SWIGTYPE_p_void buf) {\n') pcjfile.write(' ' + typename + ' data = playercore_java.' + buf_to_name + '(buf);\n') pcjfile.write(' return(' + typename + '_to_' + jclass + '(data));\n') pcjfile.write(' }\n\n') # Static method in...
# Static method in class playercore to convert from SWIGTYPE_p_void # to non-JNI Java object.
random_line_split
parse.py
#!/usr/bin/env python import re import string import sys import os USAGE = 'USAGE: parse.y <player.h> <playercore_casts.i> <playercore_arraysofclasses.i> <Jplayercore> <playercore> <player.java>' if __name__ == '__main__': if len(sys.argv) != 7: print USAGE sys.exit(-1) infilename = sys.argv[1] outfi...
# iterate through each variable for var in vars: varstring = var.string[var.start(1):var.end(1)] # is it an array or a scalar? arraysize = arraypattern.findall(varstring) if len(arraysize) > 0: arraysize = arraysize[0] varstring = arraypattern.sub('', va...
jtype = 'J' + type builtin_type = 0
conditional_block
workqueue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
(&mut self) { // Tell the workers to start. let mut work_count = AtomicUint::new(self.work_count); for worker in self.workers.mut_iter() { worker.chan.send(StartMsg(worker.deque.take_unwrap(), &mut work_count, &self.data)) } // Wait for the work to finish. dr...
run
identifier_name
workqueue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
// // FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug. loop { // FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue // cross-crate. let mut work_unit = unsafe { ...
ExitMsg => return, }; // We're off!
random_line_split
workqueue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
/// Synchronously runs all the enqueued tasks and waits for them to complete. pub fn run(&mut self) { // Tell the workers to start. let mut work_count = AtomicUint::new(self.work_count); for worker in self.workers.mut_iter() { worker.chan.send(StartMsg(worker.deque.take_unw...
{ match self.workers[0].deque { None => { fail!("tried to push a block but we don't have the deque?!") } Some(ref mut deque) => deque.push(work_unit), } self.work_count += 1 }
identifier_body
workqueue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
} } // Give the deque back to the supervisor. self.chan.send(ReturnDequeMsg(self.index, deque)) } } } /// A handle to the work queue that individual work units have. pub struct WorkerProxy<'a,QUD,WUD> { priv worker: &'a mut Worker<WorkUnit<QUD,WUD>>...
{ self.chan.send(FinishedMsg) }
conditional_block
onlinemlp_backend.py
from .base_backend import BaseBackend class MlpBackend(BaseBackend): def __init__(self, inpmulti, hidmulti, outmulti, learning_rate, inp96, hid96, out96, path, buffsize, mean, std, statspath): from neupre.misc.builders import build_model_mlp super(MlpBackend, self).__init__(int(buffsize)) ...
(self): log2 = self.model_multistep.fit(self.X_train_multistep, self.y_train_multistep, batch_size=10, nb_epoch=2, validation_split=0.1, verbose=1) log3 = self.model_onestep96.fit(self.X_train_onestep96, self.y_train_onestep96, batch_size=10, nb_epoch=2, ...
train
identifier_name
onlinemlp_backend.py
from .base_backend import BaseBackend class MlpBackend(BaseBackend):
def __init__(self, inpmulti, hidmulti, outmulti, learning_rate, inp96, hid96, out96, path, buffsize, mean, std, statspath): from neupre.misc.builders import build_model_mlp super(MlpBackend, self).__init__(int(buffsize)) self.model_multistep = build_model_mlp(inpmulti, hidmulti, outmulti) ...
identifier_body
onlinemlp_backend.py
from .base_backend import BaseBackend
from neupre.misc.builders import build_model_mlp super(MlpBackend, self).__init__(int(buffsize)) self.model_multistep = build_model_mlp(inpmulti, hidmulti, outmulti) self.model_onestep96 = build_model_mlp(inp96, hid96, out96) self.initialize(False, path, mean, std, statspath) ...
class MlpBackend(BaseBackend): def __init__(self, inpmulti, hidmulti, outmulti, learning_rate, inp96, hid96, out96, path, buffsize, mean, std, statspath):
random_line_split
plot.py
from docutils.parsers.rst import directives from sphinx.util.docutils import SphinxDirective from docutils import nodes import os import importlib.util class
(SphinxDirective): """ Sphinx class for execute_code directive """ has_content = False required_arguments = 0 optional_arguments = 2 option_spec = { 'filename': directives.path, 'screenshot': directives.flag } def run(self): """ Executes python code for an RST d...
K3D_Plot
identifier_name
plot.py
from docutils.parsers.rst import directives from sphinx.util.docutils import SphinxDirective from docutils import nodes import os import importlib.util class K3D_Plot(SphinxDirective): """ Sphinx class for execute_code directive """ has_content = False required_arguments = 0 optional_arguments = 2...
return output
output.append(nodes.raw('', code_results, format='html'))
conditional_block
plot.py
from docutils.parsers.rst import directives from sphinx.util.docutils import SphinxDirective from docutils import nodes import os import importlib.util class K3D_Plot(SphinxDirective): """ Sphinx class for execute_code directive """ has_content = False required_arguments = 0 optional_arguments = 2...
filename = self.options.get('filename') path = self.env.doc2path(self.env.docname) code_path = os.path.join(os.path.dirname(path), filename) if 'screenshot' in self.options: image_filepath = os.path.join(os.path.dirname(path), os.pat...
random_line_split
plot.py
from docutils.parsers.rst import directives from sphinx.util.docutils import SphinxDirective from docutils import nodes import os import importlib.util class K3D_Plot(SphinxDirective):
""" Sphinx class for execute_code directive """ has_content = False required_arguments = 0 optional_arguments = 2 option_spec = { 'filename': directives.path, 'screenshot': directives.flag } def run(self): """ Executes python code for an RST document, taking input f...
identifier_body
printMarkdown.js
function
(id){ hideallids(); showdiv(id); } function hideallids(){ //loop through the array and hide each element by id for (var i=0;i<ids.length;i++){ hidediv(ids[i]); } } function hidediv(id) { //safe function to hide an element with a specified id document.getElementById(id).s...
switchid
identifier_name
printMarkdown.js
function switchid(id){ hideallids(); showdiv(id); } function hideallids(){ //loop through the array and hide each element by id for (var i=0;i<ids.length;i++){ hidediv(ids[i]); } } function hidediv(id) { //safe function to hide an element with a specified id document.get...
function showdiv(id) { //safe function to show an element with a specified id document.getElementById(id).style.display = 'block'; } function printMarkdownSource() { hidediv("source"); var view = document.getElementById("view"); var source = document.getElementById("source"); view.inne...
random_line_split
printMarkdown.js
function switchid(id){ hideallids(); showdiv(id); } function hideallids(){ //loop through the array and hide each element by id for (var i=0;i<ids.length;i++){ hidediv(ids[i]); } } function hidediv(id) { //safe function to hide an element with a specified id document.get...
else { window.onload = printMarkdownSource; }
{ window.attachEvent("onload", printMarkdownSource); }
conditional_block
printMarkdown.js
function switchid(id){ hideallids(); showdiv(id); } function hideallids(){ //loop through the array and hide each element by id for (var i=0;i<ids.length;i++){ hidediv(ids[i]); } } function hidediv(id)
function showdiv(id) { //safe function to show an element with a specified id document.getElementById(id).style.display = 'block'; } function printMarkdownSource() { hidediv("source"); var view = document.getElementById("view"); var source = document.getElementById("source"); view.inn...
{ //safe function to hide an element with a specified id document.getElementById(id).style.display = 'none'; }
identifier_body
dom_sanitization_service.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DOCUMENT} from '@angular/common'; import {forwardRef, Inject, Injectable, Injector, Sanitizer, SecurityContex...
* @publicApi */ export interface SafeUrl extends SafeValue {} /** * Marker interface for a value that's safe to use as a URL to load executable code from. * * @publicApi */ export interface SafeResourceUrl extends SafeValue {} /** * DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sani...
export interface SafeScript extends SafeValue {} /** * Marker interface for a value that's safe to use as a URL linking to a document. *
random_line_split
dom_sanitization_service.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DOCUMENT} from '@angular/common'; import {forwardRef, Inject, Injectable, Injector, Sanitizer, SecurityContex...
row new Error('unsafe value used in a script context'); case SecurityContext.URL: const type = getSanitizationBypassType(value); if (allowSanitizationBypassOrThrow(value, BypassType.Url)) { return unwrapSafeValue(value); } return _sanitizeUrl(String(value)); case Se...
return unwrapSafeValue(value); } th
conditional_block
dom_sanitization_service.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DOCUMENT} from '@angular/common'; import {forwardRef, Inject, Injectable, Injector, Sanitizer, SecurityContex...
ing): SafeStyle { return bypassSanitizationTrustStyle(value); } override bypassSecurityTrustScript(value: string): SafeScript { return bypassSanitizationTrustScript(value); } override bypassSecurityTrustUrl(value: string): SafeUrl { return bypassSanitizationTrustUrl(value); } override bypassSecu...
ityTrustStyle(value: str
identifier_name
dom_sanitization_service.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DOCUMENT} from '@angular/common'; import {forwardRef, Inject, Injectable, Injector, Sanitizer, SecurityContex...
le({providedIn: 'root', useFactory: domSanitizerImplFactory, deps: [Injector]}) export class DomSanitizerImpl extends DomSanitizer { constructor(@Inject(DOCUMENT) private _doc: any) { super(); } override sanitize(ctx: SecurityContext, value: SafeValue|string|null): string|null { if (value == null) return...
new DomSanitizerImpl(injector.get(DOCUMENT)); } @Injectab
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(alloc)] #![feature(box_syntax)] #![feature(collections)] #![feature(core)] #![feature(plugin)] #![featu...
pub mod font; pub mod font_context; pub mod font_cache_task; pub mod font_template; // Misc. mod buffer_map; mod filters; // Platform-specific implementations. #[path="platform/mod.rs"] pub mod platform; // Text #[path = "text/mod.rs"] pub mod text;
#[path="display_list/mod.rs"] pub mod display_list; pub mod paint_task; // Fonts
random_line_split
Party.ts
/// <reference path="../collections.ts" /> 'use strict'; // collections import basarat = require('../collections'); import collections = basarat.collections; import Dictionary = collections.Dictionary; // interfaces import {Party} from '../api/Party'; import * as _ from "lodash"; import {PartyName} from '../api/Part...
abstract get typeName():string; /* * Get a contact method by field and type */ getContactMethod(aField:string, aType:string):ContactMethod { var findContact:ContactMethod; // Get contact for a specific type Ej: Home if (typeof this.contactMethods[aField] !== 'undefined') { this.contactMethods[aFiel...
{ this.contactMethods = {}; }
identifier_body
Party.ts
/// <reference path="../collections.ts" /> 'use strict'; // collections import basarat = require('../collections'); import collections = basarat.collections; import Dictionary = collections.Dictionary; // interfaces import {Party} from '../api/Party'; import * as _ from "lodash"; import {PartyName} from '../api/Part...
():string { // Short hand. Adds each own property return collections.makeString(this); } static fromJSON(obj:any, party:any):any { // Contacts ['addresses', 'phones', 'emails'].forEach(function (elem) { var cType = obj[elem]; if (typeof obj[elem] !== 'undefined') { party.contactMethods[elem] = []; ...
toString
identifier_name
Party.ts
/// <reference path="../collections.ts" /> 'use strict'; // collections import basarat = require('../collections'); import collections = basarat.collections; import Dictionary = collections.Dictionary; // interfaces import {Party} from '../api/Party'; import * as _ from "lodash"; import {PartyName} from '../api/Part...
if (csArray.length > 0) { csArray.forEach(function (contact:ContactMethod) { contacts.setValue(contact.type, contact); }); } else { throw new Error('Error while creating contacts dictionary for field ' + aField); } return contacts; } toString():string { // Short hand. Adds each own property ...
var csArray = this.contactMethods[aField];
random_line_split
chassis_1_0_0_chassis_actions.py
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return sel...
result[attr] = value.to_dict()
conditional_block
chassis_1_0_0_chassis_actions.py
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
(self): """ Chassis100ChassisActions - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is...
__init__
identifier_name
chassis_1_0_0_chassis_actions.py
# coding: utf-8
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 ...
""" Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License");
random_line_split
chassis_1_0_0_chassis_actions.py
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
@property def chassis_reset(self): """ Gets the chassis_reset of this Chassis100ChassisActions. :return: The chassis_reset of this Chassis100ChassisActions. :rtype: Chassis100Reset """ return self._chassis_reset @chassis_reset.setter def chassis_reset...
""" Sets the oem of this Chassis100ChassisActions. :param oem: The oem of this Chassis100ChassisActions. :type: object """ self._oem = oem
identifier_body
test_cache.py
import sys from time import sleep from cachey import Cache, Scorer, nbytes def test_cache(): c = Cache(available_bytes=nbytes(1) * 3) c.put('x', 1, 10) assert c.get('x') == 1 assert 'x' in c c.put('a', 1, 10) c.put('b', 1, 10) c.put('c', 1, 10) assert set(c.data) == set('xbc') c...
c = Cache(available_bytes=nbytes(1) * 3) flag = [0] def slow_inc(x): flag[0] += 1 sleep(0.01) return x + 1 memo_inc = c.memoize(slow_inc) assert memo_inc(1) == 2 assert memo_inc(1) == 2 assert list(c.data.values()) == [2] def test_callbacks(): hit_flag = [Fa...
def test_memoize():
random_line_split
test_cache.py
import sys from time import sleep from cachey import Cache, Scorer, nbytes def test_cache(): c = Cache(available_bytes=nbytes(1) * 3) c.put('x', 1, 10) assert c.get('x') == 1 assert 'x' in c c.put('a', 1, 10) c.put('b', 1, 10) c.put('c', 1, 10) assert set(c.data) == set('xbc') c...
c = Cache(100, hit=hit, miss=miss) c.get('x') assert miss_flag[0] == 'x' assert hit_flag[0] == False c.put('y', 1, 1) c.get('y') assert hit_flag[0] == ('y', 1) def test_just_one_reference(): c = Cache(available_bytes=1000) o = object() x = sys.getrefcount(o) c.put('key...
miss_flag[0] = key
identifier_body
test_cache.py
import sys from time import sleep from cachey import Cache, Scorer, nbytes def test_cache(): c = Cache(available_bytes=nbytes(1) * 3) c.put('x', 1, 10) assert c.get('x') == 1 assert 'x' in c c.put('a', 1, 10) c.put('b', 1, 10) c.put('c', 1, 10) assert set(c.data) == set('xbc') c...
(): c = Cache(available_bytes=nbytes(1) * 2) c.put('x', 1, 1) c.put('y', 1, 1) c.get('x') c.get('x') c.get('x') c.put('z', 1, 1) assert set(c.data) == set('xz') def test_memoize(): c = Cache(available_bytes=nbytes(1) * 3) flag = [0] def slow_inc(x): flag[0] += 1 ...
test_cache_scores_update
identifier_name
authentication.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' @Injectable()
var currentUser = JSON.parse(localStorage.getItem('currentUser')); this.token = currentUser && currentUser.token; } login(username: string, password: string): Observable<boolean> { return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password })) ...
export class AuthenticationService { public token: string; constructor(private http: Http) { // set token if saved in local storage
random_line_split
authentication.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' @Injectable() export class AuthenticationService { public token: string; constructor(private http: Http)
login(username: string, password: string): Observable<boolean> { return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password })) .map((response: Response) => { // login successful if there's a jwt token in the response let ...
{ // set token if saved in local storage var currentUser = JSON.parse(localStorage.getItem('currentUser')); this.token = currentUser && currentUser.token; }
identifier_body
authentication.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' @Injectable() export class AuthenticationService { public token: string; constructor(private http: Http) { // set token if saved in loc...
else { // return false to indicate failed login return false; } }); } logout(): void { // clear token remove user from local storage to log user out this.token = null; localStorage.removeItem('currentUser'); } }
{ // set token property this.token = token; // store username and jwt token in local storage to keep user logged in between page refreshes localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token })); ...
conditional_block
authentication.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' @Injectable() export class AuthenticationService { public token: string; constructor(private http: Http) { // set token if saved in loc...
(): void { // clear token remove user from local storage to log user out this.token = null; localStorage.removeItem('currentUser'); } }
logout
identifier_name
bootstrap-popover.js
/* =========================================================== * bootstrap-popover.js v2.0.4 * http://twitter.github.com/bootstrap/javascript.html#popovers * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"...
========================================== */ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, { constructor: Popover , setContent: function () { var $tip = this.tip() , title = this.getTitle() , content = this.getContent() $tip.find('.popover-title')[thi...
} /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
random_line_split
log-timestamps.ts
/** * @module log-timestamps * * Modifies console.log and friends to prepend a timestamp to log lines. */ /** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ ...
(): string { const currTime = new Date(); return `${currTime.getFullYear()}-${`0${currTime.getMonth() + 1}`.slice( -2 )}-${`0${currTime.getDate()}`.slice(-2)} ${`0${currTime.getHours()}`.slice( -2 )}:${`0${currTime.getMinutes()}`.slice(-2)}:${`0${currTime.getSeconds()}`.slice( -2 )}.${`00${currTim...
logPrefix
identifier_name
log-timestamps.ts
/** * @module log-timestamps * * Modifies console.log and friends to prepend a timestamp to log lines. */ /** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ ...
} const timestampFormat = winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS', }); const logger = winston.createLogger({ level: 'debug', transports: [ new winston.transports.Console({ format: winston.format.combine( timestampFormat, new CustomFormatter(), winston.form...
{ const level = info.level.toUpperCase().padEnd(7, ' '); info.message = `${info.timestamp} ${level}: ${info.message}`; return info; }
identifier_body
log-timestamps.ts
/** * @module log-timestamps * * Modifies console.log and friends to prepend a timestamp to log lines. */ /** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ ...
/* eslint-enable @typescript-eslint/no-explicit-any */
} }
random_line_split
TestNativeCosh.rs
/* * Copyright (C) 2014 The Android Open Source Project * * 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 app...
#pragma version(1) #pragma rs java_package_name(android.renderscript.cts) // Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime. float __attribute__((kernel)) testNativeCoshFloatFloat(float in) { return native_cosh(in); } float2 __attribute__((kernel)) testNativeCoshFloat2Float2(float...
random_line_split
comments.ts
/* Copyright 2020 Google 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 agreed to in writing, software dis...
{ const comment: ICommentModel = state.global.comments.index.get(commentId); if (comment) { commentFetchQueue.delete(commentId); } return comment; }
identifier_body
comments.ts
/* Copyright 2020 Google 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 agreed to in writing, software dis...
} if (payload.resolveFlags) { newComment.unresolvedFlagsCount = 0; newComment.flagsSummary = resolveFlags(newComment.flagsSummary); } index.set(commentId, newComment); } } return {index}; }, }, {index: new Map()}); export function getComment(state: I...
{ delete newComment.isAccepted; }
conditional_block
comments.ts
/* Copyright 2020 Google 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 agreed to in writing, software dis...
(state: IAppState, commentId: ModelId) { const comment: ICommentModel = state.global.comments.index.get(commentId); if (comment) { commentFetchQueue.delete(commentId); } return comment; }
getComment
identifier_name
comments.ts
/* Copyright 2020 Google 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 agreed to in writing, software dis...
let newComment = { ...comment, updatedAt: new Date().toISOString(), }; if (payload.attributes) { newComment = { ...newComment, ...payload.attributes, }; if (payload.attributes.isModerated === null) { delete new...
for (const commentId of payload.commentIds) { const comment = index.get(commentId); if (comment) {
random_line_split
chrome_test.js
/* * Copyright (c) 2014 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ 'use strict'; // Utilities to allow googletest style tests of apps / extensions. /** * @namespace. */ var chrometest = {}; /** * @p...
(a, b, context) { chrometest.expect(a <= b, 'Expected ' + a + ' <= ' + b + ' when ' + context); } function EXPECT_GE(a, b, context) { chrometest.expect(a >= b, 'Expected ' + a + ' >= ' + b + ' when ' + context); }
EXPECT_LE
identifier_name
chrome_test.js
/* * Copyright (c) 2014 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ 'use strict'; // Utilities to allow googletest style tests of apps / extensions. /** * @namespace. */ var chrometest = {}; /** * @p...
function EXPECT_GE(a, b, context) { chrometest.expect(a >= b, 'Expected ' + a + ' >= ' + b + ' when ' + context); }
{ chrometest.expect(a <= b, 'Expected ' + a + ' <= ' + b + ' when ' + context); }
identifier_body
chrome_test.js
/* * Copyright (c) 2014 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ 'use strict'; // Utilities to allow googletest style tests of apps / extensions. /** * @namespace. */ var chrometest = {}; /** * @p...
else { reject(r.status); } } } r.send(); }); }; /** * Sleep for a duration. * @param {float} ms Timeout in milliseconds. * @return {Promise} A promise to wait. */ chrometest.sleep = function(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { ...
{ resolve(r.responseText); }
conditional_block
chrome_test.js
/* * Copyright (c) 2014 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ 'use strict'; // Utilities to allow googletest style tests of apps / extensions. /** * @namespace. */ var chrometest = {}; /** * @p...
chrometest.expect(a > b, 'Expected ' + a + ' > ' + b + ' when ' + context); } function EXPECT_LE(a, b, context) { chrometest.expect(a <= b, 'Expected ' + a + ' <= ' + b + ' when ' + context); } function EXPECT_GE(a, b, context) { chrometest.expect(a >= b, 'Expected ' + a + ' >= ' + b + ' when ' + context); }
random_line_split
settings-provider.ts
import { injectable, inject } from 'inversify'; import { ISettingsProvider, IPath, IFileSystem } from './i'; import TYPES from './di/types'; import { IMapperService } from 'simple-mapper'; /** * Just a wrapper around the user-settings module, for now. */ @injectable() export class SettingsProvider<T> implements ISet...
}
random_line_split
settings-provider.ts
import { injectable, inject } from 'inversify'; import { ISettingsProvider, IPath, IFileSystem } from './i'; import TYPES from './di/types'; import { IMapperService } from 'simple-mapper'; /** * Just a wrapper around the user-settings module, for now. */ @injectable() export class SettingsProvider<T> implements ISet...
else { throw err; } } try { options = JSON.parse(rawData); } catch (err) { err.filepath = filepath; throw err; } return options; } }
{ this.fs.writeFileSync(filepath, rawData); }
conditional_block
settings-provider.ts
import { injectable, inject } from 'inversify'; import { ISettingsProvider, IPath, IFileSystem } from './i'; import TYPES from './di/types'; import { IMapperService } from 'simple-mapper'; /** * Just a wrapper around the user-settings module, for now. */ @injectable() export class SettingsProvider<T> implements ISet...
get(key: string): T { const settings = this.readSettings(); return settings[key]; } set(key: string, value: any): void { const settings = this.readSettings(); settings[key] = value; this.fs.writeFileSync(this.filepath, JSON.stringify(settings, null, 2)); } ...
{ const homedir = this.process.env.HOME || this.process.env.USERPROFILE; this.filepath = this.path.join(homedir, this.filename); }
identifier_body
settings-provider.ts
import { injectable, inject } from 'inversify'; import { ISettingsProvider, IPath, IFileSystem } from './i'; import TYPES from './di/types'; import { IMapperService } from 'simple-mapper'; /** * Just a wrapper around the user-settings module, for now. */ @injectable() export class SettingsProvider<T> implements ISet...
( @inject(TYPES.SettingsType) private TSettings: { new (): T }, @inject(TYPES.Process) private process: NodeJS.Process, @inject(TYPES.Mapper) private mapper: IMapperService, @inject(TYPES.FS) private fs: IFileSystem, @inject(TYPES.Path) private path: IPath ) { const h...
constructor
identifier_name
union-c-interop.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ LowPart: u32, HighPart: u32, } #[derive(Clone, Copy)] #[repr(C)] union LARGE_INTEGER { __unnamed__: LARGE_INTEGER_U, u: LARGE_INTEGER_U, QuadPart: u64, } #[link(name = "rust_test_helpers", kind = "static")] extern "C" { fn increment_all_parts(_: LARGE_INTEGER) -> LARGE_INTEGER; } fn main() { ...
LARGE_INTEGER_U
identifier_name
union-c-interop.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ unsafe { let mut li = LARGE_INTEGER { QuadPart: 0 }; let li_c = increment_all_parts(li); li.__unnamed__.LowPart += 1; li.__unnamed__.HighPart += 1; li.u.LowPart += 1; li.u.HighPart += 1; li.QuadPart += 1; assert_eq!(li.QuadPart, li_c.QuadPart); }...
identifier_body
union-c-interop.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(non_snake_case)] // ignore-wasm32-bare no libc to test ffi with #[derive(Clone, Copy)] #[repr(C)] struct LARGE_INTEGER_U { LowPart: u32, HighPart: u32, } #[derive(Clone, Copy)] #[repr(C)...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
last.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This should be the last code run on client application startup. declare var $: any; declare var COCALC_GIT_REVISION: string; import { webapp_client } from "./webapp-clien...
.labels(get_browser(), IS_MOBILE, IS_TOUCH, COCALC_GIT_REVISION ?? "N/A") .set(1); const initialization_time_gauge = prom_client.new_gauge( "initialization_seconds", "Time from loading app.html page until last.coffee is completely done" ); initialization_time_gauge.set( (new Da...
"Information about the browser", ["browser", "mobile", "touch", "git_version"] ); browser_info_gauge
random_line_split
last.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This should be the last code run on client application startup. declare var $: any; declare var COCALC_GIT_REVISION: string; import { webapp_client } from "./webapp-clien...
{ // see http://stackoverflow.com/questions/12197122/how-can-i-prevent-a-user-from-middle-clicking-a-link-with-javascript-or-jquery // I have some concern about performance. $(document).on("click", function (e) { if (e.button === 1 && $(e.target).hasClass("webapp-no-middle-click")) { e.preventDefault();...
t()
identifier_name
last.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This should be the last code run on client application startup. declare var $: any; declare var COCALC_GIT_REVISION: string; import { webapp_client } from "./webapp-clien...
// see http://stackoverflow.com/questions/12197122/how-can-i-prevent-a-user-from-middle-clicking-a-link-with-javascript-or-jquery // I have some concern about performance. $(document).on("click", function (e) { if (e.button === 1 && $(e.target).hasClass("webapp-no-middle-click")) { e.preventDefault(); ...
identifier_body
last.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This should be the last code run on client application startup. declare var $: any; declare var COCALC_GIT_REVISION: string; import { webapp_client } from "./webapp-clien...
}); if (webapp_client.hub_client.is_connected()) { // These events below currently (due to not having finished the react rewrite) // have to be emited after the page loads, but may happen before. webapp_client.emit("connected"); if (webapp_client.hub_client.is_signed_in()) { webapp_client.emit(...
return $('[data-toggle="popover"]').popover("hide"); }
conditional_block
angularMaterial-component.ts
import { NgModule } from '@angular/core'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MdAutocompleteModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdCheckboxModule,...
MdSortModule, MdTableModule, MdTabsModule, MdToolbarModule, MdTooltipModule, } from '@angular/material'; @NgModule({ exports: [ BrowserAnimationsModule, FormsModule, HttpModule, MdAutocompleteModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdCheckboxModule, M...
MdSelectModule, MdSidenavModule, MdSliderModule, MdSlideToggleModule, MdSnackBarModule,
random_line_split
angularMaterial-component.ts
import { NgModule } from '@angular/core'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MdAutocompleteModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdCheckboxModule,...
{}
AngularMaterialModules
identifier_name
kbo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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 ver...
assert!(kbo_gt(&precedence, &weight, &only_unary_func, &f_x, &x)); assert!(kbo_gt(&precedence, &weight, &only_unary_func, &f_f_x, &x)); assert!(!kbo_gt(&precedence, &weight, &only_unary_func, &x, &f_f_x)); assert!(!kbo_gt(&precedence, &weight, &only_unary_func, &x, &f_x)); assert...
let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(kbo_gt(&precedence, &weight, &only_unary_func, &f_f_x, &f_x));
random_line_split
kbo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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 ver...
}
{ let precedence = Precedence::default(); let weight = Weight::SimpleWeight; let only_unary_func = Some(1); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); let f_f_f_x = Term:...
identifier_body
kbo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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 ver...
} else { false } } else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn kbo_ge(precedence: &Precedence, weight: &Weight, onl...
{ false }
conditional_block