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 |
|---|---|---|---|---|
test.view.ts | /* 3rd party modules */
import { Component, OnInit, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { select } from '@angular-redux/store';
import { Observable } from 'rxjs';
/* C&C Modules */
import { AliveState } from '../../common';
/* Post module pieces */
import { PostActions } from '..... | export class PostTestView extends AliveState implements OnInit {
@select([ 'post', 'posts' ]) public posts$: Observable<Array<Post>>;
constructor(public actions: PostActions) {
super();
}
/**
* Initialize the subscription
*/
public ngOnInit(): void {
this.subscribeWhileAlive(this.actions.getAl... | random_line_split | |
middleware.js | var _ = require("lodash");
module.exports = {
// ensure client accepts json
json_request: function(req, res, next){
if(req.accepts("application/json"))
return next();
res.stash.code = 406;
_.last(req.route.stack).handle(req, res, next); | },
// init response
init_response: function(req, res, next){
res.stash = {};
res.response_start = new Date();
return next();
},
// respond to client
handle_response: function(req, res, next){
res.setHeader("X-Navigator-Response-Time", new Date() - res.response_s... | random_line_split | |
mediawiki.debug.profile.js | fade: true,
gravity: function () {
return $.fn.tipsy.autoNS.call( this )
+ $.fn.tipsy.autoWE.call( this );
},
className: 'mw-debug-profile-tipsy',
center: false,
html: true,
trigger: 'manual',
title: function () {
return profile.buildFlyout( $( this ).data( 'period' ) ).html... | formatBytes | identifier_name | |
mediawiki.debug.profile.js | * @return DOMElement
*/
createSvgElement: document.createElementNS
? document.createElementNS.bind( document, 'http://www.w3.org/2000/svg' )
// throw a error for browsers which does not support document.createElementNS (IE<8)
: function () { throw new Error( 'document.createElementNS not supported' ); ... | random_line_split | ||
mediawiki.debug.profile.js | 'svg' );
node.setAttribute( 'version', '1.2' );
node.setAttribute( 'baseProfile', 'tiny' );
}
node.style.height = totalHeight;
node.style.width = profile.width;
// use a container that can be transformed
container = profile.createSvgElement( 'g' );
node.appendChild( container );
for ( i ... |
return node;
},
/**
* Attach a hover flyout to all .mw-debug-profile-period groups.
*/
attachFlyout: function () {
// for some reason addClass and removeClass from jQuery
// arn't working on svg elements in chrome <= 33.0 (possibly more)
var $container = $( profile.container ),
addClass =... | {
contained = period.contained[i];
sum = contained.end - contained.start;
ms = '' + ( sum < 1 ? sum.toFixed( 2 ) : sum.toFixed( 0 ) ) + ' ms';
mem = formatBytes( contained.memory );
$( '<div>' ).text( contained.source.name )
.append( $( '<span>' ).text( ' ~ ' + ms + ' / ' + mem ).addClass( 'mw... | conditional_block |
mediawiki.debug.profile.js | if ( $from.closest( '.tipsy' ).length === 0 &&
$to.closest( '.tipsy' ).length === 0 &&
$to.get( 0 ).namespaceURI !== 'http://www.w4.org/2000/svg'
) {
hide();
}
} ).on( 'click', function () {
// convenience method for closing
hide();
} );
},
/**
* @return number the x co-ord... | {
return pairs.map( function ( pair ) {
return pair.join( ',' );
} ).join( ' ' );
} | identifier_body | |
product.py | # -*- coding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2012 Vauxoo - http://www.vauxoo.com
# All Rights Reserved.
# info@vauxoo.com
#####################################################... | #
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm, fields
from openerp.tools.translate import _
class pr... | # GNU Affero General Public License for more details. | random_line_split |
product.py | # -*- coding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2012 Vauxoo - http://www.vauxoo.com
# All Rights Reserved.
# info@vauxoo.com
#####################################################... |
def name_search(self, cr, user, name='', args=None, operator='ilike',
context=None, limit=80):
res = super(product_product, self).name_search(
cr, user, name, args, operator, context, limit)
if not context:
context = {}
product_customer_code_obj ... | if not default:
default = {}
default['product_customer_code_ids'] = False
res = super(product_product, self).copy(
cr, uid, id, default=default, context=context)
return res | identifier_body |
product.py | # -*- coding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2012 Vauxoo - http://www.vauxoo.com
# All Rights Reserved.
# info@vauxoo.com
#####################################################... |
if ids:
res = self.name_get(cr, user, ids, context)
return res
| id_prod_code = \
product_customer_code_obj.search(cr, user,
[('product_code',
'=', name),
('partner_id', '=',
... | conditional_block |
product.py | # -*- coding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2012 Vauxoo - http://www.vauxoo.com
# All Rights Reserved.
# info@vauxoo.com
#####################################################... | (self, cr, uid, id, default=None, context=None):
if not default:
default = {}
default['product_customer_code_ids'] = False
res = super(product_product, self).copy(
cr, uid, id, default=default, context=context)
return res
def name_search(self, cr, user, name=... | copy | identifier_name |
test_helper.py | from luigi_bigquery import ResultProxy
import os
import shutil
import tempfile
class MockClient(object):
def __init__(self, datasets, tables, jobs):
self._datasets = datasets
self._tables = tables
self._jobs = jobs
def create_dataset(self, dataset_id, friendly_name=None, description=N... |
def _dataset_resource(self, dataset_id, friendly_name=None, description=None, access=None):
data = {
"datasetReference": {
"datasetId": dataset_id,
"projectId": 'test-project-id'
}
}
if friendly_name:
data["friendlyName"] =... | return job
return {} | random_line_split |
test_helper.py | from luigi_bigquery import ResultProxy
import os
import shutil
import tempfile
class MockClient(object):
def __init__(self, datasets, tables, jobs):
self._datasets = datasets
self._tables = tables
self._jobs = jobs
def create_dataset(self, dataset_id, friendly_name=None, description=N... | (self, bucket_name, path):
for obj in self._objects:
if obj['bucket'] == bucket_name and obj['name'] == path:
return obj
return {}
def check_file(self, bucket_name, path):
file = self.get_file(bucket_name, path)
return bool(file)
class TestConfig(object)... | get_file | identifier_name |
test_helper.py | from luigi_bigquery import ResultProxy
import os
import shutil
import tempfile
class MockClient(object):
def __init__(self, datasets, tables, jobs):
|
def create_dataset(self, dataset_id, friendly_name=None, description=None, access=None):
dataset_data = _dataset_resource(dataset_id, friendly_name, description, access)
self._datasets.append(dataset_data)
return dataset_data
def get_datasets(self):
return self._datasets
... | self._datasets = datasets
self._tables = tables
self._jobs = jobs | identifier_body |
test_helper.py | from luigi_bigquery import ResultProxy
import os
import shutil
import tempfile
class MockClient(object):
def __init__(self, datasets, tables, jobs):
self._datasets = datasets
self._tables = tables
self._jobs = jobs
def create_dataset(self, dataset_id, friendly_name=None, description=N... |
return {}
def delete_table(self, dataset_id, table_id):
pass
def check_job(self, job_id):
job = self._job(job_id)
return (job.get('job_complete', False), int(job.get('total_rows', 0)))
def get_query_schema(self, job_id):
job = self._job(job_id)
return job[... | return table | conditional_block |
is_null_undefined_or_empty.ts | /*
| Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of... | MIT License
Copyright (c) 2022 Looker Data Sciences, Inc.
| random_line_split |
appevent.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AppEventMessage } from './appevent.type';
import { AppObservableObject } from '../../utils/base';
// Base class for application events
class AppEvent extends AppObservableObject<AppEventMessage> {
protected type: string;
... | extends AppEvent {
type = AppEventTypes.LOGOUT;
}
// Event for sidemenu
class SideMenuEvent extends AppEvent {
type = AppEventTypes.SIDEMENU;
}
@Injectable()
export class AppEventsService {
private events: any = {};
constructor() {
this.events[AppEventTypes.LOGOUT] = new LogoutEvent();
... | LogoutEvent | identifier_name |
appevent.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AppEventMessage } from './appevent.type';
import { AppObservableObject } from '../../utils/base';
// Base class for application events
class AppEvent extends AppObservableObject<AppEventMessage> {
protected type: string;
... |
return false;
}
} | sendEvent(name: string, data: any = null): boolean {
if ((this.events.hasOwnProperty(name))) {
return this.events[name].sendEvent(0, data);
} | random_line_split |
appevent.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AppEventMessage } from './appevent.type';
import { AppObservableObject } from '../../utils/base';
// Base class for application events
class AppEvent extends AppObservableObject<AppEventMessage> {
protected type: string;
... |
return false;
}
}
| {
return this.events[name].sendEvent(0, data);
} | conditional_block |
protractor.js | var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLi... | letterLimitInput.clear();
letterLimitInput.sendKeys('100');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
expect(limit... | it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100'); | random_line_split |
span-preservation.rs | // For each of these, we should get the appropriate type mismatch error message,
// and the function should be echoed.
// aux-build:test-macros.rs
#[macro_use]
extern crate test_macros;
#[recollect_attr]
fn a() {
let x: usize = "hello"; //~ ERROR mismatched types
}
#[recollect_attr]
fn b(x: Option<isize>) -> us... | {
a: usize,
b: usize
}
let x = Foo { a: 10isize }; //~ ERROR mismatched types
let y = Foo { a: 10, b: 10isize }; //~ ERROR has no field named `b`
}
#[recollect_attr]
extern "C" fn bar() {
0 //~ ERROR mismatched types
}
#[recollect_attr]
extern "C" fn baz() {
0 //~ ERROR mismatche... | Bar | identifier_name |
span-preservation.rs | // For each of these, we should get the appropriate type mismatch error message,
// and the function should be echoed.
// aux-build:test-macros.rs
#[macro_use]
extern crate test_macros;
#[recollect_attr]
fn a() {
let x: usize = "hello"; //~ ERROR mismatched types
}
#[recollect_attr]
fn b(x: Option<isize>) -> us... |
#[recollect_attr]
extern "Rust" fn rust_abi() {
0 //~ ERROR mismatched types
}
#[recollect_attr]
extern "\x43" fn c_abi_escaped() {
0 //~ ERROR mismatched types
}
fn main() {}
| {
0 //~ ERROR mismatched types
} | identifier_body |
Updatedserver.py | #!/usr/bin/env python
import logging
import os
import urllib
from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure
from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface
import cvmfsreplica.pluginsmanagement as pm
class Updatedserver(RepositoryPluginAcceptanceInterface):
def __ini... | (self):
'''
checks if the revision number in local copy of .cvmfspublished
is different that the revision number of remote .cvmfspublished
'''
try:
# FIXME
# maybe we should try a couple of times in case of failures before failing definitely
fo... | verify | identifier_name |
Updatedserver.py | #!/usr/bin/env python
import logging
import os
import urllib
from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure
from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface
import cvmfsreplica.pluginsmanagement as pm
class Updatedserver(RepositoryPluginAcceptanceInterface):
| # checks if file .cvmfspublished
# was updated more recently than variable
# repository.last_published
# '''
# try:
# # FIXME
# # maybe we should try a couple of times in case of failures before failing definitely
# for line in urllib.urlopen('%s/.cvmf... | def __init__(self, repository, conf):
self.log = logging.getLogger('cvmfsreplica.updatedserver')
self.repository = repository
self.conf = conf
try:
self.url = self.repository.cvmfsconf.get('CVMFS_STRATUM0')
self.reportplugins = pm.readplugins(self.repository,
... | identifier_body |
Updatedserver.py | #!/usr/bin/env python
import logging
import os
import urllib
from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure
from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface
import cvmfsreplica.pluginsmanagement as pm
class Updatedserver(RepositoryPluginAcceptanceInterface):
def __ini... | 'repository',
'report',
self.conf.namespace('acceptance.updatedserver.',
exclude=True)
... | try:
self.url = self.repository.cvmfsconf.get('CVMFS_STRATUM0')
self.reportplugins = pm.readplugins(self.repository, | random_line_split |
Updatedserver.py | #!/usr/bin/env python
import logging
import os
import urllib
from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure
from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface
import cvmfsreplica.pluginsmanagement as pm
class Updatedserver(RepositoryPluginAcceptanceInterface):
def __ini... |
return out
except:
self.log.warning('file %s/.cvmfspublished cannot be read. Returning False' %self.url)
return False
def _notify_failure(self, msg):
for report in self.reportplugins:
report.notifyfailure(msg)
| self._notify_failure('No new content at the server for repository %s' \
%self.repository.repositoryname) | conditional_block |
rowiterator.rs | // Copyright 2016 Claus Matzinger
//
// 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
// |
extern crate serde_json;
use row::Row;
use std::collections::HashMap;
use self::serde_json::Value;
use std::rc::Rc;
#[derive(Debug)]
pub struct RowIterator {
rows: Vec<Value>,
header: Rc<HashMap<String, usize>>,
}
impl RowIterator {
pub fn new(mut rows: Vec<Value>, header: HashMap<String, usize>) -> Ro... | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. | random_line_split |
rowiterator.rs | // Copyright 2016 Claus Matzinger
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | {
rows: Vec<Value>,
header: Rc<HashMap<String, usize>>,
}
impl RowIterator {
pub fn new(mut rows: Vec<Value>, header: HashMap<String, usize>) -> RowIterator {
let headers = Rc::new(header);
rows.reverse();
RowIterator {
rows: rows,
header: headers,
}... | RowIterator | identifier_name |
rowiterator.rs | // Copyright 2016 Claus Matzinger
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
pub fn len(&self) -> usize {
self.rows.len()
}
}
impl Iterator for RowIterator {
type Item = Row;
fn next(&mut self) -> Option<Row> {
match self.rows.pop() {
Some(i) => Some(Row::new(i.as_array().unwrap().to_vec(), self.header.clone())),
_ => None,
}
... | {
let headers = Rc::new(header);
rows.reverse();
RowIterator {
rows: rows,
header: headers,
}
} | identifier_body |
qt_color_dialog.py | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... |
widget.setOptions(opt)
def set_show_buttons(self, show):
""" Set the show buttons option on the underlying widget.
"""
widget = self.widget
opt = widget.options()
if show:
opt &= ~QColorDialog.NoButtons
else:
opt |= QColorDialog.NoBu... | opt &= ~QColorDialog.ShowAlphaChannel | conditional_block |
qt_color_dialog.py | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | if d is not None:
self._guard |= CURRENT_GUARD
try:
d.current_color = color_from_qcolor(qcolor)
finally:
self._guard &= ~CURRENT_GUARD
def on_color_selected(self, qcolor):
""" Handle the 'colorSelected' signal from the widget.
... | random_line_split | |
qt_color_dialog.py | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | (self, color):
""" Set the current color for the underlying widget.
"""
if not self._guard & CURRENT_GUARD:
if color is not None:
qcolor = QColor.fromRgba(color.argb)
else:
qcolor = QColor()
self.widget.setCurrentColor(qcolor)
... | set_current_color | identifier_name |
qt_color_dialog.py | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... |
def set_show_buttons(self, show):
""" Set the show buttons option on the underlying widget.
"""
widget = self.widget
opt = widget.options()
if show:
opt &= ~QColorDialog.NoButtons
else:
opt |= QColorDialog.NoButtons
widget.setOptions... | """ Set the show alpha option on the underlying widget.
"""
widget = self.widget
opt = widget.options()
if show:
opt |= QColorDialog.ShowAlphaChannel
else:
opt &= ~QColorDialog.ShowAlphaChannel
widget.setOptions(opt) | identifier_body |
atttb.py | #!/usr/bin/env python
#!coding=utf-8
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table,Column,Integer,String,Numeric,MetaData,DateTime,Date
from ._base import BaseInit,Base
'''
員工刷卡原始數據表
'''
class ATTTB(BaseInit,Base):
__tablename__='ATT | TB'
TB001=Column(String(20),nullable=False,primary_key=True,doc='員工編號')
TB002=Column(DateTime,nullable=False,primary_key=True,doc='打卡時間')
TB003=Column(Date,nullable=False,doc='出勤日期')
TB004=Column(String(30),default='',doc='員工姓名')
TB005=Column(String(10),default='',doc='員工部門編號')
TB006=Column(Str... | identifier_body | |
atttb.py | #!/usr/bin/env python
#!coding=utf-8
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table,Column,Integer,String,Numeric,MetaData,DateTime,Date
from ._base import BaseInit,Base
'''
員工刷卡原始數據表
'''
class ATTTB(BaseInit,Bas | __tablename__='ATTTB'
TB001=Column(String(20),nullable=False,primary_key=True,doc='員工編號')
TB002=Column(DateTime,nullable=False,primary_key=True,doc='打卡時間')
TB003=Column(Date,nullable=False,doc='出勤日期')
TB004=Column(String(30),default='',doc='員工姓名')
TB005=Column(String(10),default='',doc='員工部門編號')... | e):
| identifier_name |
atttb.py | #!/usr/bin/env python
#!coding=utf-8
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table,Column,Integer,String,Numeric,MetaData,DateTime,Date
from ._base import BaseInit,Base
'''
員工刷卡原始數據表
'''
class ATTTB(BaseInit,Base):
__tablename__='ATTTB'
TB001=Column(String(20),nullab... | TB012=Column(String(1),default='',doc='出勤狀態') | random_line_split | |
react-linkify-tests.tsx | import LinkifyIt = require("linkify-it");
import * as React from "react";
import ReactLinkify from 'react-linkify';
const linkifier = new LinkifyIt();
class ExampleOfUsingReactLinkify extends React.Component {
render() {
return (
<ReactLinkify
textDecorator={textDecorator}
... | <a href={decoratedHref} key={key}>
{decoratedText}
</a>
);
}
function matchDecorator(text: string) {
return linkifier.match(text);
} | function componentDecorator(decoratedHref: string, decoratedText: string, key: number): React.ReactNode {
return ( | random_line_split |
react-linkify-tests.tsx | import LinkifyIt = require("linkify-it");
import * as React from "react";
import ReactLinkify from 'react-linkify';
const linkifier = new LinkifyIt();
class ExampleOfUsingReactLinkify extends React.Component {
render() {
return (
<ReactLinkify
textDecorator={textDecorator}
... |
function hrefDecorator(urlHref: string): string {
return urlHref;
}
function componentDecorator(decoratedHref: string, decoratedText: string, key: number): React.ReactNode {
return (
<a href={decoratedHref} key={key}>
{decoratedText}
</a>
);
}
function matchDecorator(text: st... | {
return urlText + "is a great url";
} | identifier_body |
react-linkify-tests.tsx | import LinkifyIt = require("linkify-it");
import * as React from "react";
import ReactLinkify from 'react-linkify';
const linkifier = new LinkifyIt();
class ExampleOfUsingReactLinkify extends React.Component {
| () {
return (
<ReactLinkify
textDecorator={textDecorator}
hrefDecorator={hrefDecorator}
componentDecorator={componentDecorator}
matchDecorator={matchDecorator}>
This is a great website: www.wikipedia.org!
</R... | render | identifier_name |
category.js | const router = require("express").Router();
const Category = require("../model/Category");
const { categoryValidation } = require("../validation");
const verify = require("./verifyToken");
router.post("/", verify, async (req, res) => {
const { error } = categoryValidation(req.body);
if (error) return res.status(40... |
return res.send("Successfully updated!");
}
);
} catch (err) {
res.status(400).send(err);
}
});
router.delete("/:id", async (req, res) => {
try {
const data = await Category.deleteOne({ _id: req.params.id });
if (data.ok === 1) {
return res.send("Successfully deleted!");
... | {
return res.send(err);
} | conditional_block |
category.js | const router = require("express").Router();
const Category = require("../model/Category");
const { categoryValidation } = require("../validation");
const verify = require("./verifyToken");
router.post("/", verify, async (req, res) => {
const { error } = categoryValidation(req.body);
if (error) return res.status(40... | });
router.get("/", verify, async (req, res) => {
let query = {};
if (req.user.role !== "admin") {
query.owner = req.user._id;
}
try {
const allCategories = await Category.find(query);
res.send(allCategories);
} catch (err) {
res.status(400).send(err);
}
});
router.get("/:id", verify, asyn... | } catch (err) {
res.status(400).send(err);
} | random_line_split |
block-decl-global-existing-global-init.js | // This file was procedurally generated from the following sources:
// - src/annex-b-fns/global-existing-global-init.case
// - src/annex-b-fns/global/block.template
/*---
description: Variable binding is left in place by legacy function hoisting. CreateGlobalVariableBinding leaves the binding as non-enumerable even if ... | $262.evalScript(`
{
function f() { return 'inner declaration'; }
}
`);
$262.evalScript(`
verifyProperty(global, 'f', {
enumerable: true,
writable: true,
configurable: false
});
`); | random_line_split | |
failure.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from tracing.mre import job as job_module
class Failure(object):
def __init__(self, job, function_handle_string, trace_canonical_url,
fai... | failure_dict['stack']) | random_line_split | |
failure.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from tracing.mre import job as job_module
class Failure(object):
def __init__(self, job, function_handle_string, trace_canonical_url,
fai... | if failure_names_to_constructors is None:
failure_names_to_constructors = {}
failure_type_name = failure_dict['type']
if failure_type_name in failure_names_to_constructors:
cls = failure_names_to_constructors[failure_type_name]
else:
cls = Failure
return cls(job,
failur... | identifier_body | |
failure.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from tracing.mre import job as job_module
class Failure(object):
def | (self, job, function_handle_string, trace_canonical_url,
failure_type_name, description, stack):
assert isinstance(job, job_module.Job)
self.job = job
self.function_handle_string = function_handle_string
self.trace_canonical_url = trace_canonical_url
self.failure_type_name = failure_... | __init__ | identifier_name |
failure.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from tracing.mre import job as job_module
class Failure(object):
def __init__(self, job, function_handle_string, trace_canonical_url,
fai... |
failure_type_name = failure_dict['type']
if failure_type_name in failure_names_to_constructors:
cls = failure_names_to_constructors[failure_type_name]
else:
cls = Failure
return cls(job,
failure_dict['function_handle_string'],
failure_dict['trace_canonical_url... | failure_names_to_constructors = {} | conditional_block |
svg_to_svg_ordered_dithering.py | """Copyright (c) 2017 abhishek-sehgal954
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This prog... |
obj = inkex.etree.SubElement(parent, inkex.addNS('ellipse', 'svg'), attribs)
return obj
def draw_svg(self,output,parent):
startu = 0
endu = 0
for i in range(len(output)):
for j in range(len(output[i])):
if (output[i][j]==0):
s... | attribs.update({'id': id_}) | conditional_block |
svg_to_svg_ordered_dithering.py | """Copyright (c) 2017 abhishek-sehgal954
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This prog... | """
import sys
import os
import re
import subprocess
import math
import numpy as np
import inkex
import simpletransform
from PIL import Image, ImageStat, ImageDraw
import simplestyle
inkex.localize()
class ordered_dithering(inkex.Effect):
def __init__(self):
"""Init the effect library and get optio... | random_line_split | |
svg_to_svg_ordered_dithering.py | """Copyright (c) 2017 abhishek-sehgal954
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This prog... | (self, curfile, outfile):
command = "%s %s --export-png %s" %(self.options.inkscape_path,curfile,outfile)
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return_code = p.wait()
f = p.stdout
err = p.stderr
img = Image.open(outfile)... | exportPage | identifier_name |
svg_to_svg_ordered_dithering.py | """Copyright (c) 2017 abhishek-sehgal954
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This prog... |
def draw_rectangle(self,(x, y), (l,b), color, parent, id_):
style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"}
attribs = {'style': simplestyle.formatStyle(style), 'x': str(x), 'y': str(y), 'width': str(l), 'height':str(b)}
if id_ is not No... | outfile = self.options.temp_path
curfile = self.args[-1]
self.exportPage(curfile,outfile) | identifier_body |
change_detector_util_spec.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {devModeEqual} from '@angular/core/src/change_detection/change_detection_util';
{
describe('ChangeDetection... | expect(devModeEqual('one', 'one')).toBe(true);
expect(devModeEqual('one', 'two')).toBe(false);
expect(devModeEqual({}, 'one')).toBe(false);
expect(devModeEqual('one', {})).toBe(false);
});
it('should compare primitive booleans', () => {
expect(devModeEqual(true, true... | expect(devModeEqual({}, 2)).toBe(false);
expect(devModeEqual(1, {})).toBe(false);
});
it('should compare primitive strings', () => { | random_line_split |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Bml(CMakePackage):
"""The basic matrix library (bml) is a collection of various matrix dat... |
else:
args.append('-DBML_MPI=False')
return args
| args.append('-DBML_MPI=True')
args.append('-DCMAKE_C_COMPILER=%s' % spec['mpi'].mpicc)
args.append('-DCMAKE_CXX_COMPILER=%s' % spec['mpi'].mpicxx)
args.append('-DCMAKE_Fortran_COMPILER=%s' % spec['mpi'].mpifc) | conditional_block |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Bml(CMakePackage):
"""The basic matrix library (bml) is a collection of various matrix dat... | '-DBUILD_SHARED_LIBS={0}'.format(
'ON' if '+shared' in self.spec else 'OFF')
]
spec = self.spec
if '+mpi' in spec:
args.append('-DBML_MPI=True')
args.append('-DCMAKE_C_COMPILER=%s' % spec['mpi'].mpicc)
args.append('-DCMAKE_CXX_COMPI... | random_line_split | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Bml(CMakePackage):
"""The basic matrix library (bml) is a collection of various matrix dat... | args = [
'-DBUILD_SHARED_LIBS={0}'.format(
'ON' if '+shared' in self.spec else 'OFF')
]
spec = self.spec
if '+mpi' in spec:
args.append('-DBML_MPI=True')
args.append('-DCMAKE_C_COMPILER=%s' % spec['mpi'].mpicc)
args.append('-DCMAKE_... | identifier_body | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (CMakePackage):
"""The basic matrix library (bml) is a collection of various matrix data
formats (in dense and sparse) and their associated algorithms for basic
matrix operations."""
homepage = "http://lanl.github.io/bml/"
url = "https://github.com/lanl/bml/tarball/v1.2.2"
git = "http... | Bml | identifier_name |
urls.py | # elected_office/urls.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.conf.urls import url
from . import views_admin
urlpatterns = [
# views_admin
url(r'^$', views_admin.elected_office_list_view, name='elected_office_list', ),
url(r'^delete/$', views_admin.elected_office_dele... | url(r'^(?P<elected_office_id>[0-9]+)/summary/$', views_admin.elected_office_summary_view,
name='elected_office_summary'),
] | url(r'^(?P<elected_office_id>[0-9]+)/edit/$', views_admin.elected_office_edit_view, name='elected_office_edit'), | random_line_split |
markersHandler.ts | /winjs.base';
import * as strings from 'vs/base/common/strings';
import * as network from 'vs/base/common/network';
import * as errors from 'vs/base/common/errors';
import * as dom from 'vs/base/browser/dom';
import * as nls from 'vs/nls';
import {ICommonCodeEditor, IEditorViewState} from 'vs/editor/common/editorCommon... |
private static _filter: IFilter = or(matchesPrefix, matchesContiguousSubString);
public update(query: string): void {
if (this._marker.resource.scheme === network.Schemas.inMemory) {
// ignore inmemory-models
this.setHidden(true);
return;
}
const labelHighlights = MarkerEntry._filter(query, this._... | {
super();
this._editorService = editorService;
this._codeEditorService = codeEditorService;
this._labelProvider = new PathLabelProvider(contextService);
this._marker = marker;
const {message, source, resource, startLineNumber, startColumn} = marker;
this._label = source ? nls.localize('marker.msg', '[{0... | identifier_body |
markersHandler.ts | /common/winjs.base';
import * as strings from 'vs/base/common/strings';
import * as network from 'vs/base/common/network';
import * as errors from 'vs/base/common/errors';
import * as dom from 'vs/base/browser/dom';
import * as nls from 'vs/nls';
import {ICommonCodeEditor, IEditorViewState} from 'vs/editor/common/edito... | @ICodeEditorService codeEditorService: ICodeEditorService,
@IWorkspaceContextService contextService: IWorkspaceContextService
) {
super();
this._markerService = markerService;
this._editorService = editorService;
this._codeEditorService = codeEditorService;
this._contextService = contextService;
}
pu... | random_line_split | |
markersHandler.ts | /common/winjs.base';
import * as strings from 'vs/base/common/strings';
import * as network from 'vs/base/common/network';
import * as errors from 'vs/base/common/errors';
import * as dom from 'vs/base/browser/dom';
import * as nls from 'vs/nls';
import {ICommonCodeEditor, IEditorViewState} from 'vs/editor/common/edito... | extends QuickOpenHandler {
private _markerService: IMarkerService;
private _editorService: IWorkbenchEditorService;
private _codeEditorService: ICodeEditorService;
private _contextService: IWorkspaceContextService;
private _activeSession: [QuickOpenModel, IEditorViewState];
constructor(
@IMarkerService marke... | MarkersHandler | identifier_name |
markersHandler.ts | /winjs.base';
import * as strings from 'vs/base/common/strings';
import * as network from 'vs/base/common/network';
import * as errors from 'vs/base/common/errors';
import * as dom from 'vs/base/browser/dom';
import * as nls from 'vs/nls';
import {ICommonCodeEditor, IEditorViewState} from 'vs/editor/common/editorCommon... |
// file name matters for equal severity
ret = strings.localeCompare(a.resource.fsPath, b.resource.fsPath);
if (ret !== 0) {
return ret;
}
// start line matters
ret = a.startLineNumber - b.startLineNumber;
if (ret !== 0) {
return ret;
}
// start column matters
ret = a.startColumn - b.startC... | {
ret = a.source.localeCompare(b.source);
if (ret !== 0) {
return ret;
}
} | conditional_block |
reset.rs | // Copyright 2021 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | pub const RESET_SOURCE_LEN: usize = 8;
impl<'a> FromWire<'a> for ResetSource {
fn from_wire<R: Read<'a>>(mut r: R) -> Result<Self, FromWireError> {
let power_on_reset = r.read_be::<u8>()? != 0;
let low_power_reset = r.read_be::<u8>()? != 0;
let watchdog_reset = r.read_be::<u8>()? != 0;
... | }
/// The length of a ResetSource on the wire, in bytes. | random_line_split |
reset.rs | // Copyright 2021 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | else { 0u8 })?;
w.write_be(if self.lockup_reset { 1 } else { 0u8 })?;
w.write_be(if self.sysreset { 1 } else { 0u8 })?;
w.write_be(if self.software_reset { 1 } else { 0u8 })?;
w.write_be(if self.fast_burnout_circuit { 1 } else { 0u8 })?;
w.write_be(if self.security_breach_reset ... | { 1 } | conditional_block |
reset.rs | // Copyright 2021 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | <R: Read<'a>>(mut r: R) -> Result<Self, FromWireError> {
let power_on_reset = r.read_be::<u8>()? != 0;
let low_power_reset = r.read_be::<u8>()? != 0;
let watchdog_reset = r.read_be::<u8>()? != 0;
let lockup_reset = r.read_be::<u8>()? != 0;
let sysreset = r.read_be::<u8>()? != 0;
... | from_wire | identifier_name |
reset.rs | // Copyright 2021 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
| {
w.write_be(if self.power_on_reset { 1 } else { 0u8 })?;
w.write_be(if self.low_power_reset { 1 } else { 0u8 })?;
w.write_be(if self.watchdog_reset { 1 } else { 0u8 })?;
w.write_be(if self.lockup_reset { 1 } else { 0u8 })?;
w.write_be(if self.sysreset { 1 } else { 0u8 })?;
... | identifier_body |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
* | * 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 Lic... | * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | random_line_split |
works.ts | type Item = {
[name: string]: {
id: number;
name: string;
};
};
type StatusItem = {
[name: string]: {
id: number;
name: string;
background: string;
color: string;
};
};
type WorksProps = {
status: StatusItem;
roles: Item;
types: { [name: string]: string };
[prop: string]: any;
... | (id: number) {
const key =
Object.keys(works.status).find(function (key) {
return works.status[key].id === id;
}) || "";
return works.status[key];
}
export function rolesById(id: number) {
const key =
Object.keys(works.roles).find(function (key) {
return works.roles[key].id === id;
})... | statusById | identifier_name |
works.ts | type Item = {
[name: string]: {
id: number;
name: string;
};
};
type StatusItem = {
[name: string]: {
id: number;
name: string;
background: string;
color: string;
};
};
type WorksProps = {
status: StatusItem;
roles: Item;
types: { [name: string]: string };
[prop: string]: any;
... | }) || "";
return works.status[key];
}
export function rolesById(id: number) {
const key =
Object.keys(works.roles).find(function (key) {
return works.roles[key].id === id;
}) || "";
return works.roles[key];
}
export const status = works.status;
export const types = works.types;
export const ro... | random_line_split | |
works.ts | type Item = {
[name: string]: {
id: number;
name: string;
};
};
type StatusItem = {
[name: string]: {
id: number;
name: string;
background: string;
color: string;
};
};
type WorksProps = {
status: StatusItem;
roles: Item;
types: { [name: string]: string };
[prop: string]: any;
... |
export const status = works.status;
export const types = works.types;
export const roles = works.roles;
| {
const key =
Object.keys(works.roles).find(function (key) {
return works.roles[key].id === id;
}) || "";
return works.roles[key];
} | identifier_body |
osm2mimir.rs | ::ports::secondary::remote::Error,
},
#[snafu(display("Street Extraction from OSM PBF Error {}", source))]
StreetOsmExtraction {
source: mimirsbrunn::osm_reader::street::Error,
},
#[snafu(display("Street Index Creation Error {}", source))]
StreetIndexCreation {
source: mimir::d... |
Ok(())
}
#[instrument(skip_all)]
async fn import_streets(
streets: Vec<places::street::Street>,
client: &ElasticsearchStorage,
config: &ContainerConfig,
) -> Result<(), Error> {
let streets = streets
.into_iter()
.map(|street| street.set_weight_from_admins());
let _index = cl... | {
import_pois(
&mut osm_reader,
&admins_geofinder,
&settings.pois.config.clone().unwrap_or_default(),
&client,
&settings.container_poi,
)
.await?;
} | conditional_block |
osm2mimir.rs | ::ports::secondary::remote::Error,
},
#[snafu(display("Street Extraction from OSM PBF Error {}", source))]
StreetOsmExtraction {
source: mimirsbrunn::osm_reader::street::Error,
},
#[snafu(display("Street Index Creation Error {}", source))]
StreetIndexCreation {
source: mimir::d... |
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::elasticsearch::ElasticsearchStorage;
// use common::config::load_es_config_for;
// use common::document::ContainerDocument;
// use futures::TryStreamExt;
// use mimir::domain::model::query::Query;
// use mimir::domain::ports::pr... | {
// This function rely on AdminGeoFinder::get_objs_and_deps
// which use all available cpu/cores to decode osm file and cannot be limited by tokio runtime
let pois = mimirsbrunn::osm_reader::poi::pois(osm_reader, poi_config, admins_geofinder)
.context(PoiOsmExtractionSnafu)?;
let pois: Vec<pla... | identifier_body |
osm2mimir.rs | domain::ports::secondary::remote::Error,
},
#[snafu(display("Street Extraction from OSM PBF Error {}", source))]
StreetOsmExtraction {
source: mimirsbrunn::osm_reader::street::Error,
},
#[snafu(display("Street Index Creation Error {}", source))] | },
#[snafu(display("Poi Extraction from OSM PBF Error {}", source))]
PoiOsmExtraction {
source: mimirsbrunn::osm_reader::poi::Error,
},
#[snafu(display("Poi Index Creation Error {}", source))]
PoiIndexCreation {
source: mimir::domain::model::error::Error,
},
#[snafu(di... | StreetIndexCreation {
source: mimir::domain::model::error::Error, | random_line_split |
osm2mimir.rs | {
#[snafu(display("Settings (Configuration or CLI) Error: {}", source))]
Settings { source: settings::Error },
#[snafu(display("OSM PBF Reader Error: {}", source))]
OsmPbfReader {
source: mimirsbrunn::osm_reader::Error,
},
#[snafu(display("Elasticsearch Connection Pool {}", source))]
... | Error | identifier_name | |
closure-annotation-tokenizer.js | ) {
this.groupAnnotation = {};
// '*\n * @param {string} a \n * @param {string} b \n *
let lineToken = js.split('\n'); // Split each new line -> ['*',' * @param {string} a', ' * @param {string} b', '*']
lineToken = lineToken.map(this._stripComment); // Remove * from start of every line -> ['', '@param {... |
_stripComment(line) {
let res = line.trim();
if (res.indexOf('*') === 0) {
res = res.substr(1, res.length);
}
return res.trim();
}
_splitSection(flatLine) {
let indices = [], result = [];
for (let i = 0; i < flatLine.length; i++) {
if (flatLine[i] === '@') {
indices.... | {
for (let i = 0; i < token.length; i++) {
let tokenObject = token[i];
if(!this.groupAnnotation.hasOwnProperty(tokenObject.annotation)){
this.groupAnnotation[tokenObject.annotation] = {};
}
let id = 'param1', value = tokenObject.param1;
if(tokenObject.annotation === '@param' ){... | identifier_body |
closure-annotation-tokenizer.js | Format result to desired format
this._classifiedAnnotation(tokens);
let result = {token : tokens, classifiedAnnotation: this.groupAnnotation};
// Combine with previous result if provided
if(previousToken){
merge(previousToken, result);
}
return result;
}
_classifiedAnnotation(token... | _replaceNull | identifier_name | |
closure-annotation-tokenizer.js | ) {
this.groupAnnotation = {};
// '*\n * @param {string} a \n * @param {string} b \n *
let lineToken = js.split('\n'); // Split each new line -> ['*',' * @param {string} a', ' * @param {string} b', '*']
lineToken = lineToken.map(this._stripComment); // Remove * from start of every line -> ['', '@param {... |
if((w === ',' || w === ' ' || w === ')' ) && bracketCount === 0 && token.trim() !== keyword){
break;
}
nextId++;
}
resultType = resultType.replace(token, 'Function');
functionPos = type.indexOf(keyword, nextId);
}
return resultType;
}
_removeGenericDot... | {
bracketCount--;
} | conditional_block |
closure-annotation-tokenizer.js | TYPE : '@type',
RETURN : '@return'
};
const acceptedAnnotation = ['@typedef', '@param', '@type', '@return'];
const STATE = {
NONE : 0,
READING_ANNOTATION : 1,
READING_PARAM1 : 2,
READING_PARAM2 : 3,
END_READING : 4
};
export default
class ClosureAnnotationTokenizer {
constructor(){
this.importe... | const ANNOTATION = {
TYPEDEF : '@typedef',
PARAM : '@param', | random_line_split | |
unix.rs | extern crate thermal_printer;
extern crate serial;
extern crate serial_embedded_hal;
use serial::{Baud19200, Bits8, ParityNone, Stop1, FlowNone};
use serial_embedded_hal::{Serial, PortSettings};
use thermal_printer::prelude::*;
use std::thread::sleep;
fn main() {
println!("Opening serial port...");
let por... | };
println!("Serial port open");
let port = Serial::new("/dev/tty.usbserial-A700eX73", &port_settings)
.expect("Failed to open serial port");
let (tx_port, _) = port.split();
let mut printer = ThermalPrinter::new(tx_port);
printer.configure(11, 120, 40);
println!("Feeding 3 lin... | baud_rate: Baud19200,
char_size: Bits8,
parity: ParityNone,
stop_bits: Stop1,
flow_control: FlowNone, | random_line_split |
unix.rs | extern crate thermal_printer;
extern crate serial;
extern crate serial_embedded_hal;
use serial::{Baud19200, Bits8, ParityNone, Stop1, FlowNone};
use serial_embedded_hal::{Serial, PortSettings};
use thermal_printer::prelude::*;
use std::thread::sleep;
fn main() | printer.configure(11, 120, 40);
println!("Feeding 3 lines");
printer.feed_n(3).expect("Feed lines failed");
println!("Running self test");
printer.run_test().expect("Self test failed");
sleep(std::time::Duration::from_secs(1));
println!("Done!")
} | {
println!("Opening serial port...");
let port_settings = PortSettings {
baud_rate: Baud19200,
char_size: Bits8,
parity: ParityNone,
stop_bits: Stop1,
flow_control: FlowNone,
};
println!("Serial port open");
let port = Serial::new("/dev/tty.usbserial-A700eX... | identifier_body |
unix.rs | extern crate thermal_printer;
extern crate serial;
extern crate serial_embedded_hal;
use serial::{Baud19200, Bits8, ParityNone, Stop1, FlowNone};
use serial_embedded_hal::{Serial, PortSettings};
use thermal_printer::prelude::*;
use std::thread::sleep;
fn | () {
println!("Opening serial port...");
let port_settings = PortSettings {
baud_rate: Baud19200,
char_size: Bits8,
parity: ParityNone,
stop_bits: Stop1,
flow_control: FlowNone,
};
println!("Serial port open");
let port = Serial::new("/dev/tty.usbserial-A70... | main | identifier_name |
uncompress.py | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Fou... | (UncompressorHandler):
def query(self, localpath):
if localpath.endswith(".gz"):
return True
def getTargetPath(self, localpath):
return localpath[:-3]
def uncompress(self, localpath):
import gzip
try:
input = gzip.GzipFile(localpath)
out... | GZipHandler | identifier_name |
uncompress.py | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Fou... |
else:
raise Error, _("Unknown compressed file: %s") % localpath
class UncompressorHandler(object):
def query(self, localpath):
return None
def getTargetPath(self, localpath):
return None
def uncompress(self, localpath):
raise Error, _("Unsupported file type")... | return handler.uncompress(localpath) | conditional_block |
uncompress.py | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Fou... |
Uncompressor.addHandler(BZ2Handler)
class GZipHandler(UncompressorHandler):
def query(self, localpath):
if localpath.endswith(".gz"):
return True
def getTargetPath(self, localpath):
return localpath[:-3]
def uncompress(self, localpath):
import gzip
try:
... | import bz2
try:
input = bz2.BZ2File(localpath)
output = open(self.getTargetPath(localpath), "w")
data = input.read(BLOCKSIZE)
while data:
output.write(data)
data = input.read(BLOCKSIZE)
except (IOError, OSError), e:
... | identifier_body |
uncompress.py | #
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Fou... |
class GZipHandler(UncompressorHandler):
def query(self, localpath):
if localpath.endswith(".gz"):
return True
def getTargetPath(self, localpath):
return localpath[:-3]
def uncompress(self, localpath):
import gzip
try:
input = gzip.GzipFile(localpat... | random_line_split | |
directives.py | # Define a new directive `code-block` (aliased as `sourcecode`) that uses the
# `pygments` source highlighter to render code in color.
#
# Incorporates code from the `Pygments`_ documentation for `Using Pygments in
# ReST documents`_ and `Octopress`_.
#
# .. _Pygments: http://pygments.org/
# .. _Using Pygments in Re... | (self):
self.assert_has_content()
try:
lexer_name = self.arguments[0]
lexer = get_lexer_by_name(lexer_name)
except ValueError:
# no lexer found - use the text one instead of an exception
lexer_name = 'text'
lexer = TextLexer()
f... | run | identifier_name |
directives.py | # Define a new directive `code-block` (aliased as `sourcecode`) that uses the
# `pygments` source highlighter to render code in color.
#
# Incorporates code from the `Pygments`_ documentation for `Using Pygments in
# ReST documents`_ and `Octopress`_.
#
# .. _Pygments: http://pygments.org/
# .. _Using Pygments in Re... |
# Strip pre tag and everything outside it
pres = re.compile("<pre>(.+)<\/pre>", re.S)
stripped = pres.search(parsed).group(1)
# Create tabular code with line numbers
table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">'
lined = ''
... | parsed = highlight(content_text, lexer, formatter) | conditional_block |
directives.py | # Define a new directive `code-block` (aliased as `sourcecode`) that uses the
# `pygments` source highlighter to render code in color.
#
# Incorporates code from the `Pygments`_ documentation for `Using Pygments in
# ReST documents`_ and `Octopress`_.
#
# .. _Pygments: http://pygments.org/
# .. _Using Pygments in Re... | else:
parsed = highlight(content_text, lexer, formatter)
# Strip pre tag and everything outside it
pres = re.compile("<pre>(.+)<\/pre>", re.S)
stripped = pres.search(parsed).group(1)
# Create tabular code with line numbers
table = '<div class="highlight"><ta... | self.assert_has_content()
try:
lexer_name = self.arguments[0]
lexer = get_lexer_by_name(lexer_name)
except ValueError:
# no lexer found - use the text one instead of an exception
lexer_name = 'text'
lexer = TextLexer()
formatter = HtmlF... | identifier_body |
directives.py | # Define a new directive `code-block` (aliased as `sourcecode`) that uses the
# `pygments` source highlighter to render code in color.
#
# Incorporates code from the `Pygments`_ documentation for `Using Pygments in
# ReST documents`_ and `Octopress`_.
#
# .. _Pygments: http://pygments.org/
# .. _Using Pygments in Re... | directives.register_directive('code-block', Pygments)
directives.register_directive('sourcecode', Pygments) | random_line_split | |
main.rs | // --- Day 7: Internet Protocol Version 7 ---
//
// While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping).
//
// An IP supports TLS if it has an Autonomous Bridge ... | {
// read input from file
let mut f = File::open("input.txt").unwrap();
let mut input = String::new();
f.read_to_string(&mut input).ok();
// parse lines to IPAddress objects
let addresses: Vec<IPAddress> = input.lines().map(|l| l.parse().unwrap()).collect();
// figure out answer A
let ... | identifier_body | |
main.rs | // --- Day 7: Internet Protocol Version 7 ---
//
// While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping).
//
// An IP supports TLS if it has an Autonomous Bridge ... | () {
// read input from file
let mut f = File::open("input.txt").unwrap();
let mut input = String::new();
f.read_to_string(&mut input).ok();
// parse lines to IPAddress objects
let addresses: Vec<IPAddress> = input.lines().map(|l| l.parse().unwrap()).collect();
// figure out answer A
l... | main | identifier_name |
main.rs | // --- Day 7: Internet Protocol Version 7 ---
//
// While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping).
//
// An IP supports TLS if it has an Autonomous Bridge ... | // xyx[xyx]xyx does not support SSL (xyx, but no corresponding yxy).
// aaa[kek]eke supports SSL (eke in supernet with corresponding kek in hypernet; the aaa sequence is not related, because the interior character must be different).
// zazbz[bzb]cdb supports SSL (zaz has no corresponding aza, but zbz has a correspondi... | // An IP supports SSL if it has an Area-Broadcast Accessor, or ABA, anywhere in the supernet sequences (outside any square bracketed sections), and a corresponding Byte Allocation Block, or BAB, anywhere in the hypernet sequences. An ABA is any three-character sequence which consists of the same character twice with a ... | random_line_split |
__init__.py | /licenses/>.
#
"""Samba 4."""
__docformat__ = "restructuredText"
import os
import sys
import samba.param
def source_tree_topdir():
'''return the top level directory (the one containing the source4 directory)'''
paths = [ "../../..", "../../../.." ]
for p in paths:
topdir = os.path.normpath(os.pa... | :param url: Optional LDB URL to open
:param lp: Optional loadparm object
:param modules_dir: Optional modules directory
:param session_info: Optional session information
:param credentials: Optional credentials, defaults to anonymous.
:param flags: Optional LDB flags
... | random_line_split | |
__init__.py | /licenses/>.
#
"""Samba 4."""
__docformat__ = "restructuredText"
import os
import sys
import samba.param
def source_tree_topdir():
'''return the top level directory (the one containing the source4 directory)'''
paths = [ "../../..", "../../../.." ]
for p in paths:
topdir = os.path.normpath(os.pa... |
var_start = text.find("${")
var_end = text.find("}", var_start)
raise Exception("Not all variables substituted: %s" %
text[var_start:var_end+1])
def read_and_sub_file(file_name, subst_vars):
"""Read a file and sub in variables found in it
:param file_name: File to be read (typically fr... | return | conditional_block |
__init__.py | />.
#
"""Samba 4."""
__docformat__ = "restructuredText"
import os
import sys
import samba.param
def source_tree_topdir():
'''return the top level directory (the one containing the source4 directory)'''
paths = [ "../../..", "../../../.." ]
for p in paths:
topdir = os.path.normpath(os.path.join(o... | (self, ldif, controls=None):
"""Add data based on a LDIF string.
:param ldif: LDIF text.
"""
for changetype, msg in self.parse_ldif(ldif):
assert changetype == ldb.CHANGETYPE_NONE
self.add(msg, controls)
def modify_ldif(self, ldif, controls=None):
""... | add_ldif | identifier_name |
__init__.py | /licenses/>.
#
"""Samba 4."""
__docformat__ = "restructuredText"
import os
import sys
import samba.param
def source_tree_topdir():
'''return the top level directory (the one containing the source4 directory)'''
paths = [ "../../..", "../../../.." ]
for p in paths:
topdir = os.path.normpath(os.pa... | This is different from a regular Ldb file in that the Samba-specific
modules-dir is used by default and that credentials and session_info
can be passed through (required by some modules).
"""
if modules_dir is not None:
self.set_modules_dir(modules_dir)
else:... | """Simple Samba-specific LDB subclass that takes care
of setting up the modules dir, credentials pointers, etc.
Please note that this is intended to be for all Samba LDB files,
not necessarily the Sam database. For Sam-specific helper
functions see samdb.py.
"""
def __init__(self, url=None, lp... | identifier_body |
Periodo.py | from Database.Controllers.Curso import Curso
class Periodo(object):
def __init__(self,dados=None):
if dados is not None:
|
def getId(self):
return self.id
def setId_curso(self,id_curso):
self.id_curso = id_curso
def getId_curso(self):
return self.Id_curso
def getCurso(self):
return (Curso().pegarCurso('where id = %s', (self.id_curso,))).getNome()
def setPeriodo(self,periodo):
self.periodo = periodo
def getP... | self.id = dados ['id']
self.id_curso = dados ['id_curso']
self.periodo = dados ['periodo']
self.creditos = dados ['creditos'] | conditional_block |
Periodo.py | from Database.Controllers.Curso import Curso
class Periodo(object):
def __init__(self,dados=None):
if dados is not None:
self.id = dados ['id']
self.id_curso = dados ['id_curso']
self.periodo = dados ['periodo']
self.creditos = dados ['creditos']
def getId(self):
return self.id
def setId_curso... |
def getCurso(self):
return (Curso().pegarCurso('where id = %s', (self.id_curso,))).getNome()
def setPeriodo(self,periodo):
self.periodo = periodo
def getPeriodo(self):
return self.periodo
def setCreditos(self,creditos):
self.creditos = creditos
def getCreditos(self):
return self.creditos
... | return self.Id_curso | identifier_body |
Periodo.py | from Database.Controllers.Curso import Curso
class Periodo(object):
def __init__(self,dados=None):
if dados is not None:
self.id = dados ['id']
self.id_curso = dados ['id_curso']
self.periodo = dados ['periodo']
self.creditos = dados ['creditos']
def getId(self):
return self.id
def setId_curso... | (self):
return self.creditos
| getCreditos | identifier_name |
__init__.py | # MIT License
#
# Copyright (C) IBM Corporation 2019
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER ... | #
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
# | random_line_split |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from StackSmash.apps.uploader.models import Document
from StackSmash.apps.uploader.forms import DocumentF... | (request, pk):
# Make sure the user is authenticated and able to modify the blog
if not request.user.is_superuser:
raise Http404
Document.objects.filter(pk=pk).delete()
return HttpResponseRedirect(reverse('list'))
| delete | identifier_name |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from StackSmash.apps.uploader.models import Document
from StackSmash.apps.uploader.forms import DocumentF... |
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'uploader/list.html',
{'documents': documents, 'form': form},
co... | form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('upload:list')) | conditional_block |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from StackSmash.apps.uploader.models import Document
from StackSmash.apps.uploader.forms import DocumentF... | return HttpResponseRedirect(reverse('list')) | if not request.user.is_superuser:
raise Http404
Document.objects.filter(pk=pk).delete() | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.