file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
2082002.js | engine.eval("load('nashorn:mozilla_compat.js');");
/*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modi... | (mode, type, selection) {
if(mode == -1) {
cm.dispose();
return;
} else {
status++;
if(mode == 0) {
cm.sendOk("You'll get to your destination in moment. Go ahead and talk to other people, and before you know it, you'll be there already.");
cm.dispose();
return;
}
if(status == 0) {
cm.sendYesNo... | action | identifier_name |
S15.10.2.15_A1_T40.js | // Copyright 2009 the Sputnik authors. All rights reserved. | following:
2. Let a be the one character in CharSet A.
3. Let b be the one character in CharSet B.
4. Let i be the character value of character a.
5. Let j be the character value of character b.
6. If i > j, throw a SyntaxError exception.
es5id: 15.10.2.15_A1_T40
description: >
Checking if e... | // This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The internal helper function CharacterRange takes two CharSet parameters A and B and performs the | random_line_split |
S15.10.2.15_A1_T40.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The internal helper function CharacterRange takes two CharSet parameters A and B and performs the
following:
2. Let a be the one character in CharSet A.
3. L... |
}
| {
$ERROR('#1.2: /[d-G\\u0061]/.exec("a") throw SyntaxError. Actual: ' + (e));
} | conditional_block |
create-app.ts | // std
import { execSync, spawn, SpawnOptions } from 'child_process';
// 3p
import { Spinner } from 'cli-spinner';
import { cyan, red } from 'colors/safe';
// FoalTS
import { FileSystem } from '../../file-system';
import {
getNames,
initGitRepo,
} from '../../utils';
function isYarnInstalled() |
function log(msg = '', spinner = false): any {
// Do not print logs during testing.
if (process.env.P1Z7kEbSUUPMxF8GqPwD8Gx_FOAL_CLI_TEST === 'true') {
return;
}
if (spinner) {
const spinner = new Spinner(msg);
spinner.setSpinnerString(18);
spinner.start();
return spinner;
}
console.... | {
try {
execSync('yarn --version', { stdio: 'ignore' });
return true;
} catch {
return false;
}
} | identifier_body |
create-app.ts | // std
import { execSync, spawn, SpawnOptions } from 'child_process';
// 3p
import { Spinner } from 'cli-spinner';
import { cyan, red } from 'colors/safe';
// FoalTS
import { FileSystem } from '../../file-system';
import {
getNames,
initGitRepo,
} from '../../utils';
function isYarnInstalled() {
try {
exec... | log(` 📦 Installing dependencies (${packageManager})...`);
}
}
if (initRepo) {
log();
log(' 📔 Initializing git repository...');
await initGitRepo(names.kebabName);
}
log();
log('✨ Project successfully created.');
log('👉 Here are the next steps:');
log();
logCommand(`cd ${na... | log(` ❗ Installing dependencies (${packageManager})...`);
log();
log(red(' Error: ') + 'A problem occurred during the installation of');
log('the dependencies. Try installing them manually by running');
log('the following commands:');
log();
logCommand(`cd ${names.kebabName}`);
... | conditional_block |
create-app.ts | // std
import { execSync, spawn, SpawnOptions } from 'child_process';
// 3p
import { Spinner } from 'cli-spinner';
import { cyan, red } from 'colors/safe';
// FoalTS
import { FileSystem } from '../../file-system';
import {
getNames,
initGitRepo,
} from '../../utils';
function isYarnInstalled() {
try {
exec... |
log();
log('✨ Project successfully created.');
log('👉 Here are the next steps:');
log();
logCommand(`cd ${names.kebabName}`);
if (!autoInstall) {
logCommand('npm install');
}
logCommand('npm run develop');
log();
} | log();
log(' 📔 Initializing git repository...');
await initGitRepo(names.kebabName);
} | random_line_split |
create-app.ts | // std
import { execSync, spawn, SpawnOptions } from 'child_process';
// 3p
import { Spinner } from 'cli-spinner';
import { cyan, red } from 'colors/safe';
// FoalTS
import { FileSystem } from '../../file-system';
import {
getNames,
initGitRepo,
} from '../../utils';
function isYarnInstalled() {
try {
exec... | ({ name, autoInstall, initRepo, mongodb = false, yaml = false }:
{ name: string, autoInstall?: boolean, initRepo?: boolean, mongodb?: boolean,
yaml?: boolean }) {
const names = getNames(name);
log();
log(' ------------------------------------------------- ');
log('| ... | createApp | identifier_name |
subheader.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc5-master-6b1d758
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.subheader
* @description
* SubHeader module
*
* Subheaders are special list tiles that del... |
}
}
}
MdSubheaderDirective.$inject = ["$mdSticky", "$compile", "$mdTheming", "$mdUtil"];
})(window, window.angular); | {
transclude(scope, function(clone) {
// If the user adds an ng-if or ng-repeat directly to the md-subheader element, the
// compiled clone below will only be a comment tag (since they replace their elements with
// a comment) which cannot be properly passed to the $mdSticky; so we... | conditional_block |
subheader.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc5-master-6b1d758
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.subheader
* @description
* SubHeader module
*
* Subheaders are special list tiles that del... | // Transclude the user-given contents of the subheader
// the conventional way.
transclude(scope, function(clone) {
getContent(element).append(clone);
});
// Create another clone, that uses the outer and inner contents
// of the element, that will be 'stickied' as the user s... | {
return {
restrict: 'E',
replace: true,
transclude: true,
template: (
'<div class="md-subheader">' +
' <div class="md-subheader-inner">' +
' <span class="md-subheader-content"></span>' +
' </div>' +
'</div>'
),
link: function postLink(scope, element, attr, controllers... | identifier_body |
subheader.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc5-master-6b1d758
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.subheader
* @description
* SubHeader module
*
* Subheaders are special list tiles that del... | ($mdSticky, $compile, $mdTheming, $mdUtil) {
return {
restrict: 'E',
replace: true,
transclude: true,
template: (
'<div class="md-subheader">' +
' <div class="md-subheader-inner">' +
' <span class="md-subheader-content"></span>' +
' </div>' +
'</div>'
),
link: function... | MdSubheaderDirective | identifier_name |
subheader.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc5-master-6b1d758
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.subheader
* @description
* SubHeader module
*
* Subheaders are special list tiles that del... | ' <span class="md-subheader-content"></span>' +
' </div>' +
'</div>'
),
link: function postLink(scope, element, attr, controllers, transclude) {
$mdTheming(element);
var outerHTML = element[0].outerHTML;
function getContent(el) {
return angular.element(el[0].querySelec... | random_line_split | |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | type MapFunction = Nullary | Unary | Binary | Ternary;
/**
* Returns an iterator which iterates over each element in a sparse array-like object.
*
* @param src - input value
* @param mapFcn - function to invoke for each iterated value
* @param thisArg - execution context
* @returns iterator
*
* @example
* var iter = s... | random_line_split | |
middleware.py | from datetime import datetime
from parsedatetime import parsedatetime, Constants
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.utils.misc import load_object
class HistoryMiddleware(object):
DATE_FORMAT = '%Y%m%d'
... |
return response
def parse_epoch(self, epoch):
"""
bool => bool
datetime => datetime
str => datetime
"""
if isinstance(epoch, bool) or isinstance(epoch, datetime):
return epoch
elif epoch == 'True':
return True
... | self.storage.store_response(spider, request, response)
self.stats.set_value('history/cached', True, spider=spider) | conditional_block |
middleware.py | from datetime import datetime
from parsedatetime import parsedatetime, Constants
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.utils.misc import load_object
class HistoryMiddleware(object):
DATE_FORMAT = '%Y%m%d'
... |
Decide if we would like to store it in the history.
"""
if self.store_if(spider, request, response):
self.storage.store_response(spider, request, response)
self.stats.set_value('history/cached', True, spider=spider)
return response
def parse_epoch(self, epo... | A response is leaving the Downloader. It was either retreived
from the web or from another middleware. | random_line_split |
middleware.py | from datetime import datetime
from parsedatetime import parsedatetime, Constants
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.utils.misc import load_object
class HistoryMiddleware(object):
DATE_FORMAT = '%Y%m%d'
... |
def process_response(self, request, response, spider):
"""
A response is leaving the Downloader. It was either retreived
from the web or from another middleware.
Decide if we would like to store it in the history.
"""
if self.store_if(spider, request, response):
... | """
A request is approaching the Downloader.
Decide if we would like to intercept the request and supply a
response ourselves.
"""
if self.epoch and self.retrieve_if(spider, request):
request.meta['epoch'] = self.epoch
response = self.storage.retrieve_res... | identifier_body |
middleware.py | from datetime import datetime
from parsedatetime import parsedatetime, Constants
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.utils.misc import load_object
class HistoryMiddleware(object):
DATE_FORMAT = '%Y%m%d'
... | (self, spider):
self.storage.open_spider(spider)
self.store_if.spider_opened(spider)
self.retrieve_if.spider_opened(spider)
def spider_closed(self, spider):
self.storage.close_spider(spider)
self.store_if.spider_closed(spider)
self.retrieve_if.spider_closed(spider)
... | spider_opened | identifier_name |
pir.rs | extern crate rand;
extern crate pung;
use std::mem;
use pung::pir::pir_client::PirClient;
use pung::pir::pir_server::PirServer;
use pung::db::PungTuple;
use rand::Rng;
macro_rules! get_size {
($d_type:ty) => (mem::size_of::<$d_type>() as u64);
}
#[test]
fn | () {
let num = 6;
let alpha = 1;
let d = 1;
let mut collection: Vec<PungTuple> = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..num {
let mut x: [u8; 286] = [0; 286];
rng.fill_bytes(&mut x);
let pt = PungTuple::new(&x);
collection.push(pt);
}
... | pir_decode | identifier_name |
pir.rs | extern crate rand;
extern crate pung;
use std::mem;
use pung::pir::pir_client::PirClient;
use pung::pir::pir_server::PirServer; |
macro_rules! get_size {
($d_type:ty) => (mem::size_of::<$d_type>() as u64);
}
#[test]
fn pir_decode() {
let num = 6;
let alpha = 1;
let d = 1;
let mut collection: Vec<PungTuple> = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..num {
let mut x: [u8; 286] = [0; 286];
... | use pung::db::PungTuple;
use rand::Rng; | random_line_split |
pir.rs | extern crate rand;
extern crate pung;
use std::mem;
use pung::pir::pir_client::PirClient;
use pung::pir::pir_server::PirServer;
use pung::db::PungTuple;
use rand::Rng;
macro_rules! get_size {
($d_type:ty) => (mem::size_of::<$d_type>() as u64);
}
#[test]
fn pir_decode() | let client = PirClient::new(1, 1, alpha, d);
let first = 0;
let last = 1;
let test_num = last - first;
let server = PirServer::new(&collection[first..last], alpha, d);
client.update_params(get_size!(PungTuple), test_num as u64, alpha);
// for i in 0..test_num {
{
let query = cl... | {
let num = 6;
let alpha = 1;
let d = 1;
let mut collection: Vec<PungTuple> = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..num {
let mut x: [u8; 286] = [0; 286];
rng.fill_bytes(&mut x);
let pt = PungTuple::new(&x);
collection.push(pt);
}
... | identifier_body |
beanMapper.ts | import {ServerBean} from '../../models/bean/serverBean';
import {Bean} from '../../classes/bean/bean';
import {BEAN_MIX_ENUM} from '../../enums/beans/mix';
import {BEAN_ROASTING_TYPE_ENUM} from '../../enums/beans/beanRoastingType';
import {IBeanInformation} from '../../interfaces/bean/iBeanInformation';
import {UIFileH... |
public async mapServerToClientBean(_serverResponse: ServerBean): Promise<Bean> {
return new Promise<Bean>(async (resolve, reject) => {
try {
const newBean: Bean = new Bean();
newBean.name = _serverResponse.name;
newBean.roaster = _serverResponse.roaster;
newBean.roast_rang... | {
} | identifier_body |
beanMapper.ts | import {ServerBean} from '../../models/bean/serverBean';
import {Bean} from '../../classes/bean/bean';
import {BEAN_MIX_ENUM} from '../../enums/beans/mix';
import {BEAN_ROASTING_TYPE_ENUM} from '../../enums/beans/beanRoastingType';
import {IBeanInformation} from '../../interfaces/bean/iBeanInformation';
import {UIFileH... | }
}
} |
}
}
catch(ex) {
| random_line_split |
beanMapper.ts | import {ServerBean} from '../../models/bean/serverBean';
import {Bean} from '../../classes/bean/bean';
import {BEAN_MIX_ENUM} from '../../enums/beans/mix';
import {BEAN_ROASTING_TYPE_ENUM} from '../../enums/beans/beanRoastingType';
import {IBeanInformation} from '../../interfaces/bean/iBeanInformation';
import {UIFileH... |
newBean.bean_roasting_type = {
0: 'FILTER' as BEAN_ROASTING_TYPE_ENUM,
1: 'ESPRESSO' as BEAN_ROASTING_TYPE_ENUM,
2: 'OMNI' as BEAN_ROASTING_TYPE_ENUM,
3: 'UNKNOWN' as BEAN_ROASTING_TYPE_ENUM,
}[_serverResponse.bean_roasting_type];
for (const informatio... | {
newBean.roast_custom = _serverResponse.roast_custom;
} | conditional_block |
beanMapper.ts | import {ServerBean} from '../../models/bean/serverBean';
import {Bean} from '../../classes/bean/bean';
import {BEAN_MIX_ENUM} from '../../enums/beans/mix';
import {BEAN_ROASTING_TYPE_ENUM} from '../../enums/beans/beanRoastingType';
import {IBeanInformation} from '../../interfaces/bean/iBeanInformation';
import {UIFileH... | (_bean: Bean, attachments: Array<IAttachment>) {
try {
const uiFileHelper: UIFileHelper = UIFileHelper.getInstance();
for (const attachment of attachments) {
const entry: string = await uiFileHelper.downloadExternalFile(attachment.uri, undefined, attachment.extension);
_bean.attachments... | downloadAndAttachAttachments | identifier_name |
inhibit.py | # -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# 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) an... | if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
... | PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org... | identifier_body |
inhibit.py | # -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# 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) an... | (object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing... | InhibitFlags | identifier_name |
inhibit.py | # -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# 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) an... |
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
... | try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass | conditional_block |
inhibit.py | # -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# 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) an... |
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_u... | PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER | random_line_split |
test_prosody.py | """Test cltk.prosody."""
__license__ = 'MIT License. See LICENSE.'
from cltk.prosody.latin.scanner import Scansion as ScansionLatin
from cltk.prosody.latin.clausulae_analysis import Clausulae
from cltk.prosody.greek.scanner import Scansion as ScansionGreek
from cltk.prosody.latin.macronizer import Macronizer
import u... | conditional_block | ||
test_prosody.py | """Test cltk.prosody."""
__license__ = 'MIT License. See LICENSE.'
from cltk.prosody.latin.scanner import Scansion as ScansionLatin
from cltk.prosody.latin.clausulae_analysis import Clausulae
from cltk.prosody.greek.scanner import Scansion as ScansionGreek
from cltk.prosody.latin.macronizer import Macronizer
import u... | εος μεν και απειρος δικων εγωγε ετι. μεν και απειρος."
current = ScansionGreek()._clean_accents(self.test)
self.assertEqual(current, correct)
def test_tokenize_greek(self):
"""Test _tokenize method."""
correct = [['νεος', 'μεν', 'και', 'απειρος', 'δικων', 'εγωγε', 'ετι.'],
... | ος μὲν καὶ ἄπειρος δικῶν ἔγωγε ἔτι. μὲν καὶ ἄπειρος."
current = ScansionGreek()._clean_text(self.test)
self.assertEqual(current, correct)
def test_clean_accents_greek(self):
"""Test _clean_accents method."""
correct = "ν | identifier_body |
test_prosody.py | """Test cltk.prosody."""
__license__ = 'MIT License. See LICENSE.'
from cltk.prosody.latin.scanner import Scansion as ScansionLatin
from cltk.prosody.latin.clausulae_analysis import Clausulae
from cltk.prosody.greek.scanner import Scansion as ScansionGreek
from cltk.prosody.latin.macronizer import Macronizer
import u... | εν', 'και', 'απειρος.']]
current = ScansionGreek()._tokenize(self.test)
self.assertEqual(current, correct)
def test_make_syllables_greek(self):
"""Test _make_syllables method."""
correct = [[['νε', 'ος'], ['μεν'], ['και'], ['α', 'πει', 'ρος'],
['δι', 'κων'], ['ε',... | ['μ | identifier_name |
test_prosody.py | """Test cltk.prosody."""
__license__ = 'MIT License. See LICENSE.'
from cltk.prosody.latin.scanner import Scansion as ScansionLatin
from cltk.prosody.latin.clausulae_analysis import Clausulae
from cltk.prosody.greek.scanner import Scansion as ScansionGreek
from cltk.prosody.latin.macronizer import Macronizer
import u... | current = ScansionGreek()._clean_text(self.test)
self.assertEqual(current, correct)
def test_clean_accents_greek(self):
"""Test _clean_accents method."""
correct = "νεος μεν και απειρος δικων εγωγε ετι. μεν και απειρος."
current = ScansionGreek()._clean_accents(self.test)
... | def test_clean_text_greek(self):
"""Test _clean_text method."""
correct = "νέος μὲν καὶ ἄπειρος δικῶν ἔγωγε ἔτι. μὲν καὶ ἄπειρος." | random_line_split |
userland.py |
import logging
from ..calling_conventions import SYSCALL_CC
from ..errors import AngrUnsupportedSyscallError
from ..procedures import SIM_PROCEDURES as P
from .simos import SimOS
_l = logging.getLogger('angr.simos.userland')
class SimUserland(SimOS):
"""
This is a base class for any SimOS that wants to sup... |
else:
raise AngrUnsupportedSyscallError("Got a symbolic syscall number")
proc = self.syscall_from_number(num, allow_unsupported=allow_unsupported)
proc.cc = cc
return proc
def is_syscall_addr(self, addr):
"""
Return whether or not the given address corr... | num = self.syscall_library.maximum_syscall_number(self.arch.name) + 1 if self.syscall_library else 0 | conditional_block |
userland.py | import logging
from ..calling_conventions import SYSCALL_CC
from ..errors import AngrUnsupportedSyscallError
from ..procedures import SIM_PROCEDURES as P
from .simos import SimOS
_l = logging.getLogger('angr.simos.userland')
class SimUserland(SimOS):
"""
This is a base class for any SimOS that wants to supp... | self.kernel_base = self.project.loader.kernel_object.mapped_base
def syscall(self, state, allow_unsupported=True):
"""
Given a state, return the procedure corresponding to the current syscall.
This procedure will have .syscall_number, .display_name, and .addr set.
:param st... | super(SimUserland, self).configure_project() | random_line_split |
userland.py |
import logging
from ..calling_conventions import SYSCALL_CC
from ..errors import AngrUnsupportedSyscallError
from ..procedures import SIM_PROCEDURES as P
from .simos import SimOS
_l = logging.getLogger('angr.simos.userland')
class SimUserland(SimOS):
"""
This is a base class for any SimOS that wants to sup... | (self, state, allow_unsupported=True):
"""
Given a state, return the procedure corresponding to the current syscall.
This procedure will have .syscall_number, .display_name, and .addr set.
:param state: The state to get the syscall number from
:param allow_unsuppor... | syscall | identifier_name |
userland.py |
import logging
from ..calling_conventions import SYSCALL_CC
from ..errors import AngrUnsupportedSyscallError
from ..procedures import SIM_PROCEDURES as P
from .simos import SimOS
_l = logging.getLogger('angr.simos.userland')
class SimUserland(SimOS):
| :param state: The state to get the syscall number from
:param allow_unsupported: Whether to return a "dummy" sycall instead of raising an unsupported exception
"""
if state.os_name in SYSCALL_CC[state.arch.name]:
cc = SYSCALL_CC[state.arch.name][state.os_name]... | """
This is a base class for any SimOS that wants to support syscalls.
It uses the CLE kernel object to provide addresses for syscalls. Syscalls will be emulated as a jump to one of these
addresses, where a SimProcedure from the syscall library provided at construction time will be executed.
"""
de... | identifier_body |
VariableBinder.js | // Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | else {
// Formal parameters are otherwise like variable
// declarations--identifier expressions and patterns
this.bindVariableDeclaration_(parameter.binding);
}
}
/** @param {ParseTree} parameter */
bindVariableDeclaration_(tree) {
// TODO(arv): This should just visit all the BindingId... | {
this.bind_(parameter.identifier);
} | conditional_block |
VariableBinder.js | // Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | (tree) {
// functions follow the binding rules of 'let'
if (this.block_ == this.scope_)
this.bind_(tree.name.identifierToken);
}
visitFunctionExpression(tree) {
// We don't recurse into function bodies, because they create
// their own lexical scope.
}
/** @param {VariableDeclarationList... | visitFunctionDeclaration | identifier_name |
VariableBinder.js | // Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | if (parameter.isRestParameter()) {
this.bind_(parameter.identifier);
} else {
// Formal parameters are otherwise like variable
// declarations--identifier expressions and patterns
this.bindVariableDeclaration_(parameter.binding);
}
}
/** @param {ParseTree} parameter */
bindVar... | }
/** @param {ParseTree} parameter */
bindParameter_(parameter) { | random_line_split |
VariableBinder.js | // Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... |
visitFunctionDeclaration(tree) {
// functions follow the binding rules of 'let'
if (this.block_ == this.scope_)
this.bind_(tree.name.identifierToken);
}
visitFunctionExpression(tree) {
// We don't recurse into function bodies, because they create
// their own lexical scope.
}
/** @pa... | {
// Save and set current block
var parentBlock = this.block_;
this.block_ = tree;
// visit the statements
this.visitList(tree.statements);
// restore current block
this.block_ = parentBlock;
} | identifier_body |
script.js | $(document).ready(function () {
startAnimation();
});
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
return window.setTimeout(c... |
Star.prototype = {
create: function(){
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
context.fill();
},
animate: function(){
var i;
for (i = 0; i < config.length; i++) {
var star = config.stars[i];
if (star.y < 0 || star.y > canvas.he... | {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = (config.velocity - (Math.random() * 0.5));
this.vy = (config.velocity - (Math.random() * 0.5));
this.radius = Math.random() * config.star.width;
} | identifier_body |
script.js | $(document).ready(function () {
startAnimation();
});
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
return window.setTimeout(c... | () {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = (config.velocity - (Math.random() * 0.5));
this.vy = (config.velocity - (Math.random() * 0.5));
this.radius = Math.random() * config.star.width;
}
Star.prototype = {
create: function(){
context.be... | Star | identifier_name |
script.js | $(document).ready(function () {
startAnimation();
});
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
return window.setTimeout(c... | this.setCanvas = function () {
canvas.width = config.width;
canvas.height = config.height;
};
this.setContext = function () {
context.fillStyle = config.star.color;
context.strokeStyle = config.line.color;
context.lineWidth = config.line.width;
};
this.setInitialPosition = function () {
if... | };
| random_line_split |
script.js | $(document).ready(function () {
startAnimation();
});
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
return window.setTimeout(c... | context.stroke();
context.closePath();
}
}
}
}
}
};
this.createStars = function () {
var length = config.length,
star,
i;
context.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0; i < length; i++) {
config.stars.push(new Star());
star = c... | {
for (j = 0; j < length; j++) {
iStar = config.stars[i];
jStar = config.stars[j];
if (
(iStar.x - jStar.x) < config.distance &&
(iStar.y - jStar.y) < config.distance &&
(iStar.x - jStar.x) > - config.distance &&
(iStar.y - jStar.y) > - config.distance
) {
... | conditional_block |
fabfile.py | from fabric.api import lcd, local
from fabric.decorators import runs_once
import os
fabfile_dir = os.path.dirname(__file__)
def i18n_push_source():
|
def i18n_pull():
"""pull the updated translation from transifex"""
with lcd('readthedocs'):
local('rm -rf rtd_tests/tests/builds/')
local('tx pull -f ')
local('django-admin makemessages --all')
local('django-admin compilemessages')
def i18n_docs():
with lcd('docs'):
... | """rebuild and push the source language to transifex"""
with lcd('readthedocs'):
local('rm -rf rtd_tests/tests/builds/')
local('django-admin makemessages -l en')
local('tx push -s')
local('django-admin compilemessages -l en') | identifier_body |
fabfile.py | from fabric.api import lcd, local
from fabric.decorators import runs_once |
fabfile_dir = os.path.dirname(__file__)
def i18n_push_source():
"""rebuild and push the source language to transifex"""
with lcd('readthedocs'):
local('rm -rf rtd_tests/tests/builds/')
local('django-admin makemessages -l en')
local('tx push -s')
local('django-admin compilemess... |
import os | random_line_split |
fabfile.py | from fabric.api import lcd, local
from fabric.decorators import runs_once
import os
fabfile_dir = os.path.dirname(__file__)
def i18n_push_source():
"""rebuild and push the source language to transifex"""
with lcd('readthedocs'):
local('rm -rf rtd_tests/tests/builds/')
local('django-admin mak... | ():
with lcd('docs'):
# Update our tanslations
local('tx pull -a')
local('sphinx-intl build')
# Push new ones
local('make gettext')
local('tx push -s')
@runs_once
def spider():
local('patu.py -d1 readthedocs.org')
| i18n_docs | identifier_name |
createHeadingsPlugin.tsx | import type { SlateComponentPluginDefinition } from '../types/slatePluginDefinitions';
import type { HtmlBlockData } from './createSimpleHtmlBlockPlugin';
import createSimpleHtmlBlockPlugin from './createSimpleHtmlBlockPlugin';
export type HeadingsDef<T> = {
level: 1 | 2 | 3 | 4 | 5 | 6;
} & Pick<
SlateComponentPl... |
export default createHeadingsPlugin;
| {
return createSimpleHtmlBlockPlugin<T>({
type: def.type,
hotKey: 'mod+' + def.level,
replaceWithDefaultOnRemove: true,
icon: def.icon,
label: `Heading ${def.level}`,
tagName: ('h' + def.level) as keyof JSX.IntrinsicElements,
});
} | identifier_body |
createHeadingsPlugin.tsx | import type { SlateComponentPluginDefinition } from '../types/slatePluginDefinitions';
import type { HtmlBlockData } from './createSimpleHtmlBlockPlugin';
import createSimpleHtmlBlockPlugin from './createSimpleHtmlBlockPlugin';
export type HeadingsDef<T> = {
level: 1 | 2 | 3 | 4 | 5 | 6;
} & Pick<
SlateComponentPl... | });
}
export default createHeadingsPlugin; | random_line_split | |
createHeadingsPlugin.tsx | import type { SlateComponentPluginDefinition } from '../types/slatePluginDefinitions';
import type { HtmlBlockData } from './createSimpleHtmlBlockPlugin';
import createSimpleHtmlBlockPlugin from './createSimpleHtmlBlockPlugin';
export type HeadingsDef<T> = {
level: 1 | 2 | 3 | 4 | 5 | 6;
} & Pick<
SlateComponentPl... | <T = {}>(def: HeadingsDef<T>) {
return createSimpleHtmlBlockPlugin<T>({
type: def.type,
hotKey: 'mod+' + def.level,
replaceWithDefaultOnRemove: true,
icon: def.icon,
label: `Heading ${def.level}`,
tagName: ('h' + def.level) as keyof JSX.IntrinsicElements,
});
}
export default createHeadings... | createHeadingsPlugin | identifier_name |
app.js | avigationDrawer.element);
//add feed page
feedPage = new FeedPage();
appCanvas.pushContent(feedPage);
splashImage = document.createElement('img');
splashImage.setAttribute('class', 'splashOpen');
splashImage.setAttribute('src', '/public/images/splash.png');
setTimeout(function(){
page.appendChild(this.splash... | if (elements[item] instanceof Button && !elements[item].multiSelect) {
elements[item].isMouseDown = false;
}
}
for (var scrollV in scrollViewRegister) {
scrollViewRegister[scrollV].onMouseUp(event);
}
scrollViewRegister = new Array();
activeScrollViews = new Array();
activeButton = null;
}
function onM... |
for (var item in elements) { | random_line_split |
app.js | avigationDrawer.element);
//add feed page
feedPage = new FeedPage();
appCanvas.pushContent(feedPage);
splashImage = document.createElement('img');
splashImage.setAttribute('class', 'splashOpen');
splashImage.setAttribute('src', '/public/images/splash.png');
setTimeout(function(){
page.appendChild(this.splash... | (element, jsObject) {
element.setAttribute('guid', elementCount);
elements[elementCount] = jsObject;
elementCount++;
}
function refreshFeed() {
App.locator.getLoc(function(userLoc){
var event = new CustomEvent('start-feed', { detail: userLoc });
document.dispatchEvent(event);
});
}
function initialize(... | addElementToDict | identifier_name |
app.js | avigationDrawer.element);
//add feed page
feedPage = new FeedPage();
appCanvas.pushContent(feedPage);
splashImage = document.createElement('img');
splashImage.setAttribute('class', 'splashOpen');
splashImage.setAttribute('src', '/public/images/splash.png');
setTimeout(function(){
page.appendChild(this.splash... |
};
req.onerror = function (err) {
console.log('XHR Error: ' + JSON.stringify(err));
};
if (data) {
console.log('bad data: ' + JSON.stringify(data));
req.send(JSON.stringify(data));
} else {
req.send();
}
};
Constructor.prototype.fetch = function (cb) {
return th... | {
return false;
} | conditional_block |
app.js | avigationDrawer.element);
//add feed page
feedPage = new FeedPage();
appCanvas.pushContent(feedPage);
splashImage = document.createElement('img');
splashImage.setAttribute('class', 'splashOpen');
splashImage.setAttribute('src', '/public/images/splash.png');
setTimeout(function(){
page.appendChild(this.splash... |
// document.addEventListener( 'touchstart' , function stopScrolling( touchEvent ) { touchEvent.preventDefault(); } , false );
// document.addEventListener( 'touchmove' , function stopScrolling( touchEvent ) { touchEvent.preventDefault(); } , false );
function setTouchListeners() {
document.body.addEventListener('to... | {
elements[element.getAttribute('guid')].onMouseOver();
} | identifier_body |
TagDetailsUI.tsx | DetailsUI extends BaseComponentPlus({enabled: true} as Props, {} as State) {
ComponentWillMountOrReceiveProps(props, forMount) {
if (forMount || props.baseData != this.props.baseData) { // if base-data changed
this.SetState({newData: CloneWithPrototypes(props.baseData)});
/*this.SetState({newData: CloneWithPro... | }
}
class TagCompUI_MirrorChildrenFromXToY extends BaseComponentPlus({} as TagDetailsUI_SharedProps, {}) {
render() {
let {newData, enabled, splitAt, Change} = this.props;
let comp = newData.mirrorChildrenFromXToY;
return (
<>
<NodeSlotRow {...this.props} comp={comp} nodeKey="nodeX" label="Node X" mt={0... | }*/
GetNewData() {
const {newData} = this.state;
return CloneWithPrototypes(newData) as MapNodeTag; | random_line_split |
fpe.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Ben Segall <talchas@gmail.com>
// Copyright (c) edef <edef@edef.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opens... | {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
yielder.suspend(1.0 / black_box(0.0));
});
unsafe { feenableexcept(FE_DIVBYZERO); }
println!("{:?}", gen.resume(()));
} | identifier_body | |
fpe.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Ben Segall <talchas@gmail.com>
// Copyright (c) edef <edef@edef.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opens... | () {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
yielder.suspend(1.0 / black_box(0.0));
});
unsafe { feenableexcept(FE_DIVBYZERO); }
println!("{:?}", gen.resume(()));
}
| fpe | identifier_name |
fpe.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Ben Segall <talchas@gmail.com>
// Copyright (c) edef <edef@edef.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opens... |
#[test]
#[ignore]
fn fpe() {
let stack = OsStack::new(0).unwrap();
let mut gen = Generator::new(stack, move |yielder, ()| {
yielder.suspend(1.0 / black_box(0.0));
});
unsafe { feenableexcept(FE_DIVBYZERO); }
println!("{:?}", gen.resume(()));
} | } | random_line_split |
batchDeleteExistingOverlayActionsCommand.ts | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
BaseCommand,
RestHttpMethodEnum
} from '@salesforce/salesforcedx-apex-repla... | (requests: BatchRequests) {
super(undefined);
this.requests = requests;
}
public getCommandUrl(): string {
return COMPOSITE_BATCH_URL;
}
public getRequest(): string | undefined {
return JSON.stringify(this.requests);
}
}
| constructor | identifier_name |
batchDeleteExistingOverlayActionsCommand.ts | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
BaseCommand,
RestHttpMethodEnum
} from '@salesforce/salesforcedx-apex-repla... | export interface BatchDeleteResult {
statusCode: number;
result: SingleResult[] | null;
}
export interface SingleResult {
errorCode: string;
message: string;
}
export class BatchDeleteExistingOverlayActionCommand extends BaseCommand {
private readonly requests: BatchRequests;
public constructor(requests: ... | export interface BatchDeleteResponse {
hasErrors: boolean;
results: BatchDeleteResult[];
}
| random_line_split |
OptionsApp.ts | /// <reference path="../../all.d.ts" />
module OptionsApp {
angular.module('OptionsApp', ['HeaderApp', 'gettext', 'angular-google-analytics'])
.config(Helpers.setAnaliticSetting)
.run(Helpers.setCurrentLanguage)
.run(Helpers.trackPage)
.controller('OptionsCtrl', OptionsCtrl)
.directive('checkboxOption', () ... | <i class="fa fa-square fa-stack-2x"></i>
<i ng-if="param" class="fa fa-check fa-stack-1x fa-inverse"></i>
</span>`,
scope: {
param: '=?'
}
}
})
.filter('kFilter', function () {
return function (input: any, decimals: any) {
const suffixes = ['K', 'M', 'G', 'T', 'P', 'E... | template: `<input ng-model="param" type="checkbox"/>
<span class="fa-stack"> | random_line_split |
platforms.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... |
var PlatformApi;
//WEEK_HOOK
// try {
// // First we need to find whether platform exposes its' API via js module
// // If it does, then we require and instantiate it.
// var platformApiModule = path.join(platformRootDir, 'cordova', 'Api.js');
// PlatformApi = require(platfor... | {
// if platformRootDir is not specified, try to detect it first
if (!platformRootDir) {
var projectRootDir = util.isCordova();
platformRootDir = projectRootDir && path.join(projectRootDir, 'platforms', platform);
}
if (!platformRootDir) {
// If platformRootDir is still undefin... | identifier_body |
platforms.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... | 'getPlatformApi': {value: getPlatformApi, configurable: true, writable: true},
'getRealPlatformApi':{value: getRealPlatformApi, configurable: true, writable: true}
}); | random_line_split | |
platforms.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... | (platform, platformRootDir) {
var cached; //= cachedApis[__dirname];
if (cached && cached.platform == platform) return cached;
if (!platforms[platform]) throw new Error('Unknown platform ' + platform);
var PlatformApi;
try {
// First we need to find whether platform exposes its' API via js module
/... | getRealPlatformApi | identifier_name |
platforms.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... |
if (!platformRootDir) {
// If platformRootDir is still undefined, then we're probably is not inside of cordova project
throw new Error('Current location is not a weexpack project');
}
// CB-11174 Resolve symlinks first before working with root directory
platformRootDir = util.convertT... | {
var projectRootDir = util.isCordova();
platformRootDir = projectRootDir && path.join(projectRootDir, 'platforms', platform);
} | conditional_block |
appversion.py | 8# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accomp... | """
app_versions = elasticbeanstalk.get_application_versions(self.app_name)['ApplicationVersions']
appversionops.display_versions(self.app_name, self.env_name, app_versions) | random_line_split | |
appversion.py | 8# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accomp... | (AbstractBaseController.Meta):
label = 'appversion'
description = strings['appversion.info']
arguments = [
(['--delete', '-d'], dict(action='store', help=flag_text['appversion.delete'], metavar='VERSION_LABEL'))
]
usage = 'eb appversion <lifecycle> [options ...]'
... | Meta | identifier_name |
appversion.py | 8# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accomp... |
def do_command(self):
self.app_name = self.get_app_name()
# For appversion, it's fine if environment is not defined
self.env_name = self.get_env_name(noerror=True)
# if user passed in a app version label to delete
if self.app.pargs.delete is not None:
version_l... | label = 'appversion'
description = strings['appversion.info']
arguments = [
(['--delete', '-d'], dict(action='store', help=flag_text['appversion.delete'], metavar='VERSION_LABEL'))
]
usage = 'eb appversion <lifecycle> [options ...]' | identifier_body |
appversion.py | 8# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accomp... |
# if none of above, enter interactive mode
self.interactive_list_version()
def interactive_list_version(self):
"""Interactive mode which allows user to see previous
versions and allow a choice to:
- deploy a different version.
- delete a certain version
Run... | version_label_to_delete = self.app.pargs.delete
appversionops.delete_app_version_label(self.app_name, version_label_to_delete)
return | conditional_block |
views.py | import json
import os
import re
from django import http
from django.conf import settings
from django.db.transaction import non_atomic_requests
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.utils.encoding import iri_to_uri
from django.views.decorators.cache... |
else:
return render(request, 'amo/404.html', status=404)
@non_atomic_requests
def handler500(request):
if request.path_info.startswith('/api/'):
# Pass over to handler500 view in api if api was targeted.
return api.views.handler500(request)
else:
return render(request, 'am... | return api.views.handler404(request) | conditional_block |
views.py | import json
import os
import re
from django import http
from django.conf import settings
from django.db.transaction import non_atomic_requests
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.utils.encoding import iri_to_uri
from django.views.decorators.cache... | def cspreport(request):
"""Accept CSP reports and log them."""
report = ('blocked-uri', 'violated-directive', 'original-policy')
if not waffle.sample_is_active('csp-store-reports'):
return HttpResponse()
try:
v = json.loads(request.body)['csp-report']
# If possible, alter the P... |
@csrf_exempt
@require_POST
@non_atomic_requests | random_line_split |
views.py | import json
import os
import re
from django import http
from django.conf import settings
from django.db.transaction import non_atomic_requests
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.utils.encoding import iri_to_uri
from django.views.decorators.cache... | (request):
if request.path_info.startswith('/api/'):
# Pass over to handler500 view in api if api was targeted.
return api.views.handler500(request)
else:
return render(request, 'amo/500.html', status=500)
@non_atomic_requests
def csrf_failure(request, reason=''):
return render(req... | handler500 | identifier_name |
views.py | import json
import os
import re
from django import http
from django.conf import settings
from django.db.transaction import non_atomic_requests
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.utils.encoding import iri_to_uri
from django.views.decorators.cache... |
@non_atomic_requests
def loaded(request):
return http.HttpResponse('%s' % request.META['wsgi.loaded'],
content_type='text/plain')
@csrf_exempt
@require_POST
@non_atomic_requests
def cspreport(request):
"""Accept CSP reports and log them."""
report = ('blocked-uri', 'violate... | return render(request, 'amo/403.html',
{'because_csrf': 'CSRF' in reason}, status=403) | identifier_body |
wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// This file was forked from https://github.com/lowRISC/manticore.
//! Wire format traits.
//!
//! This module provides [`FromWire`] and [`ToWire`], a pair of traits si... | (e: io::Error) -> Self {
Self::Io(e)
}
}
/// A type which can be serialized into the Cerberus wire format.
pub trait ToWire: Sized {
/// Serializes `self` into `w`.
fn to_wire<W: Write>(&self, w: W) -> Result<(), ToWireError>;
}
/// A serializerion error.
#[derive(Clone, Copy, Debug)]
pub enum ToW... | from | identifier_name |
wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// This file was forked from https://github.com/lowRISC/manticore.
//! Wire format traits.
//!
//! This module provides [`FromWire`] and [`ToWire`], a pair of traits si... |
fn from_str(s: &str) -> Result<Self, $crate::protocol::wire::WireEnumFromStrError> {
use $crate::protocol::wire::WireEnum;
match $name::from_name(s) {
Some(val) => Ok(val),
None => Err($crate::protocol::wire::WireEnumFromStrError),
... | }
impl core::str::FromStr for $name {
type Err = $crate::protocol::wire::WireEnumFromStrError; | random_line_split |
wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// This file was forked from https://github.com/lowRISC/manticore.
//! Wire format traits.
//!
//! This module provides [`FromWire`] and [`ToWire`], a pair of traits si... |
}
| {
use crate::protocol::wire::*;
assert_eq!(DemoEnum::First.name(), "First");
assert_eq!(DemoEnum::Second.name(), "Second");
} | identifier_body |
prompt.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Components for rendering input and output prompts.
*/
import { React, Component } from "../app-framework";
import { Icon, TimeAgo, Tip } from "../r_misc";
const misc = req... | const kernel = misc.capitalize(
this.props.kernel != null ? this.props.kernel : ""
);
let tip: string | JSX.Element = "Enter code to be evaluated.";
switch (this.props.state) {
case "start":
n = <Icon name="arrow-circle-o-left" style={{ fontSize: "80%" }} />;
tip = `Sending to ... | return <div style={INPUT_STYLE} />;
}
| conditional_block |
prompt.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Components for rendering input and output prompts.
*/
import { React, Component } from "../app-framework";
import { Icon, TimeAgo, Tip } from "../r_misc";
const misc = req... | tip = (
<span>
Evaluated <TimeAgo date={new Date(this.props.end)} /> using{" "}
{kernel}.
</span>
);
} else if (kernel) {
tip = `Last evaluated using ${kernel}.`;
}
} else {
n = " ";
... | default:
// done (or never run)
if (this.props.exec_count) {
n = this.props.exec_count;
if (this.props.end != null) { | random_line_split |
plot_ensemble_oob.py | """
=============================
OOB Errors for Random Forests
=============================
The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where
each new tree is fit from a bootstrap sample of the training observations
:math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average er... | from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
# Author: Kian Ho <hui.kian.ho@gmail.com>
# Gilles Louppe <g.louppe@gmail.com>
# Andreas Mueller <amueller@ais.uni-bonn.de>
#
# License: BSD 3 Clause
print(__doc__)
RANDOM_STATE = 123
# Generate a binary classification dataset... | from collections import OrderedDict
from sklearn.datasets import make_classification | random_line_split |
plot_ensemble_oob.py | """
=============================
OOB Errors for Random Forests
=============================
The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where
each new tree is fit from a bootstrap sample of the training observations
:math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average er... |
plt.xlim(min_estimators, max_estimators)
plt.xlabel("n_estimators")
plt.ylabel("OOB error rate")
plt.legend(loc="upper right")
plt.show()
| xs, ys = zip(*clf_err)
plt.plot(xs, ys, label=label) | conditional_block |
archive_test.py | # archive_test.py - unit tests for archive.py
# Authors:
# * Erich Blume <blume.erich@gmail.com>
#
# Copyright 2011 Erich Blume <blume.erich@gmail.com>
#
# This file is part of Tiger Lily.
#
# Tiger Lily is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... |
def test_tar(self):
"archive.py: Test .tar archive support"
arch = ar.Archive(filepath=self.tar)
self._handle_arch(arch)
def test_zip(self):
"archive.py: Test .zip archive support"
arch = ar.Archive(filepath=self.zip)
self._handle_arch(arch)
def _handle_arc... | """Test harness for ``tigerlily.utility.archive.Archive`` class.
"""
def setUp(self):
"""archive.py: Create the testing environment"""
self.test_dir = os.path.join(os.path.dirname(__file__),'test_archives')
self.targz = os.path.join(self.test_dir, 'test_fasta_archive.tar.gz')
se... | identifier_body |
archive_test.py | # archive_test.py - unit tests for archive.py
# Authors:
# * Erich Blume <blume.erich@gmail.com>
#
# Copyright 2011 Erich Blume <blume.erich@gmail.com>
#
# This file is part of Tiger Lily.
#
# Tiger Lily is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... | self.assertEqual(len(nofasta_files),1)
# Finally, just test to make sure that FASTA can handle the test files
# This isn't really a test of this unit, but it's a logical extension
# and it would be bad if it failed, so let's do the test.
for fasta_fileobj in arch.getfasta():
... | fasta_files = [f for f in arch.getfasta()]
self.assertEqual(len(fasta_files),3)
nofasta_files = [f for f in arch.getnofasta()] | random_line_split |
archive_test.py | # archive_test.py - unit tests for archive.py
# Authors:
# * Erich Blume <blume.erich@gmail.com>
#
# Copyright 2011 Erich Blume <blume.erich@gmail.com>
#
# This file is part of Tiger Lily.
#
# Tiger Lily is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... | self.assertTrue(len(fasta_seq.sequence) > 0)
self.assertTrue(fasta_seq.identifier.startswith('seq')) | conditional_block | |
archive_test.py | # archive_test.py - unit tests for archive.py
# Authors:
# * Erich Blume <blume.erich@gmail.com>
#
# Copyright 2011 Erich Blume <blume.erich@gmail.com>
#
# This file is part of Tiger Lily.
#
# Tiger Lily is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... | (self,arch):
"handler for testing an Archive object regardless of format"
self.assertEqual(len(arch.getnames()),4)
fasta_files = [f for f in arch.getfasta()]
self.assertEqual(len(fasta_files),3)
nofasta_files = [f for f in arch.getnofasta()]
self.assertEqual(len(nofasta... | _handle_arch | identifier_name |
Cdrom.py | # encoding: utf-8
# module apt_pkg
# from /usr/lib/python3/dist-packages/apt_pkg.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
"""
Classes and functions wrapping the apt-pkg library.
The apt_pkg module provides several classes and functions for accessing
the functionality provided by the apt-pkg library. Typica... | (object):
"""
Cdrom()
Cdrom objects can be used to identify Debian installation media and to
add them to /etc/apt/sources.list.
"""
def add(self, progress): # real signature unknown; restored from __doc__
"""
add(progress: apt_pkg.CdromProgress) -> bool
Add ... | Cdrom | identifier_name |
Cdrom.py | # encoding: utf-8
# module apt_pkg
# from /usr/lib/python3/dist-packages/apt_pkg.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
"""
Classes and functions wrapping the apt-pkg library.
The apt_pkg module provides several classes and functions for accessing
the functionality provided by the apt-pkg library. Typica... | """ Create and return a new object. See help(type) for accurate signature. """
pass |
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown | random_line_split |
Cdrom.py | # encoding: utf-8
# module apt_pkg
# from /usr/lib/python3/dist-packages/apt_pkg.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
"""
Classes and functions wrapping the apt-pkg library.
The apt_pkg module provides several classes and functions for accessing
the functionality provided by the apt-pkg library. Typica... |
def __init__(self): # real signature unknown; restored from __doc__
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
| """
ident(progress: apt_pkg.CdromProgress) -> str
Try to identify the CD-ROM and if successful return the hexadecimal
CDROM-ID (and a integer version suffix separated by -) as a
string. Otherwise, return None or raise an error.
The ID is created by hashing all f... | identifier_body |
archive_viewer.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013-2020, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... | (name, arch):
if isinstance(arch.toc, dict):
(ispkg, pos, length) = arch.toc.get(name, (0, None, 0))
if pos is None:
return None
with arch.lib:
arch.lib.seek(arch.start + pos)
return zlib.decompress(arch.lib.read(length))
ndx = arch.toc.find(name)
... | get_data | identifier_name |
archive_viewer.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013-2020, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... |
from __future__ import print_function
import argparse
import os
import pprint
import sys
import tempfile
import zlib
from PyInstaller.loader import pyimod02_archive
from PyInstaller.archive.readers import CArchiveReader, NotAnArchiveError
from PyInstaller.compat import stdin_input
import PyInstaller.log
stack = []
... | """ | random_line_split |
archive_viewer.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013-2020, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... |
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--log',
default=False,
action='store_true',
dest='debug',
help='Print an archive log (default: %(default)s)')
parser.add_argument('-r', ... | """ Overridable.
Check to see if the file object self.lib actually has a file
we understand.
"""
self.lib.seek(self.start) # default - magic is at start of file.
if self.lib.read(len(self.MAGIC)) != self.MAGIC:
raise RuntimeError("%s is not a valid %s archive... | identifier_body |
archive_viewer.py | #-----------------------------------------------------------------------------
# Copyright (c) 2013-2020, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... |
return CArchiveReader(name)
parent = stack[-1][1]
try:
return parent.openEmbedded(name)
except KeyError:
return None
except (ValueError, RuntimeError):
ndx = parent.toc.find(name)
dpos, dlen, ulen, flag, typcd, name = parent.toc[ndx]
x, data = parent.extr... | return ZlibArchive(name) | conditional_block |
htmlbaseelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... |
/// <https://html.spec.whatwg.org/multipage/#frozen-base-url>
pub fn frozen_base_url(&self) -> ServoUrl {
let href = self
.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("href"))
.expect(
"The frozen base url is only defined for base element... | {
Node::reflect_node(
Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)),
document,
HTMLBaseElementBinding::Wrap,
)
} | identifier_body |
htmlbaseelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... | (&self) -> ServoUrl {
let href = self
.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("href"))
.expect(
"The frozen base url is only defined for base elements \
that have a base url.",
);
let document = document_fr... | frozen_base_url | identifier_name |
htmlbaseelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... | }
// https://html.spec.whatwg.org/multipage/#dom-base-href
make_setter!(SetHref, "href");
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&dyn VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
}
fn attribute_mutated(&self, attr: &At... | random_line_split | |
htmlbaseelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use crate::dom::... |
}
}
impl HTMLBaseElementMethods for HTMLBaseElement {
// https://html.spec.whatwg.org/multipage/#dom-base-href
fn Href(&self) -> DOMString {
// Step 1.
let document = document_from_node(self);
// Step 2.
let attr = self
.upcast::<Element>()
.get_att... | {
let document = document_from_node(self);
document.refresh_base_element();
} | conditional_block |
configuration.get.js | /*
* Copyright (C) 2008-2010 Surevine Limited.
*
* Although intended for deployment and use alongside Alfresco this module should
* be considered 'Not a Contribution' as defined in Alfresco'sstandard contribution agreement, see
* http://www.alfresco.org/resource/AlfrescoContributionAgreementv2.pdf
*
* This p... |
//Get the security label header
model.securityLabelHeaderNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/security_label.txt');
//Get the help url
model.helpLinkNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_help.txt');
model.launchChatUrlNode =... | // Get the change password url
model.changePasswordUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_change_password.txt'); | random_line_split |
GithubException.py | ############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | (GithubException):
"""
Exception raised when Github requires a onetime password for two-factor authentication
"""
class IncompletableObject(GithubException):
"""
Exception raised when we can not request an object from Github because the data returned did not include a URL
"""
class MockExcep... | TwoFactorException | identifier_name |
GithubException.py | ############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... |
class BadUserAgentException(GithubException):
"""
Exception raised when request is sent with a bad user agent header (when Github API replies with a 403 bad user agent HTML status)
"""
class RateLimitExceededException(GithubException):
"""
Exception raised when the rate limit is exceeded (when ... | """
Exception raised when a non-existing object is requested (when Github API replies with a 404 HTML status)
""" | identifier_body |
GithubException.py | ############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | # #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) ... | # #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ # | random_line_split |
M668.py | """
GCode M668
Adjust backlash compensation for each named axis
M668 Xn Yn Zn En Hn An Bn Cn
Author: Anthony Clay | License: CC BY-SA: http://creativecommons.org/licenses/by-sa/2.0/
"""
from GCodeCommand import GCodeCommand
import logging
class M668(GCodeCommand):
def execute(self, g):
for index, axis in enumerate(["X", "Y", "Z", "E", "H", "A", "B", "C"]):
if g.has_letter(axis):
self.prin... | random_line_split | |
M668.py | """
GCode M668
Adjust backlash compensation for each named axis
M668 Xn Yn Zn En Hn An Bn Cn
Author: Anthony Clay
License: CC BY-SA: http://creativecommons.org/licenses/by-sa/2.0/
"""
from GCodeCommand import GCodeCommand
import logging
class M668(GCodeCommand):
def execute(self, g):
for index, axis ... | return "Adjust backlash compensation for each named axis" | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.