file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
globalize.culture.no.js
/* * Globalize Culture no * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to b...
Globalize.addCultureInfo( "no", "default", { name: "no", englishName: "Norwegian", nativeName: "norsk", language: "no", numberFormat: { ",": " ", ".": ",", negativeInfinity: "-INF", positiveInfinity: "INF", percent: { ",": " ", ".": "," }, currency: { pattern: ["$ -n","$ n"], ",": " ", ...
{ // Global variable Globalize = window.Globalize; }
conditional_block
access_permission_service.js
/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Relevance UI Team, * Aug 2015 */ //This is a global service and will be cache angular.module('factory.appPermission', ...
(category, permissionto, permissionset) { var perms = []; if (permissionset) { for (var i = 0; i < permissionset.length; i++) { var obj = permissionset[i].permissions; for (var j = 0; j < obj.length; j++) { if (obj[j].category === category) { var acc = obj[j].access.toString().split(',...
getpermissionforcategory
identifier_name
access_permission_service.js
/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Relevance UI Team, * Aug 2015 */ //This is a global service and will be cache angular.module('factory.appPermission', ...
} } } } if (perms.indexOf(permissionto) >= 0) { return (true); } else{ return (false); } } else { return (false); } } var permissionService = { hasPermission: function(category, permissionto){ var retVal = ''; if (!session.getUser()) { return fals...
perms.push(acc[ac]); }
random_line_split
access_permission_service.js
/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Relevance UI Team, * Aug 2015 */ //This is a global service and will be cache angular.module('factory.appPermission', ...
} else { return (false); } } var permissionService = { hasPermission: function(category, permissionto){ var retVal = ''; if (!session.getUser()) { return false; // return permission denied }else { retVal = getpermissionforcategory(category, permissionto, session.getUser().permiss...
{ return (false); }
conditional_block
access_permission_service.js
/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Relevance UI Team, * Aug 2015 */ //This is a global service and will be cache angular.module('factory.appPermission', ...
} } else { return (false); } } var permissionService = { hasPermission: function(category, permissionto){ var retVal = ''; if (!session.getUser()) { return false; // return permission denied }else { retVal = getpermissionforcategory(category, permissionto, session.getUser().pe...
{ var perms = []; if (permissionset) { for (var i = 0; i < permissionset.length; i++) { var obj = permissionset[i].permissions; for (var j = 0; j < obj.length; j++) { if (obj[j].category === category) { var acc = obj[j].access.toString().split(','); for (var ac in acc) { ...
identifier_body
ukraineGiveaways.ts
export type Giveaway = { name: string logo: string website: string description: string perk: string claimInstructions?: string } export const GIVEAWAYS = [ { name: "UNUM", logo: "https://uploads-ssl.webflow.com/61005d24feea1032c4ad8d29/61005d24feea1025daad8d51_UNUM%20Logo%20Black.svg", ...
logo: "/images/fundraiser/bearapp.jpeg", perk: "1 year of Bear Pro (only 50 spots)", description: "Bear is a beautiful, flexible writing app for crafting notes and prose.", claimInstructions: "You will receive a promo code you can use in the app." } ] as const
name: "Bear App", website: "https://bear.app",
random_line_split
box-click.service.ts
import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { BoxClickInterface, BoxClickMezzi, BoxClickRichieste } from './box-click-interface'; @Injectable({ providedIn: 'root' }) export class BoxClickService { boxClickRichieste: BoxClickRichieste = allFalse.richieste; ...
(): Observable<BoxClickInterface> { return this.clickSubject.asObservable(); } allTrue() { this.clickSubject.next(allTrue); } allFalse() { this.clickSubject.next(allFalse); } allTrueByRichiesta(statoRichiesta: string) { const richieste: BoxClickRichieste = Obje...
getBoxClick
identifier_name
box-click.service.ts
import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { BoxClickInterface, BoxClickMezzi, BoxClickRichieste } from './box-click-interface'; @Injectable({ providedIn: 'root' }) export class BoxClickService { boxClickRichieste: BoxClickRichieste = allFalse.richieste; ...
allFalse() { this.clickSubject.next(allFalse); } allTrueByRichiesta(statoRichiesta: string) { const richieste: BoxClickRichieste = Object.assign({}, allFalse.richieste); const mezzi: BoxClickMezzi = Object.assign({}, allTrue.mezzi); richieste[wipeStatoRichiesta(statoRichie...
{ this.clickSubject.next(allTrue); }
identifier_body
box-click.service.ts
import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { BoxClickInterface, BoxClickMezzi, BoxClickRichieste } from './box-click-interface'; @Injectable({ providedIn: 'root' }) export class BoxClickService { boxClickRichieste: BoxClickRichieste = allFalse.richieste; ...
mezzi: mezzi }; this.clickSubject.next(byRichiesta); } } const allFalse: BoxClickInterface = { richieste: { chiamate: false, sospesi: false, assegnati: false, presidiati: false, chiusi: false }, mezzi: { inSede: false, ...
const richieste: BoxClickRichieste = Object.assign({}, allFalse.richieste); const mezzi: BoxClickMezzi = Object.assign({}, allTrue.mezzi); richieste[wipeStatoRichiesta(statoRichiesta)] = true; const byRichiesta: BoxClickInterface = { richieste: richieste,
random_line_split
index.spec.ts
import * as path from 'path'; import { EmptyTree } from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; describe('Update 6.1.0', () => { let appTree: UnitTestTree; const schematicRunner = new SchematicTestRunner('ig-migrate', path.join(__di...
'/testSrc/appPrefix/component/test.component.html', `<igx-tab-bar attr igxForRemote="true"></igx-tab-bar>` + `<elem igxToggle (onOpen)="handler" (onClose)="handler"></elem>` ); const tree = await schematicRunner.runSchematicAsync('migration-04', {}, appTree) ...
random_line_split
settings.py
""" Django settings for keyman project. Generated by 'django-admin startproject' using Django 1.11.7. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os ...
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'
random_line_split
network.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from frame import DStatFrame from shee.util import get_result_dir_name import matplotlib.pyplot as plt import matplotlib.dates as mdates class DStatNetwork(DStatFrame): def __init__(self, filename, frame=None, eth=None, grain=False): if frame is not None: ...
ax.set_title(ylab) ax.plot(self.df[xlab], self.df[ylab]) @staticmethod def _set_subplots_time(ax, hours, mins): ax.xaxis.set_major_locator(hours) ax.xaxis.set_minor_locator(mins) ax.xaxis.set_major_formatter(mdates.DateFormatter('')) ax.xaxis.set_minor_formatter(...
ax.tick_params(axis='x', pad=20) plt.setp(ax.xaxis.get_minorticklabels(), rotation=40) def _set_subplots_title_and_plot(self, ax, xlab, ylab):
random_line_split
network.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from frame import DStatFrame from shee.util import get_result_dir_name import matplotlib.pyplot as plt import matplotlib.dates as mdates class DStatNetwork(DStatFrame): def __init__(self, filename, frame=None, eth=None, grain=False): if frame is not None: ...
(self, ax, xlab, ylab): ax.set_title(ylab) ax.plot(self.df[xlab], self.df[ylab]) @staticmethod def _set_subplots_time(ax, hours, mins): ax.xaxis.set_major_locator(hours) ax.xaxis.set_minor_locator(mins) ax.xaxis.set_major_formatter(mdates.DateFormatter('')) ax.xa...
_set_subplots_title_and_plot
identifier_name
network.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from frame import DStatFrame from shee.util import get_result_dir_name import matplotlib.pyplot as plt import matplotlib.dates as mdates class DStatNetwork(DStatFrame): def __init__(self, filename, frame=None, eth=None, grain=False): if frame is not None: ...
else: self.filename = sname + '/network/' + sname.split("/")[-1] df = self._read_dataframe(['epoch', 'net/total'], grain=grain) df.columns = df.columns.droplevel() df.ix[:, df.columns != 'epoch'] = df.ix[:, df.columns != 'epoch'].divide(1024*1024/8) self.df = df...
self.filename = sname + '/network/eth' + str(eth) + '/' + sname.split("/")[-1] df = self._read_dataframe(['epoch', 'net/eth' + str(eth)], grain=grain) self.device = eth
conditional_block
network.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from frame import DStatFrame from shee.util import get_result_dir_name import matplotlib.pyplot as plt import matplotlib.dates as mdates class DStatNetwork(DStatFrame): def __init__(self, filename, frame=None, eth=None, grain=False): if frame is not None: ...
def _set_subplots_title_and_plot(self, ax, xlab, ylab): ax.set_title(ylab) ax.plot(self.df[xlab], self.df[ylab]) @staticmethod def _set_subplots_time(ax, hours, mins): ax.xaxis.set_major_locator(hours) ax.xaxis.set_minor_locator(mins) ax.xaxis.set_major_formatter(m...
for ax in axs: ax.grid(True) ax.tick_params(axis='x', pad=20) plt.setp(ax.xaxis.get_minorticklabels(), rotation=40)
identifier_body
decoder.rs
use std::io::{Error, ErrorKind, Read, Result}; use std::ptr; use super::liblz4::*; use libc::size_t; const BUFFER_SIZE: usize = 32 * 1024; struct DecoderContext { c: LZ4FDecompressionContext, } pub struct Decoder<R> { c: DecoderContext, r: R, buf: Box<[u8]>, pos: usize, len: usize, next: ...
} assert_eq!(expected, actual); finish_decode(decoder); } }
{ let mut encoder = EncoderBuilder::new().level(1).build(Vec::new()).unwrap(); let mut expected = Vec::new(); let mut rnd: u32 = 42; for _ in 0..1027 * 1023 * 7 { expected.push((rnd & 0xFF) as u8); rnd = ((1664525 as u64) * (rnd as u64) + (1013904223 as u64)) as u...
identifier_body
decoder.rs
use std::io::{Error, ErrorKind, Read, Result}; use std::ptr; use super::liblz4::*; use libc::size_t; const BUFFER_SIZE: usize = 32 * 1024; struct DecoderContext { c: LZ4FDecompressionContext, } pub struct Decoder<R> { c: DecoderContext, r: R, buf: Box<[u8]>, pos: usize, len: usize, next: ...
finish_decode(decoder); } #[test] fn test_decoder_smoke() { let mut encoder = EncoderBuilder::new().level(1).build(Vec::new()).unwrap(); let mut expected = Vec::new(); expected.write(b"Some data").unwrap(); encoder.write(&expected[..4]).unwrap(); encoder.writ...
random_line_split
decoder.rs
use std::io::{Error, ErrorKind, Read, Result}; use std::ptr; use super::liblz4::*; use libc::size_t; const BUFFER_SIZE: usize = 32 * 1024; struct DecoderContext { c: LZ4FDecompressionContext, } pub struct Decoder<R> { c: DecoderContext, r: R, buf: Box<[u8]>, pos: usize, len: usize, next: ...
() { let mut encoder = EncoderBuilder::new().level(1).build(Vec::new()).unwrap(); let mut expected = Vec::new(); let mut rnd: u32 = 42; for _ in 0..1027 * 1023 * 7 { expected.push((rnd & 0xFF) as u8); rnd = ((1664525 as u64) * (rnd as u64) + (1013904223 as u64)) a...
test_decoder_random
identifier_name
restore_hotel_2000w_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, MySQLdb, csv table_sql = """drop table if exists hotel; create table hotel( id int primary key, Name varchar(255), CardNo varchar(255), Descriot varchar(255), CtfTp varchar(255), CtfId varchar(255), Gender varchar(255), Birthday v...
if __name__ == "__main__": main()
db = MySQLdb.connect(user='root', passwd='oseasy_db', db='test', use_unicode=True) insert_sql = "insert into hotel('Name', 'CardNo', 'Descriot', 'CtfTp', 'CtfId', 'Gender', 'Birthday', 'Address', 'Zip', 'Dirty', 'District1', 'District2', 'District3', 'District4', 'District5', 'District6', 'FirstNm', 'LastNm', 'Duty...
identifier_body
restore_hotel_2000w_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, MySQLdb, csv table_sql = """drop table if exists hotel; create table hotel( id int primary key, Name varchar(255), CardNo varchar(255), Descriot varchar(255), CtfTp varchar(255), CtfId varchar(255), Gender varchar(255), Birthday v...
db.commit() db.close() if __name__ == "__main__": main()
for i, val in enumerate(row): if isinstance(val, basestring): row[i] = val.decode('utf-8') row[-1] = int(row[-1]) cursor.execute(insert_sql, row)
conditional_block
restore_hotel_2000w_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, MySQLdb, csv table_sql = """drop table if exists hotel; create table hotel( id int primary key, Name varchar(255), CardNo varchar(255), Descriot varchar(255), CtfTp varchar(255), CtfId varchar(255), Gender varchar(255), Birthday v...
CZip varchar(255), Family varchar(255), Version varchar(255) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;""" def main(): db = MySQLdb.connect(user='root', passwd='oseasy_db', db='test', use_unicode=True) insert_sql = "insert into hotel('Name', 'CardNo', 'Descriot', 'CtfTp', 'CtfId', 'Gender', 'Birthday', ...
Company varchar(255), CTel varchar(255), CAddress varchar(255),
random_line_split
restore_hotel_2000w_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, MySQLdb, csv table_sql = """drop table if exists hotel; create table hotel( id int primary key, Name varchar(255), CardNo varchar(255), Descriot varchar(255), CtfTp varchar(255), CtfId varchar(255), Gender varchar(255), Birthday v...
(): db = MySQLdb.connect(user='root', passwd='oseasy_db', db='test', use_unicode=True) insert_sql = "insert into hotel('Name', 'CardNo', 'Descriot', 'CtfTp', 'CtfId', 'Gender', 'Birthday', 'Address', 'Zip', 'Dirty', 'District1', 'District2', 'District3', 'District4', 'District5', 'District6', 'FirstNm', 'LastNm...
main
identifier_name
StringInOutNode.py
########################################################################## # # Copyright (c) 2012, John Haddon. 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 so...
if output.isSame( self["out"] ) : self["in"].hash( h ) self.numHashCalls += 1 def compute( self, plug, context ) : if plug.isSame( self["out"] ) : plug.setValue( self["in"].getValue() ) self.numComputeCalls += 1 IECore.registerRunTimeTyped( StringInOutNode, typeName = "GafferTest::StringInOutNode"...
def __init__( self, name="StringInOutNode", defaultValue="", substitutions = IECore.StringAlgo.Substitutions.AllSubstitutions ) : Gaffer.ComputeNode.__init__( self, name ) self.addChild( Gaffer.StringPlug( "in", Gaffer.Plug.Direction.In, defaultValue, substitutions = substitutions ) ) self.addChild( Gaffer.Stri...
identifier_body
StringInOutNode.py
########################################################################## # # Copyright (c) 2012, John Haddon. 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 so...
return outputs def hash( self, output, context, h ) : if output.isSame( self["out"] ) : self["in"].hash( h ) self.numHashCalls += 1 def compute( self, plug, context ) : if plug.isSame( self["out"] ) : plug.setValue( self["in"].getValue() ) self.numComputeCalls += 1 IECore.registerRunTimeTyped...
outputs.append( self["out"] )
conditional_block
StringInOutNode.py
########################################################################## # # Copyright (c) 2012, John Haddon. 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 so...
import Gaffer class StringInOutNode( Gaffer.ComputeNode ) : def __init__( self, name="StringInOutNode", defaultValue="", substitutions = IECore.StringAlgo.Substitutions.AllSubstitutions ) : Gaffer.ComputeNode.__init__( self, name ) self.addChild( Gaffer.StringPlug( "in", Gaffer.Plug.Direction.In, defaultValue,...
# ########################################################################## import IECore
random_line_split
StringInOutNode.py
########################################################################## # # Copyright (c) 2012, John Haddon. 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 so...
( self, input ) : outputs = Gaffer.ComputeNode.affects( self, input ) if input.isSame( self["in"] ) : outputs.append( self["out"] ) return outputs def hash( self, output, context, h ) : if output.isSame( self["out"] ) : self["in"].hash( h ) self.numHashCalls += 1 def compute( self, plug, contex...
affects
identifier_name
contrib-remove.js
'use strict'; // Modules const _ = require('lodash'); const LandoApiClient = require('./../lib/api'); module.exports = lando => { // Get the API client const api = new LandoApiClient(lando.log); // Return the task
id: { describe: 'The resource id to remove', alias: ['i'], string: true, interactive: { type: 'list', message: 'Which contributor do you want to remove?', choices: _(api.read('contributors')) .map(contributor => ({name: contributor.name, va...
return { command: 'contrib:remove', level: 'tasks', describe: 'Removes a Lando Contributor', options: {
random_line_split
StatusIcon.tsx
/* * 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/. * */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { s...
flex-direction: column; white-space: wrap; max-width: 200px; margin-bottom: -15px; padding: 0 5px; background-color: #000; color: white; z-index: 9999; `; const TooltipHeader = styled('div')` font-size: 16px; font-weight: bold; `; const TooltipDescription = styled('p')` font-size: 12px; `; expo...
random_line_split
StatusIcon.tsx
/* * 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/. * */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { s...
private onShowTooltip = (event: MouseEvent) => { const content = <TooltipContainer> <TooltipHeader>{this.props.status.name}</TooltipHeader> <TooltipDescription>{this.props.status.description}</TooltipDescription> </TooltipContainer>; showTooltip({ content, event }); } priva...
{ return !_.isEqual(nextProps.status, this.props.status); }
identifier_body
StatusIcon.tsx
/* * 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/. * */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { s...
else { return null; } } public shouldComponentUpdate(nextProps: StatusIconProps, nextState: StatusIconState) { return !_.isEqual(nextProps.status, this.props.status); } private onShowTooltip = (event: MouseEvent) => { const content = <TooltipContainer> <TooltipHeader>{this.pro...
{ return ( <Container> <Icon onMouseEnter={this.onShowTooltip} onMouseLeave={this.onHideTooltip} style={{ backgroundImage: `url(${status.iconURL}), url(images/unknown-item.jpg)` }} /> </Container> ); }
conditional_block
StatusIcon.tsx
/* * 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/. * */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { s...
() { const { status } = this.props; if (status) { return ( <Container> <Icon onMouseEnter={this.onShowTooltip} onMouseLeave={this.onHideTooltip} style={{ backgroundImage: `url(${status.iconURL}), url(images/unknown-item.jpg)` }} /> </...
render
identifier_name
conf.py
another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documen...
# Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category)
random_line_split
conf.py
configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative ...
# get all the versions that will appear in the version dropdown f = open(join(dirname(abspath(__file__)), "all_versions.txt")) all_versions = [x.strip() for x in reversed(f.readlines())] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None #...
ersion = release = settings.docs_version()
conditional_block
__init__.py
You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License...
(host, user='~'): # check for ssh host key hasKey = False userknownhosts = os.path.expanduser('%s/.ssh/known_hosts' % user) for file in [ '/etc/ssh/ssh_known_hosts', userknownhosts ]: for line in open(file): if host in line: hasKey = True break if ...
check_known_hosts
identifier_name
__init__.py
You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License...
child.expect('/admin1->') if debug: print '\n'.join(child.before.split('\n')[1:]) else: print '+- Skipping password change for: %s' % cfg.duser if not configured: print ' because %s was not successfully created' % cfg.puser # leaving drac print '+- Exiting DRAC' child....
# alter password for root user if cfg.puser in userdata: print '+- Changing password for: %s' % cfg.duser child.sendline('%s 2 -o cfgUserAdminPassword %s' % (adm_pre,cfg.dpass))
random_line_split
__init__.py
You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License...
out['eth%d' % (int(num)-1)] = match.group('hwaddr') else: for key in match.groupdict().keys(): out[key] = match.group(key) if key == 'model' and re.match('PowerEdge', match.group(key)): ou...
""" Parses information returned from drac getsysinfo command and returns it as a dictionary """ out={} parsers = [ r'(Firmware Version\s+=\s(?P<firmware>[.\d]+))', r'(System BIOS Version\s+=\s(?P<bios>[.\d]+))', r'(System Model\s+=\s(?P<model>[ \w]+))', r'(Service Tag...
identifier_body
__init__.py
You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License...
# leaving drac print '+- Exiting DRAC' child.sendline('exit') child.expect('CLP Session terminated') if basics or ipmi: # enable IPMI, continued # settings new admin user privileges with IPMI (apparently racadm was not enough) print '+- Updating IP
print ' because %s was not successfully created' % cfg.puser
conditional_block
profile.container.ts
* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it wi...
/** * Copyright (C) 2017 3D Repo Ltd *
random_line_split
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ from abc import ABCMeta, abstractmethod from django.contrib.auth.models import User, Group from xmodule.modulestore import Location from xmodule.modulest...
(OrgRole): """An organization staff member""" def __init__(self, *args, **kwargs): super(OrgStaffRole, self).__init__('staff', *args, **kwargs) class OrgInstructorRole(OrgRole): """An organization instructor""" def __init__(self, *args, **kwargs): super(OrgInstructorRole, self).__init_...
OrgStaffRole
identifier_name
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ from abc import ABCMeta, abstractmethod from django.contrib.auth.models import User, Group from xmodule.modulestore import Location from xmodule.modulest...
locator = loc_mapper().translate_location(location.course_id, location, False, False) groupnames.append('{0}_{1}'.format(role, locator.package_id)) except (InvalidLocationError, ItemNotFoundError): # if it's never been mapped, the auth won't be via the Locator...
if course_context is None: raise CourseContextRequired() else: groupnames.append('{0}_{1}'.format(role, course_context)) try:
random_line_split
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ from abc import ABCMeta, abstractmethod from django.contrib.auth.models import User, Group from xmodule.modulestore import Location from xmodule.modulest...
def remove_users(self, *users): """ Remove the supplied django users from this role. """ group, _ = Group.objects.get_or_create(name=self._group_names[0]) group.user_set.remove(*users) for user in users: if hasattr(user, '_groups'): del u...
if hasattr(user, '_groups'): del user._groups
conditional_block
roles.py
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ from abc import ABCMeta, abstractmethod from django.contrib.auth.models import User, Group from xmodule.modulestore import Location from xmodule.modulest...
if course_context is None: raise CourseContextRequired() else: groupnames.append('{0}_{1}'.format(role, course_context)) try: locator = loc_mapper().translate_location(location.course_id, location, False, False) ...
""" A named role in a particular course """ def __init__(self, role, location, course_context=None): """ Location may be either a Location, a string, dict, or tuple which Location will accept in its constructor, or a CourseLocator. Handle all these giving some preference to t...
identifier_body
organizeImports.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
import API from '../utils/api'; import { nulToken } from '../utils/cancellation'; import { Command, CommandManager } from '../utils/commandManager'; import { conditionalRegistration, requireMinVersion } from '../utils/dependentRegistration'; import { DocumentSelector } from '../utils/documentSelector'; import { Telemet...
import * as vscode from 'vscode'; import * as nls from 'vscode-nls'; import type * as Proto from '../protocol'; import { ITypeScriptServiceClient } from '../typescriptService';
random_line_split
organizeImports.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
( private readonly client: ITypeScriptServiceClient, private readonly telemetryReporter: TelemetryReporter, ) { } public async execute(file: string): Promise<boolean> { /* __GDPR__ "organizeImports.execute" : { "${include}": [ "${TypeScriptCommonProperties}" ] } */ this.telemetryReporter...
constructor
identifier_name
organizeImports.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
const edits = typeconverts.WorkspaceEdit.fromFileCodeEdits(this.client, response.body); return vscode.workspace.applyEdit(edits); } } export class OrganizeImportsCodeActionProvider implements vscode.CodeActionProvider { public static readonly minVersion = API.v280; public constructor( private readonly clie...
{ return false; }
conditional_block
show.rs
use actix_identity::Identity; use actix_web::{error, get, web, Error, HttpResponse, Result}; use askama::Template; use crate::DbPool; use super::actions; use crate::models::Like; use crate::uri_helpers::*; use crate::utils as filters; #[derive(Template)] #[template(path = "likes/show.html.jinja")] struct Show<'a> {...
Ok(HttpResponse::Ok().content_type("text/html; charset=utf-8").body(s)) }
{ let like = web::block(move || { let conn = pool.get()?; actions::get_like(id.into_inner(), &conn) }) .await? .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; let s = Show { title: Some(&format!("♥ {}", like.in_reply_to)), page_type:...
identifier_body
show.rs
use actix_identity::Identity; use actix_web::{error, get, web, Error, HttpResponse, Result}; use askama::Template; use crate::DbPool; use super::actions; use crate::models::Like; use crate::uri_helpers::*; use crate::utils as filters;
#[derive(Template)] #[template(path = "likes/show.html.jinja")] struct Show<'a> { title: Option<&'a str>, page_type: Option<&'a str>, page_image: Option<&'a str>, body_id: Option<&'a str>, logged_in: bool, like: &'a Like, index: bool, atom: bool, } #[get("/{id}")] pub async fn show(id...
random_line_split
show.rs
use actix_identity::Identity; use actix_web::{error, get, web, Error, HttpResponse, Result}; use askama::Template; use crate::DbPool; use super::actions; use crate::models::Like; use crate::uri_helpers::*; use crate::utils as filters; #[derive(Template)] #[template(path = "likes/show.html.jinja")] struct
<'a> { title: Option<&'a str>, page_type: Option<&'a str>, page_image: Option<&'a str>, body_id: Option<&'a str>, logged_in: bool, like: &'a Like, index: bool, atom: bool, } #[get("/{id}")] pub async fn show(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpRe...
Show
identifier_name
jwt-optional.hook.ts
// 3p import { HookDecorator } from '@foal/core'; // FoalTS import { JWT, JWTOptions, VerifyOptions } from './jwt.hook'; /** * Hook factory to authenticate users using JSON Web Tokens. * * The hook does not return any error when no user could be authenticated. * * If `options.cookie` is not defined, the hook exp...
{ return JWT(false, options, verifyOptions); }
identifier_body
jwt-optional.hook.ts
// 3p import { HookDecorator } from '@foal/core'; // FoalTS import { JWT, JWTOptions, VerifyOptions } from './jwt.hook'; /** * Hook factory to authenticate users using JSON Web Tokens. * * The hook does not return any error when no user could be authenticated. * * If `options.cookie` is not defined, the hook exp...
(options: JWTOptions = {}, verifyOptions: VerifyOptions = {}): HookDecorator { return JWT(false, options, verifyOptions); }
JWTOptional
identifier_name
jwt-optional.hook.ts
// 3p import { HookDecorator } from '@foal/core'; // FoalTS import { JWT, JWTOptions, VerifyOptions } from './jwt.hook'; /** * Hook factory to authenticate users using JSON Web Tokens.
* The hook does not return any error when no user could be authenticated. * * If `options.cookie` is not defined, the hook expects the JWT to be included in the * `Authorization` header using the `Bearer` schema. Once the token is verified and decoded, * `ctx.user` is set with the payload (by default) or a custom ...
*
random_line_split
textarea-live-pseudo-selectors.js
description("This test performs a check that :valid/:invalid CSS psudo selectors are lively applied."); // Setup for static elements. var form = document.createElement('form'); document.body.appendChild(form); var nonForm = document.createElement('div'); document.body.appendChild(nonForm); function makeInvalid() { ...
// value change // -------------------------------- debug('Change the value by DOM attribute:'); el = makeInvalid(); el.value = 'abc'; shouldBe(elBackground, 'validColor'); el.value = ''; shouldBe(elBackground, 'invalidColor'); debug('Change the value by key input:'); el = makeInvalid(); el.focus(); eventSender.ke...
random_line_split
textarea-live-pseudo-selectors.js
description("This test performs a check that :valid/:invalid CSS psudo selectors are lively applied."); // Setup for static elements. var form = document.createElement('form'); document.body.appendChild(form); var nonForm = document.createElement('div'); document.body.appendChild(nonForm); function makeInvalid()
function backgroundOf(el) { return document.defaultView.getComputedStyle(el, null).getPropertyValue('background-color'); } var elBackground = 'backgroundOf(el)'; var invalidColor = 'rgb(255, 0, 0)'; var normalColor = 'rgb(255, 255, 255)'; var disabledColor = 'rgb(0, 0, 0)'; var readOnlyColor = 'rgb(0, 255, 0)'; ...
{ var i = document.createElement('textarea'); i.name = 'foo'; i.required = true; i.value = ''; form.appendChild(i); return i; }
identifier_body
textarea-live-pseudo-selectors.js
description("This test performs a check that :valid/:invalid CSS psudo selectors are lively applied."); // Setup for static elements. var form = document.createElement('form'); document.body.appendChild(form); var nonForm = document.createElement('div'); document.body.appendChild(nonForm); function makeInvalid() { ...
(el) { return document.defaultView.getComputedStyle(el, null).getPropertyValue('background-color'); } var elBackground = 'backgroundOf(el)'; var invalidColor = 'rgb(255, 0, 0)'; var normalColor = 'rgb(255, 255, 255)'; var disabledColor = 'rgb(0, 0, 0)'; var readOnlyColor = 'rgb(0, 255, 0)'; var validColor = 'rgb(0...
backgroundOf
identifier_name
matcher.py
import itertools, logging from gibbs.models import CommonName, Compound, Enzyme from haystack.query import SearchQuerySet class Error(Exception): pass class IllegalQueryError(Error): pass class Match(object): """An object containing a string match and it's score.""" def __init__(self, key, va...
group_key = lambda match: match.Key() filtered_matches = [] for _, g in itertools.groupby(filtered, key=group_key): # Keep the unique match with the top score. max_match = None for match in g: if not max_match or max_match.score < match.score: ...
random_line_split
matcher.py
import itertools, logging from gibbs.models import CommonName, Compound, Enzyme from haystack.query import SearchQuerySet class Error(Exception): pass class IllegalQueryError(Error): pass class Match(object): """An object containing a string match and it's score.""" def __init__(self, key, va...
elif self.IsEnzyme(): return 'Enzyme' return '' def IsCompound(self): return isinstance(self.value, Compound) def IsEnzyme(self): return isinstance(self.value, Enzyme) def Key(self): if self.IsCompound(): return self.value.kegg_id ...
return 'Compound'
conditional_block
matcher.py
import itertools, logging from gibbs.models import CommonName, Compound, Enzyme from haystack.query import SearchQuerySet class Error(Exception):
class IllegalQueryError(Error): pass class Match(object): """An object containing a string match and it's score.""" def __init__(self, key, value, score): """Initialize a Match. Args: key: the object that matched. value: the value of the match (the ...
pass
identifier_body
matcher.py
import itertools, logging from gibbs.models import CommonName, Compound, Enzyme from haystack.query import SearchQuerySet class Error(Exception): pass class IllegalQueryError(Error): pass class Match(object): """An object containing a string match and it's score.""" def __init__(self, key, va...
(self, query, match): """Get the score for a query-match pair. Args: query: the query string. match: the Match object. Returns: A score between 0.0 and 1.0. """ query_len = float(len(query)) candidate_len = float(len(s...
_GetScore
identifier_name
error.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 ...
}
}
random_line_split
convert.py
self._export_age_info() # Step 2: Gather a list of objects that we need to export, given what the user has told # us to export (both in the Age and Object Properties)... fun self._collect_objects() # Step 2.1: Run through all the...
def _export_empty_blobj(self, so, bo): self.animation.convert_object_animations(bo, so) def _export_lamp_blobj(self, so, bo): self.animation.convert_object_animations(bo, so) self.light.export_rtlight(so, bo) def _export_mesh_blobj(self, so, bo):
camera = bo.data.plasma_camera self.camera.export_camera(so, bo, camera.camera_type, camera.settings, camera.transitions)
identifier_body
convert.py
if parent.plasma_object.enabled: self.report.msg("Attaching to parent SceneObject '{}'", parent.name, indent=1) parent_ci = self._export_coordinate_interface(None, parent) parent_ci.addChild(so.key) else: self.report.warn("You have parented Pl...
do_pre_export(bl_obj) inc_progress()
conditional_block
convert.py
to see if that is enabled... for page in age.pages: if page.seq_suffix == 0: default_enabled = page.enabled default_inited = True break else: default_enabled = True default_inited = False # Now we loop through ...
# So, we have to keep in mind shared layers (whee) in the synch options kode
random_line_split
convert.py
that the SceneObject has a CoordinateInterface""" if so is None: so = self.mgr.find_create_object(plSceneObject, bl=bl) if so.coord is None: ci_cls = bl.plasma_object.ci_type ci = self.mgr.add_object(ci_cls, bl=bl, so=so) # Now we have the "fun" work of ...
_save_age
identifier_name
helper_each.rs
use serialize::json::{Json, ToJson}; use helpers::{HelperDef}; use registry::{Registry}; use context::{Context}; use render::{Renderable, RenderContext, RenderError, render_error, Helper}; #[derive(Clone, Copy)] pub struct EachHelper; impl HelperDef for EachHelper{ fn
(&self, c: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<(), RenderError> { let param = h.param(0); if param.is_none() { return Err(render_error("Param not found for helper \"each\"")); } let template = h.template(); match template { ...
call
identifier_name
helper_each.rs
use serialize::json::{Json, ToJson}; use helpers::{HelperDef}; use registry::{Registry}; use context::{Context}; use render::{Renderable, RenderContext, RenderError, render_error, Helper}; #[derive(Clone, Copy)] pub struct EachHelper; impl HelperDef for EachHelper{ fn call(&self, c: &Context, h: &Helper, r: &Reg...
for i in 0..len { rc.set_local_var("@first".to_string(), (i == 0usize).to_json()); rc.set_local_var("@last".to_string(), (i == len - 1).to_json()); rc.set_local_var("@index".to_string(), i.to_json()); ...
let len = list.len();
random_line_split
helper_each.rs
use serialize::json::{Json, ToJson}; use helpers::{HelperDef}; use registry::{Registry}; use context::{Context}; use render::{Renderable, RenderContext, RenderError, render_error, Helper}; #[derive(Clone, Copy)] pub struct EachHelper; impl HelperDef for EachHelper{ fn call(&self, c: &Context, h: &Helper, r: &Reg...
, _ => { Err(render_error("Param is not an iteratable.")) } }; rc.set_path(path); rc.demote_local_vars(); rendered }, None => Ok(()) } } } pub static EACH_...
{ let mut first:bool = true; for k in obj.keys() { rc.set_local_var("@first".to_string(), first.to_json()); if first { first = false; } ...
conditional_block
context.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/. */ //! Data needed by the layout task. #![allow(unsafe_code)] use css::matching::{ApplicableDeclarationsCache, Styl...
pub fn heap_size_of_local_context() -> usize { LOCAL_CONTEXT_KEY.with(|r| { r.borrow().clone().map_or(0, |context| context.heap_size_of_children()) }) } fn create_or_get_local_context(shared_layout_context: &SharedLayoutContext) -> Rc<LocalLayoutContext> { LOCAL_CONT...
} thread_local!(static LOCAL_CONTEXT_KEY: RefCell<Option<Rc<LocalLayoutContext>>> = RefCell::new(None));
random_line_split
context.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/. */ //! Data needed by the layout task. #![allow(unsafe_code)] use css::matching::{ApplicableDeclarationsCache, Styl...
(&self) -> usize { self.font_context.heap_size_of_children() } } thread_local!(static LOCAL_CONTEXT_KEY: RefCell<Option<Rc<LocalLayoutContext>>> = RefCell::new(None)); pub fn heap_size_of_local_context() -> usize { LOCAL_CONTEXT_KEY.with(|r| { r.borrow().clone().map_or(0, |context| context.hea...
heap_size_of_children
identifier_name
manual_admin_registration.py
.repository.editor.superadmin import SchemaModelAdmin from metashare.repository.models import resourceInfoType_model, \ identificationInfoType_model, metadataInfoType_model, \ communicationInfoType_model, validationInfoType_model, \ relationInfoType_model, foreseenUseInfoType_model, \ corpusMediaTypeTyp...
(AdminRelatedInfo, SchemaModelAdmin): exclude = ('source_url', 'copy_status') list_display = ('instance_data', 'num_related_resources', 'related_resources') def instance_data(self, obj): return obj.__unicode__() instance_data.short_description = _('Project') class DocumentModelAdmin(AdminR...
ProjectModelAdmin
identifier_name
manual_admin_registration.py
are.repository.editor.superadmin import SchemaModelAdmin from metashare.repository.models import resourceInfoType_model, \ identificationInfoType_model, metadataInfoType_model, \ communicationInfoType_model, validationInfoType_model, \ relationInfoType_model, foreseenUseInfoType_model, \ corpusMediaType...
#### end modification #### context = { 'title': _('Change %s') % force_unicode(opts.verbose_name), 'adminform': adminForm, 'object_id': object_id, 'original': obj, 'is_popup': "_popup" in request.REQUEST or \ "_popup_o2...
media = media + adminForm.media
random_line_split
manual_admin_registration.py
.repository.editor.superadmin import SchemaModelAdmin from metashare.repository.models import resourceInfoType_model, \ identificationInfoType_model, metadataInfoType_model, \ communicationInfoType_model, validationInfoType_model, \ relationInfoType_model, foreseenUseInfoType_model, \ corpusMediaTypeTyp...
if '_popup' in request.REQUEST: if request.POST.has_key("_continue"): return self.save_and_continue_in_popup(obj, request) return self.edit_response_close_popup_magic(obj) else: return super(DocumentUnstructuredStringModelAdmin, self).response_change(...
caller = None if '_caller' in request.REQUEST: caller = request.REQUEST['_caller'] return self.edit_response_close_popup_magic_o2m(obj, caller)
conditional_block
manual_admin_registration.py
.repository.editor.superadmin import SchemaModelAdmin from metashare.repository.models import resourceInfoType_model, \ identificationInfoType_model, metadataInfoType_model, \ communicationInfoType_model, validationInfoType_model, \ relationInfoType_model, foreseenUseInfoType_model, \ corpusMediaTypeTyp...
if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)}) if request.method == 'POST' and "_saveasnew" in request.POST: return self.add_view(request, form_url='../add/') ...
""" The 'change' admin view for this model. This follows closely the base implementation from Django 1.3's django.contrib.admin.options.ModelAdmin, with the explicitly marked modifications. """ # pylint: disable-msg=C0103 model = self.model opts = model._m...
identifier_body
mod.rs
; pub mod audiotrack; pub mod audiotracklist; pub mod baseaudiocontext; pub mod beforeunloadevent; pub mod bindings; pub mod biquadfilternode; pub mod blob; pub mod bluetooth; pub mod bluetoothadvertisingevent; pub mod bluetoothcharacteristicproperties; pub mod bluetoothdevice; pub mod bluetoothpermissionresult; pub mo...
pub mod xrinputsourcearray; pub mod xrinputsourceevent; pub mod xrpose; pub mod xrreferencespace; pub mod xrrenderstate;
random_line_split
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib 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 ap...
* ## Notes * * - The function assumes host byte order (endianness). * * @param bytes - byte array * @param stride - index stride * @param offset - index offset * @returns double-precision floating-point number * * @example * var Uint8Array = require( `@stdlib/array/uint8` ); * * var bytes = new Uint8Array( [ 255, 255...
import { NumericArray } from '@stdlib/types/array'; /** * Converts a signed 64-bit integer byte array to a double-precision floating-point number. *
random_line_split
file.py
import errno import os import sys from contextlib import contextmanager @contextmanager def
(filename: str, mode: str = "r", encoding: str = "utf-8"): try: f = open(filename, mode=mode, encoding=encoding) except IOError as err: yield None, err else: try: yield f, None finally: f.close() def get_next_file_path(folder: str, base_filename: str...
open_with_error
identifier_name
file.py
import errno import os import sys from contextlib import contextmanager @contextmanager def open_with_error(filename: str, mode: str = "r", encoding: str = "utf-8"): try: f = open(filename, mode=mode, encoding=encoding) except IOError as err: yield None, err else: try: ...
full_path = folder + base_filename if not os.path.isfile(full_path): return full_path filename, file_extension = os.path.splitext(base_filename) min_nbr, max_nbr = 1, 2 while os.path.isfile( os.path.join(folder, pattern.format(filename=filename, nb=str(max_nbr), ext=file_ext...
folder += os.path.sep
conditional_block
file.py
import errno import os import sys from contextlib import contextmanager @contextmanager def open_with_error(filename: str, mode: str = "r", encoding: str = "utf-8"): try: f = open(filename, mode=mode, encoding=encoding) except IOError as err: yield None, err
def get_next_file_path(folder: str, base_filename: str): """ Python version of this C# code: http://stackoverflow.com/a/1078898 Given a base file name, creates a unique filename. Check to see if the given file exists, and if it does tries to find the next available file name by appending numbers to t...
else: try: yield f, None finally: f.close()
random_line_split
file.py
import errno import os import sys from contextlib import contextmanager @contextmanager def open_with_error(filename: str, mode: str = "r", encoding: str = "utf-8"):
def get_next_file_path(folder: str, base_filename: str): """ Python version of this C# code: http://stackoverflow.com/a/1078898 Given a base file name, creates a unique filename. Check to see if the given file exists, and if it does tries to find the next available file name by appending numbers to ...
try: f = open(filename, mode=mode, encoding=encoding) except IOError as err: yield None, err else: try: yield f, None finally: f.close()
identifier_body
mod.rs
#[allow(dead_code)] // FIXME pub mod environment; #[macro_use] pub mod logger; #[macro_use] pub mod term; #[cfg(test)] pub mod test; pub mod table; #[macro_export] //TODO move to more relevant place macro_rules! update_json_map_opt_key { ($map:expr, $key:expr, $val:expr) => (match $val { Some(val) => { $ma...
self::execute, Some(self::cleanup), ) } ) } #[macro_export] //TODO move to more relevant place macro_rules! unwrap_or_return { ($result:expr, $err:expr) => { match $result { Some(res) => res, None => return $err }; ...
macro_rules! command_with_cleanup { ($meta:expr) => ( pub fn new() -> Command { Command::new( $meta,
random_line_split
useErrorModal.tsx
import { createContext, useContext, useState } from "react" import { ErrorModal } from "v2/Components/Modal/ErrorModal" interface ErrorModalContextT { openErrorModal: ( modalHeader?: string, contactEmailDisplayed?: string, modalCloseButtonText?: string ) => void isErrorModalOpen: boolean } const Err...
}} > <ErrorModal show={isErrorModalOpen} headerText={headerText} contactEmail={contactEmail} closeText={closeText} onClose={() => setIsErrorModalOpen(false)} /> {children} </ErrorModalContext.Provider> ) } export const useErrorModal = () => useC...
<ErrorModalContext.Provider value={{ openErrorModal, isErrorModalOpen,
random_line_split
quantum.py
stop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2012 Yahoo! Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses...
# Config files (some only modified if running as openvswitch) PLUGIN_CONF = "plugins.ini" QUANTUM_CONF = 'quantum.conf' PLUGIN_LOC = ['etc'] AGENT_CONF = 'ovs_quantum_plugin.ini' AGENT_LOC = ["etc", "quantum", "plugins", "openvswitch"] AGENT_BIN_LOC = ["quantum", "plugins", "openvswitch", 'agent'] CONFIG_FILES = [PLUGI...
# Openvswitch special settings VSWITCH_PLUGIN = 'openvswitch' V_PROVIDER = "quantum.plugins.openvswitch.ovs_quantum_plugin.OVSQuantumPlugin"
random_line_split
quantum.py
=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2012 Yahoo! Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LIC...
(self, *args, **kargs): comp.PkgInstallComponent.__init__(self, *args, **kargs) self.q_vswitch_agent = False self.q_vswitch_service = False plugin = self.cfg.getdefaulted("quantum", "q_plugin", VSWITCH_PLUGIN) if plugin == VSWITCH_PLUGIN: self.q_vswitch_agent = True ...
__init__
identifier_name
quantum.py
stop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2012 Yahoo! Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses...
else: return comp.PkgInstallComponent._config_adjust(self, contents, config_fn) def _setup_bridge(self): if not self.q_vswitch_agent or \ 'no-ovs-bridge-init' in self.options: return bridge = self.cfg.getdefaulted("quantum", "ovs_bridge", 'br-int') ...
newcontents = contents with io.BytesIO(contents) as stream: config = cfg.IgnoreMissingConfigParser() config.readfp(stream) db_dsn = config.get("DATABASE", "sql_connection") if db_dsn: generated_dsn = db.fetch_dbdsn(self.cfg,...
conditional_block
quantum.py
stop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2012 Yahoo! Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses...
def _get_apps_to_start(self): app_list = comp.ProgramRuntime._get_apps_to_start(self) if self.q_vswitch_service: app_list.append({ 'name': APP_Q_SERVER, 'path': sh.joinpths(self.app_dir, BIN_DIR, APP_Q_SERVER), }) if self.q_vs...
comp.ProgramRuntime.__init__(self, *args, **kargs) self.q_vswitch_agent = False self.q_vswitch_service = False plugin = self.cfg.getdefaulted("quantum", "q_plugin", VSWITCH_PLUGIN) if plugin == VSWITCH_PLUGIN: # Default to on if not specified self.q_vswitch_agent ...
identifier_body
rao.py
= a_M2.nonzero() IDX2 = [(x, y) for x, y in zip(X, Y) if (x, y) not in IDX1] IDX = list(IDX1) IDX.extend(IDX2) IDX.sort() for x_i, y_i in IDX: # print("a_M1[{:d}, {:d}] = {:f}".format(x_i, y_i, a_M1[x_i, y_i])) # print("a_M2[{:d}, {:d}] = {:f}".format(x_i, y_i, a_M2[x_i, y_i])) ...
_set_neut_one
identifier_name
rao.py
eq_sparse(a_M1, a_M2):
IDX.sort() for x_i, y_i in IDX: # print("a_M1[{:d}, {:d}] = {:f}".format(x_i, y_i, a_M1[x_i, y_i])) # print("a_M2[{:d}, {:d}] = {:f}".format(x_i, y_i, a_M2[x_i, y_i])) # print("is_close", np.isclose(a_M1[x_i, y_i], a_M2[x_i, y_i])) if not np.isclose(a_M1[x_i, y_i], a_M2[x_i, y_i...
"""Compare two sparse matrices. @param a_M1 - first sparse matrix to compare @param a_M2 - second sparse matrix to compare @return True if both matrices are equal, non-False otherwise """ if type(a_M1) != type(a_M2): return False if not np.allclose(a_M1.get_shape(), a_M1.get_shape())...
identifier_body
rao.py
eq_sparse(a_M1, a_M2): """Compare two sparse matrices. @param a_M1 - first sparse matrix to compare @param a_M2 - second sparse matrix to compare @return True if both matrices are equal, non-False otherwise """ if type(a_M1) != type(a_M2): return False if not np.allclose(a_M1.get...
def prune_normalize(a_M): """Make each of the adjacency matrix sum up to one. Args: a_M (scipy.sparse.csr): matrix to be normalized Returns: void: Note: modifies the input matrix in place """ # remove negative transitions nonzero_xy = a_M.nonzero() for i, j in zi...
a_Y[i, j] /= float(Z[i, 0]) or 1. # print("*a_Y[{:d}, {:d}] =".format(i, j), repr(a_Y[i, j]))
conditional_block
rao.py
eq_sparse(a_M1, a_M2): """Compare two sparse matrices. @param a_M1 - first sparse matrix to compare @param a_M2 - second sparse matrix to compare @return True if both matrices are equal, non-False otherwise """ if type(a_M1) != type(a_M2): return False if not np.allclose(a_M1.get...
Z = a_M.sum(0) nonzero_xy = a_M.nonzero() for i, j in zip(*nonzero_xy): a_M[i, j] /= float(Z[0, j]) or 1. def rao_min_cut(a_germanet, a_pos, a_neg, a_neut, a_seed_pos, a_ext_syn_rels): """Extend sentiment lexicons using the min-cut method of Rao (2009). @param a_germanet -...
# normalize all outgoing transitions
random_line_split
ColorPickerTestStory.tsx
import { storiesOf } from '@storybook/react'; import * as React from 'react'; import { ColorPicker } from '..'; import { StoryCategory } from '../../../../stories/storyHierarchy'; function
(props?: any) { const [selectedColorName, setSelectedColorName] = React.useState('white'); const _onChange = (value) => setSelectedColorName(value); const PRODUCT_COLORS = { 1: 'white', 2: 'lightblue', 3: '#ffcc66', 4: '#00cc66', }; return ( <> <div tabIndex={0} id="initial-focus">...
ColorPickerTest
identifier_name
ColorPickerTestStory.tsx
import { storiesOf } from '@storybook/react'; import * as React from 'react'; import { ColorPicker } from '..'; import { StoryCategory } from '../../../../stories/storyHierarchy'; function ColorPickerTest(props?: any) { const [selectedColorName, setSelectedColorName] = React.useState('white'); const _onChange = (v...
/> <ColorPicker.Item key={3} aria-label="orange color" value={PRODUCT_COLORS[3]} checked={selectedColorName === PRODUCT_COLORS[3]} /> <ColorPicker.Item key={4} aria-label="green color" value={PRODUCT_COLORS[4]} ...
value={PRODUCT_COLORS[2]} checked={selectedColorName === PRODUCT_COLORS[2]}
random_line_split
ColorPickerTestStory.tsx
import { storiesOf } from '@storybook/react'; import * as React from 'react'; import { ColorPicker } from '..'; import { StoryCategory } from '../../../../stories/storyHierarchy'; function ColorPickerTest(props?: any)
value={PRODUCT_COLORS[1]} checked={selectedColorName === PRODUCT_COLORS[1]} /> <ColorPicker.Item key={2} aria-label="light blue color" value={PRODUCT_COLORS[2]} checked={selectedColorName === PRODUCT_COLORS[2]} /> <ColorPicker.I...
{ const [selectedColorName, setSelectedColorName] = React.useState('white'); const _onChange = (value) => setSelectedColorName(value); const PRODUCT_COLORS = { 1: 'white', 2: 'lightblue', 3: '#ffcc66', 4: '#00cc66', }; return ( <> <div tabIndex={0} id="initial-focus"> Eleme...
identifier_body
dialogs.py
# dialogs - provide common dialogs # # Copyright (c) 2006 FSF Europe # # Authors: # Sebastian Heinlein <glatzor@ubuntu.com> # Michael Vogt <mvo@canonical.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License...
p = "<span weight=\"bold\" size=\"larger\">%s</span>" % primary dialog = Gtk.MessageDialog(parent,Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR,Gtk.ButtonsType.CLOSE,"") dialog.set_markup(p); dialog.format_secondary_text(secondary); dialog.run() dialog.hide()
identifier_body
dialogs.py
# dialogs - provide common dialogs # # Copyright (c) 2006 FSF Europe # # Authors: # Sebastian Heinlein <glatzor@ubuntu.com> # Michael Vogt <mvo@canonical.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License...
(parent, primary, secondary): p = "<span weight=\"bold\" size=\"larger\">%s</span>" % primary dialog = Gtk.MessageDialog(parent,Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR,Gtk.ButtonsType.CLOSE,"") dialog.set_markup(p); dialog.format_secondary_text(secondary); dialog....
show_error_dialog
identifier_name
dialogs.py
# dialogs - provide common dialogs # # Copyright (c) 2006 FSF Europe # # Authors: # Sebastian Heinlein <glatzor@ubuntu.com> # Michael Vogt <mvo@canonical.com> # # This program is free software; you can redistribute it and/or
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License...
# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version.
random_line_split
languages.py
# encoding: utf-8 # Author: Zhang Huangbin <zhb@iredmail.org> import os import glob import web langmaps = { 'en_US': u'English (US)', 'sq_AL': u'Albanian', 'ar_SA': u'Arabic', 'hy_AM': u'Armenian', 'az_AZ': u'Azerbaijani', 'bs_BA': u'Bosnian (Serbian Latin)', 'bg_BG': u'Bulgarian', 'ca...
return languagemaps
conditional_block
languages.py
# encoding: utf-8 # Author: Zhang Huangbin <zhb@iredmail.org> import os import glob import web langmaps = { 'en_US': u'English (US)', 'sq_AL': u'Albanian', 'ar_SA': u'Arabic', 'hy_AM': u'Armenian', 'az_AZ': u'Azerbaijani', 'bs_BA': u'Bosnian (Serbian Latin)', 'bg_BG': u'Bulgarian', 'ca...
return languagemaps
ame(__file__)) + '/../' available_langs = [ web.safestr(os.path.basename(v)) for v in glob.glob(rootdir + 'i18n/[a-z][a-z]_[A-Z][A-Z]') if os.path.basename(v) in langmaps] available_langs += [ web.safestr(os.path.basename(v)) for v in glob.glob(rootdir + 'i18n/[a-z][a-z...
identifier_body
languages.py
# encoding: utf-8 # Author: Zhang Huangbin <zhb@iredmail.org> import os import glob import web langmaps = { 'en_US': u'English (US)', 'sq_AL': u'Albanian', 'ar_SA': u'Arabic', 'hy_AM': u'Armenian', 'az_AZ': u'Azerbaijani', 'bs_BA': u'Bosnian (Serbian Latin)', 'bg_BG': u'Bulgarian', 'ca...
'ga_IE': u'Irish', 'it_IT': u'Italiano', 'ja_JP': u'Japanese (日本語)', 'ko_KR': u'Korean', 'ku': u'Kurdish (Kurmancî)', 'lv_LV': u'Latvian', 'lt_LT': u'Lithuanian', 'mk_MK': u'Macedonian', 'ms_MY': u'Malay', 'nl_NL': u'Netherlands', 'ne_NP': u'Nepali', 'nb_NO': u'Norsk (Bok...
'id_ID': u'Indonesian',
random_line_split
languages.py
# encoding: utf-8 # Author: Zhang Huangbin <zhb@iredmail.org> import os import glob import web langmaps = { 'en_US': u'English (US)', 'sq_AL': u'Albanian', 'ar_SA': u'Arabic', 'hy_AM': u'Armenian', 'az_AZ': u'Azerbaijani', 'bs_BA': u'Bosnian (Serbian Latin)', 'bg_BG': u'Bulgarian', 'ca...
rootdir = os.path.abspath(os.path.dirname(__file__)) + '/../' available_langs = [ web.safestr(os.path.basename(v)) for v in glob.glob(rootdir + 'i18n/[a-z][a-z]_[A-Z][A-Z]') if os.path.basename(v) in langmaps] available_langs += [ web.safestr(os.path.basename(v)) for v...
le languages.
identifier_name
regression.py
if category != i.split('|')[0]: category = i.split('|')[0] ret_dict.append("Category:" + category.strip()) ret_dict.append(self.categories) ret_dict.append('|'.join(sample_type + tmp)) return ret_dict if sample...
ret_dict = [] tmp = [] sample_type = category = None for i in test_dict: line = i.split('|')[1:] if not sample_type: sample_type = line[0:2] if sample_type != line[0:2]: ret_dict.append('|'.join(s...
identifier_body
regression.py
l" % sysinfodir) status_path = os.path.join(os.path.dirname(files[0]), "../status") status_file = open(status_path, 'r') content = status_file.readlines() self.testdata = re.findall("localtime=(.*)\t", content[-1])[-1] cpunum = len(re.findall("processor\s+: ...
else: (_, p) = stats.ttest_ind(sample1, sample2) flag = "+" if float(avg1) > float(avg2): flag = "-" tmp.append(flag + "%f" % (1 - p)) tmp = "|".join(tmp) ret.appe...
if (ratio): (_, p) = stats.ttest_rel(np.log(sample1), np.log(sample2)) else: (_, p) = stats.ttest_rel(sample1, sample2)
conditional_block