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 |
|---|---|---|---|---|
handler.js | const config = require('../../../server/config'),
Manager = require('./manager'),
manager = new Manager();
// Responsible for handling requests for sitemap files
module.exports = function handler(siteApp) {
const verifyResourceType = function verifyResourceType(req, res, next) {
if (!Object.prototy... |
next();
};
siteApp.get('/sitemap.xml', function sitemapXML(req, res) {
res.set({
'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'),
'Content-Type': 'text/xml'
});
res.send(manager.getIndexXml());
});
siteApp.get('/site... | {
return res.sendStatus(404);
} | conditional_block |
handler.js | const config = require('../../../server/config'),
Manager = require('./manager'),
manager = new Manager();
// Responsible for handling requests for sitemap files
module.exports = function handler(siteApp) {
const verifyResourceType = function verifyResourceType(req, res, next) {
if (!Object.prototy... | next();
};
siteApp.get('/sitemap.xml', function sitemapXML(req, res) {
res.set({
'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'),
'Content-Type': 'text/xml'
});
res.send(manager.getIndexXml());
});
siteApp.get('/sitema... | }
| random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# Sphinx RTD theme demo documentation build configuration file, created by
# sphinx-quickstart on Sun Nov 3 11:56:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated... |
# General information about the project.
project = u'Sphinx RTD theme demo'
copyright = u'2013, Dave Snider'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version ... | master_doc = 'index' | random_line_split |
std-uncopyable-atomics.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let x = INIT_ATOMIC_BOOL;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_INT;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_UINT;
let x = *&x; //~ ERROR: cannot move out of dereference
let x: AtomicPtr<uint> = AtomicPtr::new(ptr::mut_n... | fn main() {
let x = INIT_ATOMIC_FLAG;
let x = *&x; //~ ERROR: cannot move out of dereference | random_line_split |
std-uncopyable-atomics.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = INIT_ATOMIC_FLAG;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_BOOL;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_INT;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_UINT;
let x = *&x; //... | main | identifier_name |
std-uncopyable-atomics.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = INIT_ATOMIC_FLAG;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_BOOL;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_INT;
let x = *&x; //~ ERROR: cannot move out of dereference
let x = INIT_ATOMIC_UINT;
let x = *&x; //~ E... | identifier_body | |
tmp-tests.ts | import tmp = require('tmp');
tmp.file((err, path, fd, cleanupCallback) => {
if (err) throw err;
console.log("File: ", path);
console.log("Filedescriptor: ", fd);
cleanupCallback();
});
tmp.dir((err, path, cleanupCallback) => {
if (err) throw err;
console.log("Dir: ", path);
cleanupCallback();
});
| if (err) throw err;
console.log("Created temporary filename: ", path);
});
tmp.file({ mode: 644, prefix: 'prefix-', postfix: '.txt' }, (err, path, fd) => {
if (err) throw err;
console.log("File: ", path);
console.log("Filedescriptor: ", fd);
});
tmp.dir({ mode: 750, prefix: 'myTmpDir_' }, (err, path) => {
if ... | tmp.tmpName((err, path) => { | random_line_split |
sms_send_verification_code.rs | extern crate open189;
fn main() {
let args: Vec<_> = std::env::args().collect();
if args.len() < 6 {
println!("usage: {} <app id> <secret> <access token> <phone> <code> <expire time>",
args[0]);
std::process::exit(1);
}
let app_id = &args[1];
let secret = &args[2]... | ;
let app = open189::Open189App::new(app_id, secret);
let sms_token = app.sms_get_token(access_token);
println!("sms token = {:?}", sms_token);
let sms_token = sms_token.unwrap();
let config = open189::SmsCodeConfig::prepared(phone, code, expire_time);
let result = app.sms_send_verification_c... | {
Some(args[6].parse().unwrap())
} | conditional_block |
sms_send_verification_code.rs | extern crate open189;
fn main() {
let args: Vec<_> = std::env::args().collect();
if args.len() < 6 {
println!("usage: {} <app id> <secret> <access token> <phone> <code> <expire time>",
args[0]);
std::process::exit(1);
}
let app_id = &args[1];
let secret = &args[2]... | } | let config = open189::SmsCodeConfig::prepared(phone, code, expire_time);
let result = app.sms_send_verification_code(access_token, &sms_token, config);
println!("send result = {:?}", result); | random_line_split |
sms_send_verification_code.rs | extern crate open189;
fn main() | {
let args: Vec<_> = std::env::args().collect();
if args.len() < 6 {
println!("usage: {} <app id> <secret> <access token> <phone> <code> <expire time>",
args[0]);
std::process::exit(1);
}
let app_id = &args[1];
let secret = &args[2];
let access_token = &args[3];... | identifier_body | |
sms_send_verification_code.rs | extern crate open189;
fn | () {
let args: Vec<_> = std::env::args().collect();
if args.len() < 6 {
println!("usage: {} <app id> <secret> <access token> <phone> <code> <expire time>",
args[0]);
std::process::exit(1);
}
let app_id = &args[1];
let secret = &args[2];
let access_token = &args[... | main | identifier_name |
testqueue.js | // Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless requ... |
return this.events_.shift();
};
| {
throw Error('Handler is empty: ' + opt_comment);
} | conditional_block |
testqueue.js | // Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless requ... | };
/**
* Adds a new event onto the queue.
* @param {Object} event The event to queue.
*/
goog.testing.TestQueue.prototype.enqueue = function(event) {
this.events_.push(event);
};
/**
* Returns whether the queue is empty.
* @return {boolean} Whether the queue is empty.
*/
goog.testing.TestQueue.prototype.isEm... | random_line_split | |
WavesAPI.spec.ts | import { expect } from './getChai';
import * as WavesAPI from '../dist/waves-api';
let requiredConfigValues;
let allConfigValues;
describe('WavesAPI', () => {
beforeEach(() => {
requiredConfigValues = {
networkByte: 1,
nodeAddress: '1',
matcherAddress: '1',
... |
it('should throw when created without required fields in config', () => {
expect(() => WavesAPI.create({})).to.throw();
expect(() => WavesAPI.create({ networkByte: 1, nodeAddress: '1' })).to.throw();
expect(() => WavesAPI.create({ networkByte: 1, matcherAddress: '1' })).to.throw();
... | requestLimit: 1
};
}); | random_line_split |
mk.js | /*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'mk', {
copy: 'Копирај (Copy)',
copyError: 'Опциите за безбедност на вашиот прелистувач не дозволуваат уредувачот а... | paste: 'Залепи (Paste)',
pasteNotification: 'Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.', // MISSING
pasteArea: 'Простор за залепување',
pasteMsg: 'Paste your content inside the area below and press OK.' // MISSING
} ); | random_line_split | |
pl-pl.py | # coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyra\xc5\xbceniem postaci "pole1=\'nowawarto\xc5\x9b\xc4\x87\'". Nie mo\xc5\xbcesz uaktualni\xc4\x87 lub usun\xc4\x85\xc4\x87 wynik\xc3\xb3w z JOIN:',
'%Y-%m... | 'Edit Profile': 'Edit Profile',
'Edit This App': 'Edit This App',
'Edit current record': 'Edytuj aktualny rekord',
'Hello World': 'Witaj \xc5\x9awiecie',
'Import/Export': 'Importuj/eksportuj',
'Index': 'Index',
'Internal State': 'Stan wewn\xc4\x99trzny',
'Invalid Query': 'B\xc5\x82\xc4\x99dne zapytanie',
'Layout': 'Lay... | 'Current session': 'Aktualna sesja',
'DB Model': 'DB Model',
'Database': 'Database',
'Delete:': 'Usu\xc5\x84:',
'Edit': 'Edit', | random_line_split |
MultipartParser.spec.ts | /* tslint:disable:no-unused-expression */
import * as Chai from "chai";
import { SinonSpy, spy } from "sinon";
import App from "./../../../src/lib/App";
import MultipartParser from "./../../../src/lib/http/bodyParsers/MultipartParser";
import HttpRequest from "./../../../src/lib/http/HttpRequest";
import HttpUploadedFi... | beforeEach(() => {
event = Object.assign({}, mainEvent);
event.headers = Object.assign({}, mainEvent.headers);
next = spy();
});
it("should call 'next' WITHOUT an error if the body can not be parsed and header contentType is undefined.", () => {
event.body = "errorBody";
event.headers["Conte... | random_line_split | |
F3D_syn.py | #!/usr/bin/env python
import numpy as np
import os,sys
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import argparse
ap=argparse.ArgumentParser()
ap.add_argument('-vis') # 1 plot cropped point cloud
ap.add_argument('-refine') # 1 refine mesh
ap.add_argument('-clean') # 1 remove tmp... | #omg=(np.random.rand(wl.shape[0])-.5)*np.pi
L=dat_vert[1,:].max()-dat_vert[1,:].min()
zmax=z.max(); zmin=z.min()
for i in range(len(wl)):
phs=dat_vert[:,1]/wl[i]*np.pi+omg[i]
dat_vert[:,0]=dat_vert[:,0]+amp[i]*np.cos(phs)*(e*zmax-dat_vert[:,2])/(e*zmax-zmin)*np.exp(r*abs(phs)/np.pi)
dat_vert[:,0]=dat_vert[:,0]... | # weak
wl=np.linspace(.12,.18,num=8); amp=.03125*np.sqrt(wl)
e=1.025; r=-.2
dip=70.; zcnt=-.35
omg=[ 0.82976173, 0.89624834, 0.03829284, -0.50016345, -1.06606012, 1.40505898, -1.24256034, 1.28623393] | random_line_split |
F3D_syn.py | #!/usr/bin/env python
import numpy as np
import os,sys
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import argparse
ap=argparse.ArgumentParser()
ap.add_argument('-vis') # 1 plot cropped point cloud
ap.add_argument('-refine') # 1 refine mesh
ap.add_argument('-clean') # 1 remove tmp... |
slope1=10.;slope2=-10.
trunc1=.1;trunc2=.6
hup=0.;hlw=.08
#dat_vert=flt_patch(dat_vert,slope1,slope2,trunc1,trunc2,hlw,hup)
print omg
fout='F3D_syn.xyz'
f=open(fout,'w+')
np.savetxt(f,dat_vert,delimiter=' ', fmt='%.6f '*3)
f.close()
from subprocess import call
fin=fout
fout=fout.rsplit('.')[0]+'.stl'
mxl='xyz2stl.mlx... | b1=-slope1*trunc1-.7
b2=-slope2*trunc2-.7
in_id=np.where(np.logical_and(dat_vert[:,2]-slope1*dat_vert[:,1]<b1, dat_vert[:,2]-slope2*dat_vert[:,1]<b2))[0]
out_id=np.setdiff1d(np.array(range(len(dat_vert)),dtype=np.int32),in_id)
x_shift=dat_vert[in_id,0]
# ridge patch
k=0
zup=dat_vert[:,2].ma... | identifier_body |
F3D_syn.py | #!/usr/bin/env python
import numpy as np
import os,sys
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import argparse
ap=argparse.ArgumentParser()
ap.add_argument('-vis') # 1 plot cropped point cloud
ap.add_argument('-refine') # 1 refine mesh
ap.add_argument('-clean') # 1 remove tmp... |
if 'surface 46 94 95 97 size' in line.lower():
line='surface 46 94 95 97 size %0.6f' %(2*hf)
if 'volume all size' in line.lower():
line='volume all size %0.6f' %(2*hm)
txt_jou_tmp.write(line+'\n')
if 'mesh volume all' in line.lower() and refine==1:
txt_jou_tmp.write('refine vol... | line='export mesh "'+fout+'" dimension 3 overwrite' | conditional_block |
F3D_syn.py | #!/usr/bin/env python
import numpy as np
import os,sys
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import argparse
ap=argparse.ArgumentParser()
ap.add_argument('-vis') # 1 plot cropped point cloud
ap.add_argument('-refine') # 1 refine mesh
ap.add_argument('-clean') # 1 remove tmp... | (dat_vert,slope1,slope2,trunc1,trunc2,hlw,hup):
b1=-slope1*trunc1-.7
b2=-slope2*trunc2-.7
in_id=np.where(np.logical_and(dat_vert[:,2]-slope1*dat_vert[:,1]<b1, dat_vert[:,2]-slope2*dat_vert[:,1]<b2))[0]
out_id=np.setdiff1d(np.array(range(len(dat_vert)),dtype=np.int32),in_id)
x_shift=dat_vert[in_id,0... | flt_patch | identifier_name |
render.ts | import jTool from '@jTool';
import {getRowData, getTableData} from '@common/cache';
import { getAllTh, getDiv, getEmpty, getTbody, getThead, getVisibleTh, setAreVisible, updateVisibleLast } from '@common/base';
import { DISABLE_CUSTOMIZE, EMPTY_DATA_CLASS_NAME, EMPTY_TPL_KEY, ODD, PX, ROW_CLASS_NAME, TH_NAME, TR_CACHE_... | CHE_KEY}]`) as HTMLTableRowElement;
if (firstCacheTr && !isUndefined(row)) {
const firstNum = getRowData(_, firstCacheTr, true)[ROW_INDEX_KEY];
const nowNum = row[ROW_INDEX_KEY];
if (nowNum < firstNum) {
prependFragment.appendChild(tr);
} else {
df.appendChild(tr);
}
} else ... | firstCacheTr = df.querySelector(`[${TR_CA | conditional_block |
render.ts | import jTool from '@jTool';
import {getRowData, getTableData} from '@common/cache';
import { getAllTh, getDiv, getEmpty, getTbody, getThead, getVisibleTh, setAreVisible, updateVisibleLast } from '@common/base';
import { DISABLE_CUSTOMIZE, EMPTY_DATA_CLASS_NAME, EMPTY_TPL_KEY, ODD, PX, ROW_CLASS_NAME, TH_NAME, TR_CACHE_... | each(df.children, (item: HTMLTableRowElement, index: number) => {
// DOM中不存在开始行与结束行的tr: 清空所有tr
if (!isNumber(firstLineIndex) && !isNumber(lastLineIndex)) {
list.push(item);
return;
}
// DOM中存在开始行的tr: 清空小于开始的tr
if (isNumber(firstLineIndex) && index < firstLineIndex) {
list.push(ite... | random_line_split | |
FileTypes.py | # Copyright (C) 2008 LibreSoft
#
# 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 program is distributed in the ... |
cursor.close()
def __get_files_for_repository(self, repo_id, cursor):
query = "SELECT ft.file_id from file_types ft, files f " + \
"WHERE f.id = ft.file_id and f.repository_id = ?"
cursor.execute(statement(query, self.db.place_holder), (repo_id,))
file... | cursor.close()
raise | conditional_block |
FileTypes.py | # Copyright (C) 2008 LibreSoft
#
# 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 program is distributed in the ... | (Extension):
def __init__(self):
self.db = None
def __create_table(self, cnn):
cursor = cnn.cursor()
if isinstance(self.db, SqliteDatabase):
import sqlite3.dbapi2
try:
cursor.execute("CREATE TABLE file_types (" +
... | FileTypes | identifier_name |
FileTypes.py | # Copyright (C) 2008 LibreSoft
#
# 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 program is distributed in the ... |
register_extension("FileTypes", FileTypes)
| def __init__(self):
self.db = None
def __create_table(self, cnn):
cursor = cnn.cursor()
if isinstance(self.db, SqliteDatabase):
import sqlite3.dbapi2
try:
cursor.execute("CREATE TABLE file_types (" +
"... | identifier_body |
FileTypes.py | # Copyright (C) 2008 LibreSoft
#
# 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 program is distributed in the ... |
cursor = cnn.cursor()
cursor.execute(statement("SELECT id from repositories where uri = ?",
db.place_holder), (repo_uri,))
repo_id = cursor.fetchone()[0]
files = []
try:
self.__create_table(cnn)
except Table... | cnn = self.db.connect() | random_line_split |
migrate.ts | import { json5Require, makeFile } from './file-util'
import * as fs from 'fs'
import * as path from 'path'
async function migrate(): Promise<void> {
const filePath: string = path.resolve(process.cwd(), 'jmockr.config.json')
if (!fs.existsSync(filePath)) {
console.error(`Can't find config file [${filePa... |
const retCode200URLs: string = fs.readFileSync(originDataPath.url200, { encoding: 'utf8' })
const newUrl200Path: string = path.resolve(newRetCode200Folder, `url.json5`)
await makeFile({
mode: 'w',
path: newUrl200Path,
content: retCode200URLs,
})
... | {
fs.mkdirSync(newRetCode200Folder)
} | conditional_block |
migrate.ts | import { json5Require, makeFile } from './file-util'
import * as fs from 'fs'
import * as path from 'path'
async function migrate(): Promise<void> |
export {
migrate,
}
| {
const filePath: string = path.resolve(process.cwd(), 'jmockr.config.json')
if (!fs.existsSync(filePath)) {
console.error(`Can't find config file [${filePath}]`)
throw new Error(`Can't find config file [${filePath}]`)
}
try {
const json: any = json5Require(filePath)
json... | identifier_body |
migrate.ts | import { json5Require, makeFile } from './file-util'
import * as fs from 'fs'
import * as path from 'path'
async function migrate(): Promise<void> {
const filePath: string = path.resolve(process.cwd(), 'jmockr.config.json')
if (!fs.existsSync(filePath)) {
console.error(`Can't find config file [${filePa... | })
json.dataPath = {
urlMap: originDataPath.urlMap,
commonSync: originDataPath.commonFtl,
commonAsync: commonAsyncDataPath,
pageSync: originDataPath.pageFtl,
pageAsync: originDataPath.ajax,
}
json.authConfig.casDomain = ''
... | mode: 'w',
path: newURL200DataPath,
content: JSON.stringify({ retCode: 200 }, null, 4), | random_line_split |
migrate.ts | import { json5Require, makeFile } from './file-util'
import * as fs from 'fs'
import * as path from 'path'
async function | (): Promise<void> {
const filePath: string = path.resolve(process.cwd(), 'jmockr.config.json')
if (!fs.existsSync(filePath)) {
console.error(`Can't find config file [${filePath}]`)
throw new Error(`Can't find config file [${filePath}]`)
}
try {
const json: any = json5Require(file... | migrate | identifier_name |
renderers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template import RequestContext
from rest_framework import renderers
class CMSPageRenderer(renderers.TemplateHTMLRenderer):
"""
Modified TemplateHTMLRenderer, which is able to render CMS pages containing the templatetag
`{% render_... | (self, data, accepted_media_type=None, context=None):
request = context['request']
response = context['response']
if response.exception:
template = self.get_exception_template(response)
else:
view = context['view']
template_names = self.get_template_n... | render | identifier_name |
renderers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template import RequestContext
from rest_framework import renderers
class CMSPageRenderer(renderers.TemplateHTMLRenderer):
"""
Modified TemplateHTMLRenderer, which is able to render CMS pages containing the templatetag
`{% render_... |
else:
view = context['view']
template_names = self.get_template_names(response, view)
template = self.resolve_template(template_names)
context['paginator'] = view.paginator
# set edit_mode, so that otherwise invisible placeholders can be edited inline... | template = self.get_exception_template(response) | conditional_block |
renderers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template import RequestContext |
class CMSPageRenderer(renderers.TemplateHTMLRenderer):
"""
Modified TemplateHTMLRenderer, which is able to render CMS pages containing the templatetag
`{% render_placeholder ... %}`, and which accept ordinary Python objects in their rendering
context.
The serialized data object, as available to oth... | from rest_framework import renderers
| random_line_split |
renderers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template import RequestContext
from rest_framework import renderers
class CMSPageRenderer(renderers.TemplateHTMLRenderer):
"""
Modified TemplateHTMLRenderer, which is able to render CMS pages containing the templatetag
`{% render_... | request = context['request']
response = context['response']
if response.exception:
template = self.get_exception_template(response)
else:
view = context['view']
template_names = self.get_template_names(response, view)
template = self.resolve_templ... | identifier_body | |
hr_language.py | # -*- encoding: utf-8 -*-
###############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it un... | 'speak': fields.boolean('Speak'),
}
_defaults = {
'read': True,
'write': True,
'speak': True,
}
class hr_employee(orm.Model):
_inherit = 'hr.employee'
_columns = {
'language_ids': fields.one2many('hr.language', 'employee_id', 'Languages'),
}
# vim:expan... | 'write': fields.boolean('Write'), | random_line_split |
hr_language.py | # -*- encoding: utf-8 -*-
###############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it un... |
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| _inherit = 'hr.employee'
_columns = {
'language_ids': fields.one2many('hr.language', 'employee_id', 'Languages'),
} | identifier_body |
hr_language.py | # -*- encoding: utf-8 -*-
###############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it un... | (orm.Model):
_inherit = 'hr.employee'
_columns = {
'language_ids': fields.one2many('hr.language', 'employee_id', 'Languages'),
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| hr_employee | identifier_name |
livingsocial_spider.py | #! -*- coding: utf-8 -*-
"""
Web Scraper Project
Scrape data from a regularly updated website livingsocial.com and
save to a database (postgres).
Scrapy spider part - it actually performs scraping.
"""
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.loader impo... | (BaseSpider):
"""
Spider for regularly updated livingsocial.com site, San Francisco page
"""
name = "livingsocial"
allowed_domains = ["livingsocial.com"]
start_urls = ["https://www.livingsocial.com/cities/15-san-francisco"]
deals_list_xpath = '//li[@dealid]'
item_fields = {
'tit... | LivingSocialSpider | identifier_name |
livingsocial_spider.py | #! -*- coding: utf-8 -*-
"""
Web Scraper Project
Scrape data from a regularly updated website livingsocial.com and
save to a database (postgres).
Scrapy spider part - it actually performs scraping.
"""
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.loader impo... |
# iterate over deals
for deal in selector.xpath(self.deals_list_xpath):
loader = XPathItemLoader(LivingSocialDeal(), selector=deal)
# define processors
loader.default_input_processor = MapCompose(unicode.strip)
loader.default_output_processor = Join()
... | random_line_split | |
livingsocial_spider.py | #! -*- coding: utf-8 -*-
"""
Web Scraper Project
Scrape data from a regularly updated website livingsocial.com and
save to a database (postgres).
Scrapy spider part - it actually performs scraping.
"""
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.loader impo... |
yield loader.load_item()
| loader.add_xpath(field, xpath) | conditional_block |
livingsocial_spider.py | #! -*- coding: utf-8 -*-
"""
Web Scraper Project
Scrape data from a regularly updated website livingsocial.com and
save to a database (postgres).
Scrapy spider part - it actually performs scraping.
"""
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.loader impo... | """
Spider for regularly updated livingsocial.com site, San Francisco page
"""
name = "livingsocial"
allowed_domains = ["livingsocial.com"]
start_urls = ["https://www.livingsocial.com/cities/15-san-francisco"]
deals_list_xpath = '//li[@dealid]'
item_fields = {
'title': './/span[@ite... | identifier_body | |
search.py | # 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 under the Li... | name = Text()
normalized_name = Text(analyzer=NameAnalyzer)
version = Keyword(multi=True)
latest_version = Keyword()
summary = Text(analyzer="snowball")
description = Text(analyzer="snowball")
author = Text()
author_email = Text(analyzer=EmailAnalyzer)
maintainer = Text()
maintainer_... | identifier_body | |
search.py | # 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 under the Li... | filter=["lowercase", "stop", "snowball"],
)
NameAnalyzer = analyzer(
"normalized_name",
tokenizer="lowercase",
filter=["lowercase", "word_delimiter"],
)
@doc_type
class Project(Document):
name = Text()
normalized_name = Text(analyzer=NameAnalyzer)
version = Keyword(multi=True)
latest... | tokenizer="uax_url_email", | random_line_split |
search.py | # 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 under the Li... | :
# make sure this class can match any index so it will always be used to
# deserialize data coming from elasticsearch.
name = "*"
| Index | identifier_name |
primitives.rs | use super::defines::*;
//TODO: convert to macro with usage
//format!(indent!(5, "format:{}"), 6)
pub fn tabs(num: usize) -> String {
format!("{:1$}", "", TAB_SIZE * num)
}
pub fn format_block(prefix: &str, suffix: &str, body: &[String]) -> Vec<String> {
let mut v = Vec::new();
if !prefix.is_empty() {
... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tabs() {
assert_eq!(tabs(0), "");
assert_eq!(tabs(1), TAB);
assert_eq!(tabs(2), format!("{0}{0}", TAB));
}
#[test]
fn test_format_block() {
let body = vec!["0 => 1,".into(), "1 => 0,".into()];
let ... | {
body.iter().map(|s| format!("//{}", s)).collect()
} | identifier_body |
primitives.rs | use super::defines::*;
//TODO: convert to macro with usage
//format!(indent!(5, "format:{}"), 6)
pub fn tabs(num: usize) -> String {
format!("{:1$}", "", TAB_SIZE * num)
}
pub fn format_block(prefix: &str, suffix: &str, body: &[String]) -> Vec<String> {
let mut v = Vec::new();
if !prefix.is_empty() {
... |
}
pub fn comment_block(body: &[String]) -> Vec<String> {
body.iter().map(|s| format!("//{}", s)).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tabs() {
assert_eq!(tabs(0), "");
assert_eq!(tabs(1), TAB);
assert_eq!(tabs(2), format!("{0}{0}", TAB));
}
... | {
let s = format_block_one_line(prefix, suffix, body, outer_separator, inner_separator);
vec![s]
} | conditional_block |
primitives.rs | use super::defines::*;
//TODO: convert to macro with usage
//format!(indent!(5, "format:{}"), 6)
pub fn tabs(num: usize) -> String {
format!("{:1$}", "", TAB_SIZE * num)
}
pub fn format_block(prefix: &str, suffix: &str, body: &[String]) -> Vec<String> {
let mut v = Vec::new();
if !prefix.is_empty() {
... | v.push(s);
}
if !suffix.is_empty() {
v.push(suffix.into());
}
v
}
pub fn format_block_one_line(
prefix: &str,
suffix: &str,
body: &[String],
outer_separator: &str,
inner_separator: &str,
) -> String {
let mut s = format!("{}{}", prefix, outer_separator);
let ... | for s in body.iter() {
let s = format!("{}{}", TAB, s); | random_line_split |
primitives.rs | use super::defines::*;
//TODO: convert to macro with usage
//format!(indent!(5, "format:{}"), 6)
pub fn tabs(num: usize) -> String {
format!("{:1$}", "", TAB_SIZE * num)
}
pub fn format_block(prefix: &str, suffix: &str, body: &[String]) -> Vec<String> {
let mut v = Vec::new();
if !prefix.is_empty() {
... | () {
let body = vec!["0 => 1,".into(), "1 => 0,".into()];
let actual = format_block("match a {", "}", &body);
let expected = ["match a {", " 0 => 1,", " 1 => 0,", "}"];
assert_eq!(actual, expected);
}
#[test]
fn test_format_block_smart_width_one_line_outer_separator() ... | test_format_block | identifier_name |
task.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | stack_start: stack_top,
stack_end: stack_base - stack_size,
status: Runnable,
}
}
pub fn load(&self) {
sched::set_task_stack_pointer(self.stack_start);
stack::set_stack_limit(self.stack_end);
}
pub fn save(&mut self) {
self.stack_start = sched::get_task_stack_pointer();
}
... | random_line_split | |
task.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | (&mut self) {
self.stack_end = 0;
}
}
#[inline(always)]
pub unsafe fn task_scheduler() {
stack::set_stack_limit(stack::stack_base() - ReservedPivilegedStackSize);
Tasks.current_task().save();
Tasks.next_task();
Tasks.current_task().load();
}
// TODO(farcaller): this should not actually use stack!
// At ... | invalidate | identifier_name |
task.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
pub fn set(val: u32) {
unsafe { CurrentStackOffset = val };
}
}
/// Bytes to reserve in privileged stack based on stack size at the time of task::setup() call.
static ReservedPivilegedStackSize: u32 = 256;
/// Maximum number of tasks.
static MaxTasksCount: uint = 4;
mod defined_tasks_count {
use core::in... | {
unsafe { CurrentStackOffset }
} | identifier_body |
delegate.ts | import {
Cursor,
Dict,
ElementBuilder,
Environment,
Helper,
Option,
RenderResult,
} from '@glimmer/interfaces';
import { serializeBuilder } from '@glimmer/node';
import { createConstRef, Reference } from '@glimmer/reference';
import { ASTPluginBuilder, PrecompileOptions } from '@glimmer/syntax';
import { ... | (
template: string,
context: Dict<unknown>,
takeSnapshot: () => void,
element: SimpleElement | undefined = undefined
): string {
element = element || this.serverDoc.createElement('div');
let cursor = { element, nextSibling: null };
let { env } = this.serverEnv.runtime;
// Emulate serv... | renderServerSide | identifier_name |
delegate.ts | import {
Cursor,
Dict,
ElementBuilder,
Environment,
Helper,
Option,
RenderResult,
} from '@glimmer/interfaces';
import { serializeBuilder } from '@glimmer/node';
import { createConstRef, Reference } from '@glimmer/reference';
import { ASTPluginBuilder, PrecompileOptions } from '@glimmer/syntax';
import { ... |
renderTemplate(
template: string,
context: Dict<unknown>,
element: SimpleElement,
snapshot: () => void
): RenderResult {
let serialized = this.renderServerSide(template, context, snapshot);
replaceHTML(element, serialized);
qunitFixture().appendChild(element);
return this.renderCl... | {
let env = this.clientEnv.runtime.env;
this.self = null;
// Client-side rehydration
let cursor = { element, nextSibling: null };
let builder = this.getElementBuilder(env, cursor) as DebugRehydrationBuilder;
let result = renderTemplate(
template,
this.clientEnv,
this.getSelf(e... | identifier_body |
delegate.ts | import {
Cursor,
Dict,
ElementBuilder,
Environment,
Helper,
Option,
RenderResult,
} from '@glimmer/interfaces';
import { serializeBuilder } from '@glimmer/node';
import { createConstRef, Reference } from '@glimmer/reference';
import { ASTPluginBuilder, PrecompileOptions } from '@glimmer/syntax';
import { ... |
renderClientSide(template: string, context: Dict<unknown>, element: SimpleElement): RenderResult {
let env = this.clientEnv.runtime.env;
this.self = null;
// Client-side rehydration
let cursor = { element, nextSibling: null };
let builder = this.getElementBuilder(env, cursor) as DebugRehydration... | }
serialize(element: SimpleElement): string {
return toInnerHTML(element);
} | random_line_split |
delegate.ts | import {
Cursor,
Dict,
ElementBuilder,
Environment,
Helper,
Option,
RenderResult,
} from '@glimmer/interfaces';
import { serializeBuilder } from '@glimmer/node';
import { createConstRef, Reference } from '@glimmer/reference';
import { ASTPluginBuilder, PrecompileOptions } from '@glimmer/syntax';
import { ... |
return serializeBuilder(env, cursor);
}
renderServerSide(
template: string,
context: Dict<unknown>,
takeSnapshot: () => void,
element: SimpleElement | undefined = undefined
): string {
element = element || this.serverDoc.createElement('div');
let cursor = { element, nextSibling: nul... | {
return debugRehydration(env, cursor);
} | conditional_block |
sfsetup.js | "use strict";
var async = require('async');
var fs = require('fs');
var util = require('util');
var prompt = require('prompt');
var httpRequest = require('emsoap').subsystems.httpRequest;
var common = require('./common');
var mms = require('./mms');
var mmscmd = require('./mmscmd');
var deploy = require('./deploy');
... | process.exit(1);
}
try {
mappedObjects = JSON.parse(text);
} catch(err) {
console.log('Error parsing JSON in salesforce.json:' + err);
process.exit(1);
}
if(mappedObjects._verbose_logging_) {
verboseLoggingForExternalSystem = mappedObjects._verbose_logging_;
... | text = fs.readFileSync("salesforce.json");
} catch(err) {
console.log('Error reading file salesforce.json:' + err); | random_line_split |
sfsetup.js | "use strict";
var async = require('async');
var fs = require('fs');
var util = require('util');
var prompt = require('prompt');
var httpRequest = require('emsoap').subsystems.httpRequest;
var common = require('./common');
var mms = require('./mms');
var mmscmd = require('./mmscmd');
var deploy = require('./deploy');
... | (cb) {
// munge mappedObjects as required
for (var name in mappedObjects) {
var map = mappedObjects[name];
if (!map.typeBindingProperties) {
map.typeBindingProperties = {};
for (var propName in map) {
switch(propName) {
case "target":
... | afterAuth | identifier_name |
sfsetup.js | "use strict";
var async = require('async');
var fs = require('fs');
var util = require('util');
var prompt = require('prompt');
var httpRequest = require('emsoap').subsystems.httpRequest;
var common = require('./common');
var mms = require('./mms');
var mmscmd = require('./mmscmd');
var deploy = require('./deploy');
... |
});
}
function createExternalSystem(cb) {
if (!session.creds.username)
{
console.log("session.creds.username was null");
process.exit(1);
}
if(verboseLoggingForExternalSystem) console.log('VERBOSE LOGGING IS ON FOR ' + externalSystem);
session.directive({
op: 'I... | {
console.log("Please navigate to " + addr.underline + " with your browser");
prompt.start();
prompt.colors = false;
prompt.message = 'Press Enter when done';
prompt.delimiter = '';
var props = {
properties: {
q:... | conditional_block |
sfsetup.js | "use strict";
var async = require('async');
var fs = require('fs');
var util = require('util');
var prompt = require('prompt');
var httpRequest = require('emsoap').subsystems.httpRequest;
var common = require('./common');
var mms = require('./mms');
var mmscmd = require('./mmscmd');
var deploy = require('./deploy');
... |
exports.deployModel = function deployModel(externalSystemName,mmsSession,cb) {
session = mmsSession;
externalSystem = externalSystemName;
var text;
if(!session.creds.externalCredentials) {
console.log("Profile must include externalCredentials");
process.exit(1);
}
credential... | {
// munge mappedObjects as required
for (var name in mappedObjects) {
var map = mappedObjects[name];
if (!map.typeBindingProperties) {
map.typeBindingProperties = {};
for (var propName in map) {
switch(propName) {
case "target":
... | identifier_body |
extern-fail.rs | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-test linked failure
// error-pattern:explicit failure
// Testing that runtime ... | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split | |
extern-fail.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
for _ in range(0, 10u) {
task::spawn(proc() {
let result = count(5u);
println!("result = %?", result);
fail!();
});
}
} | identifier_body | |
extern-fail.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
fn count(n: uint) -> uint {
unsafe {
task::deschedule();
rustrt::rust_dbg_call(cb, n)
}
}
fn main() {
for _ in range(0, 10u) {
task::spawn(proc() {
let result = count(5u);
println!("result = %?", result);
fail!();
});
}
}
| {
count(data - 1u) + count(data - 1u)
} | conditional_block |
extern-fail.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (n: uint) -> uint {
unsafe {
task::deschedule();
rustrt::rust_dbg_call(cb, n)
}
}
fn main() {
for _ in range(0, 10u) {
task::spawn(proc() {
let result = count(5u);
println!("result = %?", result);
fail!();
});
}
}
| count | identifier_name |
validation.js | /**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
/*jshint jquery:true*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define([
"jquery",
"mage/validation",
"mage/translate"
], factory);
} else... |
}(function ($) {
"use strict";
/**
* Validation rule for grouped product, with multiple qty fields,
* only one qty needs to have a positive integer
*/
$.validator.addMethod(
"validate-grouped-qty",
function(value, element, params) {
var result = false;
... | {
factory(jQuery);
} | conditional_block |
validation.js | /**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
/*jshint jquery:true*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define([
"jquery",
"mage/validation",
"mage/translate"
], factory);
} else... | } else {
$(container).addClass('validation-failed');
$(container).removeClass('validation-passed');
return false;
}
},
'Please select one of the options.'
);
$.validator.addMethod(
"validate-date-between",
f... | if (checkedCount > 0) {
$(container).removeClass('validation-failed');
$(container).addClass('validation-passed');
return true; | random_line_split |
menuDirective.js | /**
* @ngdoc directive
* @name mdMenu
* @module material.components.menu
* @restrict E
* @description
*
* Menus are elements that open when clicked. They are useful for displaying
* additional options within the context of an action.
*
* Every `md-menu` must specify exactly two child elements. The first eleme... | triggerElement = triggerElement
.querySelector(prefixer.buildSelector(['ng-click', 'ng-mouseenter'])) || triggerElement;
}
if (triggerElement && (
triggerElement.nodeName == 'MD-BUTTON' ||
triggerElement.nodeName == 'BUTTON'
) && !triggerElement.hasAttribute('type')) {
trig... | templateElement.addClass('md-menu');
var triggerElement = templateElement.children()[0];
var prefixer = $mdUtil.prefixer();
if (!prefixer.hasAttribute(triggerElement, 'ng-click')) { | random_line_split |
menuDirective.js | /**
* @ngdoc directive
* @name mdMenu
* @module material.components.menu
* @restrict E
* @description
*
* Menus are elements that open when clicked. They are useful for displaying
* additional options within the context of an action.
*
* Every `md-menu` must specify exactly two child elements. The first eleme... |
if (templateElement.children().length != 2) {
throw Error(INVALID_PREFIX + 'Expected two children elements.');
}
// Default element for ARIA attributes has the ngClick or ngMouseenter expression
triggerElement && triggerElement.setAttribute('aria-haspopup', 'true');
var nestedMenus = templ... | {
triggerElement.setAttribute('type', 'button');
} | conditional_block |
menuDirective.js | /**
* @ngdoc directive
* @name mdMenu
* @module material.components.menu
* @restrict E
* @description
*
* Menus are elements that open when clicked. They are useful for displaying
* additional options within the context of an action.
*
* Every `md-menu` must specify exactly two child elements. The first eleme... |
}
| {
var mdMenuCtrl = ctrls[0];
var isInMenuBar = ctrls[1] != undefined;
// Move everything into a md-menu-container and pass it to the controller
var menuContainer = angular.element( '<div class="_md md-open-menu-container md-whiteframe-z2"></div>');
var menuContents = element.children()[1];
elem... | identifier_body |
menuDirective.js | /**
* @ngdoc directive
* @name mdMenu
* @module material.components.menu
* @restrict E
* @description
*
* Menus are elements that open when clicked. They are useful for displaying
* additional options within the context of an action.
*
* Every `md-menu` must specify exactly two child elements. The first eleme... | (templateElement) {
templateElement.addClass('md-menu');
var triggerElement = templateElement.children()[0];
var prefixer = $mdUtil.prefixer();
if (!prefixer.hasAttribute(triggerElement, 'ng-click')) {
triggerElement = triggerElement
.querySelector(prefixer.buildSelector(['ng-click', 'n... | compile | identifier_name |
applicable_declarations.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/. */
//! Applicable declarations management.
use properties::PropertyDeclarationBlock;
use rule_tree::{CascadeLevel, S... | (&self) -> u32 {
self.order_and_level.order()
}
/// Returns the cascade level of the block.
#[inline]
pub fn level(&self) -> CascadeLevel {
self.order_and_level.level()
}
/// Convenience method to consume self and return the source alongside the
/// level.
#[inline]
... | source_order | identifier_name |
applicable_declarations.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/. */
//! Applicable declarations management.
use properties::PropertyDeclarationBlock;
use rule_tree::{CascadeLevel, S... |
}
| {
let level = self.level();
(self.source, level)
} | identifier_body |
applicable_declarations.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/. */
//! Applicable declarations management.
use properties::PropertyDeclarationBlock;
use rule_tree::{CascadeLevel, S... | pub fn level(&self) -> CascadeLevel {
self.order_and_level.level()
}
/// Convenience method to consume self and return the source alongside the
/// level.
#[inline]
pub fn order_and_level(self) -> (StyleSource, CascadeLevel) {
let level = self.level();
(self.source, leve... | /// Returns the cascade level of the block.
#[inline] | random_line_split |
category-list.component.ts | import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {CategorySummary} from '../category-summary';
import {DiffsUtil} from '../../util/diffs-util';
import {CrudItemState} from '../../widgets/crud-list/crut-item-state';
i... |
private fetchCategories(type) {
this.httpClient
.get<CategorySummary[]>(`/api/v1/category/${type}`)
.subscribe(categories => this.categories = categories);
}
}
|
this.route
.paramMap
.map(map => map.get('type'))
.subscribe(data => this.type = `_category_${data}`);
this.route
.paramMap
.map(map => map.get('type'))
.map(type => `_category_${type}`)
.subscribe(this.fetchCategories.bind(this));
}
| identifier_body |
category-list.component.ts | import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {CategorySummary} from '../category-summary';
import {DiffsUtil} from '../../util/diffs-util';
import {CrudItemState} from '../../widgets/crud-list/crut-item-state';
i... | } | .get<CategorySummary[]>(`/api/v1/category/${type}`)
.subscribe(categories => this.categories = categories);
}
| random_line_split |
category-list.component.ts | import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {CategorySummary} from '../category-summary';
import {DiffsUtil} from '../../util/diffs-util';
import {CrudItemState} from '../../widgets/crud-list/crut-item-state';
i... | ): void {
this.route
.paramMap
.map(map => map.get('type'))
.subscribe(data => this.type = `_category_${data}`);
this.route
.paramMap
.map(map => map.get('type'))
.map(type => `_category_${type}`)
.subscribe(this.fetchCategories.bind(this));
}
private fetchCategori... | gOnInit( | identifier_name |
passport-local-tests.ts | /// <reference path="./passport-local.d.ts" />
/**
* Created by Maxime LUCE <https://github.com/SomaticIT>.
*/
import express = require("express");
import passport = require('passport');
import local = require('passport-local');
//#region Test Models
interface IUser {
username: string;
}
class User implements... | (password: string): boolean {
return true;
}
}
//#endregion
// Sample from https://github.com/jaredhanson/passport-local#configure-strategy
passport.use(new local.Strategy((username: any, password: any, done: any) => {
User.findOne({ username: username }, function (err, user) {
if (err) {
... | verifyPassword | identifier_name |
passport-local-tests.ts | /// <reference path="./passport-local.d.ts" />
/**
* Created by Maxime LUCE <https://github.com/SomaticIT>.
*/
import express = require("express");
import passport = require('passport');
import local = require('passport-local');
//#region Test Models
interface IUser {
username: string;
}
class User implements... | return done(null, false);
}
return done(null, user);
});
}));
// Sample from https://github.com/jaredhanson/passport-local#authenticate-requests
var app = express();
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function (req, res) {
... | if (!user.verifyPassword(password)) { | random_line_split |
passport-local-tests.ts | /// <reference path="./passport-local.d.ts" />
/**
* Created by Maxime LUCE <https://github.com/SomaticIT>.
*/
import express = require("express");
import passport = require('passport');
import local = require('passport-local');
//#region Test Models
interface IUser {
username: string;
}
class User implements... |
if (!user) {
return done(null, false);
}
if (!user.verifyPassword(password)) {
return done(null, false);
}
return done(null, user);
});
}));
passport.use(new local.Strategy({
passReqToCallback: true
}, function (req, username, password, done) ... | {
return done(err);
} | conditional_block |
passport-local-tests.ts | /// <reference path="./passport-local.d.ts" />
/**
* Created by Maxime LUCE <https://github.com/SomaticIT>.
*/
import express = require("express");
import passport = require('passport');
import local = require('passport-local');
//#region Test Models
interface IUser {
username: string;
}
class User implements... |
verifyPassword(password: string): boolean {
return true;
}
}
//#endregion
// Sample from https://github.com/jaredhanson/passport-local#configure-strategy
passport.use(new local.Strategy((username: any, password: any, done: any) => {
User.findOne({ username: username }, function (err, user) {
... | {
callback(null, new User());
} | identifier_body |
org_app.py | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
from django.conf.urls.defaults import url
from soc.logic.models.org_app_survey import logic as org_app_logic
from soc.views import forms
from soc.views.models.org_app_survey import OrgAppSurveyForm
from soc.modules.gsoc.views.base import RequestHandler
from soc.modules.gsoc.views.helper import url_patterns
class O... | random_line_split | |
org_app.py | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | (self):
"""Returns the list of tuples for containing URL to view method mapping.
"""
return [
url(r'^gsoc/org_app/apply/%s$' % url_patterns.SURVEY, self,
name='gsoc_org_app_apply')
]
def checkAccess(self):
"""Access checks for GSoC Organization Application.
"""
pass
... | djangoURLPatterns | identifier_name |
org_app.py | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
class OrgApp(RequestHandler):
"""View methods for Organization Application Applications.
"""
def templatePath(self):
return 'v2/modules/gsoc/org_app/apply.html'
def djangoURLPatterns(self):
"""Returns the list of tuples for containing URL to view method mapping.
"""
return [
url(r'... | """Form for Organization Applications inherited from Surveys.
"""
#TODO: Rewrite this class while refactoring surveys
def __init__(self, *args, **kwargs):
"""Act as a bridge between the new Forms APIs and the existing Survey
Form classes.
"""
kwargs.update({
'survey': kwargs.get('instan... | identifier_body |
org_app.py | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
else:
org_app_form = OrgAppForm(instance=org_app_entity)
return {
'page_name': 'Organization Application',
'org_app_form': org_app_form,
}
| org_app_form = OrgAppForm(self.data.POST, instance=org_app_entity) | conditional_block |
task_arc_wake.rs | use futures::task::{self, ArcWake, Waker};
use std::panic;
use std::sync::{Arc, Mutex};
struct | {
nr_wake: Mutex<i32>,
}
impl CountingWaker {
fn new() -> Self {
Self { nr_wake: Mutex::new(0) }
}
fn wakes(&self) -> i32 {
*self.nr_wake.lock().unwrap()
}
}
impl ArcWake for CountingWaker {
fn wake_by_ref(arc_self: &Arc<Self>) {
let mut lock = arc_self.nr_wake.lock()... | CountingWaker | identifier_name |
task_arc_wake.rs | use futures::task::{self, ArcWake, Waker};
use std::panic;
use std::sync::{Arc, Mutex};
struct CountingWaker {
nr_wake: Mutex<i32>,
}
impl CountingWaker {
fn new() -> Self {
Self { nr_wake: Mutex::new(0) }
}
fn wakes(&self) -> i32 {
*self.nr_wake.lock().unwrap()
}
}
impl ArcWake ... |
#[test]
fn ref_wake_same() {
let some_w = Arc::new(CountingWaker::new());
let w1: Waker = task::waker(some_w.clone());
let w2 = task::waker_ref(&some_w);
let w3 = w2.clone();
assert!(w1.will_wake(&w2));
assert!(w2.will_wake(&w3));
}
#[test]
fn proper_refcount_on_wake_panic() {
struct Pa... | {
let some_w = Arc::new(CountingWaker::new());
let w1: Waker = task::waker(some_w.clone());
assert_eq!(2, Arc::strong_count(&some_w));
w1.wake_by_ref();
assert_eq!(1, some_w.wakes());
let w2 = w1.clone();
assert_eq!(3, Arc::strong_count(&some_w));
w2.wake_by_ref();
assert_eq!(2, s... | identifier_body |
task_arc_wake.rs | use futures::task::{self, ArcWake, Waker};
use std::panic;
use std::sync::{Arc, Mutex};
struct CountingWaker {
nr_wake: Mutex<i32>,
}
impl CountingWaker {
fn new() -> Self {
Self { nr_wake: Mutex::new(0) }
}
fn wakes(&self) -> i32 {
*self.nr_wake.lock().unwrap()
}
}
impl ArcWake ... |
#[test]
fn proper_refcount_on_wake_panic() {
struct PanicWaker;
impl ArcWake for PanicWaker {
fn wake_by_ref(_arc_self: &Arc<Self>) {
panic!("WAKE UP");
}
}
let some_w = Arc::new(PanicWaker);
let w1: Waker = task::waker(some_w.clone());
assert_eq!(
"WAKE U... |
assert!(w1.will_wake(&w2));
assert!(w2.will_wake(&w3));
} | random_line_split |
static.rs | const FILE_GENERIC_READ: DWORD =
STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE;
static boolnames: &'static [&'static str] = &[ |
static mut name: SomeType =
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
pub static count: u8 = 10;
pub const test: &Type = &val;
impl Color {
pub const WHITE: u32 = 10;
}
// #1391
pub const XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX: NTSTATUS =
... | "bw", "am", "xsb", "xhp", "xenl", "eo", "gn", "hc", "km", "hs", "in", "db", "da", "mir",
"msgr", "os", "eslok", "xt", "hz", "ul", "xon", "nxon", "mc5i", "chts", "nrrmc", "npc",
"ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy", "xvpa", "sam", "cpix", "lpix", "OTbs",
"OTns", "OTnc", "OTMT", "OTNL", "... | random_line_split |
datasource.ts | import _ from 'lodash';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { getBackendSrv } from '@grafana/runtime';
import { DataQueryResponse, ScopedVars } from '@grafana/data';
import ResponseParser from './response_parser';
import PostgresQuery from 'app/plugins/datasource/postgre... | (target: any) {
let rawSql = '';
if (target.rawQuery) {
rawSql = target.rawSql;
} else {
const query = new PostgresQuery(target);
rawSql = query.buildQuery();
}
rawSql = rawSql.replace('$__', '');
return this.templateSrv.variableExists(rawSql);
}
}
| targetContainsTemplate | identifier_name |
datasource.ts | import _ from 'lodash';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { getBackendSrv } from '@grafana/runtime';
import { DataQueryResponse, ScopedVars } from '@grafana/data';
import ResponseParser from './response_parser';
import PostgresQuery from 'app/plugins/datasource/postgre... |
const quotedValues = _.map(value, v => {
return this.queryModel.quoteLiteral(v);
});
return quotedValues.join(',');
};
interpolateVariablesInQueries(
queries: PostgresQueryForInterpolation[],
scopedVars: ScopedVars
): PostgresQueryForInterpolation[] {
let expandedQueries = queries... | {
return value;
} | conditional_block |
datasource.ts | import _ from 'lodash';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { getBackendSrv } from '@grafana/runtime';
import { DataQueryResponse, ScopedVars } from '@grafana/data';
import ResponseParser from './response_parser';
import PostgresQuery from 'app/plugins/datasource/postgre... |
interpolateVariable = (value: string | string[], variable: { multi: any; includeAll: any }) => {
if (typeof value === 'string') {
if (variable.multi || variable.includeAll) {
return this.queryModel.quoteLiteral(value);
} else {
return value;
}
}
if (typeof value === 'n... | {
this.name = instanceSettings.name;
this.id = instanceSettings.id;
this.jsonData = instanceSettings.jsonData;
this.responseParser = new ResponseParser();
this.queryModel = new PostgresQuery({});
this.interval = (instanceSettings.jsonData || {}).timeInterval || '1m';
} | identifier_body |
datasource.ts | import _ from 'lodash';
import { Observable, of } from 'rxjs'; | import { DataQueryResponse, ScopedVars } from '@grafana/data';
import ResponseParser from './response_parser';
import PostgresQuery from 'app/plugins/datasource/postgres/postgres_query';
import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv';
import { getTimeSrv, TimeSrv } from 'app/feature... | import { map } from 'rxjs/operators';
import { getBackendSrv } from '@grafana/runtime'; | random_line_split |
gdocs.py | #!/usr/bin/env python
from exceptions import KeyError
import os
import requests
class GoogleDoc(object):
"""
A class for accessing a Google document as an object.
Includes the bits necessary for accessing the document and auth and such.
For example:
doc = {
"key": "123456abcdef",... |
else:
data['Email'] = self.email
data['Passwd'] = self.password
data['scope'] = self.scope
data['service'] = self.service
data['session'] = self.session
r = requests.post("https://www.google.com/accounts/ClientLogin", data=data)
... | raise KeyError("Error! You're missing some variables. You need to export APPS_GOOGLE_EMAIL and APPS_GOOGLE_PASS.") | conditional_block |
gdocs.py | #!/usr/bin/env python
from exceptions import KeyError
import os
import requests
class GoogleDoc(object):
"""
A class for accessing a Google document as an object.
Includes the bits necessary for accessing the document and auth and such.
For example:
doc = {
"key": "123456abcdef",... |
if r.status_code != 200:
raise KeyError("Error! Your Google Doc does not exist.")
with open('data/%s.%s' % (self.file_name, self.file_format), 'wb') as writefile:
writefile.write(r.content) | if r.status_code != 200:
url = self.new_spreadsheet_url % url_params
r = requests.get(url, headers=headers) | random_line_split |
gdocs.py | #!/usr/bin/env python
from exceptions import KeyError
import os
import requests
class GoogleDoc(object):
| """
A class for accessing a Google document as an object.
Includes the bits necessary for accessing the document and auth and such.
For example:
doc = {
"key": "123456abcdef",
"file_name": "my_google_doc",
"gid": "2"
}
g = GoogleDoc(**doc)
... | identifier_body | |
gdocs.py | #!/usr/bin/env python
from exceptions import KeyError
import os
import requests
class | (object):
"""
A class for accessing a Google document as an object.
Includes the bits necessary for accessing the document and auth and such.
For example:
doc = {
"key": "123456abcdef",
"file_name": "my_google_doc",
"gid": "2"
}
g = GoogleDoc(... | GoogleDoc | identifier_name |
mod.rs | extern crate combine;
use self::combine::*;
use self::combine::combinator::{Many, SepBy};
use self::combine::primitives::{Consumed, Stream};
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq)]
pub enum Object {
IntObject(i32),
Boolean(bool),
String(String),
VecObject(Vec<Object>),
Struc... | (input: State<&str>) -> ParseResult<char, &str> {
let (c, input) = try!(any().parse_lazy(input));
let mut back_slash_char = satisfy(|c| "\"\\/bfnrt".chars().find(|x| *x == c).is_some()).map(|c| {
match c {
'"' => '"',
'\\' => '\\',
'/' => '/',
... | escaped_char_parser | identifier_name |
mod.rs | extern crate combine;
use self::combine::*;
use self::combine::combinator::{Many, SepBy};
use self::combine::primitives::{Consumed, Stream};
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq)]
pub enum Object { | IntObject(i32),
Boolean(bool),
String(String),
VecObject(Vec<Object>),
StructVecObject(Vec<HashMap<String, Object>>),
RandomText(String),
}
pub type Section = HashMap<String, Object>;
pub type Sections = Vec<Section>;
fn title_parser(input: State<&str>) -> ParseResult<String, &str> {
betwee... | random_line_split | |
mod.rs | extern crate combine;
use self::combine::*;
use self::combine::combinator::{Many, SepBy};
use self::combine::primitives::{Consumed, Stream};
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq)]
pub enum Object {
IntObject(i32),
Boolean(bool),
String(String),
VecObject(Vec<Object>),
Struc... |
#[test]
fn test_boolean_parser() {
test(boolean_parser, "TRUE", true_object);
}
#[test]
fn test_wierd_exception_parser() {
let wierd_object : Object = Object::RandomText("wierd".to_string());
test(wierd_exception, "$$wierd", wierd_object);
}
#[test]
fn test_si... | {
test(string_parser, "\"hello \\\"world\\\"\"", "hello \"world\"".to_string());
} | identifier_body |
leap.js | /**
* Copyright (c) 2013, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var as... | value: [new FunctionEntry(emitter.finalLoc)]
}
});
}
var LMp = LeapManager.prototype;
exports.LeapManager = LeapManager;
LMp.withEntry = function(entry, callback) {
assert.ok(entry instanceof Entry);
this.entryStack.push(entry);
try {
callback.call(this.emitter);
} finally {
var popped = t... | emitter: { value: emitter },
entryStack: { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.