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 |
|---|---|---|---|---|
http_downloader.ts | ///<reference path="../../../typings/tsd.d.ts"/>
import http = require('http')
import https = require('https')
import url = require('url')
interface HttpOptionsObject {
host:string,
path:string
}
export class HttpDownloader {
constructor() {}
/**
* HTTP GET request
*
* @... | (httpsOpts: HttpOptionsObject,
callbackDone: (body:string)=>any,
callbackData?: (chunk:string, progress:number)=>any) {
console.log("HTTPS-GET: {host:%s, path:%s}", httpsOpts.host + httpsOpts.path);
https.get(httpsOpts).on('response', function(response) {
var body ... | gets | identifier_name |
placessidebar.rs | // This file is part of rgtk.
//
// rgtk 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) any later version.
//
// rgtk is distributed in the hop... | self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_local_only(&self, local_only: bool) {
unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(local_onl... | t_show_connect_to_server(& | identifier_name |
placessidebar.rs | // This file is part of rgtk.
//
// rgtk 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) any later version.
//
// rgtk is distributed in the hop... | pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) {
unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.get_widget()), flags) }
}
pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags {
unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.get_wi... | let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() };
check_pointer!(tmp_pointer, PlacesSidebar)
}
| identifier_body |
placessidebar.rs | // This file is part of rgtk.
//
// rgtk 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) any later version.
//
// rgtk is distributed in the hop... |
impl_widget_events!(PlacesSidebar) | random_line_split | |
gamemenu.py | quer/)
#
#------------------------------------------------------------------------
class TGameMenu:
def __init__(self, screen, bg_image, logo1, menu_items, start_vec, spacing=50):
# Currently selected menuitem's index
self.pos = 0
# List of menuitems
self.menu_items = menu_items
... | (self):
# User selects a menu item
return self.menu_items[self.pos][1]
# end of class TGameMenu
###################################################################
def text_input(plotter, caption, corner_1, span_vec, fonts, only_numbers=False):
# Make an input-box and prompt it for input
asse... | select | identifier_name |
gamemenu.py | quer/)
#
#------------------------------------------------------------------------
class TGameMenu:
def __init__(self, screen, bg_image, logo1, menu_items, start_vec, spacing=50):
# Currently selected menuitem's index
self.pos = 0
# List of menuitems
self.menu_items = menu_items
... | tmp.set_colorkey(tmp.get_at((0, 0)))
image_handler.add_image(tmp, "cell_3")
tmp = pygame.image.load(graphics_path + "hextile4_.png").convert()
tmp.set_colorkey(tmp.get_at((0, 0)))
image_handler.add_image(tmp, "cell_4")
tmp = pygame.image.load(graphics_path + " | tmp = pygame.image.load(graphics_path + "hextile_.png").convert()
tmp.set_colorkey(tmp.get_at((0, 0)))
image_handler.add_image(tmp, "cell_2")
tmp = pygame.image.load(graphics_path + "hextile3_.png").convert() | random_line_split |
gamemenu.py | quer/)
#
#------------------------------------------------------------------------
class TGameMenu:
def __init__(self, screen, bg_image, logo1, menu_items, start_vec, spacing=50):
# Currently selected menuitem's index
self.pos = 0
# List of menuitems
self.menu_items = menu_items
... |
if self.menu_items[self.pos][2][1] > self.menu_items[self.pos][2][2][1]:
self.menu_items[self.pos][2][1] = self.menu_items[self.pos][2][2][1]
if self.menu_items[self.pos][2][0] == "value_bool_editor":
self.menu_items[self.pos][2][1] = not self.men... | self.menu_items[self.pos][2][1] = self.menu_items[self.pos][2][2][0] | conditional_block |
gamemenu.py | quer/)
#
#------------------------------------------------------------------------
class TGameMenu:
def __init__(self, screen, bg_image, logo1, menu_items, start_vec, spacing=50):
# Currently selected menuitem's index
self.pos = 0
# List of menuitems
self.menu_items = menu_items
... |
def get_selection(self, text=None):
"""
Render the menu as long as user selects a menuitem
text -> optional text to be rendered
"""
# Draw the items
self.draw_items(text)
# Create instance of pygame Clock
clock = pygame.time.Clock()
# Endl... | if len(self.menu_items[self.pos][2]) >= 2:
if self.menu_items[self.pos][2][0] == "value_int_editor":
self.menu_items[self.pos][2][1] += dv
if len(self.menu_items[self.pos][2]) >= 3:
if self.menu_items[self.pos][2][1] < self.menu_items[self.pos][2][2][0]:
... | identifier_body |
comments.js | Gm.Comments = function() {
var last_click_on_comment = 0;
return {
name: 'Comments',
ContentInit: function() {
$('.comments form').sisyphus({
timeout: 30,
onSave: Gm.Comments.DraftSaved,
});
$('.spoiler').click(function(e) {
$(e.currentTarget).find('.spoiler-cont... |
},
FullPageInit: function() {
this.ContentInit();
},
}; // return
}();
Gm.registerModule(Gm.Comments);
| {
$(".draft-feedback").html(
"(" + now.toLocaleTimeString() + ") Borrador guardado");
} | conditional_block |
comments.js | Gm.Comments = function() {
var last_click_on_comment = 0;
| ContentInit: function() {
$('.comments form').sisyphus({
timeout: 30,
onSave: Gm.Comments.DraftSaved,
});
$('.spoiler').click(function(e) {
$(e.currentTarget).find('.spoiler-content').toggle();
e.stopPropagation();
});
$('.fullquote-opener').click(func... | return {
name: 'Comments',
| random_line_split |
compare_xz.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn decode_xz_lzmars(compressed: &[u8]) -> Result<Vec<u8>> {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)... | Ok(decomp)
}
fuzz_target!(|data: &[u8]| {
let result_lzmars = decode_xz_lzmars(data);
let result_xz2 = decode_xz_xz2(data);
match (result_lzmars, result_xz2) {
(Err(_), Err(_)) => (), // both failed, so behavior matches
(Ok(_), Err(_)) => panic!("lzma-rs succeeded but xz2 failed"),
... | random_line_split | |
compare_xz.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn decode_xz_lzmars(compressed: &[u8]) -> Result<Vec<u8>> |
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
// create new XZ decompression stream with 8Gb memory limit and checksum verification disabled
let xz_stream =
stream::Stream::new_stream_decoder(8 * 1024 *... | {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)?;
Ok(decomp)
} | identifier_body |
compare_xz.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn | (compressed: &[u8]) -> Result<Vec<u8>> {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)?;
Ok(decomp)
}
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
let mut d... | decode_xz_lzmars | identifier_name |
0030_auto_20150806_2136.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import wagtail.core.blocks
import wagtail.core.fields
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('articles', '0029_auto_20150811_1924'),
]
operations = [
migrations.AddField(
model_name='chapteredarticlepage',
name='end_notes',
field=wagtail.core.fields.StreamField([('end_note', wagtail.core.blocks.StructBlock([(b'identifier', wagtail.c... | identifier_body | |
0030_auto_20150806_2136.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import wagtail.core.blocks
import wagtail.core.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0029_auto_20150811_1924'),
]
operations = [
migrations.Add... | model_name='chapteredarticlepage',
name='end_notes',
field=wagtail.core.fields.StreamField([('end_note', wagtail.core.blocks.StructBlock([(b'identifier', wagtail.core.blocks.CharBlock()), (b'text', wagtail.core.blocks.TextBlock())]))], null=True, blank=True),
),
migra... | random_line_split | |
0030_auto_20150806_2136.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import wagtail.core.blocks
import wagtail.core.fields
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('articles', '0029_auto_20150811_1924'),
]
operations = [
migrations.AddField(
model_name='chapteredarticlepage',
name='end_notes',
field=wagtail.core.fields.StreamField([('end_note', wagtail.core.blocks.StructBlo... | Migration | identifier_name |
upload.py | #!/usr/bin/env python3
from argparse import ArgumentParser
from os import environ
from sys import argv
from requests import put
def read_file(file_path): # pragma: no cover
|
def upload(file_path, repository, repository_path, url, username, password):
url = f'{url}/repository/{repository}/{repository_path}'
data = read_file(file_path)
headers = {'Content-Type': 'application/octet-stream'}
response = put(url, data=data, headers=headers, auth=(username, password))
if re... | with open(file_path, 'rb') as f:
return f.read() | identifier_body |
upload.py | #!/usr/bin/env python3
from argparse import ArgumentParser
from os import environ
from sys import argv
from requests import put
def read_file(file_path): # pragma: no cover
with open(file_path, 'rb') as f:
return f.read()
def upload(file_path, repository, repository_path, url, username, password):
... | (file_path, repository, repository_path, url, username, password):
print(upload(file_path, repository, repository_path, url, username, password))
if __name__ == '__main__': # pragma: no cover
main(**parse_args(argv[1:]).__dict__)
| main | identifier_name |
upload.py | #!/usr/bin/env python3 | from os import environ
from sys import argv
from requests import put
def read_file(file_path): # pragma: no cover
with open(file_path, 'rb') as f:
return f.read()
def upload(file_path, repository, repository_path, url, username, password):
url = f'{url}/repository/{repository}/{repository_path}'
... | from argparse import ArgumentParser | random_line_split |
upload.py | #!/usr/bin/env python3
from argparse import ArgumentParser
from os import environ
from sys import argv
from requests import put
def read_file(file_path): # pragma: no cover
with open(file_path, 'rb') as f:
return f.read()
def upload(file_path, repository, repository_path, url, username, password):
... | main(**parse_args(argv[1:]).__dict__) | conditional_block | |
unverified-certificate.test.ts | /*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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... | },
],
};
const testCasesRequest = {
valid: [
{
code: `
const request = require('request');
var socket = request.get({
url: 'https://self-signed.badssl.com',
secureProtocol: 'TLSv1_2_method',
rejectUnauthorized: true
}); // Compliant
`,
... | }),
},
], | random_line_split |
sanitize.js | /*
//
// BEGIN SONGBIRD GPL
//
// This file is part of the Songbird web player.
//
// Copyright(c) 2005-2008 POTI, Inc.
// http://songbirdnest.com
//
// This file may be licensed under the terms of of the
// GNU General Public License Version 2 (the "GPL").
//
// Software distributed under the License is distributed
/... |
},
onSanitizerStartup: function() {
Sanitizer.onStartup();
Sanitizer.prefs.setBoolPref(Sanitizer.prefDidShutdown, false);
},
onSanitizerShutdown: function() {
Sanitizer.onShutdown();
},
};
window.addEventListener('load', gSongbirdSanitize.onLoad, false);
}
| {
this.onSanitizerShutdown();
} | conditional_block |
sanitize.js | /*
//
// BEGIN SONGBIRD GPL
//
// This file is part of the Songbird web player.
//
// Copyright(c) 2005-2008 POTI, Inc.
// http://songbirdnest.com
//
// This file may be licensed under the terms of of the
// GNU General Public License Version 2 (the "GPL").
//
// Software distributed under the License is distributed
/... | ()
{
return webLibrary.length > 0;
}
};
if (typeof(gSanitizePromptDialog) != "undefined") {
var oldfn = gSanitizePromptDialog.sanitize;
gSanitizePromptDialog.sanitize = function() {
oldfn.call(gSanitizePromptDialog);
if (document.getElementById("... | canClear | identifier_name |
sanitize.js | /*
//
// BEGIN SONGBIRD GPL
//
// This file is part of the Songbird web player.
//
// Copyright(c) 2005-2008 POTI, Inc.
// http://songbirdnest.com
//
// This file may be licensed under the terms of of the
// GNU General Public License Version 2 (the "GPL").
//
// Software distributed under the License is distributed
/... |
};
if (typeof(gSanitizePromptDialog) != "undefined") {
var oldfn = gSanitizePromptDialog.sanitize;
gSanitizePromptDialog.sanitize = function() {
oldfn.call(gSanitizePromptDialog);
if (document.getElementById("sanitize.mediaHistory").checked) {
Sanitizer.proto... | {
return webLibrary.length > 0;
} | identifier_body |
sanitize.js | /*
//
// BEGIN SONGBIRD GPL
//
// This file is part of the Songbird web player.
//
// Copyright(c) 2005-2008 POTI, Inc.
// http://songbirdnest.com
//
// This file may be licensed under the terms of of the
// GNU General Public License Version 2 (the "GPL").
//
// Software distributed under the License is distributed
/... | Sanitizer.prototype.items["mediaHistory"].clear();
}
};
}
},
reset: function() {
window.removeEventListener('unload', gSongbirdSanitize.onUnload, false);
if (document.documentElement.getAttribute("windowtype") == "Songbird:Core") {
this.onSanitizerShutdow... | if (typeof(gSanitizePromptDialog) != "undefined") {
var oldfn = gSanitizePromptDialog.sanitize;
gSanitizePromptDialog.sanitize = function() {
oldfn.call(gSanitizePromptDialog);
if (document.getElementById("sanitize.mediaHistory").checked) { | random_line_split |
bok_choy.py | LMS.
Bok Choy uses two different settings files:
1. test_static_optimized is used when invoking collectstatic
2. bok_choy is used when running the tests
Note: it isn't possible to have a single settings file, because Django doesn't
support both generating static assets to a directory and also serving static
from the... | LOG_DIR = (TEST_ROOT / "log").abspath()
# Configure modulestore to use the test folder within the repo
update_module_store_settings(
MODULESTORE,
module_store_options={
'fs_root': (TEST_ROOT / "data").abspath(),
},
xml_store_options={
'data_dir': (TEST_ROOT / "data").abspath(),
},
... |
######################### Testing overrides ####################################
# Redirect to the test_root folder within the repo
GITHUB_REPO_ROOT = (TEST_ROOT / "data").abspath() | random_line_split |
bok_choy.py | LMS.
Bok Choy uses two different settings files:
1. test_static_optimized is used when invoking collectstatic
2. bok_choy is used when running the tests
Note: it isn't possible to have a single settings file, because Django doesn't
support both generating static assets to a directory and also serving static
from the... |
# TODO: TNL-6546: Remove this waffle and flag code.
from django.db.utils import ProgrammingError
from waffle.models import Flag
try:
flag, created = Flag.objects.get_or_create(name='unified_course_view')
WAFFLE_OVERRIDE = True
except ProgrammingError:
# during initial reset_db, the table for the flag does... | HELP_TOKENS_BOOKS = {
'learner': 'http://edx.readthedocs.io/projects/edx-guide-for-students',
'course_author': 'http://edx.readthedocs.io/projects/edx-partner-course-staff',
} | conditional_block |
custom.js |
// https://github.com/jgthms/bulma/issues/238 thanks!
document.getElementById("nav-toggle").addEventListener("click", toggleNav);
function toggleNav() {
var nav = document.getElementById("nav-menu");
var className = nav.getAttribute("class");
if(className == "nav-right nav-menu") {
nav.class... |
}, false);
function searchHandler() {
var searchInput = document.getElementById('search-text');
var text = searchInput.value;
// add site:example.com in the placeholder
window.location.href = "https://www.google.com/search?q=site:wangxin1248.github.io " + text;
} | { searchHandler(); } | conditional_block |
custom.js |
// https://github.com/jgthms/bulma/issues/238 thanks!
document.getElementById("nav-toggle").addEventListener("click", toggleNav);
function toggleNav() |
// for the random quote in the header
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "/quotes.txt", true);
txtFile.onreadystatechange = function () {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) {
allText = txtFile.responseText;
lines = txtFile.resp... | {
var nav = document.getElementById("nav-menu");
var className = nav.getAttribute("class");
if(className == "nav-right nav-menu") {
nav.className = "nav-right nav-menu is-active";
} else {
nav.className = "nav-right nav-menu";
}
} | identifier_body |
custom.js |
// https://github.com/jgthms/bulma/issues/238 thanks!
document.getElementById("nav-toggle").addEventListener("click", toggleNav);
function toggleNav() {
var nav = document.getElementById("nav-menu");
var className = nav.getAttribute("class");
if(className == "nav-right nav-menu") {
nav.class... | () {
var searchInput = document.getElementById('search-text');
var text = searchInput.value;
// add site:example.com in the placeholder
window.location.href = "https://www.google.com/search?q=site:wangxin1248.github.io " + text;
} | searchHandler | identifier_name |
custom.js | // https://github.com/jgthms/bulma/issues/238 thanks!
document.getElementById("nav-toggle").addEventListener("click", toggleNav);
function toggleNav() {
var nav = document.getElementById("nav-menu");
var className = nav.getAttribute("class");
if(className == "nav-right nav-menu") {
nav.classNa... | var text = searchInput.value;
// add site:example.com in the placeholder
window.location.href = "https://www.google.com/search?q=site:wangxin1248.github.io " + text;
} | random_line_split | |
DifferentEmojiDatabaseTest.ts | import { UiFinder, Waiter } from '@ephox/agar';
import { before, describe, it } from '@ephox/bedrock-client';
import { Arr } from '@ephox/katamari';
import { McEditor, TinyUiActions } from '@ephox/mcagar';
import { SugarBody } from '@ephox/sugar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Edi... |
return '';
};
describe('browser.tinymce.plugins.emoticons.DifferentEmojiDatabaseTest', () => {
before(() => {
Plugin();
Theme();
});
const pTestEditorWithSettings = async (categories: string[], databaseUrl: string) => {
const editor = await McEditor.pFromSettings<Editor>({
plugins: 'emotico... | {
return m[1];
} | conditional_block |
DifferentEmojiDatabaseTest.ts | import { UiFinder, Waiter } from '@ephox/agar';
import { before, describe, it } from '@ephox/bedrock-client';
import { Arr } from '@ephox/katamari';
import { McEditor, TinyUiActions } from '@ephox/mcagar';
import { SugarBody } from '@ephox/sugar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Edi... | await Waiter.pTryUntil(
'Wait for emojis to load',
() => UiFinder.notExists(SugarBody.body(), '.tox-spinner')
);
const tabs = UiFinder.findAllIn(SugarBody.body(), '[role="tab"]');
const actualCategories = Arr.map(tabs, (elm) => elm.dom.textContent);
assert.deepEqual(actualCategories, ca... | emoticons_database_id: 'tinymce.plugins.emoticons.' + getFilename(databaseUrl)
});
TinyUiActions.clickOnToolbar(editor, 'button');
await TinyUiActions.pWaitForDialog(editor); | random_line_split |
PanelUpdater.ts | module minerva.controls.panel {
export interface IPanelUpdaterAssets extends core.IUpdaterAssets, measure.IInput, arrange.IInput, processup.IInput, render.IInput {
}
export class PanelUpdater extends core.Updater {
assets: IPanelUpdaterAssets;
tree: PanelUpdaterTree;
init (... |
}
export module reactTo {
export function zIndex (updater: core.Updater, oldValue: number, newValue: number) {
var vp = <PanelUpdater>updater.tree.visualParent;
if (vp)
vp.tree.zSorted = null;
}
}
} | {
this.tree.children = children;
return this;
} | identifier_body |
PanelUpdater.ts | module minerva.controls.panel {
export interface IPanelUpdaterAssets extends core.IUpdaterAssets, measure.IInput, arrange.IInput, processup.IInput, render.IInput {
}
export class PanelUpdater extends core.Updater {
assets: IPanelUpdaterAssets;
tree: PanelUpdaterTree;
init (... | } | if (vp)
vp.tree.zSorted = null;
}
}
| random_line_split |
PanelUpdater.ts | module minerva.controls.panel {
export interface IPanelUpdaterAssets extends core.IUpdaterAssets, measure.IInput, arrange.IInput, processup.IInput, render.IInput {
}
export class PanelUpdater extends core.Updater {
assets: IPanelUpdaterAssets;
tree: PanelUpdaterTree;
init (... | (updater: core.Updater, oldValue: number, newValue: number) {
var vp = <PanelUpdater>updater.tree.visualParent;
if (vp)
vp.tree.zSorted = null;
}
}
} | zIndex | identifier_name |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R,... | }
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&self) -> MAR {
let bits = {
const MASK: u32 = 4294967295;
const... | self.w | random_line_split |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R,... | (&mut self) -> _MAW {
_MAW { w: self }
}
}
| ma | identifier_name |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R,... |
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&mut self) -> _MAW {
_MAW { w: self }
}
}
| {
self.bits = bits;
self
} | identifier_body |
invoke-function.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | (client: &Client, arn: &str) -> Result<(), Error> {
client.invoke().function_name(arn).send().await?;
println!("Invoked function.");
Ok(())
}
// snippet-end:[lambda.rust.invoke-function]
/// Invokes a Lambda function by its ARN.
/// # Arguments
///
/// * `-a ARN` - The ARN of the Lambda function.
/// * `... | run_function | identifier_name |
invoke-function.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
| struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The AWS Lambda function's Amazon Resource Name (ARN).
#[structopt(short, long)]
arn: String,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
// ... | use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)] | random_line_split |
invoke-function.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
run_function(&client, &arn).await
}
| {
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Lambda function ARN: {}", arn);
println!();
} | conditional_block |
Toaster.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as cx from 'classnames';
import * as ReactTransitionGroup from 'react-transition-group/TransitionGroup';
import { findDOMNode, Children } from '../utils';
import { warn } from '../utils/log';
import { TransitionWrapper } from '../Transition... | transitionStyles?: TransitionWrapper.TransitionStyles;
/** duration of enter transition in milliseconds (used by `TransitionWrapper`) */
transitionEnterTimeout: number;
/** duration of leave transition in milliseconds (used by `TransitionWrapper`) */
transitionLeaveTimeout: number;
id?: string;
className?... | /** object with style for each transition event (used by `TransitionWrapper`) */ | random_line_split |
Toaster.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as cx from 'classnames';
import * as ReactTransitionGroup from 'react-transition-group/TransitionGroup';
import { findDOMNode, Children } from '../utils';
import { warn } from '../utils/log';
import { TransitionWrapper } from '../Transition... |
}
componentDidUpdate(prevProps: Toaster.Props) {
if (prevProps.attachTo !== this.props.attachTo) {
warn('You can\'t change "attachTo" prop after the first render!');
}
this.renderToaster();
}
}
| {
return this.getToaster();
} | conditional_block |
Toaster.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as cx from 'classnames';
import * as ReactTransitionGroup from 'react-transition-group/TransitionGroup';
import { findDOMNode, Children } from '../utils';
import { warn } from '../utils/log';
import { TransitionWrapper } from '../Transition... | extends React.Component<Toaster.Props> {
private toaster: HTMLElement | null = null;
static defaultProps: ToasterDefaultProps = {
transitionGroup: {},
position: 'top-right'
};
componentWillMount() {
this.appendToaster();
this.renderToaster();
}
componentDidMount() {
const node = this... | Toaster | identifier_name |
experimentService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
export interface IExperimentActionPromptCommand {
text: string | { [key: string]: string };
externalLink?: string;
curatedExtensionsKey?: string;
curatedExtensionsList?: string[];
}
export interface IExperiment {
id: string;
enabled: boolean;
state: ExperimentState;
action?: IExperimentAction;
}
export inter... | } | random_line_split |
licenses.py | # -*- coding: utf-8 -*-
# Verify that each license added to this list has 'OSI Approved?: Y' on https://spdx.org/licenses/
LICENSE_ALIASES = dict((key.lower(), value) for (key, value) in {
'https://polymer.github.io/LICENSE.txt': 'BSD-3-Clause', # Verified on 26-Sep-2016
'http://polymer.github.io/LICENSE.txt':... | er = LICENSE_ALIASES.get(license_name.lower(), license_name.lower()).lower()
return SPDX_IDENTIFIERS.get(spdx_identifier, None)
| identifier_body | |
licenses.py | # -*- coding: utf-8 -*-
# Verify that each license added to this list has 'OSI Approved?: Y' on https://spdx.org/licenses/
LICENSE_ALIASES = dict((key.lower(), value) for (key, value) in {
'https://polymer.github.io/LICENSE.txt': 'BSD-3-Clause', # Verified on 26-Sep-2016
'http://polymer.github.io/LICENSE.txt':... | ):
spdx_identifier = LICENSE_ALIASES.get(license_name.lower(), license_name.lower()).lower()
return SPDX_IDENTIFIERS.get(spdx_identifier, None)
| (license_name | identifier_name |
licenses.py | # -*- coding: utf-8 -*-
# Verify that each license added to this list has 'OSI Approved?: Y' on https://spdx.org/licenses/
LICENSE_ALIASES = dict((key.lower(), value) for (key, value) in {
'https://polymer.github.io/LICENSE.txt': 'BSD-3-Clause', # Verified on 26-Sep-2016
'http://polymer.github.io/LICENSE.txt':... | 'Historic Permission Notice and Disclaimer': 'HPND',
'IBM Public License v1.0': 'IPL-1.0',
'Intel Open Source License': 'Intel',
'IPA Font License': 'IPA',
'ISC License': 'ISC',
'LaTeX Project Public License v1.3c': 'LPPL-1.3c',
'Licence Libre du Québec – Permissive version 1.1': 'LiLiQ-P-1.... | 'GNU Lesser General Public License v3.0 only': 'LGPL-3.0',
'GNU Library General Public License v2 only': 'LGPL-2.0', | random_line_split |
summary_key_matcher.py | from ert.cwrap import CWrapper, BaseCClass
from ert.enkf import ENKF_LIB
from ert.util import StringList
class SummaryKeyMatcher(BaseCClass):
def __init__(self):
c_ptr = SummaryKeyMatcher.cNamespace().alloc()
super(SummaryKeyMatcher, self).__init__(c_ptr)
def addSummaryKey(self, key):
... |
def isRequired(self, key):
""" @rtype: bool """
return SummaryKeyMatcher.cNamespace().is_required(self, key)
def keys(self):
""" @rtype: StringList """
return SummaryKeyMatcher.cNamespace().keys(self)
def free(self):
SummaryKeyMatcher.cNamespace().free(self)
cwr... | return SummaryKeyMatcher.cNamespace().match_key(self, key) | identifier_body |
summary_key_matcher.py | from ert.cwrap import CWrapper, BaseCClass
from ert.enkf import ENKF_LIB
from ert.util import StringList
class | (BaseCClass):
def __init__(self):
c_ptr = SummaryKeyMatcher.cNamespace().alloc()
super(SummaryKeyMatcher, self).__init__(c_ptr)
def addSummaryKey(self, key):
assert isinstance(key, str)
return SummaryKeyMatcher.cNamespace().add_key(self, key)
def __len__(self):
re... | SummaryKeyMatcher | identifier_name |
summary_key_matcher.py | from ert.cwrap import CWrapper, BaseCClass
from ert.enkf import ENKF_LIB
from ert.util import StringList
| super(SummaryKeyMatcher, self).__init__(c_ptr)
def addSummaryKey(self, key):
assert isinstance(key, str)
return SummaryKeyMatcher.cNamespace().add_key(self, key)
def __len__(self):
return SummaryKeyMatcher.cNamespace().size(self)
def __contains__(self, key):
return... | class SummaryKeyMatcher(BaseCClass):
def __init__(self):
c_ptr = SummaryKeyMatcher.cNamespace().alloc()
| random_line_split |
main.rs | use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum Instruction {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruct... | *entry /= 2;
head + 1
},
Instruction::Triple(r) => {
let entry = computer.entry(r).or_insert(0);
*entry *= 3;
head + 1
},
Instruction::Increment(r) => {
let entry = computer.entry(r).or_insert(0);
*entry ... | match instructions[head as usize] {
Instruction::Half(r) => {
let entry = computer.entry(r).or_insert(0); | random_line_split |
main.rs | use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum Instruction {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruct... |
else { head + 1 }
},
Instruction::JumpIfOne(r, offset) => {
if *computer.get(&r).unwrap_or(&0) == 1 { head + offset }
else { head + 1 }
}
}
}
fn execute_program(computer: &mut Computer, program: &Vec<Instruction>) {
let mut head: i32 = 0;
loop {
... | { head + offset } | conditional_block |
main.rs | use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum | {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruction(computer: &mut Computer, instructions: &Vec<Instruction>, head: i32) -> i32 {
match instructions[head as usize] {
Instruction::Half(r) =>... | Instruction | identifier_name |
client.py | # Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
return weighted_test_cases
def run_test(args):
test_cases = _parse_weighted_test_cases(args.test_cases)
test_servers = args.server_addresses.split(',')
# Propagate any client exceptions with a queue
exception_queue = queue.Queue()
stop_event = threading.Event()
hist = histogram.Histogram(1, 1)
runner... | name, weight = test_case_arg.split(':', 1)
test_case = _test_case_from_arg(name)
weighted_test_cases[test_case] = int(weight) | conditional_block |
client.py | # Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | '--test_cases',
help='comma seperated list of testcase:weighting of tests to run',
default='large_unary:100',
type=str)
parser.add_argument(
'--test_duration_secs',
help='number of seconds to run the stress test',
default=-1, type=int)
parser.add_argument(
'--num_chan... | '--server_addresses',
help='comma seperated list of hostname:port to run servers on',
default='localhost:8080', type=str)
parser.add_argument( | random_line_split |
client.py | # Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | (test_case_arg):
for test_case in methods.TestCase:
if test_case_arg == test_case.value:
return test_case
else:
raise ValueError('No test case {}!'.format(test_case_arg))
def _parse_weighted_test_cases(test_case_args):
weighted_test_cases = {}
for test_case_arg in test_case_args.split(','):
... | _test_case_from_arg | identifier_name |
client.py | # Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | exception_queue, stop_event)
runners.append(runner)
for runner in runners:
runner.start()
try:
timeout_secs = args.test_duration_secs
if timeout_secs < 0:
timeout_secs = None
raise exception_queue.get(block=True, timeout=timeout_secs)
except q... | test_cases = _parse_weighted_test_cases(args.test_cases)
test_servers = args.server_addresses.split(',')
# Propagate any client exceptions with a queue
exception_queue = queue.Queue()
stop_event = threading.Event()
hist = histogram.Histogram(1, 1)
runners = []
server = metrics_pb2.beta_create_MetricsServ... | identifier_body |
share_tensor_test.py | # third party
# third party
import numpy as np
import pytest
# syft absolute
# absolute
from syft.core.tensor.smpc.share_tensor import ShareTensor
@pytest.mark.smpc
def | () -> None:
share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np.array([[21, 32], [-54, 89]], dtype=np.int32)
share.child = data
exp_res1 = np.array([[False, False], [True, False]], dtype=np.bool_)
res = share.bit_extraction(31).child
assert (res == exp_res1).all()
exp_r... | test_bit_extraction | identifier_name |
share_tensor_test.py | # third party
# third party
import numpy as np
import pytest
# syft absolute
# absolute
from syft.core.tensor.smpc.share_tensor import ShareTensor
@pytest.mark.smpc
def test_bit_extraction() -> None:
share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np.array([[21, 32], [-54, 89]], dtype=np... | share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np.array([[21, 32], [-54, 89]], dtype=np.int32)
share.child = data
with pytest.raises(Exception):
share >> 33
with pytest.raises(Exception):
share >> -1 | identifier_body | |
share_tensor_test.py | # third party
# third party
import numpy as np
import pytest
# syft absolute
# absolute
from syft.core.tensor.smpc.share_tensor import ShareTensor
@pytest.mark.smpc
def test_bit_extraction() -> None:
share = ShareTensor(rank=0, parties_info=[], ring_size=2**32)
data = np.array([[21, 32], [-54, 89]], dtype=np... | share >> 33
with pytest.raises(Exception):
share >> -1 | random_line_split | |
host_common.rs | //
// Copyright 2021 The Project Oak 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 o... |
pub fn wait_for_signal(&self) -> Signal {
for _ in 0..SIGNAL_REPS {
let signal = Signal::from(unsafe { *self.signal });
if signal != Signal::Idle {
return signal;
}
thread::sleep(Duration::from_millis(SIGNAL_WAIT));
}
panic!("c... | random_line_split | |
host_common.rs | //
// Copyright 2021 The Project Oak 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 o... | (shared_ro: cptr, shared_rw: cptr, index: usize) -> Self {
assert!(index == HUNTER_SIGNAL_INDEX || index == RUNNER_SIGNAL_INDEX);
Self {
shared_ro,
shared_rw,
index,
signal: unsafe { shared_rw.add(index) as *mut u8 },
}
}
pub fn wait_for_s... | new | identifier_name |
host_common.rs | //
// Copyright 2021 The Project Oak 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 o... |
// Aligns to next largest page boundary, unless ptr is already aligned.
pub fn page_align(ptr: i64) -> i64 {
((ptr - 1) & !(PAGE_SIZE - 1)) + PAGE_SIZE
}
| {
let cname = CString::new(name).unwrap();
let (open_flags, map_flags) = match read_only {
false => (O_RDWR, PROT_READ | PROT_WRITE),
true => (O_RDONLY, PROT_READ),
};
unsafe {
let fd = libc::shm_open(cname.as_ptr(), open_flags, S_IRUSR | S_IWUSR);
if fd == -1 {
... | identifier_body |
host_common.rs | //
// Copyright 2021 The Project Oak 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 o... |
if !self.shared_rw.is_null()
&& libc::munmap(self.shared_rw, READ_WRITE_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_rw");
}
}
}
}
// Uses the libc POSIX API to map in a shared memory buffer.
pub fn map_buffer(aligned_ptr: i64, name:... | {
println!("munmap failed for shared_ro");
} | conditional_block |
publication_counts.py | import logging
import pandas as pd
from catalog.core.search_indexes import PublicationDocSearch
from ..data_access import data_cache, IncludedStatistics
from query import Query
logger = logging.getLogger(__name__)
def | (df):
return df.groupby(['year_published']) \
.agg(dict(title='count', is_archived='sum', has_formal_description='sum',
has_odd='sum', has_visual_documentation='sum')) \
.rename(columns={
'title': 'count',
'is_archived': IncludedStatistics.code_availability_count.na... | _create_count_dataframe | identifier_name |
publication_counts.py | import logging
import pandas as pd
from catalog.core.search_indexes import PublicationDocSearch
from ..data_access import data_cache, IncludedStatistics
from query import Query
logger = logging.getLogger(__name__)
def _create_count_dataframe(df):
|
def create_publication_counts_dataset(query: Query):
publication_ids = [p.id for p in
PublicationDocSearch().find(q=query.search, facet_filters=query.filters).source(['id']).scan()]
publication_matches = data_cache.publications.loc[publication_ids]
publication_match_counts = _creat... | return df.groupby(['year_published']) \
.agg(dict(title='count', is_archived='sum', has_formal_description='sum',
has_odd='sum', has_visual_documentation='sum')) \
.rename(columns={
'title': 'count',
'is_archived': IncludedStatistics.code_availability_count.name,
... | identifier_body |
publication_counts.py | from ..data_access import data_cache, IncludedStatistics
from query import Query
logger = logging.getLogger(__name__)
def _create_count_dataframe(df):
return df.groupby(['year_published']) \
.agg(dict(title='count', is_archived='sum', has_formal_description='sum',
has_odd='sum', has_vis... | import logging
import pandas as pd
from catalog.core.search_indexes import PublicationDocSearch | random_line_split | |
read_sqs_queue.py | #!/usr/bin/env python
'''Check a queue and get times and info for messages in q'''
import sys
import os
import logging
import json
import datetime
import boto.sqs as sqs
QUEUE_OAI_HARVEST = os.environ.get('QUEUE_OAI_HARVEST', 'OAI_harvest')
QUEUE_OAI_HARVEST_ERR = os.environ.get('QUEUE_OAI_HARVEST_ERR', 'OAI_harvest_e... | if len(sys.argv) < 2:
print 'Usage: read_sqs_queue.py <queue_name>'
main(sys.argv) | print msg_dict
print '\n\n'
msgs = q_harvesting.get_messages(num_messages=10, visibility_timeout=10, attributes='All')
if __name__=="__main__": | random_line_split |
read_sqs_queue.py | #!/usr/bin/env python
'''Check a queue and get times and info for messages in q'''
import sys
import os
import logging
import json
import datetime
import boto.sqs as sqs
QUEUE_OAI_HARVEST = os.environ.get('QUEUE_OAI_HARVEST', 'OAI_harvest')
QUEUE_OAI_HARVEST_ERR = os.environ.get('QUEUE_OAI_HARVEST_ERR', 'OAI_harvest_e... |
if __name__=="__main__":
if len(sys.argv) < 2:
print 'Usage: read_sqs_queue.py <queue_name>'
main(sys.argv)
| for m in msgs:
msg_dict = json.loads(m.get_body())
print 'ID:', m.id, '\n'
sent_dt = datetime.datetime.fromtimestamp(float(m.attributes['SentTimestamp'])/1000)
print 'SENT AT: ', sent_dt
print 'IN QUEUE FOR:', datetime.datetime.now()-sent_dt
print ... | conditional_block |
read_sqs_queue.py | #!/usr/bin/env python
'''Check a queue and get times and info for messages in q'''
import sys
import os
import logging
import json
import datetime
import boto.sqs as sqs
QUEUE_OAI_HARVEST = os.environ.get('QUEUE_OAI_HARVEST', 'OAI_harvest')
QUEUE_OAI_HARVEST_ERR = os.environ.get('QUEUE_OAI_HARVEST_ERR', 'OAI_harvest_e... | (args):
q_name = args[1]
q_harvesting = SQS_CONNECTION.get_queue(q_name)
msgs = q_harvesting.get_messages(num_messages=10, visibility_timeout=10, attributes='All') #copied from boto implementation of save_to_file
while(msgs):
for m in msgs:
msg_dict = json.loads(m.get_body())
... | main | identifier_name |
read_sqs_queue.py | #!/usr/bin/env python
'''Check a queue and get times and info for messages in q'''
import sys
import os
import logging
import json
import datetime
import boto.sqs as sqs
QUEUE_OAI_HARVEST = os.environ.get('QUEUE_OAI_HARVEST', 'OAI_harvest')
QUEUE_OAI_HARVEST_ERR = os.environ.get('QUEUE_OAI_HARVEST_ERR', 'OAI_harvest_e... |
if __name__=="__main__":
if len(sys.argv) < 2:
print 'Usage: read_sqs_queue.py <queue_name>'
main(sys.argv)
| q_name = args[1]
q_harvesting = SQS_CONNECTION.get_queue(q_name)
msgs = q_harvesting.get_messages(num_messages=10, visibility_timeout=10, attributes='All') #copied from boto implementation of save_to_file
while(msgs):
for m in msgs:
msg_dict = json.loads(m.get_body())
print '... | identifier_body |
exceptions.py | # -*- coding: utf-8 -*-
#
##################################################################################
#
# This program is part of OSRFramework. 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 3 of... | (self, platform, *args, **kwargs):
msg = """
[*] Warning:\t{}. Details:
No valid credentials provided for '{}'.
Update the configuration file at: '{}'.
""".format(
self.__class__.__name__,
platform,
os.path.join(configuration.getCon... | __init__ | identifier_name |
exceptions.py | # -*- coding: utf-8 -*-
#
##################################################################################
#
# This program is part of OSRFramework. 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 3 of... | msg = """
[*] Error:\t{}. Details:
{}.
{}""".format(
self.__class__.__name__,
original_message,
"The wrapper may be missing an attribute like self.creds empty list in its constructor."
)
OSRFrameworkError.__init__(self, msg)
sel... | identifier_body | |
exceptions.py | # -*- coding: utf-8 -*-
#
##################################################################################
#
# This program is part of OSRFramework. 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 3 of... | platform,
mode
)
OSRFrameworkError.__init__(self, msg)
self.generic = "A wrapper has tried to launch a mode which is not yet implemented. This error should not be happening unless you have added a new method out of the standard ones for mailfy, phonefy, searchfy or usufy.... | [*] Error:\t{}. Details:
The '{}' wrapper has tried to call 'self.do_{}(...)'.
The method seems be implemented wrongly or not implemented.""".format(
self.__class__.__name__, | random_line_split |
test_base_output.py | # -*- coding: utf-8 -*-
#
# This tool helps you to rebase package to the latest version
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# 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
# he Free Software Foundation; either version 2 ... | (self):
"""
Test Output logger info
:return:
"""
info_results = OutputLogger.get_summary_info()
expect_dict = self.info_data
expect_dict.update(self.info_data2)
assert info_results == expect_dict
def test_base_output_patches(self):
"""
... | test_base_output_info | identifier_name |
test_base_output.py | # -*- coding: utf-8 -*-
#
# This tool helps you to rebase package to the latest version
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# 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
# he Free Software Foundation; either version 2 ... | OutputLogger.set_build_data('new', self.new_rpm_data)
def test_base_output_global(self):
expect_dict = self.info_data
expect_dict.update(self.info_data2)
build_dict = {'old': self.old_rpm_data,
'new': self.new_rpm_data}
expected_result = {'build': build... | OutputLogger.set_info_text('Next Information', 'some another information text')
OutputLogger.set_patch_output('Patches:', self.patches_data)
OutputLogger.set_build_data('old', self.old_rpm_data) | random_line_split |
test_base_output.py | # -*- coding: utf-8 -*-
#
# This tool helps you to rebase package to the latest version
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# 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
# he Free Software Foundation; either version 2 ... |
def test_base_output_builds_old(self):
"""
Test Output logger old builds
:return:
"""
build_results = OutputLogger.get_build('old')
assert build_results == self.old_rpm_data
def test_base_output_builds_new(self):
"""
Test Output logger new buil... | """
Test Output logger patches
:return:
"""
patch_results = OutputLogger.get_patches()
expected_patches = self.patches_data
assert patch_results == expected_patches | identifier_body |
test_base_output.py | # -*- coding: utf-8 -*-
#
# This tool helps you to rebase package to the latest version
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# 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
# he Free Software Foundation; either version 2 ... |
def test_base_output_info(self):
"""
Test Output logger info
:return:
"""
info_results = OutputLogger.get_summary_info()
expect_dict = self.info_data
expect_dict.update(self.info_data2)
assert info_results == expect_dict
def test_base_output_pa... | assert value == expected_result[key] | conditional_block |
util.ts | import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
import type {SchemaCxt, SchemaObjCxt} from "."
import {_, getProperty, Code, Name, CodeGen} from "./codegen"
import {_Code} from "./codegen/code"
import type {Rule, ValidationRules} from "./rules"
// TODO refactor to use Set
export function t... |
export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {
const {opts, self} = it
if (!opts.strictSchema) return
if (typeof schema === "boolean") return
const rules = self.RULES.keywords
for (const key in schema) {
if (!rules[key]) checkStrictMode(it, `unknown keyword: "${k... | {
if (typeof schema == "boolean") return schema
if (Object.keys(schema).length === 0) return true
checkUnknownRules(it, schema)
return !schemaHasRules(schema, it.self.RULES.all)
} | identifier_body |
util.ts | import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
import type {SchemaCxt, SchemaObjCxt} from "."
import {_, getProperty, Code, Name, CodeGen} from "./codegen"
import {_Code} from "./codegen/code"
import type {Rule, ValidationRules} from "./rules"
// TODO refactor to use Set
export function t... |
}
type SomeEvaluated = EvaluatedProperties | EvaluatedItems
type MergeEvaluatedFunc<T extends SomeEvaluated> = (
gen: CodeGen,
from: Name | T,
to: Name | Exclude<T, true> | undefined,
toName?: typeof Name
) => Name | T
interface MakeMergeFuncArgs<T extends SomeEvaluated> {
mergeNames: (gen: CodeGen, from:... | {
f(xs)
} | conditional_block |
util.ts | import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
import type {SchemaCxt, SchemaObjCxt} from "."
import {_, getProperty, Code, Name, CodeGen} from "./codegen"
import {_Code} from "./codegen/code"
import type {Rule, ValidationRules} from "./rules"
// TODO refactor to use Set
export function t... | (it: SchemaCxt, schema: AnySchema = it.schema): void {
const {opts, self} = it
if (!opts.strictSchema) return
if (typeof schema === "boolean") return
const rules = self.RULES.keywords
for (const key in schema) {
if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`)
}
}
export function schem... | checkUnknownRules | identifier_name |
util.ts | import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
import type {SchemaCxt, SchemaObjCxt} from "."
import {_, getProperty, Code, Name, CodeGen} from "./codegen"
import {_Code} from "./codegen/code"
import type {Rule, ValidationRules} from "./rules"
// TODO refactor to use Set
export function t... | if (Object.keys(schema).length === 0) return true
checkUnknownRules(it, schema)
return !schemaHasRules(schema, it.self.RULES.all)
}
export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {
const {opts, self} = it
if (!opts.strictSchema) return
if (typeof schema === "boolean")... | if (typeof schema == "boolean") return schema | random_line_split |
dependency_format.rs | The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just ... | attempt_static | identifier_name | |
dependency_format.rs |
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. ... | ,
}
let mut formats = HashMap::new();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum... | {} | conditional_block |
dependency_format.rs | A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains on... | {
match m.find(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locati... | identifier_body | |
dependency_format.rs | your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependenc... | // Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_cr... | random_line_split | |
js.js | 'use strict';
let gulp = require('gulp');
let config = require('../config');
let $ = require('gulp-load-plugins')();
let _ = require('lodash');
let path = require('path');
let prefix = 'js';
let taskName = function(bundle) {
return prefix + '-' + bundle.name;
};
let bundles = config.js;
gulp.task(prefix, _.map(bun... | }; | random_line_split | |
utils.js | /* eslint-disable node/no-deprecated-api */
module.exports.pathBasename = pathBasename
module.exports.hasSuffix = hasSuffix
module.exports.serialize = serialize
module.exports.translate = translate
module.exports.stringToStream = stringToStream
module.exports.debrack = debrack
module.exports.stripLineEndings = stripLi... |
// TODO: cache this value?
const size = await actualSize(root)
return (size > quota)
}
/**
* Returns the number of bytes that is occupied by the actual files in
* the file system. IMPORTANT NOTE: Since it traverses the directory
* to find the actual file sizes, this does a costly operation, but
* neglible f... | {
return false
} | conditional_block |
utils.js | /* eslint-disable node/no-deprecated-api */
module.exports.pathBasename = pathBasename
module.exports.hasSuffix = hasSuffix
module.exports.serialize = serialize
module.exports.translate = translate
module.exports.stringToStream = stringToStream
module.exports.debrack = debrack
module.exports.stripLineEndings = stripLi... | (headers) {
const value = headers.get ? headers.get('content-type') : headers['content-type']
return value ? value.replace(/;.*/, '') : 'application/octet-stream'
}
| getContentType | identifier_name |
utils.js | /* eslint-disable node/no-deprecated-api */
module.exports.pathBasename = pathBasename
module.exports.hasSuffix = hasSuffix
module.exports.serialize = serialize
module.exports.translate = translate
module.exports.stringToStream = stringToStream
module.exports.debrack = debrack
module.exports.stripLineEndings = stripLi... | .on('data', function (chunk) {
data += chunk
})
.on('end', function () {
const graph = $rdf.graph()
$rdf.parse(data, graph, baseUri, from, function (err) {
if (err) return reject(err)
resolve(serialize(graph, baseUri, to))
})
})
})
}
functio... |
function translate (stream, baseUri, from, to) {
return new Promise((resolve, reject) => {
let data = ''
stream | random_line_split |
utils.js | /* eslint-disable node/no-deprecated-api */
module.exports.pathBasename = pathBasename
module.exports.hasSuffix = hasSuffix
module.exports.serialize = serialize
module.exports.translate = translate
module.exports.stringToStream = stringToStream
module.exports.debrack = debrack
module.exports.stripLineEndings = stripLi... |
/**
* Adds a route that serves a static file from another Node module
*/
function routeResolvedFile (router, path, file, appendFileName = true) {
const fullPath = appendFileName ? path + file.match(/[^/]+$/) : path
const fullFile = require.resolve(file)
router.get(fullPath, (req, res) => res.sendFile(fullFile... | {
if (!obj) { return obj }
return obj.replace(/(\r\n|\n|\r)/gm, '')
} | identifier_body |
integrations.js | /**
* Created by rosaeliana on 30/01/15.
*/
$(document).ready(function() {
$('#formIntegration')
.bootstrapValidator({
container: 'tooltip',
feedbackIcons: {
valid: 'glyphicon',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyp... | var_url = $("#formIntegration").attr('action');
var_url = var_url.replace('/save/', '');
var_url = var_url + '/validate/' + client_id + "/";
$.ajax({
url: var_url,
type: 'get',
success: function(data) {
var objJSON = $... | $('#validateCode').click(
function(){
client_id = $('#client_id').val(); | random_line_split |
admin.py | from django.contrib import admin
# Register your models here.
from rcps.models import *
class | (admin.TabularInline):
model = Ingredient.recipes.through
verbose_name = 'Ингредиент'
verbose_name_plural = 'Ингредиенты'
class EquipmentInline(admin.TabularInline):
model = Equipment.equipment_recipes.through
verbose_name = 'Инструмент'
verbose_name_plural = 'Инструменты'
class TagInline(ad... | IngredientToRecipeInline | identifier_name |
admin.py | from django.contrib import admin
# Register your models here.
from rcps.models import *
class IngredientToRecipeInline(admin.TabularInline):
model = Ingredient.recipes.through
verbose_name = 'Ингредиент'
verbose_name_plural = 'Ингредиенты'
class EquipmentInline(admin.TabularInline):
model = Equipme... | ient)
admin.site.register(IngredientAlternative, IngredientAlternativeAdmin)
admin.site.register(IngredientCategory)
admin.site.register(Equipment)
admin.site.register(EquipmentCategory)
admin.site.register(IngredientReplacement)
admin.site.register(Tag) | entInAlternativeInline,
)
admin.site.register(Recipe, RecipeAdmin)
admin.site.register(Ingred | identifier_body |
admin.py | from django.contrib import admin
# Register your models here.
from rcps.models import *
class IngredientToRecipeInline(admin.TabularInline):
model = Ingredient.recipes.through
verbose_name = 'Ингредиент'
verbose_name_plural = 'Ингредиенты'
class EquipmentInline(admin.TabularInline):
model = Equipme... | class TagInline(admin.TabularInline):
model = Tag.tag_recipes.through
verbose_name = 'Тег'
verbose_name_plural = 'Теги'
class RecipeAdmin(admin.ModelAdmin):
model = Recipe
fields = ['recipe_name', 'recipe_link']
inlines = (
IngredientToRecipeInline,
EquipmentInline,
Tag... | random_line_split | |
network.dashboard.py | #!/usr/bin/env python3
# Copyright 2019 The Kubernetes 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 appl... | expr='count(container_memory_usage_bytes{namespace="probes", container=~"ping-client|ping-server"}) by (container, namespace)'
)
],
nullPointMode="null",
),
d.Graph(
title="probes: memory usage",
targets=[
d.Target(
expr='mi... | title="probe: # running",
targets=[
d.TargetWithInterval( | random_line_split |
user-activity.ts | import {gettext} from 'core/utils';
import {reactToAngular1} from 'superdesk-ui-framework';
import UserActivityWidgetWithUser from './components/UserActivityWidgetWithUser';
angular
.module('superdesk.apps.dashboard.user-activity', [
'superdesk.apps.dashboard',
])
.config([
'dashboardWidget... | ); | random_line_split | |
DragDrop.js | /**
* Copyright (C) 2009 eXo Platform SAS.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* This softwar... | o.root.onDrag = new Function();
};
DragDrop.prototype.start = function(e) {
var o = obj = this;
var jRoot = $(o.root);
if((e.which && e.which != 1) || jRoot.data("dragging")) {
return false;
}
var position = jRoot.position();
o.lastMouseX = e.pageX || e.originalEvent.touches[0].pageX... | o.root = oRoot && oRoot != null ? oRoot : o ;
o.root.onDragStart = new Function();
o.root.onDragEnd = new Function(); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.