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
query_external_sheets_permanent_table.py
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(dataset_id): # [START bigquery_query_external_sheets_perm] from google.cloud import bigquery import google.auth # Create credentials with Drive & BigQuery API scopes. # Both APIs must be enabled for your project before running this code. # # If you are using credentials from gcloud, you m...
query_external_sheets_permanent_table
identifier_name
query_external_sheets_permanent_table.py
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
from google.cloud import bigquery import google.auth # Create credentials with Drive & BigQuery API scopes. # Both APIs must be enabled for your project before running this code. # # If you are using credentials from gcloud, you must authorize the # application first with the following command:...
identifier_body
query_external_sheets_permanent_table.py
# Copyright 2019 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 # # https://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 WARRANTIE...
random_line_split
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client is distribut...
def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port def connect(self): try: self.connection = pymongo.Connection(self.host, self.port) self.db = self.connection[self.name] except AutoReconnect: ...
identifier_body
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client is distribut...
(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0 def status(self): docs =...
get_last_tid
identifier_name
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client is distribut...
else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc def delete(self, doc): ...
pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced}
conditional_block
mongo.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client.
# # lai-client is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-client is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MER...
random_line_split
__init__.py
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ impo...
(shoop.apps.AppConfig): name = __name__ verbose_name = _("Simple CMS") label = "shoop_simple_cms" provides = { "front_urls_post": [__name__ + ".urls:urlpatterns"], "admin_module": [ "shoop.simple_cms.admin_module:SimpleCMSAdminModule" ], "front_template_helpe...
AppConfig
identifier_name
__init__.py
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ impo...
verbose_name = _("Simple CMS") label = "shoop_simple_cms" provides = { "front_urls_post": [__name__ + ".urls:urlpatterns"], "admin_module": [ "shoop.simple_cms.admin_module:SimpleCMSAdminModule" ], "front_template_helper_namespace": [ "shoop.simple_cm...
class AppConfig(shoop.apps.AppConfig): name = __name__
random_line_split
__init__.py
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ impo...
default_app_config = __name__ + ".AppConfig"
name = __name__ verbose_name = _("Simple CMS") label = "shoop_simple_cms" provides = { "front_urls_post": [__name__ + ".urls:urlpatterns"], "admin_module": [ "shoop.simple_cms.admin_module:SimpleCMSAdminModule" ], "front_template_helper_namespace": [ ...
identifier_body
ecies_hkdf_recipient_kem.rs
// Copyright 2021 The Tink-Rust 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
<'a> { recipient_private_key: &'a EcPrivateKey, } impl<'a> EciesHkdfRecipientKem<'a> { pub fn new(priv_key: &'a EcPrivateKey) -> Self { Self { recipient_private_key: priv_key, } } /// Uses the KEM to generate a new HKDF-based key. pub(crate) fn decapsulate( &sel...
EciesHkdfRecipientKem
identifier_name
ecies_hkdf_recipient_kem.rs
// Copyright 2021 The Tink-Rust 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
recipient_private_key: priv_key, } } /// Uses the KEM to generate a new HKDF-based key. pub(crate) fn decapsulate( &self, kem: &[u8], hash_alg: HashType, salt: &[u8], info: &[u8], key_size: usize, point_format: EcPointFormat, )...
random_line_split
ecies_hkdf_recipient_kem.rs
// Copyright 2021 The Tink-Rust 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
}
{ let pub_point = subtle::point_decode( self.recipient_private_key.public_key().curve(), point_format, kem, )?; let secret = subtle::compute_shared_secret(&pub_point, self.recipient_private_key)?; let mut i = kem.to_vec(); i.extend_from_slice(&...
identifier_body
column.spec.ts
/** * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> * @author David Sehnal <david.sehnal@gmail.com> */ import { FixedColumnProvider as FixedColumn } from '../common/text/column/fixed'; import { TokenColumnProvider...
for (const l of lines) { tokens.push(last, last + l.length); last += l.length + 1; } if (tokens[tokens.length - 1] > linesData.length) tokens[tokens.length - 1] = linesData.length; return tokens; }()); describe('fixed text column', () => { const col = FixedColumn({ data: linesData, ...
random_line_split
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class DNSLabel(obje...
def __repr__(self): return "<DNSLabel: '%s'>" % str(self) def __hash__(self): return hash(self.label) def __ne__(self,other): return not self == other def __eq__(self,other): if type(other) != DNSLabel: return self.__eq__(DNSLabel(other)) else: ...
return ".".join([ s.decode() for s in self.label ]) + "."
identifier_body
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class DNSLabel(obje...
>>> b = DNSBuffer() >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 13 >>> b.encode_name_nocompress(b'aaa.bbb.ccc.') >>> len(b) 26 >>> b.offset = 0 >>> print(b.decode_name()) aaa.bbb.ccc. >>> print(b.decode_name()) aaa.bbb.ccc. """ def __init__(self,dat...
>>> b.offset = 0 >>> len(b.decode_name().label) 3
random_line_split
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class DNSLabel(obje...
return new def matchGlob(self,pattern): if type(pattern) != DNSLabel: pattern = DNSLabel(pattern) return fnmatch.fnmatch(str(self).lower(),str(pattern).lower()) def matchSuffix(self,suffix): """ Return True if label suffix matches """ s...
new.label += self.label
conditional_block
label.py
# -*- coding: utf-8 -*- """ DNSLabel/DNSBuffer - DNS label handling & encoding/decoding """ from __future__ import print_function import fnmatch from mitmflib.dnslib.bit import get_bits,set_bits from mitmflib.dnslib.buffer import Buffer, BufferError class DNSLabelError(Exception): pass class
(object): """ Container for DNS label Supports IDNA encoding for unicode domain names >>> l1 = DNSLabel("aaa.bbb.ccc.") >>> l2 = DNSLabel([b"aaa",b"bbb",b"ccc"]) >>> l1 == l2 True >>> l3 = DNSLabel("AAA.BBB.CCC") >>> l1 == l3 True >>> l1 == 'AAA.BBB.CCC' True >>> x...
DNSLabel
identifier_name
about-assistant.js
function AboutAssistant()
AboutAssistant.prototype.setup = function() { this.appMenuModel = { visible: true, items: [ { label: "Records", command: 'do-records' }, { label: "PuzzleMaker", command: 'do-puzzlemaker' }, { label: "Help", command: 'do-help' } ] }; this.controller.setupWidget(Mojo...
{ /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that needs the scene controller...
identifier_body
about-assistant.js
function AboutAssistant() { /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that ...
{ label: "Help", command: 'do-help' } ] }; this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel); } AboutAssistant.prototype.activate = function(event) { /* put in event handlers here that should only be in effect when this scene is active. For ...
random_line_split
about-assistant.js
function
() { /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that needs the scene control...
AboutAssistant
identifier_name
constructPermissionHierarchy.ts
import { topologicalSort } from 'gracl'; import * as _ from 'lodash'; import { GraclPlugin } from '../classes/GraclPlugin'; import { Hash, PermissionHierarchy, PermissionTypeList, PermissionHierarchyNode } from '../interfaces'; import { parsePermissionString } from '../permission/parsePermissionString'; /** *...
{ plugin.log(`constructing permissions hierarchy...`); if (!plugin.graclHierarchy) { plugin.error( `Must build subject/resource hierarchy before creating permission hierarchy` ); } /** * Run topological sort on permissions values, checking for circular dependencies / missing nodes */ ...
identifier_body
constructPermissionHierarchy.ts
import { topologicalSort } from 'gracl'; import * as _ from 'lodash'; import { GraclPlugin } from '../classes/GraclPlugin'; import { Hash, PermissionHierarchy, PermissionTypeList, PermissionHierarchyNode } from '../interfaces'; import { parsePermissionString } from '../permission/parsePermissionString'; /**
if (!plugin.graclHierarchy) { plugin.error( `Must build subject/resource hierarchy before creating permission hierarchy` ); } /** * Run topological sort on permissions values, checking for circular dependencies / missing nodes */ const sorted = _.compact( topologicalSort( _....
* validate and insert provided permissionHierarchy into model */ export function constructPermissionHierarchy(plugin: GraclPlugin) { plugin.log(`constructing permissions hierarchy...`);
random_line_split
constructPermissionHierarchy.ts
import { topologicalSort } from 'gracl'; import * as _ from 'lodash'; import { GraclPlugin } from '../classes/GraclPlugin'; import { Hash, PermissionHierarchy, PermissionTypeList, PermissionHierarchyNode } from '../interfaces'; import { parsePermissionString } from '../permission/parsePermissionString'; /** *...
(plugin: GraclPlugin) { plugin.log(`constructing permissions hierarchy...`); if (!plugin.graclHierarchy) { plugin.error( `Must build subject/resource hierarchy before creating permission hierarchy` ); } /** * Run topological sort on permissions values, checking for circular dependencies ...
constructPermissionHierarchy
identifier_name
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY =...
def fetch_client(base_url=BASE_URL): this.client = docker.APIClient(base_url=base_url, version='1.24') try: this.client.version() except requests.exceptions.ConnectionError as e: click.echo('[!] Unable to connect to Docker daemon @ {}'.format(BASE_URL)) sys.exit(1) if __name__=="_...
this.client.create_container( REGISTRY, detach=False, name=inst_name, ports=[8888], host_config=this.client.create_host_config( port_bindings={8888: ('127.0.0.1',8888)} ...
identifier_body
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY =...
time.sleep(1) repeat += 1 else: click.echo('[!] Container status: {}'.format(cont_status)) return def start_container(inst_name): this.client.create_container( REGISTRY, detach=False, na...
return
conditional_block
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY =...
(): """ basic functional test to ensure containers can be managed """ click.echo('[*] Testing docker container creation/removal') cont_name = 'funky_aardvark' try: runner = CliRunner() # Test the RUN command result = runner.invoke(run, [cont_name]) result_txt = result...
test
identifier_name
dockcli.py
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY =...
@click.group() def default(): """ A basic docker container management wrapper """ pass @click.command() @click.argument('container') def run(container): """ attempts to start the docker container specified """ try: fetch_client() this.client.pull(REGISTRY) start_container(con...
random_line_split
fields.py
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.M...
"""Validate otp and detect type""" # remove any whitespace from the string if value: value = value.strip().replace(' ', '') value = super(OATHPasswordField, self).clean(value) if self.SIX.match(value): return value elif self.EIGHT.match(value): ...
identifier_body
fields.py
# GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.MultipleChoiceField): widget = CommaSeparatedWidget def clean...
# Copyright 2010 Canonical Ltd. This software is licensed under the
random_line_split
fields.py
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.M...
elif self.EIGHT.match(value): return value raise forms.ValidationError( _('Please enter a 6-digit or 8-digit one-time password.'))
return value
conditional_block
fields.py
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.M...
(forms.CharField): """A string of between 6 or 8 digits.""" widget = forms.widgets.TextInput(attrs={ 'autocomplete': 'off', 'autofocus': 'autofocus' }) SIX = re.compile('[0-9]{6}$') EIGHT = re.compile('[0-9]{8}$') def clean(self, value): """Validate otp and detect type""...
OATHPasswordField
identifier_name
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
{ let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local; use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now(); let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) ...
identifier_body
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
}; let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) { None => { NaiveDate::from_ymd(now.year() + 1, 1, 1).and_hms(0, 0, 0) }, Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); ...
{ trace_error(&e); return 1 }
conditional_block
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
(rt: &Runtime) -> i32 { let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local; use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now(); let start = match cmd.value_of("start").map(::chrono::naive::Nai...
year
identifier_name
year.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) { None => NaiveDate::from_ymd(now.year(), 1, 1).and_hms(0, 0, 0), Some(Ok(dt)) => dt, Some(Err(e)) => { trace_error(&e); return 1 } }; ...
use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now();
random_line_split
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def getActionScore(action): if action == "rec": return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data):
def compute_user_history_interaction(trainFile): records = [] lineList = [] lineNum = 1 result = [] lineList = [line for line in file(trainFile)] for line in lineList: if lineNum == 1: #ignore the title in first line lineNum += 1 continue records.append(line) lineNum += 1 i...
interaction = {} for line in data: (userA,userB,times,action) = line.split(' ') action = action[:-1] key = userB + " " + action interaction.setdefault(key, 0) interaction[key] += 1 return interaction
identifier_body
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def getActionScore(action):
return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data): interaction = {} for line in data: (userA,userB,times,action) = line.split(' ') action = action[:-1] key = userB + " " + action interaction.setdefault(key, 0) interaction[key...
if action == "rec":
random_line_split
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def getActionScore(action): if action == "rec": return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data): interaction = {} for line in data: ...
interaction = compute_interaction(records) out = file('user_interaction.txt', 'w') for (key, times) in interaction.items(): out.write('%s %d' % (key, times)) out.write('\n') for (key, times) in interaction.items(): user, action = key.split(' '); result.append((user, action, times)) r...
if lineNum == 1: #ignore the title in first line lineNum += 1 continue records.append(line) lineNum += 1
conditional_block
compute_user_popularity.py
# -*- coding: utf-8 -*- # compute the times of action(rec|click|msg) for each user from math import sqrt def
(action): if action == "rec": return 0 elif action == "click" : return 1 else: return 2 def compute_interaction(data): interaction = {} for line in data: (userA,userB,times,action) = line.split(' ') action = action[:-1] key = userB + " " + action interaction.set...
getActionScore
identifier_name
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html import json, math from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App._...
self.Quit() def authOk(self, user): self.user = user self.cfg.user = user mf = MainFrame(parent=None, title=self.user['name'] + u' 你好,欢迎使用本软件') #( {} )'.format(self.expirationTip) ) mf.app = self if self.user.isAdmin(): ManagerPanel(mf, self) else: OperatorPanel(mf) mf.maxWindow() def getPrinte...
'' return True # skip expiration check self.appExpireInDays = self.cfg.expiration time0 = self.modelUser.getEarliestDate() daysElapsed = 0 if time0>0: daysElapsed = int( (time.time()-time0)/86400 ) if daysElapsed > -1: if self.appExpireInDays < daysElapsed: self.expire() self.appExpireInDays...
identifier_body
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html import json, math from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App._...
().SetPaperSize( wx.Size(-1, 400) ) self.getPrinter().GetPrintData().PaperSize = wx.Size(-1, 400) self.getPrinter().PrintText( self.getSheetHtml(sheet) ) def getSheetHtml(self, sheet): data = sheet.getDict() data['bigamount'] = cnNumber( data['amount'] ) return getPrintTpl().format( **data ) def printViaHtm...
sheet ) self.getPrinter().GetPrintData
conditional_block
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html
from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App.__init__(self, *args) # do not redirect for now self.user = None self.cfg = conf self.printer = None def OnInit(self): return True @staticmethod d...
import json, math
random_line_split
main.py
#!python #-*- encoding=utf-8 -*- import sys, sqlite3, logging, os, os.path import wx, time, re, copy, webbrowser import wx.grid, wx.html import json, math from cfg import config from util import * from model import * from view import * class App(wx.App): instance = None def __init__(self, conf, *args): wx.App._...
(self): if not os.path.isfile( self.cfg.datapath ): self.setup() else: self.bootstrap() self.checkExpiration() AuthFrame(self).Show() def bootstrap(self): self.dbconn = DB.getInstance().conn self.modelUser = ModelUser( self.dbconn ) self.modelSheet= ModelSheet( self.dbconn ) self.logger = XLog.ge...
Run
identifier_name
PanelHeaderButton.js
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["children", "primary", "label"]; import { createScopedElement } from "../../lib/jsxRuntime"; import Tappable from "../Tappable/Tappable"; import { getClassName }...
case VKCOM: hoverMode = "PanelHeaderButton--hover"; activeMode = "PanelHeaderButton--active"; } return createScopedElement(Tappable, _extends({}, restProps, { hoverMode: hoverMode, Component: restProps.href ? "a" : "button", activeEffectDelay: 200, activeMode: activeMode, vkuiCl...
hoverMode = "background"; activeMode = "opacity"; break;
random_line_split
PanelHeaderButton.js
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["children", "primary", "label"]; import { createScopedElement } from "../../lib/jsxRuntime"; import Tappable from "../Tappable/Tappable"; import { getClassName }...
return createScopedElement(Text, { weight: platform === VKCOM ? "regular" : "medium" }, children); }; export var PanelHeaderButton = function PanelHeaderButton(_ref2) { var children = _ref2.children, primary = _ref2.primary, label = _ref2.label, restProps = _objectWithoutProperties(_ref2,...
{ return createScopedElement(Title, { Component: "span", level: "3", weight: primary ? "semibold" : "regular" }, children); }
conditional_block
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
conn_config['ssl'] = dejson_ssl if conn.extra_dejson.get('unix_socket'): conn_config['unix_socket'] = conn.extra_dejson['unix_socket'] if local_infile: conn_config["local_infile"] = 1 conn = MySQLdb.connect(**conn_config) return conn def bulk_loa...
dejson_ssl = json.loads(dejson_ssl)
conditional_block
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
(self, table, tmp_file): """ Loads a tab-delimited file into a database table """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' INTO TABLE {table} """.format(tmp_file=tmp_file, table=tabl...
bulk_load
identifier_name
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
def get_iam_token(self, conn): """ Uses AWSHook to retrieve a temporary password to connect to MySQL Port is required. If none is provided, default 3306 is used """ from airflow.contrib.hooks.aws_hook import AwsHook aws_conn_id = conn.extra_dejson.get('aws_conn_id'...
""" MySQLdb converts an argument to a literal when passing those separately to execute. Hence, this method does nothing. :param cell: The cell to insert into the table :type cell: object :param conn: The database connection :type conn: connection object :return: ...
identifier_body
mysql_hook.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
"db": self.schema or conn.schema or '' } # check for authentication via AWS IAM if conn.extra_dejson.get('iam', False): conn_config['passwd'], conn.port = self.get_iam_token(conn) conn_config["read_default_group"] = 'enable-cleartext-plugin' if not c...
"host": conn.host or 'localhost',
random_line_split
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def program(): # These are the ...
program()
else: print ('Nope. The color I was thinking of was {0}'.format(c2.color)) if __name__ == "__main__":
random_line_split
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def program(): # These are the ...
c1 = Color() c2 = Color() c3 = Color() guesses_made = 0 # This input causes the program to refer to you as your name. c1.name = input('Hello! What is your name?\n') c2.color = [BLUE, GREEN, RED, ORANGE, PURPLE, PINK] # This randomizes what color is chosen c2.color = random.choice(c2.colo...
pass
identifier_body
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def
(): # These are the constants declaring what the colors are. RED = 'red' BLUE = 'blue' GREEN = 'green' ORANGE = 'orange' PURPLE = 'purple' PINK = 'pink' class Color: pass c1 = Color() c2 = Color() c3 = Color() guesses_made = 0 # This input causes the program to...
program
identifier_name
guessnameclass.py
# A program that has a list of six colors and chooses one by random. The user can then has three chances to quess the right color. After the third attepmt the program outputs "Nope. The color I was thinking of was..." import random # this is the function that will execute the program def program(): # These are the ...
else: print ('Nope. The color I was thinking of was {0}'.format(c2.color)) if __name__ == "__main__": program()
print ('Good job, {0}! You guessed my color in {1} guesses!'.format(c1.name, guesses_made))
conditional_block
skip_step.js
/** * @license * Copyright 2014 The Lovefield Project Authors. 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 ...
/** @override */ lf.proc.SkipStep.prototype.toContextString = function(context) { return this.toString().replace('?', context.skip.toString()); }; /** @override */ lf.proc.SkipStep.prototype.execInternal = function( relations, opt_journal, context) { return [new lf.proc.Relation( relations[0].entries.s...
return 'skip(?)'; };
random_line_split
ExplorerUrlMigrations.ts
import { Url } from "../../clientUtils/urls/Url.js" import { performUrlMigrations,
import { covidUrlMigration } from "./CovidUrlMigration.js" export enum ExplorerUrlMigrationId { legacyToGridCovidExplorer = "legacyToGridCovidExplorer", } export interface ExplorerUrlMigrationSpec { explorerSlug: string migrateUrl: (url: Url, baseQueryStr: string) => Url } export const explorerUrlMigrati...
UrlMigration, } from "../../clientUtils/urls/UrlMigration.js" import { legacyCovidMigrationSpec } from "./LegacyCovidUrlMigration.js" import { co2UrlMigration } from "./CO2UrlMigration.js" import { energyUrlMigration } from "./EnergyUrlMigration.js"
random_line_split
image-alt.js
/** * @license Copyright 2017 The Lighthouse Authors. 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...
} module.exports = ImageAlt; module.exports.UIStrings = UIStrings;
failureTitle: str_(UIStrings.failureTitle), description: str_(UIStrings.description), requiredArtifacts: ['Accessibility'], }; }
random_line_split
image-alt.js
/** * @license Copyright 2017 The Lighthouse Authors. 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...
() { return { id: 'image-alt', title: str_(UIStrings.title), failureTitle: str_(UIStrings.failureTitle), description: str_(UIStrings.description), requiredArtifacts: ['Accessibility'], }; } } module.exports = ImageAlt; module.exports.UIStrings = UIStrings;
meta
identifier_name
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def main():
if __name__ == '__main__': main()
print('Append version stamp to UBOOT.bin') latest_cl = ['0','0','0','0','0','0','0','0'] stamp_index = 0 stamp_flag_found = 0 ver_string_chip_customer="C300000" check_input() check_sum_odd=0 check_sum_even=0 check_sum_version =0 count=0 size_without_ver...
identifier_body
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def main(): print('Append ve...
stamp_index=0 target_file.close() target_file =open(sys.argv[1],"r+b") target_file.seek(-32,2) target_file.write(ver_string_head+ver_string_lib+ver_string_build_number) target_file.write(bytearray(latest_cl)) print ('ChangeList:'+s...
random_line_split
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def main(): print('Append ve...
elif 2==stamp_index and 'V'==byte: stamp_index=3 elif 3==stamp_index and 'C'==byte: stamp_index=4 elif 3<stamp_index and stamp_index<22: if stamp_index>13: latest_...
stamp_index=2
conditional_block
append_UBOOT_version.py
#!/usr/bin/python import re, fnmatch, os, sys, array ver_string_head="MSVC00" ver_string_lib="IL" ver_string_build_number="000000" def check_input(): if not os.path.exists(sys.argv[1]): print 'ERROR!! \"%s\" file not existed!!' % sys.argv[1] sys.exit(-1) def
(): print('Append version stamp to UBOOT.bin') latest_cl = ['0','0','0','0','0','0','0','0'] stamp_index = 0 stamp_flag_found = 0 ver_string_chip_customer="C300000" check_input() check_sum_odd=0 check_sum_even=0 check_sum_version =0 count=0 size_wit...
main
identifier_name
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # 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 ...
"%s"), ex_gw_port['network_id']) if is_first and fip_agent_port: if 'subnets' not in fip_agent_port: LOG.error(_LE('Missing subnet/agent_gateway_port')) else: self.fip_ns.create_gateway_port(fip_agent_p...
if not fip_agent_port: LOG.error(_LE("No FloatingIP agent gateway port " "returned from server for 'network-id': "
random_line_split
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # 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 ...
(self): host = self.router.get('gw_port_host') if not host: LOG.debug("gw_port_host missing from router: %s", self.router['id']) return host def internal_network_added(self, port): super(DvrLocalRouter, self).internal_network_added(port) # ...
get_gw_port_host
identifier_name
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # 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 ...
except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("DVR: Failed updating arp entry")) def _set_subnet_arp_info(self, subnet_id): """Set ARP info retrieved from Plugin for existing ports.""" # TODO(Carl) Can we eliminate the need to m...
device.neigh.delete(ip, mac)
conditional_block
dvr_local_router.py
# Copyright (c) 2015 Openstack Foundation # # 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 ...
def get_floating_agent_gw_interface(self, ext_net_id): """Filter Floating Agent GW port for the external network.""" fip_ports = self.router.get(l3_constants.FLOATINGIP_AGENT_INTF_KEY, []) return next( (p for p in fip_ports if p['network_id'] == ext_net_id), None) def get_...
self._dvr_internal_network_removed(port) super(DvrLocalRouter, self).internal_network_removed(port)
identifier_body
template.js
define( ({ "viewer": { "main": { "scaleBarUnits": "metric", "timePattern": "h:mma", // added 2.5.2013 "datePattern": "MMM d, yyyy" // added 2.5.2013 }, "applicationTitle": { "PIM": "خريطة المعلومات العامة" // ad...
"distanceSlider": { "local": "محلي", "regional": "إقليمي", "national": "وطني" }, "about": { "title": "نبذة عن", "access": "قيود الاستخدام والوصول" }, "buttons": { "...
"placesTitle": "أماكن العلامة المرجعية", "myLocation": "موقعي الحالي", "myLocationTitle": "تمركز الخريطة على موقعي" },
random_line_split
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss)
growl.append(message); if (options.top_offset) { options.offset = { from: "top", amount: options.top_offset }; } return growl; } function makeAlign(alert, options) { switch (options.align) { case "center": alert.css({ ...
{ growl.addClass("alert-dismissible"); growl.append("<button class=\"close\" data-dismiss=\"alert\" type=\"button\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>"); }
conditional_block
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss) { growl.addClass("alert-dismissible"); growl.append("<...
}; } return growl; } function makeAlign(alert, options) { switch (options.align) { case "center": alert.css({ "left": "50%", "margin-left": "-" + (alert.outerWidth() / 2) + "px" }); break; case "left": ...
if (options.top_offset) { options.offset = { from: "top", amount: options.top_offset
random_line_split
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss) { growl.addClass("alert-dismissible"); growl.append("<...
let GrowlNotify = { notify: function(message, opt) { let options = $.extend({}, createOptionsDefault(), opt); let growl = createGrowl(options, message); let offsetAmount = calcNextPosition(options); let css = createStyleClass(options); css[options.offset.from] ...
{ return obj && (obj.constructor == Array); }
identifier_body
alert.js
'use strict' function createGrowl(options, message) { let growl = $("<div>"); growl.attr("class", "bootstrap-growl alert"); if (options.type) { growl.addClass("alert-" + options.type); } if (options.allow_dismiss) { growl.addClass("alert-dismissible"); growl.append("<...
(options) { return { "position": (options.ele === "body" ? "fixed" : "absolute"), "margin": 0, "z-index": "9999", "display": "none" }; } function calcNextPosition(options) { let offsetAmount = options.offset.amount; $(".bootstrap-growl").each(function() { offset...
createStyleClass
identifier_name
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import ge...
else: context = {"admin_page_title": "Delete Block", "item_name": str(block), "help_text": "Deleting this block will remove all records " "of it related to eighth period."} return render(request, "eighth/admin/delete_form.html",...
block.delete() invalidate_model(EighthBlock) messages.success(request, "Successfully deleted block.") return redirect("eighth_admin_dashboard")
conditional_block
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import ge...
(request, block_id): if "schact_id" in request.POST: response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "inline; filename=\"block_{}_rosters.pdf\"".format(block_id) sched_act_ids = request.POST.getlist("schact_id") pdf_buffer = generate_roster_...
print_block_rosters_view
identifier_name
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import ge...
if "schact_id" in request.POST: response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "inline; filename=\"block_{}_rosters.pdf\"".format(block_id) sched_act_ids = request.POST.getlist("schact_id") pdf_buffer = generate_roster_pdf(sched_act_ids, True) ...
identifier_body
blocks.py
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import ge...
form.save() invalidate_model(EighthBlock) messages.success(request, "Successfully edited block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") else: form = BlockForm(instance=block) con...
form = BlockForm(request.POST, instance=block) if form.is_valid():
random_line_split
tooltip.d.ts
// Type definitions for iview 3.1.0 // Project: https://github.com/iview/iview // Definitions by: yangdan // Definitions: https://github.com/yangdan8/iview.git import Vue, { VNode } from 'vue';
/** * 显示的内容 * @default 空 */ content?: string | number; /** * 提示框出现的位置,可选值为 * top,top-start,top-end,bottom,bottom-start,bottom-end, * left,left-start,left-end,right,right-start,right-end * 2.12.0 版本开始支持自动识别 * @default bottom */ placement?: 'top' | 'top-start' | 'top-end' | 'bottom' | '...
export declare interface Tooltip extends Vue {
random_line_split
ProofTree.js
// Structure to represent a proof class ProofTree { constructor({equation, rule, newScope=false }) { this.equation = equation; this.rule = rule; this.newScope = newScope; this.parent = null; this.children = []; this.isSound = !newScope; }
() { return this.newScope; } isEmpty() { return this.parent === null && this.children === []; } size() { if (this.isEmpty()) return 0; if (this.children.length) return 1 + this.children.map(c=>c.size()).reduce((acc, c)=>acc+c); return 1; } lastNumber() { return this.size(); ...
isAssumption
identifier_name
ProofTree.js
// Structure to represent a proof class ProofTree { constructor({equation, rule, newScope=false }) { this.equation = equation; this.rule = rule; this.newScope = newScope; this.parent = null; this.children = []; this.isSound = !newScope; } isAssumption() { return this.newScope; } ...
inScope(target) { if (this.lineNumber === target) { return true; } else { if (this.parent === null) return false; var child = null; var anySiblings = this.parent.children.some(child => { return !child.isAssumption() && (child.lineNumber === target) }) if (anySibli...
{ if (this.parent === null) return this; return this.parent.root(); }
identifier_body
ProofTree.js
// Structure to represent a proof class ProofTree { constructor({equation, rule, newScope=false }) { this.equation = equation; this.rule = rule; this.newScope = newScope; this.parent = null; this.children = []; this.isSound = !newScope; } isAssumption() { return this.newScope; } ...
} } // inScope(line1, line2, context=this.root()) { // // if (line1 === line2) return true; // if (line1 > line2) return false; // var line1Obj = context.line(line1); // var line2Obj = context.line(line2); // return this.inScope(line1Obj.lineNumber, line2Obj.parent.lineNumber, context); ...
return true; } return this.parent.inScope(target);
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; i...
(store: StoreType) { if (!store || !store.state) { return; } console.log('HMR store', JSON.stringify(store, null, 2)); // set state this.appState._state = store.state; // set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; ...
hmrOnInit
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; i...
public hmrOnInit(store: StoreType) { if (!store || !store.state) { return; } console.log('HMR store', JSON.stringify(store, null, 2)); // set state this.appState._state = store.state; // set input values if ('restoreInputValues' in store) { let restoreInputValues = store.rest...
{}
identifier_body
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; i...
} this.appRef.tick(); delete store.state; delete store.restoreInputValues; } public hmrOnDestroy(store: StoreType) { const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement); // save state const state = this.appState._state; store.state = state; // re...
// set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues);
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; i...
console.log('HMR store', JSON.stringify(store, null, 2)); // set state this.appState._state = store.state; // set input values if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues); } this.appRef.tick(); delet...
{ return; }
conditional_block
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/. */ #![deny(unsafe_code)] extern crate ipc_channel; extern crate msg; #[macro_use] extern crate serde_derive; pub ext...
pub use webvr::VRStageParameters as WebVRStageParameters; pub use webvr_traits::{WebVRMsg, WebVRResult};
pub use webvr::VRPose as WebVRPose;
random_line_split
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase fr...
# Set up the API base try: # Create an instance of the APIBase and run the constructor api_obj = APIBase( name = self.api_name, endpoint = self.endpoint, utils = self.api_utils, acl ...
return self._req_error(acl_gateway.auth_error)
random_line_split
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase fr...
# All template maps constructed return valid(LOG.info('Constructed API template map')) def handler(self): """ Main method for constructing and returning the endpoint map. @return valid|invalid """ map_rsp = self._build_m...
try: endpoint_rmap = json.loads(endpoint['rmap']) # Map base object rmap_base = { 'root': endpoint_rmap } # Merge the web socket request validator self._merge_socket(rmap_bas...
conditional_block
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase fr...
def _authenticate(self): """ Authenticate the API request. """ # Set the API user and group self.api_user = self.request['api_user'] self.api_group = None if not ('api_group' in self.request) else self.request['api_group'] LOG.info('Authenticat...
err_response = { 'message': 'An error occured when processing the API request', 'endpoint': self.endpoint, 'error': err } LOG.error('%s:%s' % (self.endpoint, err)) return HttpResponse(json.dumps(err_response), content_type='application/json', status=400)
identifier_body
request.py
import os import re import json import importlib # Django Libraries from django.http import HttpResponse, HttpResponseServerError # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.vars import T_BASE from cloudscape.engine.api.base import APIBase fr...
(self,j,e): """ Helper method used to merge token authentication parameters into the endpoint request map. Mainly so I don't have to redundantly include the same code in every map. Also makes modification much easier. """ # Ignore the authentication endpoint, as ...
_merge_auth
identifier_name
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { ...
RuleObject.prototype.validate = function (field, args) { if (this.function != null) { return this.function.apply(field, [args.value].concat(this.arguments)); } else if (this.validator != null) { return this.validator.validate(args); } else { var validator =...
this.name = name; this.function = func; this.validator = validator; this.arguments = arguments; }
identifier_body
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { ...
if (!validated) { error = { field: _this, rule: rule.name, value: validatedValue, arguments: rule.arguments }; } } }); retu...
validatedValue = result; }
conditional_block
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { ...
})(); var RuleObject = (function () { function RuleObject(name, func, validator, arguments) { this.name = name; this.function = func; this.validator = validator; this.arguments = arguments; } RuleObject.prototype.validate = function (field, args) { if (this.function ...
return Field;
random_line_split
Field.js
var Core = require('cw-core'); var Exception = Core.Exception; var ArgumentNullException = Core.ArgumentNullException; var ArgumentException = Core.ArgumentException; var Arr = Core.Arr; var Enumerable = require('linq'); var _ = require('underscore'); var Field = (function () { function Field(form, name) { ...
ame, func, validator, arguments) { this.name = name; this.function = func; this.validator = validator; this.arguments = arguments; } RuleObject.prototype.validate = function (field, args) { if (this.function != null) { return this.function.apply(field, [args.v...
leObject(n
identifier_name
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class TukeysFilter(BaseTask): def __init__(se...
quantile_75 = quantile_75.value if quantile_25 > quantile_75: self.logger.error('Inconsistent Quantile Values (Q25: %f, Q75: %f). Exiting' % ( quantile_25, quantile_75)) return None # group by metric (e.g. instance) first and find then closest datapoint ...
self.logger.error('Quantile75 Value is too old (Timestamp: %d) of: %s. Exiting' % ( quantile_75.timestamp, quantile_75.name)) return None
conditional_block
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class TukeysFilter(BaseTask): def __init__(se...
data = self.read() if data: state = self.process(data) self.write(state) return True else: return None
identifier_body
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class TukeysFilter(BaseTask): def __init__(se...
if state: invalid += 1 name = extract_service_name(name) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, name), now, state)) tuples.append(TimeSeriesTuple('%s.%s' % (prefix, 'quantile_25'), now, quantile_25)) tuples.append(TimeSeriesTuple('%s.%s' % (...
random_line_split
tukeys_filter.py
""" Outlier Detection using Tukeys Filter Class """ import sys import itertools from time import time from lib.modules.base_task import BaseTask from lib.modules.helper import extract_service_name, get_closest_datapoint from lib.modules.models import TimeSeriesTuple class
(BaseTask): def __init__(self, config, logger, options): super(TukeysFilter, self).__init__(config, logger, resource={'metric_sink': 'RedisSink', 'output_sink': 'GraphiteSink'}) self.namespace = 'TukeysFilter' self.service...
TukeysFilter
identifier_name
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
(self): return self._scm def scm_for_path(self, path): # FIXME: consider supporting more than one SCM so that we can do more comprehensive testing. self.initialize_scm() return self._scm def checkout(self): return self._checkout
scm
identifier_name
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
self.buildbot = MockBuildBot() # Note: We're using a real PortFactory here. Tests which don't wish to depend # on the list of known ports should override this with a MockPortFactory. self.port_factory = PortFactory(self) def initialize_scm(self, patch_directories=None): i...
self.initialize_scm()
conditional_block
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
return self._scm def checkout(self): return self._checkout
random_line_split
host_mock.py
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
def checkout(self): return self._checkout
self.initialize_scm() return self._scm
identifier_body