file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
entry-popup.service.ts | import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';
import { Entry } from './entry.model';
import { EntryService } from './entry.service';
@Injectable()
export cl... | if (this.isOpen) {
return;
}
this.isOpen = true;
if (id) {
this.entryService.find(id).subscribe((entry) => {
entry.date = this.datePipe
.transform(entry.date, 'yyyy-MM-ddThh:mm');
this.entryModalRef(component, e... | random_line_split | |
error-pages.js | module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function handler (err, req, res, next) | {
debug('Error page because of ' + err.message)
var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.errorHandler) {
return ldp.errorHandler(err, req, res, next)
}
// If noErrorPages is set,
// then use built-in express... | identifier_body | |
error-pages.js | module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function handler (err, req, res, next) {
debug('Error page because of ' + err.message)
var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.e... |
// Check if error page exists
var errorPage = ldp.errorPages + err.status.toString() + '.html'
fs.readFile(errorPage, 'utf8', function (readErr, text) {
if (readErr) {
return res
.status(err.status)
.send(err.message || '')
}
res.status(err.status)
res.header('Content-Type... | {
return res
.status(err.status)
.send(err.message + '\n' || '')
} | conditional_block |
error-pages.js | module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function | (err, req, res, next) {
debug('Error page because of ' + err.message)
var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.errorHandler) {
return ldp.errorHandler(err, req, res, next)
}
// If noErrorPages is set,
// th... | handler | identifier_name |
error-pages.js | module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function handler (err, req, res, next) {
debug('Error page because of ' + err.message)
| return ldp.errorHandler(err, req, res, next)
}
// If noErrorPages is set,
// then use built-in express default error handler
if (ldp.noErrorPages) {
return res
.status(err.status)
.send(err.message + '\n' || '')
}
// Check if error page exists
var errorPage = ldp.errorPages + err.sta... | var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.errorHandler) { | random_line_split |
extends.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 Vladislav Orlov
//
// 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,... | (body: String, _iter: &mut Iter<Token>) -> Result<Option<NodeType>> {
Ok(Some(NodeType::Extends(ExtendsNode::new(body))))
} | build | identifier_name |
extends.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 Vladislav Orlov
//
// 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,... | {
Ok(Some(NodeType::Extends(ExtendsNode::new(body))))
} | identifier_body | |
extends.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 Vladislav Orlov
//
// 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,... | use ast::ExtendsNode;
use scanner::Token;
pub fn build(body: String, _iter: &mut Iter<Token>) -> Result<Option<NodeType>> {
Ok(Some(NodeType::Extends(ExtendsNode::new(body))))
} | random_line_split | |
remove_issue_test.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
def test_succeed(self):
"""Remove issue from a testcase."""
testcase = data_types.Testcase()
testcase.bug_information = '1234'
testcase.put()
resp = self.app.post_json('/', {
'testcaseId': testcase.key.id(),
'csrf_token': form.generate_csrf_token(),
})
self.assertEqual(... | test_helpers.patch(self, [
'handlers.testcase_detail.show.get_testcase_detail',
'libs.auth.get_current_user',
'libs.auth.is_current_user_admin',
])
self.mock.is_current_user_admin.return_value = True
self.mock.get_testcase_detail.return_value = {'testcase': 'yes'}
self.mock.get_c... | identifier_body |
remove_issue_test.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (self):
"""Remove issue from a testcase."""
testcase = data_types.Testcase()
testcase.bug_information = '1234'
testcase.put()
resp = self.app.post_json('/', {
'testcaseId': testcase.key.id(),
'csrf_token': form.generate_csrf_token(),
})
self.assertEqual(200, resp.status_int... | test_succeed | identifier_name |
remove_issue_test.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | """Test Handler."""
def setUp(self):
test_helpers.patch(self, [
'handlers.testcase_detail.show.get_testcase_detail',
'libs.auth.get_current_user',
'libs.auth.is_current_user_admin',
])
self.mock.is_current_user_admin.return_value = True
self.mock.get_testcase_detail.return_v... | random_line_split | |
find-many.js | import toId from '../utils/to-id'
/**
* Returns all objects matching the given ids or objects.
*
* @param {PouchDB} {REQUIRED} db Reference to PouchDB
* @param {Array} {REQUIRED} idsOrObjects An array of ids or objects
* @param {String} {OPTIONAL} prefix optional id prefix
* @return {Pro... | (db, idsOrObjects, prefix) {
let ids = idsOrObjects.map(toId)
// add prefix if it's not included in the id already
if (prefix) {
ids = ids.map(function (id) {
return id.substr(0, prefix.length) === prefix ? id : prefix + id
})
}
return db.allDocs({ keys: ids, include_docs: true })
.then(f... | findMany | identifier_name |
find-many.js | import toId from '../utils/to-id'
/**
* Returns all objects matching the given ids or objects.
*
* @param {PouchDB} {REQUIRED} db Reference to PouchDB
* @param {Array} {REQUIRED} idsOrObjects An array of ids or objects
* @param {String} {OPTIONAL} prefix optional id prefix
* @return {Pro... |
export default findMany
| {
let ids = idsOrObjects.map(toId)
// add prefix if it's not included in the id already
if (prefix) {
ids = ids.map(function (id) {
return id.substr(0, prefix.length) === prefix ? id : prefix + id
})
}
return db.allDocs({ keys: ids, include_docs: true })
.then(function (response) {
/... | identifier_body |
find-many.js | import toId from '../utils/to-id'
/**
* Returns all objects matching the given ids or objects.
*
* @param {PouchDB} {REQUIRED} db Reference to PouchDB | function findMany (db, idsOrObjects, prefix) {
let ids = idsOrObjects.map(toId)
// add prefix if it's not included in the id already
if (prefix) {
ids = ids.map(function (id) {
return id.substr(0, prefix.length) === prefix ? id : prefix + id
})
}
return db.allDocs({ keys: ids, include_docs: tr... | * @param {Array} {REQUIRED} idsOrObjects An array of ids or objects
* @param {String} {OPTIONAL} prefix optional id prefix
* @return {Promise}
*/ | random_line_split |
find-many.js | import toId from '../utils/to-id'
/**
* Returns all objects matching the given ids or objects.
*
* @param {PouchDB} {REQUIRED} db Reference to PouchDB
* @param {Array} {REQUIRED} idsOrObjects An array of ids or objects
* @param {String} {OPTIONAL} prefix optional id prefix
* @return {Pro... |
return db.allDocs({ keys: ids, include_docs: true })
.then(function (response) {
// gather a hashmap of ids
const docsById = response.rows.reduce(function (map, row) {
map[row.id] = row.doc
return map
}, {})
// for each requested id, use foundMap to get the document with... | {
ids = ids.map(function (id) {
return id.substr(0, prefix.length) === prefix ? id : prefix + id
})
} | conditional_block |
ExportGeometryInfo.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExportGeometryInfo.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********************... | self.calc_methods = [self.tr('Layer CRS'),
self.tr('Project CRS'),
self.tr('Ellipsoidal')]
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
... | random_line_split | |
ExportGeometryInfo.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExportGeometryInfo.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********************... |
else:
if geometry.numGeometries() > 0:
pt = geometry.geometryN(0)
attrs = []
if pt:
attrs.append(pt.x())
attrs.append(pt.y())
# add point z/m
if self.export_z:
attrs.append(pt.z())
if self.ex... | pt = geometry.geometry() | conditional_block |
ExportGeometryInfo.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExportGeometryInfo.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********************... | (QgisAlgorithm):
INPUT = 'INPUT'
METHOD = 'CALC_METHOD'
OUTPUT = 'OUTPUT'
def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'export_geometry.png'))
def tags(self):
return self.tr('export,add,information,measurements,areas,lengths,perimeters,latitudes,longit... | ExportGeometryInfo | identifier_name |
ExportGeometryInfo.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExportGeometryInfo.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********************... |
def __init__(self):
super().__init__()
self.export_z = False
self.export_m = False
self.distance_area = None
self.calc_methods = [self.tr('Layer CRS'),
self.tr('Project CRS'),
self.tr('Ellipsoidal')]
def initAlg... | return self.tr('Vector geometry') | identifier_body |
Item.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from '../grid';
import { ListGridType, ColumnType } from './index';
export interface ListItemProps {
className?: string;
children?: React.ReactNode;
prefixCls?: string;
style?: React.CSSPrope... | }
export const Meta = (props: ListItemMetaProps) => {
const {
prefixCls = 'ant-list',
className,
avatar,
title,
description,
...others,
} = props;
const classString = classNames(`${prefixCls}-item-meta`, className);
const content = (
<div className={`${prefixCls}-item-meta-content... | prefixCls?: string;
style?: React.CSSProperties;
title: React.ReactNode; | random_line_split |
Item.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from '../grid';
import { ListGridType, ColumnType } from './index';
export interface ListItemProps {
className?: string;
children?: React.ReactNode;
prefixCls?: string;
style?: React.CSSPrope... |
const GridColumns = ['', 1, 2, 3, 4, 6, 8, 12, 24];
export default class Item extends React.Component<ListItemProps, any> {
static Meta: typeof Meta = Meta;
static propTypes = {
column: PropTypes.oneOf(GridColumns),
xs: PropTypes.oneOf(GridColumns),
sm: PropTypes.oneOf(GridColumns),
md: PropType... | {
return grid[t] && Math.floor(24 / grid[t]!);
} | identifier_body |
Item.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from '../grid';
import { ListGridType, ColumnType } from './index';
export interface ListItemProps {
className?: string;
children?: React.ReactNode;
prefixCls?: string;
style?: React.CSSPrope... |
});
const contentClassString = classNames(`${prefixCls}-item-content`, {
[`${prefixCls}-item-content-single`]: (metaContent.length < 1),
});
const content = otherContent.length > 0 ? (
<div className={contentClassString}>
{otherContent}
</div>) : null;
let actionsContent... | {
otherContent.push(element);
} | conditional_block |
Item.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from '../grid';
import { ListGridType, ColumnType } from './index';
export interface ListItemProps {
className?: string;
children?: React.ReactNode;
prefixCls?: string;
style?: React.CSSPrope... | (grid: ListGridType, t: ColumnType) {
return grid[t] && Math.floor(24 / grid[t]!);
}
const GridColumns = ['', 1, 2, 3, 4, 6, 8, 12, 24];
export default class Item extends React.Component<ListItemProps, any> {
static Meta: typeof Meta = Meta;
static propTypes = {
column: PropTypes.oneOf(GridColumns),
xs... | getGrid | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
#
# Yaafe
#
# Copyright (c) 2009-2010 Institut Télécom - Télécom Paristech
# Télécom ParisTech / dept. TSI
#
# Author : Benoit Mathieu
#
# This file is part of Yaafe.
#
# Yaafe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License a... | # load available plugins
__import__(
'yaafe_extensions.yaafefeatures',
globals(), locals(), [], -1
)
yaafe_path = os.getenv('YAAFE_PATH')
if not yaafe_path:
return
if not yaafe_path in sys.path:
sys.path.append(yaafe_path)
for f in os.listdir(yaafe_path):
... | ugins():
| identifier_name |
__init__.py | # -*- coding: utf-8 -*-
#
# Yaafe
#
# Copyright (c) 2009-2010 Institut Télécom - Télécom Paristech
# Télécom ParisTech / dept. TSI
#
# Author : Benoit Mathieu
#
# This file is part of Yaafe.
#
# Yaafe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License a... | 'setPreferedDataBlockSize',
'setVerbose',
'readH5FeatureDescriptions',
'getYaafeVersion',
'DataFlow',
'AudioFeatureFactory',
'AudioFeature',
'check_dataflow_params',
'dataflow_safe_append',
'FeaturePlan',
... | 'getOutputFormatList',
'getOutputFormatDescription',
'getOutputFormatParameters', | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
#
# Yaafe
#
# Copyright (c) 2009-2010 Institut Télécom - Télécom Paristech
# Télécom ParisTech / dept. TSI
#
# Author : Benoit Mathieu
#
# This file is part of Yaafe.
#
# Yaafe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License a... | Plugins()
| rt__(
'yaafe_extensions.yaafefeatures',
globals(), locals(), [], -1
)
yaafe_path = os.getenv('YAAFE_PATH')
if not yaafe_path:
return
if not yaafe_path in sys.path:
sys.path.append(yaafe_path)
for f in os.listdir(yaafe_path):
parts = f.split('.')
if no... | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
#
# Yaafe
#
# Copyright (c) 2009-2010 Institut Télécom - Télécom Paristech
# Télécom ParisTech / dept. TSI
#
# Author : Benoit Mathieu
#
# This file is part of Yaafe.
#
# Yaafe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License a... | or f in os.listdir(yaafe_path):
parts = f.split('.')
if not parts[-1] == 'py':
continue
extension = '.'.join(parts[:-1])
try:
__import__(extension, globals(), locals(), [], -1)
except ImportError, err:
print 'ERROR: cannot load yaafe extension ... | th.append(yaafe_path)
f | conditional_block |
test_sqlstore.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
from misura.canon import option
from misura.canon.option import get_typed_cols, get_insert_cmd, base_col_def, print_tree
import sqlite3
from misura.canon.tests import testdir
db = testdir + 'storage/tmpdb'
c1 = testdir + 'storage/Conf.csv'
def go(t)... | print(get_insert_cmd(go('Integer'), base_col_def))
print(get_insert_cmd(go('String'), base_col_def))
print(get_insert_cmd(go('Point'), base_col_def))
print(get_insert_cmd(go('Role'), base_col_def))
print(get_insert_cmd(go('RoleIO'), base_col_def))
print(get_insert_cmd(go(... | print(get_typed_cols(go('Meta')))
def test_get_insert_cmd(self): | random_line_split |
test_sqlstore.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
from misura.canon import option
from misura.canon.option import get_typed_cols, get_insert_cmd, base_col_def, print_tree
import sqlite3
from misura.canon.tests import testdir
db = testdir + 'storage/tmpdb'
c1 = testdir + 'storage/Conf.csv'
def go(t)... | (self):
print(get_typed_cols(go('Integer')))
print(get_typed_cols(go('String')))
print(get_typed_cols(go('Point')))
print(get_typed_cols(go('Role')))
print(get_typed_cols(go('RoleIO')))
print(get_typed_cols(go('Log')))
print(get_typed_cols(go('Meta')))
def te... | test_get_typed_cols | identifier_name |
test_sqlstore.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
from misura.canon import option
from misura.canon.option import get_typed_cols, get_insert_cmd, base_col_def, print_tree
import sqlite3
from misura.canon.tests import testdir
db = testdir + 'storage/tmpdb'
c1 = testdir + 'storage/Conf.csv'
def go(t)... | unittest.main() | conditional_block | |
test_sqlstore.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
from misura.canon import option
from misura.canon.option import get_typed_cols, get_insert_cmd, base_col_def, print_tree
import sqlite3
from misura.canon.tests import testdir
db = testdir + 'storage/tmpdb'
c1 = testdir + 'storage/Conf.csv'
def go(t)... |
def test_column_definition(self):
s = option.SqlStore()
print(s.column_definition(go('Integer'))[1])
print(s.column_definition(go('String'))[1])
print(s.column_definition(go('Point'))[1])
print(s.column_definition(go('Role'))[1])
print(s.column_definition(go('RoleIO... | print(get_insert_cmd(go('Integer'), base_col_def))
print(get_insert_cmd(go('String'), base_col_def))
print(get_insert_cmd(go('Point'), base_col_def))
print(get_insert_cmd(go('Role'), base_col_def))
print(get_insert_cmd(go('RoleIO'), base_col_def))
print(get_insert_cmd(go('Log'), ... | identifier_body |
scenario.service.ts | import { EmbeddedFunctionsEnvironment } from './embedded-functions.environment';
import { PortalService } from './../portal.service';
import { LogCategories } from './../../models/constants';
import { AzureTryEnvironment } from './azure-try.environment';
import { TranslateService } from '@ngx-translate/core';
import { ... | new DynamicSiteEnvironment(this._translateService),
new LinuxSiteEnvironment(this._translateService),
new AzureTryEnvironment(),
new EmbeddedFunctionsEnvironment(this._portalService)
];
constructor(
private _logService: LogService,
private _translateService: Tran... | new SiteSlotEnvironment(this._translateService), | random_line_split |
scenario.service.ts | import { EmbeddedFunctionsEnvironment } from './embedded-functions.environment';
import { PortalService } from './../portal.service';
import { LogCategories } from './../../models/constants';
import { AzureTryEnvironment } from './azure-try.environment';
import { TranslateService } from '@ngx-translate/core';
import { ... |
}
// Does a synchronous check against all possible environments to see whether a
// scenario should be either enabled (whitelisted) or disabled (blacklisted). Things to note:
// 1. Blacklisting takes priority, so if there are several environments which say that a scenario is
// enabled, but th... | {
this._environments.splice(0, 0, new AzureEnvironment());
} | conditional_block |
scenario.service.ts | import { EmbeddedFunctionsEnvironment } from './embedded-functions.environment';
import { PortalService } from './../portal.service';
import { LogCategories } from './../../models/constants';
import { AzureTryEnvironment } from './azure-try.environment';
import { TranslateService } from '@ngx-translate/core';
import { ... | {
private _environments: Environment[] = [
new StandaloneEnvironment(),
new OnPremEnvironment(),
new SiteSlotEnvironment(this._translateService),
new DynamicSiteEnvironment(this._translateService),
new LinuxSiteEnvironment(this._translateService),
new AzureTryEnviro... | ScenarioService | identifier_name |
scenario.service.ts | import { EmbeddedFunctionsEnvironment } from './embedded-functions.environment';
import { PortalService } from './../portal.service';
import { LogCategories } from './../../models/constants';
import { AzureTryEnvironment } from './azure-try.environment';
import { TranslateService } from '@ngx-translate/core';
import { ... |
// Does a synchronous check against all possible environments to see whether a
// scenario should be either enabled (whitelisted) or disabled (blacklisted). Things to note:
// 1. Blacklisting takes priority, so if there are several environments which say that a scenario is
// enabled, but there is... | {
// National cloud environments inherit from AzureEnvironment so we ensure there
// aren't duplicates to reduce the chance of conflicts in behavior.
if (NationalCloudEnvironment.isNationalCloud()) {
this._environments.splice(0, 0, new NationalCloudEnvironment());
} else {
... | identifier_body |
media_queries.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/. */
use std::ascii::StrAsciiExt;
use cssparser::parse_rule_list;
use cssparser::ast::*;
use errors::{ErrorLoggerItera... | rules: ~[CSSRule],
}
pub struct MediaQueryList {
// "not all" is omitted from the list.
// An empty list never matches.
media_queries: ~[MediaQuery]
}
// For now, this is a "Level 2 MQ", ie. a media type.
struct MediaQuery {
media_type: MediaQueryType,
// TODO: Level 3 MQ expressions
}
enum... |
pub struct MediaRule {
media_queries: MediaQueryList, | random_line_split |
media_queries.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/. */
use std::ascii::StrAsciiExt;
use cssparser::parse_rule_list;
use cssparser::ast::*;
use errors::{ErrorLoggerItera... | {
media_type: MediaQueryType,
// TODO: Level 3 MQ expressions
}
enum MediaQueryType {
All, // Always true
MediaType(MediaType),
}
#[deriving(Eq)]
pub enum MediaType {
Screen,
Print,
}
pub struct Device {
media_type: MediaType,
// TODO: Level 3 MQ data: viewport size, etc.
}
pub f... | MediaQuery | identifier_name |
media_queries.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/. */
use std::ascii::StrAsciiExt;
use cssparser::parse_rule_list;
use cssparser::ast::*;
use errors::{ErrorLoggerItera... | ,
// Ingnore this comma-separated part
_ => loop {
match iter.next() {
Some(&Comma) => break,
None => return MediaQueryList{ media_queries: queries },
_ => (),
}
},
}
next = it... | {
for mq in mq.move_iter() {
queries.push(mq);
}
} | conditional_block |
local_settings.py | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'jumodjango',
'USER': 'jumo',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
},
}
PROXY_SERVER = ""
BROKER_HOST = ""
BROKER_PORT = 5672
BROKER_USER = ""
BROKER_PASSWORD = ""
BROKER_VHOST =... | AWS_SECRET_KEY = ''
AWS_PHOTO_UPLOAD_BUCKET = "" | AWS_ACCESS_KEY = '' | random_line_split |
0006_auto_20160716_1641.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-16 16:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
| dependencies = [
('campaign', '0005_auto_20160716_1624'),
]
operations = [
migrations.AddField(
model_name='charity',
name='gateway',
field=models.ManyToManyField(through='campaign.GatewayProperty', to='campaign.Gateway'),
),
migrations.AlterF... | identifier_body | |
0006_auto_20160716_1641.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-16 16:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class | (migrations.Migration):
dependencies = [
('campaign', '0005_auto_20160716_1624'),
]
operations = [
migrations.AddField(
model_name='charity',
name='gateway',
field=models.ManyToManyField(through='campaign.GatewayProperty', to='campaign.Gateway'),
... | Migration | identifier_name |
0006_auto_20160716_1641.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-16 16:41
from __future__ import unicode_literals
from django.db import migrations, models |
class Migration(migrations.Migration):
dependencies = [
('campaign', '0005_auto_20160716_1624'),
]
operations = [
migrations.AddField(
model_name='charity',
name='gateway',
field=models.ManyToManyField(through='campaign.GatewayProperty', to='campaign.G... | import django.utils.timezone | random_line_split |
emptyFunction.js | "use strict"; | * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed unde... | /**
* Copyright 2013 Facebook, Inc.
* | random_line_split |
emptyFunction.js | "use strict";
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law... | () {}
copyProperties(emptyFunction, {
thatReturns: makeEmptyFunction,
thatReturnsFalse: makeEmptyFunction(false),
thatReturnsTrue: makeEmptyFunction(true),
thatReturnsNull: makeEmptyFunction(null),
thatReturnsThis: function() { return this; },
thatReturnsArgument: function(arg) { return arg; }
});
export... | emptyFunction | identifier_name |
emptyFunction.js | "use strict";
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law... |
copyProperties(emptyFunction, {
thatReturns: makeEmptyFunction,
thatReturnsFalse: makeEmptyFunction(false),
thatReturnsTrue: makeEmptyFunction(true),
thatReturnsNull: makeEmptyFunction(null),
thatReturnsThis: function() { return this; },
thatReturnsArgument: function(arg) { return arg; }
});
exports["def... | {} | identifier_body |
test.py | from __future__ import print_function
import sys
sys.path.append('..') # help python find cyton.py relative to scripts folder
from openbci import cyton as bci
import logging
import time
def | (sample):
# os.system('clear')
print("----------------")
print("%f" % (sample.id))
print(sample.channel_data)
print(sample.aux_data)
print("----------------")
if __name__ == '__main__':
# port = '/dev/tty.OpenBCI-DN008VTF'
port = '/dev/tty.usbserial-DB00JAM0'
# port = '/dev/tty.Ope... | printData | identifier_name |
test.py | from __future__ import print_function
import sys
sys.path.append('..') # help python find cyton.py relative to scripts folder
from openbci import cyton as bci
import logging
import time
def printData(sample):
# os.system('clear')
print("----------------")
print("%f" % (sample.id))
print(sample.chann... | port = '/dev/tty.usbserial-DB00JAM0'
# port = '/dev/tty.OpenBCI-DN0096XA'
baud = 115200
logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG)
logging.info('---------LOG START-------------')
board = bci.OpenBCICyton(port=port, scaled_output=... | conditional_block | |
test.py | from __future__ import print_function
import sys
sys.path.append('..') # help python find cyton.py relative to scripts folder
from openbci import cyton as bci
import logging
import time
def printData(sample):
# os.system('clear')
|
if __name__ == '__main__':
# port = '/dev/tty.OpenBCI-DN008VTF'
port = '/dev/tty.usbserial-DB00JAM0'
# port = '/dev/tty.OpenBCI-DN0096XA'
baud = 115200
logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG)
logging.info('---------LOG ... | print("----------------")
print("%f" % (sample.id))
print(sample.channel_data)
print(sample.aux_data)
print("----------------") | identifier_body |
test.py | from __future__ import print_function
import sys
sys.path.append('..') # help python find cyton.py relative to scripts folder
from openbci import cyton as bci
import logging
import time
def printData(sample):
# os.system('clear')
print("----------------")
print("%f" % (sample.id)) |
if __name__ == '__main__':
# port = '/dev/tty.OpenBCI-DN008VTF'
port = '/dev/tty.usbserial-DB00JAM0'
# port = '/dev/tty.OpenBCI-DN0096XA'
baud = 115200
logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG)
logging.info('---------LOG S... | print(sample.channel_data)
print(sample.aux_data)
print("----------------") | random_line_split |
app.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import * as electron from 'electron';
const ipc = electron.ipcRenderer;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit{
... | else {
this.trayOn = true
ipc.send('put-in-tray')
}
});
// Tray removed from context menu on icon
ipc.on('tray-removed', function () {
ipc.send('remove-tray')
this.trayOn = false
})
}
}
| {
this.trayOn = false;
ipc.send('remove-tray');
} | conditional_block |
app.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import * as electron from 'electron';
const ipc = electron.ipcRenderer;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit{
... |
title = 'app';
constructor(){
}
private RegisterTrayButtonEvents(){
this.trayBtn.addEventListener('click', () => {
if (this.trayOn) {
this.trayOn = false;
ipc.send('remove-tray');
} else {
this.trayOn = true
ipc.send('put-in-... | {
} | identifier_body |
app.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import * as electron from 'electron';
const ipc = electron.ipcRenderer;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit{
... | (){
this.trayBtn.addEventListener('click', () => {
if (this.trayOn) {
this.trayOn = false;
ipc.send('remove-tray');
} else {
this.trayOn = true
ipc.send('put-in-tray')
}
});
// Tray removed from context menu on ico... | RegisterTrayButtonEvents | identifier_name |
app.component.ts | import { Component, AfterViewInit, OnInit } from '@angular/core';
import * as electron from 'electron';
const ipc = electron.ipcRenderer;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit{
... | } else {
this.trayOn = true
ipc.send('put-in-tray')
}
});
// Tray removed from context menu on icon
ipc.on('tray-removed', function () {
ipc.send('remove-tray')
this.trayOn = false
})
}
} | ipc.send('remove-tray'); | random_line_split |
import_repo.py | from __future__ import absolute_import, print_function
import logging
from datetime import datetime
from changes.config import db
from changes.models import Repository, RepositoryStatus
from changes.queue.task import tracked_task
logger = logging.getLogger('repo.sync')
@tracked_task(max_retries=None)
def import_r... | repo = Repository.query.get(repo_id)
if not repo:
logger.error('Repository %s not found', repo_id)
return
vcs = repo.get_vcs()
if vcs is None:
logger.warning('Repository %s has no VCS backend set', repo.id)
return
if repo.status == RepositoryStatus.inactive:
log... | identifier_body | |
import_repo.py | from __future__ import absolute_import, print_function
import logging
from datetime import datetime
from changes.config import db
from changes.models import Repository, RepositoryStatus
from changes.queue.task import tracked_task
logger = logging.getLogger('repo.sync')
@tracked_task(max_retries=None)
def import_r... |
Repository.query.filter(
Repository.id == repo.id,
).update({
'last_update_attempt': datetime.utcnow(),
}, synchronize_session=False)
db.session.commit()
if vcs.exists():
vcs.update()
else:
vcs.clone()
for commit in vcs.log(parent=parent):
revision,... | logger.info('Repository %s is inactive', repo.id)
return | random_line_split |
import_repo.py | from __future__ import absolute_import, print_function
import logging
from datetime import datetime
from changes.config import db
from changes.models import Repository, RepositoryStatus
from changes.queue.task import tracked_task
logger = logging.getLogger('repo.sync')
@tracked_task(max_retries=None)
def | (repo_id, parent=None):
repo = Repository.query.get(repo_id)
if not repo:
logger.error('Repository %s not found', repo_id)
return
vcs = repo.get_vcs()
if vcs is None:
logger.warning('Repository %s has no VCS backend set', repo.id)
return
if repo.status == Repository... | import_repo | identifier_name |
import_repo.py | from __future__ import absolute_import, print_function
import logging
from datetime import datetime
from changes.config import db
from changes.models import Repository, RepositoryStatus
from changes.queue.task import tracked_task
logger = logging.getLogger('repo.sync')
@tracked_task(max_retries=None)
def import_r... |
for commit in vcs.log(parent=parent):
revision, created = commit.save(repo)
db.session.commit()
parent = commit.id
Repository.query.filter(
Repository.id == repo.id,
).update({
'last_update': datetime.utcnow(),
'status': RepositoryStatus.active,
}, sync... | vcs.clone() | conditional_block |
UUID.js | // Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var ID = {};
ID.uuid = function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | ... | // A more compact, but less performant, RFC4122v4 solution:
ID.uuidCompact = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
module.exports = ID; | return uuid.join('');
};
| random_line_split |
auth.ts | import fetch from './util/fetch-wrapper';
import config, {
baseUrl, clientAuthorization, isTokenExpired, token,
} from './util/config';
import qsEncode from './util/qs-encode';
export interface IAOuthToken {
access_token: string;
refresh_token: string;
expires_in: number;
}
export interface IConfigUser {
ac... | else {
return Promise.reject(new Error('Unable to find valid token'));
}
},
getToken() {
return token();
},
isTokenExpired() {
return isTokenExpired();
},
};
| {
if (this.isTokenExpired()) {
return this.refresh();
} else {
return Promise.resolve();
}
} | conditional_block |
auth.ts | import fetch from './util/fetch-wrapper';
import config, {
baseUrl, clientAuthorization, isTokenExpired, token,
} from './util/config';
import qsEncode from './util/qs-encode';
export interface IAOuthToken {
access_token: string;
refresh_token: string;
expires_in: number;
}
export interface IConfigUser {
ac... | if (this.isTokenExpired()) {
return this.refresh();
} else {
return Promise.resolve();
}
} else {
return Promise.reject(new Error('Unable to find valid token'));
}
},
getToken() {
return token();
},
isTokenExpired() {
return isTokenExpired();
},
}; | },
ensureLogin() {
const accessToken = this.getToken();
if (accessToken) { | random_line_split |
auth.ts | import fetch from './util/fetch-wrapper';
import config, {
baseUrl, clientAuthorization, isTokenExpired, token,
} from './util/config';
import qsEncode from './util/qs-encode';
export interface IAOuthToken {
access_token: string;
refresh_token: string;
expires_in: number;
}
export interface IConfigUser {
ac... |
export default {
login(username: string, password: string) {
return oauthToken({ username, password, grant_type: 'password', scope: 'read%20write' });
},
logout() {
config.set('user.access_token', null);
config.set('user.expires_at', 0);
return Promise.resolve();
},
refresh() {
const ref... | {
return fetch<IAOuthToken>(`${baseUrl()}/oauth/token`, {
method: 'POST',
body: qsEncode({
client_id: config.get('registry.oauth.client_id'),
client_secret: config.get('registry.oauth.client_secret'),
...body,
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
... | identifier_body |
auth.ts | import fetch from './util/fetch-wrapper';
import config, {
baseUrl, clientAuthorization, isTokenExpired, token,
} from './util/config';
import qsEncode from './util/qs-encode';
export interface IAOuthToken {
access_token: string;
refresh_token: string;
expires_in: number;
}
export interface IConfigUser {
ac... | (username: string, password: string) {
return oauthToken({ username, password, grant_type: 'password', scope: 'read%20write' });
},
logout() {
config.set('user.access_token', null);
config.set('user.expires_at', 0);
return Promise.resolve();
},
refresh() {
const refreshToken = config.get('us... | login | identifier_name |
push-notifications.module.ngfactory.ts | /**
* This file is generated by the Angular 2 template compiler.
* Do not edit.
*/
/* tslint:disable */
import * as import0 from '@angular/core/src/linker/ng_module_factory';
import * as import1 from '../../src/push-notifications.module';
import * as import2 from '../../src/push-notifications.service';
import * as... |
if ((token === import2.PushNotificationsService)) { return this._PushNotificationsService_1; }
return notFoundResult;
}
destroyInternal():void {
}
}
export const PushNotificationsModuleNgFactory:import0.NgModuleFactory<import1.PushNotificationsModule> = new import0.NgModuleFactory(PushNotificationsModule... | { return this._PushNotificationsModule_0; } | conditional_block |
push-notifications.module.ngfactory.ts | /**
* This file is generated by the Angular 2 template compiler.
* Do not edit.
*/
/* tslint:disable */
import * as import0 from '@angular/core/src/linker/ng_module_factory';
import * as import1 from '../../src/push-notifications.module';
import * as import2 from '../../src/push-notifications.service';
import * as... | ():void {
}
}
export const PushNotificationsModuleNgFactory:import0.NgModuleFactory<import1.PushNotificationsModule> = new import0.NgModuleFactory(PushNotificationsModuleInjector,import1.PushNotificationsModule); | destroyInternal | identifier_name |
push-notifications.module.ngfactory.ts | /**
* This file is generated by the Angular 2 template compiler.
* Do not edit.
*/
/* tslint:disable */
import * as import0 from '@angular/core/src/linker/ng_module_factory';
import * as import1 from '../../src/push-notifications.module';
import * as import2 from '../../src/push-notifications.service';
import * as... |
get _PushNotificationsService_1():import2.PushNotificationsService {
if ((this.__PushNotificationsService_1 == (null as any))) { (this.__PushNotificationsService_1 = new import2.PushNotificationsService()); }
return this.__PushNotificationsService_1;
}
createInternal():import1.PushNotificationsModule {
... | {
super(parent,([] as any[]),([] as any[]));
} | identifier_body |
push-notifications.module.ngfactory.ts | /**
* This file is generated by the Angular 2 template compiler.
* Do not edit.
*/
/* tslint:disable */
import * as import0 from '@angular/core/src/linker/ng_module_factory';
import * as import1 from '../../src/push-notifications.module';
import * as import2 from '../../src/push-notifications.service'; | import * as import3 from '@angular/core/src/di/injector';
class PushNotificationsModuleInjector extends import0.NgModuleInjector<import1.PushNotificationsModule> {
_PushNotificationsModule_0:import1.PushNotificationsModule;
__PushNotificationsService_1:import2.PushNotificationsService;
constructor(parent:import3.... | random_line_split | |
bootstrap-table-th-TH.min.js | /* | * Copyright (c) 2017 zhixin wen
* Licensed MIT License
*/
!function(a){"use strict";a.fn.bootstrapTable.locales["th-TH"]={formatLoadingMessage:function(){return"กำลังโหลดข้อมูล, กรุณารอสักครู่..."},formatRecordsPerPage:function(a){return a+" รายการต่อหน้า"},formatShowingRows:function(a,b,c){return"รายการที่ "+a+" ถึง "... | * bootstrap-table - v1.11.1 - 2017-08-03
* https://github.com/wenzhixin/bootstrap-table | random_line_split |
vagueTime-en-fr.js | /**
* This module formats precise time differences as a vague/fuzzy
* time, e.g. '3 weeks ago', 'just now' or 'in 2 hours'.
*/
/*globals define, module */
(function (globals) {
'use strict';
var times = {
year: 31557600000, // 1000 ms * 60 s * 60 m * 24 h * 365.25 d
month: 2629800000, // ... | },
future: function (vagueTime, unit) {
return 'dans ' + vagueTime + ' ' + unit;
},
defaults: {
past: 'tout de suite',
future: 'bientôt'
}
}
},
defaultLanguage = 'en',
func... | minute: [ 'minute', 'minutes' ],
past: function (vagueTime, unit) {
return 'il y a ' + vagueTime + ' ' + unit; | random_line_split |
vagueTime-en-fr.js | /**
* This module formats precise time differences as a vague/fuzzy
* time, e.g. '3 weeks ago', 'just now' or 'in 2 hours'.
*/
/*globals define, module */
(function (globals) {
'use strict';
var times = {
year: 31557600000, // 1000 ms * 60 s * 60 m * 24 h * 365.25 d
month: 2629800000, // ... | (date) {
return Object.prototype.toString.call(date) !== '[object Date]' || isNaN(date.getTime());
}
function isNotTimestamp (timestamp) {
return typeof timestamp !== 'number' || isNaN(timestamp);
}
function estimate (difference, type, language) {
var time, vagueTime, lang = la... | sNotDate | identifier_name |
vagueTime-en-fr.js | /**
* This module formats precise time differences as a vague/fuzzy
* time, e.g. '3 weeks ago', 'just now' or 'in 2 hours'.
*/
/*globals define, module */
(function (globals) {
'use strict';
var times = {
year: 31557600000, // 1000 ms * 60 s * 60 m * 24 h * 365.25 d
month: 2629800000, // ... |
function isNotTimestamp (timestamp) {
return typeof timestamp !== 'number' || isNaN(timestamp);
}
function estimate (difference, type, language) {
var time, vagueTime, lang = languages[language] || languages[defaultLanguage];
for (time in times) {
if (times.hasOwnPrope... |
return Object.prototype.toString.call(date) !== '[object Date]' || isNaN(date.getTime());
}
| identifier_body |
vagueTime-en-fr.js | /**
* This module formats precise time differences as a vague/fuzzy
* time, e.g. '3 weeks ago', 'just now' or 'in 2 hours'.
*/
/*globals define, module */
(function (globals) {
'use strict';
var times = {
year: 31557600000, // 1000 ms * 60 s * 60 m * 24 h * 365.25 d
month: 2629800000, // ... |
if (units === 's' || units === 'ms') {
return units;
}
throw new Error('Invalid units');
}
function normaliseTime(time, units, defaultTime) {
if (typeof time === 'undefined') {
return defaultTime;
}
if (typeof time === 'string') {
... |
return 'ms';
}
| conditional_block |
call_once.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::ops::FnMut;
use core::ops::FnOnce;
type T = i32;
struct F;
type Args = (T,);
impl FnOnce<Args> for F {
type Output = T;
extern "rust-call" fn call_once(self, (x,): Args) -> Self::Output {
x + 1... | assert_eq!(result, 70);
}
#[test]
fn call_once_test2() {
fn foo<F: FnOnce(T) -> T>(f: F, x: T) -> T {
f(x)
}
let mut f: F = F;
let f_ptr: &mut F = &mut f;
let x: T = 68;
let result: T = foo(f_ptr, x);
assert_eq!(result, x + 2);
assert_eq!(result, 70);
}
} |
assert_eq!(result, x + 2); | random_line_split |
call_once.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::ops::FnMut;
use core::ops::FnOnce;
type T = i32;
struct F;
type Args = (T,);
impl FnOnce<Args> for F {
type Output = T;
extern "rust-call" fn | (self, (x,): Args) -> Self::Output {
x + 1
}
}
impl FnMut<Args> for F {
extern "rust-call" fn call_mut(&mut self, (x,): Args) -> Self::Output {
x + 2
}
}
#[test]
fn call_once_test1() {
let mut f: F = F;
let f_ptr: &mut F = &mut f;
let x: T = 68;
let result: T = f_ptr.call_once((x,... | call_once | identifier_name |
call_once.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::ops::FnMut;
use core::ops::FnOnce;
type T = i32;
struct F;
type Args = (T,);
impl FnOnce<Args> for F {
type Output = T;
extern "rust-call" fn call_once(self, (x,): Args) -> Self::Output |
}
impl FnMut<Args> for F {
extern "rust-call" fn call_mut(&mut self, (x,): Args) -> Self::Output {
x + 2
}
}
#[test]
fn call_once_test1() {
let mut f: F = F;
let f_ptr: &mut F = &mut f;
let x: T = 68;
let result: T = f_ptr.call_once((x,));
assert_eq!(result, x + 2);
assert_eq!(resul... | {
x + 1
} | identifier_body |
lzw.rs | //! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm
// Note: This implementation borrows heavily from the work of Julius Pettersson
// See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations
// and a C++ implementatation
use std::io;
use std::io::Read;
use... | c > entry.c {
if let Some(k) = entry.right {
j = k
} else {
entry.right = Some(table_size);
break;
}
} else {
return Som... | if let Some(k) = entry.left {
j = k
} else {
entry.left = Some(table_size);
break;
}
} else if | conditional_block |
lzw.rs | //! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm
// Note: This implementation borrows heavily from the work of Julius Pettersson
// See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations
// and a C++ implementatation
use std::io;
use std::io::Read;
use... | > Code {
1u16 << self.min_size
}
#[inline(always)]
fn end_code(&self) -> Code {
self.clear_code() + 1
}
// Searches for a new prefix
fn search_and_insert(&mut self, i: Option<Code>, c: u8) -> Option<Code> {
if let Some(i) = i.map(|v| v as usize) {
let table_... | e(&self) - | identifier_name |
lzw.rs | //! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm
// Note: This implementation borrows heavily from the work of Julius Pettersson
// See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations
// and a C++ implementatation
use std::io;
use std::io::Read;
use... | search_initials(&self, i: Code) -> Code {
self.table[i as usize].c as Code
}
}
/// Convenience function that reads and compresses all bytes from `R`.
pub fn encode<R, W>(r: R, mut w: W, min_code_size: u8) -> io::Result<()>
where
R: Read,
W: BitWriter,
{
let mut dict = EncodingDict::new(min_code... | self.table.len()
}
fn | identifier_body |
lzw.rs | //! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm
// Note: This implementation borrows heavily from the work of Julius Pettersson
// See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations
// and a C++ implementatation
use std::io;
use std::io::Read;
use... | self.push_node(Node::new(i as u8));
}
}
#[inline(always)]
fn push_node(&mut self, node: Node) {
self.table.push(node)
}
#[inline(always)]
fn clear_code(&self) -> Code {
1u16 << self.min_size
}
#[inline(always)]
fn end_code(&self) -> Code {
... | }
fn reset(&mut self) {
self.table.clear();
for i in 0..(1u16 << self.min_size as usize) { | random_line_split |
unittest_strings.py | # Copyright (c) 2015-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2018 Lucas Cimon <lucas.cimon@gmail.com>
# Copyright (c) 2018 Yury Gribov <tetra2005@gmail.com>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyrig... | ssert strings.str_eval(token) == "X"
| conditional_block | |
unittest_strings.py | # Copyright (c) 2015-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2018 Lucas Cimon <lucas.cimon@gmail.com>
# Copyright (c) 2018 Yury Gribov <tetra2005@gmail.com>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyrig... | or token in TEST_TOKENS:
assert strings.str_eval(token) == "X"
| identifier_body | |
unittest_strings.py | # Copyright (c) 2015-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2018 Lucas Cimon <lucas.cimon@gmail.com>
# Copyright (c) 2018 Yury Gribov <tetra2005@gmail.com>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyrig... | ) -> None:
for token in TEST_TOKENS:
assert strings.str_eval(token) == "X"
| est_str_eval( | identifier_name |
unittest_strings.py | # Copyright (c) 2015-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2018 Lucas Cimon <lucas.cimon@gmail.com>
# Copyright (c) 2018 Yury Gribov <tetra2005@gmail.com>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyrig... | # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
from pylint.checkers import strings
TEST_TOKENS = (
'"X"',
"'X'",
"'''X'''",
'"""X"""',
'r"X"',
"R'X'",
'u"X"',
"F'X'",
'f"X"',
"F'X'",
'fr"X"',
'Fr"X"',
'fR"X"',
'FR"X"',
'rf"X"',
'rF"X"'... | # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html | random_line_split |
angular-locale_en-tv_1.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function | (n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
... | getVF | identifier_name |
angular-locale_en-tv_1.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pre... | "longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
... | "WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y", | random_line_split |
angular-locale_en-tv_1.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) |
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
... | {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
} | identifier_body |
angular-locale_en-tv_1.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pre... |
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday... | {
v = Math.min(getDecimals(n), 3);
} | conditional_block |
htmldivelement.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/. */
use dom::bindings::codegen::Bindings::HTMLDivElementBinding::{self, HTMLDivElementMethods};
use dom::bindings::js:... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLDivElement {
HTMLDivElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMSt... | new_inherited | identifier_name |
htmldivelement.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/. */
use dom::bindings::codegen::Bindings::HTMLDivElementBinding::{self, HTMLDivElementMethods};
use dom::bindings::js:... | // https://html.spec.whatwg.org/multipage/#dom-div-align
make_setter!(SetAlign, "align");
} | random_line_split | |
preferences.component.ts | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
setUserData(data){
this.userData = data
this.defaultEmail = data["Email"]
}
onSubmit(){
this.afService.user.subscribe((user)=>
{
user.getIdToken().then(token=>{
var formData = new FormData()
formData.append("email",this.defaultEmail)
var result = fetch('/api/users/... | {
this.userEmitter.getData().subscribe(data => this.setUserData(data));
} | identifier_body |
preferences.component.ts | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
});
});
});
}
} | {
this.snackBar.open("Updated Preferences", "close", {
duration: 2000,
});
this.userData["Email"] = this.defaultEmail
this.userEmitter.saveData(this.userData)
this.prefForm.form.markAsPristine()
} | conditional_block |
preferences.component.ts | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | @Component({
selector: 'app-preferences',
templateUrl: './preferences.component.html',
styleUrls: ['./preferences.component.scss']
})
export class PreferencesComponent implements OnInit {
defaultEmail: string
userData: JSON
@ViewChild('preferenceForm') prefForm: NgForm;
constructor(
public snack... | import {NgForm} from '@angular/forms'
import {MdSnackBar,MdInputModule} from '@angular/material';
import { Observable } from 'rxjs/Observable';
import {UserDataService} from '../misc/services'
| random_line_split |
preferences.component.ts | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | (
public snackBar: MdSnackBar,
private afService: AF,
private userEmitter:UserDataService,
){}
ngOnInit() {
this.userEmitter.getData().subscribe(data => this.setUserData(data));
}
setUserData(data){
this.userData = data
this.defaultEmail = data["Email"]
}
onSubmit(){
... | constructor | identifier_name |
ShapefileIndexReader.py | """
This script exposes a class used to read the Shapefile Index format
used in conjunction with a shapefile. The Index file gives the record
number and content length for every record stored in the main shapefile.
This is useful if you need to extract specific features from a shapefile
without reading the entire file.... |
def __init__(self, path=None):
if path and os.path.exists(path) and os.path.splitext(path)[1] == '.shx':
self.Path = path
else:
raise FileNotFoundError | with open(self.Path, 'rb') as shpindex:
self.__bytes_to_index_records(shpindex.read()) | identifier_body |
ShapefileIndexReader.py | """
This script exposes a class used to read the Shapefile Index format
used in conjunction with a shapefile. The Index file gives the record
number and content length for every record stored in the main shapefile.
This is useful if you need to extract specific features from a shapefile |
How to use:
from ShapefileIndexReader import ShapefileIndex
shx = ShapefileIndex(Path/To/index.shx)
shx.read()
The 'shx' object will expose three properties
1) Path - the path given to the shapefile, if it exists
2) Offsets - an array of byte offsets for each record in the main shapefile
3) Le... | without reading the entire file. | random_line_split |
ShapefileIndexReader.py | """
This script exposes a class used to read the Shapefile Index format
used in conjunction with a shapefile. The Index file gives the record
number and content length for every record stored in the main shapefile.
This is useful if you need to extract specific features from a shapefile
without reading the entire file.... | (self,file_bytes):
file_length = len(file_bytes)
num_records = int((file_length - 100) / 8)
for record_counter in range(0,num_records):
byte_position = 100 + (record_counter * 8)
offset = int.from_bytes(file_bytes[byte_position:byte_position+4], byteorder='big')
... | __bytes_to_index_records | identifier_name |
ShapefileIndexReader.py | """
This script exposes a class used to read the Shapefile Index format
used in conjunction with a shapefile. The Index file gives the record
number and content length for every record stored in the main shapefile.
This is useful if you need to extract specific features from a shapefile
without reading the entire file.... |
def read(self):
with open(self.Path, 'rb') as shpindex:
self.__bytes_to_index_records(shpindex.read())
def __init__(self, path=None):
if path and os.path.exists(path) and os.path.splitext(path)[1] == '.shx':
self.Path = path
else:
raise FileNotFound... | byte_position = 100 + (record_counter * 8)
offset = int.from_bytes(file_bytes[byte_position:byte_position+4], byteorder='big')
length = int.from_bytes(file_bytes[byte_position+4:byte_position+8], byteorder='big')
self.Records.append([offset,length]) | conditional_block |
problem_0005.rs | extern crate projecteuler;
use projecteuler::primes::*;
use std::collections::HashMap;
fn main() | {
let mut result_factorized = HashMap::<u64,u64>::new();
let mut primes = Primes::new();
for i in 1..21{//TODO: Make this a LCM function.
let factorization = primes.factorize(i);
for factor in factorization{
let current_factor = match result_factorized.get(&factor.0){
Some(i) => {*i},
... | identifier_body | |
problem_0005.rs | extern crate projecteuler;
use projecteuler::primes::*;
use std::collections::HashMap;
fn | (){
let mut result_factorized = HashMap::<u64,u64>::new();
let mut primes = Primes::new();
for i in 1..21{//TODO: Make this a LCM function.
let factorization = primes.factorize(i);
for factor in factorization{
let current_factor = match result_factorized.get(&factor.0){
Some(i) => {*i},
... | main | identifier_name |
problem_0005.rs | extern crate projecteuler;
use projecteuler::primes::*;
use std::collections::HashMap;
fn main(){
let mut result_factorized = HashMap::<u64,u64>::new(); | let mut primes = Primes::new();
for i in 1..21{//TODO: Make this a LCM function.
let factorization = primes.factorize(i);
for factor in factorization{
let current_factor = match result_factorized.get(&factor.0){
Some(i) => {*i},
_ => {0}
};
if current_factor < factor.1{
... | random_line_split | |
problem_0005.rs | extern crate projecteuler;
use projecteuler::primes::*;
use std::collections::HashMap;
fn main(){
let mut result_factorized = HashMap::<u64,u64>::new();
let mut primes = Primes::new();
for i in 1..21{//TODO: Make this a LCM function.
let factorization = primes.factorize(i);
for factor in factorization{
... |
};
if current_factor < factor.1{
result_factorized.insert(factor.0, factor.1);
}
}
}
let result = {
let mut result = 1;
for x in result_factorized{
result *= x.0.pow(x.1 as u32);//gather all the prime exponents together
}
result
};
println!("{}", result);
... | {0} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.