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 |
|---|---|---|---|---|
p2p-feefilter.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from te... |
# Set a filter of 15 sat/byte
test_node.send_filter(15000)
# Test that txs are still being received (paying 20 sat/byte)
txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)]
assert(allInvsMatch(txids, test_node))
test_node.clear_invs()
# Ch... | node1 = self.nodes[1]
node0 = self.nodes[0]
# Get out of IBD
node1.generate(1)
sync_blocks(self.nodes)
node0.generate(21)
sync_blocks(self.nodes)
# Setup the p2p connections and start up the network thread.
test_node = TestNode()
connection = Node... | identifier_body |
configure.py | ('when running: ', cmdline)
raise
parser = OptionParser()
profilers = ['gmon', 'pprof']
parser.add_option('--bootstrap', action='store_true',
help='bootstrap a ninja binary from nothing')
parser.add_option('--verbose', action='store_true',
help='enable verbose build')
p... | n.rule('cxx',
command='$cxx $cflags -c $in /Fo$out',
description='CXX $out',
deps='msvc' # /showIncludes is included in $cflags.
) | conditional_block | |
configure.py |
def is_aix(self):
return self._platform == 'aix'
def uses_usr_local(self):
return self._platform in ('freebsd', 'openbsd', 'bitrig', 'dragonfly', 'netbsd')
def supports_ppoll(self):
return self._platform in ('freebsd', 'linux', 'openbsd', 'bitrig',
... | return self._platform == 'solaris' | identifier_body | |
configure.py | (self, key, val):
# In bootstrap mode, we have no ninja process to catch /showIncludes
# output.
self.vars[key] = self._expand(val).replace('/showIncludes', '')
return self.writer.variable(key, val)
def rule(self, name, **kwargs):
self.rules[name] = kwargs
return sel... | variable | identifier_name | |
configure.py | local_vars[key] = ' '.join(ninja_syntax.as_list(val))
self._run_command(self._expand(cmd, local_vars))
return self.writer.build(outputs, rule, inputs, **kwargs)
def default(self, paths):
return self.writer.default(paths)
def _expand_paths(self, paths):
"""Expand $... | def shell_escape(str):
"""Escape str such that it's interpreted as a single argument by
the shell.""" | random_line_split | |
main.js | "use strict"
$("document").ready(function () {
setLandingImage();
});
// random background images
function setLandingImage () {
var imageFolder;
var chosenImageArray;
var fullSizeImageArray = [
"construction-rs",
"daisy-rs",
"dandelion-rs",
"forest-rs",
"hydrant-rs",
"lake-rs",
"river-rs",
"roots... | (page) {
$(".landing").fadeOut(600)
$(".section").each(function () {
if ($(this).attr("id") == page) {
$(this).fadeIn(1000)
} else {
$(this).hide()
}
})
}
// go back to landing page
function backToLanding (page) {
$(`.${page}`).fadeOut(600, function () {
$(".landing").fadeIn(1000)
})
}
| navigateLanding | identifier_name |
main.js | "use strict"
$("document").ready(function () {
setLandingImage();
});
// random background images
function setLandingImage () {
var imageFolder;
var chosenImageArray;
var fullSizeImageArray = [
"construction-rs",
"daisy-rs",
"dandelion-rs",
"forest-rs",
"hydrant-rs",
"lake-rs",
"river-rs",
"roots... | else {
imageFolder = "full_screen"
chosenImageArray = fullSizeImageArray
}
var randomNumber = Math.floor(Math.random() * chosenImageArray.length);
var randomImageName = chosenImageArray[randomNumber];
$(".landing").css("background", `url(dist/css/img/${imageFolder}/${randomImageName}.jpg) no-repeat center`)
... | {
imageFolder = "mobile"
chosenImageArray = mobileImageArray
} | conditional_block |
main.js | "use strict"
$("document").ready(function () {
setLandingImage();
});
// random background images
function setLandingImage () {
var imageFolder;
var chosenImageArray;
var fullSizeImageArray = [
"construction-rs",
"daisy-rs",
"dandelion-rs",
"forest-rs",
"hydrant-rs",
"lake-rs",
"river-rs",
"roots... |
// go back to landing page
function backToLanding (page) {
$(`.${page}`).fadeOut(600, function () {
$(".landing").fadeIn(1000)
})
}
| {
$(".landing").fadeOut(600)
$(".section").each(function () {
if ($(this).attr("id") == page) {
$(this).fadeIn(1000)
} else {
$(this).hide()
}
})
} | identifier_body |
main.js | "use strict"
$("document").ready(function () {
setLandingImage();
});
// random background images
function setLandingImage () { | var imageFolder;
var chosenImageArray;
var fullSizeImageArray = [
"construction-rs",
"daisy-rs",
"dandelion-rs",
"forest-rs",
"hydrant-rs",
"lake-rs",
"river-rs",
"roots-rs",
"sunrise-rs"
];
var mobileImageArray = [
"hydrant",
"sunrise",
"lights",
"tree",
"fan",
"beach"
];
if (sc... | random_line_split | |
cache_generate_metadata.rs | use anyhow::Result;
use clap::{App, Arg};
use std::path::Path;
use std::process;
use std::sync::Arc;
use crate::cache::metadata_generator::*;
use crate::io_engine::{AsyncIoEngine, IoEngine, SyncIoEngine};
//------------------------------------------
const MAX_CONCURRENT_IO: u32 = 1024;
//---------------------------... | else {
commit_new_transaction()?;
}
Ok(())
}
//------------------------------------------
pub fn run(args: &[std::ffi::OsString]) {
let parser = App::new("cache_generate_metadata")
.color(clap::ColorChoice::Never)
.version(crate::version::tools_version())
.about("A tool f... | {
set_needs_check(engine)?;
} | conditional_block |
cache_generate_metadata.rs | use anyhow::Result;
use clap::{App, Arg};
use std::path::Path;
use std::process;
use std::sync::Arc;
use crate::cache::metadata_generator::*;
use crate::io_engine::{AsyncIoEngine, IoEngine, SyncIoEngine};
//------------------------------------------
const MAX_CONCURRENT_IO: u32 = 1024;
//---------------------------... | (opts: &CacheGenerateOpts) -> Result<()> {
let engine: Arc<dyn IoEngine + Send + Sync> = if opts.async_io {
Arc::new(AsyncIoEngine::new(opts.output, MAX_CONCURRENT_IO, true)?)
} else {
let nr_threads = std::cmp::max(8, num_cpus::get() * 2);
Arc::new(SyncIoEngine::new(opts.output, nr_thre... | generate_metadata | identifier_name |
cache_generate_metadata.rs | use anyhow::Result;
use clap::{App, Arg};
use std::path::Path;
use std::process;
use std::sync::Arc;
use crate::cache::metadata_generator::*;
use crate::io_engine::{AsyncIoEngine, IoEngine, SyncIoEngine};
//------------------------------------------
const MAX_CONCURRENT_IO: u32 = 1024;
//---------------------------... | let parser = App::new("cache_generate_metadata")
.color(clap::ColorChoice::Never)
.version(crate::version::tools_version())
.about("A tool for creating synthetic cache metadata.")
// flags
.arg(
Arg::new("ASYNC_IO")
.help("Force use of io_uring for... | pub fn run(args: &[std::ffi::OsString]) { | random_line_split |
robot-http.service.ts | import { $WebSocket, WebSocketConfig, WebSocketSendMode } from 'angular2-websocket/angular2-websocket';
import { BaScrollPosition } from './../../../../theme/directives/baScrollPosition/baScrollPosition.directive';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Obse... | {
public name: string = 'hyman';
private baseurl = 'http://localhost:3000/';
private baseSocketUrl = 'ws://192.168.21.240:30018/cable';
private restfulUrl = 'http://192.168.21.240:30014/welcome/say_hello';
private websocketSetting: WebSocketConfig = {
initialTimeout: 500,
maxTimeout: 300000,
reco... | RobotHttpService | identifier_name |
robot-http.service.ts | import { $WebSocket, WebSocketConfig, WebSocketSendMode } from 'angular2-websocket/angular2-websocket';
import { BaScrollPosition } from './../../../../theme/directives/baScrollPosition/baScrollPosition.directive';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Obse... | };
return this.socket
.send4Observable(JSON.stringify(sendData))
.do(qq => { console.log('subscribe channel', qq); })
.catch((e: any) => Observable.throw(e));
}
showData(isShowData: boolean): Observable<any> {
const data = {
command: 'message',
identifier: JSON.stringify({... | const sendData = {
command: 'subscribe',
identifier: JSON.stringify({ channel: 'RobotsChannel', roomId: 'Andy' }) | random_line_split |
robot-http.service.ts | import { $WebSocket, WebSocketConfig, WebSocketSendMode } from 'angular2-websocket/angular2-websocket';
import { BaScrollPosition } from './../../../../theme/directives/baScrollPosition/baScrollPosition.directive';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Obse... |
getPollingData(duration: number = 2000): Observable<any> {
const request = () => this.http.get(this.restfulUrl)
.map((response: Response) => response.json())
.catch((e: any) => Observable.throw(e));
return Observable
.interval(duration)
.switchMap(request);
}
getComment(postId: ... | {
console.log(this);
} | identifier_body |
proj.js | /**
*
* @param options.args_origin sets the origin in the args where the routing begins. Defaults to second arg, which matches the pattern 'node {filename} {arg1} {arg2} ...
* @param options.root_process overrided the process in use
* @returns {{args: args, getFileName: getFileName, getRoot: getRoot, getFilePath: ... | //
//}
js: "./js",
env: {
PROD: "P",
TEST: "T",
DEV: "D",
LOC: "L"
},
paths: {
root_path: './',
dir: '',
js: './js/',
file: '',
shellRoot: ''
}
};
... | var project_utils = {
//__proto__: { | random_line_split |
entry.js | // React app
import React from 'react'
import {render} from 'react-dom'
import App from './components/base_layout/App.jsx'
// Redux state manager
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './state_manager/reducers'
// Electron IPC communication events
import ipcRe... | )
//////////////////////////////
/// IPC with main process ////
//////////////////////////////
ipcRendererEvents(store)
///////////////////
/// Workarounds ///
///////////////////
/* The chunk below will be executed after the react app is rendered */
import {resizer} from './components/base_layout/layout.css'
let nav... | </Provider>,
document.getElementById('app') | random_line_split |
client.rs | use std::env;
use std::time::Duration;
use once_cell::sync::OnceCell;
use reqwest::{
self,
header::{HeaderValue, CONTENT_TYPE},
};
use thiserror::Error;
use crate::feed::Rss;
static RESP_SIZE_LIMIT: OnceCell<u64> = OnceCell::new();
static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
#[derive(Error, ... |
if env::var("RSSBOT_DONT_PROXY_FEEDS")
.or_else(|_| env::var("rssbot_dont_proxy_feeds"))
.is_ok()
{
client_builder = client_builder.no_proxy();
}
let client = client_builder.build().unwrap();
CLIENT.set(client).expect("CLIENT already initialized");
RESP_SIZE_LIMIT
... | {
let mut headers = reqwest::header::HeaderMap::new();
let ua = format!(
concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" (+https://t.me/{})"
),
bot_name
);
headers.insert(
reqwest::header::USER_AGENT,
... | identifier_body |
client.rs | use std::env;
use std::time::Duration;
use once_cell::sync::OnceCell;
use reqwest::{
self,
header::{HeaderValue, CONTENT_TYPE},
};
use thiserror::Error;
use crate::feed::Rss;
static RESP_SIZE_LIMIT: OnceCell<u64> = OnceCell::new();
static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
#[derive(Error, ... | (value: &HeaderValue) -> bool {
value
.to_str()
.map(|value| {
value
.split(';')
.map(|v| v.trim())
.any(|v| v == "application/json")
})
.unwrap_or(false)
}
/// About the "kiB" not "KiB": https://en.wikipedia.org/wiki/Metri... | content_type_is_json | identifier_name |
client.rs | use std::env;
use std::time::Duration;
use once_cell::sync::OnceCell;
use reqwest::{
self,
header::{HeaderValue, CONTENT_TYPE}, | use thiserror::Error;
use crate::feed::Rss;
static RESP_SIZE_LIMIT: OnceCell<u64> = OnceCell::new();
static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
#[derive(Error, Debug)]
pub enum FeedError {
#[error("network error")]
Network(#[from] reqwest::Error),
#[error("feed parsing failed")]
Pars... | }; | random_line_split |
config.py | from PyQt4 import QtCore, QtGui
import os
class ConfigPage(QtGui.QWizardPage):
def __init__(self, templates, parent=None):
super(ConfigPage, self).__init__(parent)
#self.setTitle("Configuration")
#self.setSubTitle("Alter configuration and build your own platform.")
#self.setPixmap(... |
self.view.activated.connect(click)
self.view.entered.connect(click)
self.view.clicked.connect(click)
#self.view.setModel(model)
self.layout = QtGui.QGridLayout()
self.layout.addWidget(self.vsplit)
#self.setStyleSheet("* { background: yellow }")
#self.s... | item = index.internalPointer()
self.info.setText(QtCore.QVariant(item.description).toString())
self.model.clicked(item) | identifier_body |
config.py | from PyQt4 import QtCore, QtGui
import os
class ConfigPage(QtGui.QWizardPage):
def __init__(self, templates, parent=None):
super(ConfigPage, self).__init__(parent)
#self.setTitle("Configuration")
#self.setSubTitle("Alter configuration and build your own platform.")
#self.setPixmap(... | self.view.setModel(self.model)
self.view.expandAll()
self.view.setColumnWidth(0, 220)
self.view.setColumnWidth(1, 20)
self.setLayout(self.layout)
#self.vsplit.moveSplitter(280,1)
#self.hsplit.moveSplitter(120,1) | random_line_split | |
config.py | from PyQt4 import QtCore, QtGui
import os
class ConfigPage(QtGui.QWizardPage):
def __init__(self, templates, parent=None):
super(ConfigPage, self).__init__(parent)
#self.setTitle("Configuration")
#self.setSubTitle("Alter configuration and build your own platform.")
#self.setPixmap(... | (self):
self.panel.setParent(None)
self.panel = QtGui.QWidget()
self.hsplit.insertWidget(0, self.panel)
self.model = self.templates.getModel(self.panel)
self.view.setModel(self.model)
self.view.expandAll()
self.view.setColumnWidth(0, 220)
self.view.setColu... | initializePage | identifier_name |
search_near_title.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Copyright (c) 2014, Kersten Doering <kersten.doering@gmail.com>, Bjoern Gruening <bjoern.gruening@gmail.com>
"""
#Kersten Doering 16.06.2014
#check http://xapian.org/docs/queryparser.html for syntax and functions
import xappy
searchConn = xappy.SearchConnection("x... | #write the first 1000 PubMed-IDs and titles with term "pancreatic" or stem "pancreat"
for index,result in enumerate(results):
outfile.write("<tr><td>" + str(index) + "</td><td>" + result.id + "</td><td>" + results.get_hit(index).highlight('title')[0] +"</td></tr>")
# if index == 999:
# break
... | print "### save results in Xapian_query_results_NEAR.html ###" | random_line_split |
search_near_title.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Copyright (c) 2014, Kersten Doering <kersten.doering@gmail.com>, Bjoern Gruening <bjoern.gruening@gmail.com>
"""
#Kersten Doering 16.06.2014
#check http://xapian.org/docs/queryparser.html for syntax and functions
import xappy
searchConn = xappy.SearchConnection("x... |
# if index == 999:
# break
#write string for finishing HTML document
outfile.write(end_string)
#close file connection
outfile.close()
#close connection to Xapian database
#searchConn.close()
| outfile.write("<tr><td>" + str(index) + "</td><td>" + result.id + "</td><td>" + results.get_hit(index).highlight('title')[0] +"</td></tr>") | conditional_block |
bthsdpdef.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | SDP_TYPE_INT = 0x02,
SDP_TYPE_UUID = 0x03,
SDP_TYPE_STRING = 0x04,
SDP_TYPE_BOOLEAN = 0x05,
SDP_TYPE_SEQUENCE = 0x06,
SDP_TYPE_ALTERNATIVE = 0x07,
SDP_TYPE_URL = 0x08,
SDP_TYPE_CONTAINER = 0x20,
}}
ENUM!{enum SDP_SPECIFICTYPE {
SDP_ST_NONE = 0x0000,
SDP_ST_UINT8 = 0x0010,
SDP... | pub type PSDP_ERROR = *mut USHORT;
ENUM!{enum SDP_TYPE {
SDP_TYPE_NIL = 0x00,
SDP_TYPE_UINT = 0x01, | random_line_split |
Sphere.py | import bounds
from py3D import Vector, Ray, Color, Body
class Sphere(Body):
center = Vector()
radius = 0.0
R = 0.0
color = [0.01,0.01,0.01]
def p(self):
"""Returns the name of the type of body this is."""
return 'Sphere'
def set_position(self, c):
self.cen... | # and R be the square of the radius of the sphere
#
# Then call S dot S SS, and, similarly, SD is S dot D
#
# Now the intersections occur at the following distances:
# -SD +/- sqrt(SD**2 + R - SS)
def intersection(self, ray):
"""Returns distance from ray to closest intersection w... |
# Intersection of ray with a sphere boils down to the solutions to a
# quadratic vector equation.
#
# Let S be the vector from sphere center to ray origin, D be ray direction | random_line_split |
Sphere.py | import bounds
from py3D import Vector, Ray, Color, Body
class Sphere(Body):
center = Vector()
radius = 0.0
R = 0.0
color = [0.01,0.01,0.01]
def p(self):
"""Returns the name of the type of body this is."""
return 'Sphere'
def set_position(self, c):
self.cen... |
def normal(self, point):
"""Returns normal vector of body at given point."""
return (point - self.center).scale(1/self.radius)
def set_reflectivity(self, r):
self._r = max(0.0,min(1.0,r))
return self
def reflectivity(self, point):
"""Returns percentage... | """Returns color of body at given point."""
return self.color.dup() | identifier_body |
Sphere.py | import bounds
from py3D import Vector, Ray, Color, Body
class Sphere(Body):
center = Vector()
radius = 0.0
R = 0.0
color = [0.01,0.01,0.01]
def p(self):
"""Returns the name of the type of body this is."""
return 'Sphere'
def set_position(self, c):
self.cen... |
else:
return hit
| hit = -1 * SD + radical
if hit < bounds.too_small:
return -1.0
else:
return hit | conditional_block |
Sphere.py | import bounds
from py3D import Vector, Ray, Color, Body
class Sphere(Body):
center = Vector()
radius = 0.0
R = 0.0
color = [0.01,0.01,0.01]
def | (self):
"""Returns the name of the type of body this is."""
return 'Sphere'
def set_position(self, c):
self.center = c
return self
def set_radius(self, r):
self.radius = abs(r)
self.R = r ** 2.0
return self
def set_color(self, c):
... | p | identifier_name |
test_engine.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants.base.exce... | def throw():
raise error
return throw
def test_execute_raise(self):
engine = self.RecordingEngine(action=self._throw(TaskError()))
result = engine.execute(self.context, self.as_goals('three'))
self.assertEqual(1, result)
self.assert_attempt(engine, 'three')
def test_execute_code(self... |
def _throw(self, error): | random_line_split |
test_engine.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants.base.exce... | (self, error):
def throw():
raise error
return throw
def test_execute_raise(self):
engine = self.RecordingEngine(action=self._throw(TaskError()))
result = engine.execute(self.context, self.as_goals('three'))
self.assertEqual(1, result)
self.assert_attempt(engine, 'three')
def test_ex... | _throw | identifier_name |
test_engine.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants.base.exce... |
context, goals = engine.attempts[0]
self.assertEqual(self.context, context)
self.assertEqual(self.as_goals(*goal_names), goals)
def test_execute_success(self):
engine = self.RecordingEngine()
result = engine.execute(self.context, self.as_goals('one', 'two'))
self.assertEqual(0, result)
s... | class RecordingEngine(Engine):
def __init__(self, action=None):
super(EngineTest.RecordingEngine, self).__init__()
self._action = action
self._attempts = []
@property
def attempts(self):
return self._attempts
def attempt(self, context, goals):
self._attempts.append((conte... | identifier_body |
test_engine.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants.base.exce... |
def setUp(self):
self.context = create_context()
def assert_attempt(self, engine, *goal_names):
self.assertEqual(1, len(engine.attempts))
context, goals = engine.attempts[0]
self.assertEqual(self.context, context)
self.assertEqual(self.as_goals(*goal_names), goals)
def test_execute_succes... | self._action() | conditional_block |
ScrollingTableScript.ts | "use strict";
/*
* Copyright (C) 1998-2017 by Northwoods Software Corporation. All Rights Reserved.
*/
import * as go from "../release/go";
var myDiagram: go.Diagram = null;
export function init() | resizable: true, resizeObjectName: "SCROLLER",
portSpreading: go.Node.SpreadingNone
},
new go.Binding("location").makeTwoWay(),
$(go.TextBlock,
{ font: "bold 14px sans-serif" },
new go.Binding("text", "key")),
$(go.Panel, "Auto",
$(go.Sha... | {
if (typeof (<any>window)["goSamples"] === 'function') (<any>window)["goSamples"](); // init for these samples -- you don't need to call this
var $ = go.GraphObject.make;
myDiagram =
$(go.Diagram, "myDiagramDiv",
{
initialContentAlignment: go.Spot.Center,
"PartResized":... | identifier_body |
ScrollingTableScript.ts | "use strict";
/*
* Copyright (C) 1998-2017 by Northwoods Software Corporation. All Rights Reserved.
*/
import * as go from "../release/go";
var myDiagram: go.Diagram = null;
export function | () {
if (typeof (<any>window)["goSamples"] === 'function') (<any>window)["goSamples"](); // init for these samples -- you don't need to call this
var $ = go.GraphObject.make;
myDiagram =
$(go.Diagram, "myDiagramDiv",
{
initialContentAlignment: go.Spot.Center,
"PartResize... | init | identifier_name |
ScrollingTableScript.ts | "use strict";
/*
* Copyright (C) 1998-2017 by Northwoods Software Corporation. All Rights Reserved.
*/
import * as go from "../release/go";
var myDiagram: go.Diagram = null;
export function init() {
if (typeof (<any>window)["goSamples"] === 'function') (<any>window)["goSamples"](); // init for these samples --... | { from: "Alpha", fromPort: "D", to: "Beta", toPort: "Ff" },
{ from: "Alpha", fromPort: "A", to: "Beta", toPort: "Nn" },
{ from: "Alpha", fromPort: "G", to: "Beta", toPort: "Aa" }
]
});
} | { name: "Nn", value: 14 }
]
}
],
linkDataArray: [ | random_line_split |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... | {
for patch in get_patches(crate_name) {
eprintln!("[PATCH] {:?} <- {:?}", target_dir.file_name().unwrap(), patch);
let patch_arg = env::current_dir().unwrap().join("patches").join(patch);
let mut apply_patch_cmd = Command::new("git");
apply_patch_cmd.arg("am").arg(patch_arg).arg("-q... | identifier_body | |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... | () {
let rustc_path = get_rustc_path();
let sysroot_src_orig = rustc_path.parent().unwrap().join("../lib/rustlib/src/rust");
let sysroot_src = env::current_dir().unwrap().join("build_sysroot").join("sysroot_src");
assert!(sysroot_src_orig.exists());
if sysroot_src.exists() {
fs::remove_dir... | prepare_sysroot | identifier_name |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... |
clone_repo(
"simple-raytracer",
"https://github.com/ebobby/simple-raytracer",
"804a7a21b9e673a482797aa289a18ed480e4d813",
);
eprintln!("[LLVM BUILD] simple-raytracer");
let mut build_cmd = Command::new("cargo");
build_cmd.arg("build").env_remove("CARGO_TARGET_DIR").current_... | "8cf7a62e5d2552961df51e5200aaa5b7c890a4bf",
);
apply_patches("portable-simd", Path::new("portable-simd")); | random_line_split |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... |
fs::create_dir_all(sysroot_src.join("library")).unwrap();
eprintln!("[COPY] sysroot src");
copy_dir_recursively(&sysroot_src_orig.join("library"), &sysroot_src.join("library"));
let rustc_version = get_rustc_version();
fs::write(Path::new("build_sysroot").join("rustc_version"), &rustc_version).unw... | {
fs::remove_dir_all(&sysroot_src).unwrap();
} | conditional_block |
hough_transform.rs | // Implements http://rosettacode.org/wiki/Hough_transform
//
// Contributed by Gavin Baker <gavinb@antonym.org>
// Adapted from the Go version
use std::io::{BufReader, BufRead, BufWriter, Write, Read};
use std::fs::File;
use std::iter::repeat;
// Simple 8-bit grayscale image
struct ImageGray8 {
width: usize,
... |
// Transform extents
let rmax = (in_width as f64).hypot(in_height as f64);
let dr = rmax / (out_height/2) as f64;
let dth = std::f64::consts::PI / out_width as f64;
// Process input image in raster order
for y in (0..in_height) {
for x in (0..in_width) {
let in_idx = y*in... | data: repeat(255).take(out_width*out_height).collect(),
}; | random_line_split |
hough_transform.rs | // Implements http://rosettacode.org/wiki/Hough_transform
//
// Contributed by Gavin Baker <gavinb@antonym.org>
// Adapted from the Go version
use std::io::{BufReader, BufRead, BufWriter, Write, Read};
use std::fs::File;
use std::iter::repeat;
// Simple 8-bit grayscale image
struct ImageGray8 {
width: usize,
... | () {
let image = load_pgm("../src/resources/Pentagon.pgm");
let accum = hough(&image, 460, 360);
save_pgm(&accum, "hough.pgm");
}
| main | identifier_name |
hough_transform.rs | // Implements http://rosettacode.org/wiki/Hough_transform
//
// Contributed by Gavin Baker <gavinb@antonym.org>
// Adapted from the Go version
use std::io::{BufReader, BufRead, BufWriter, Write, Read};
use std::fs::File;
use std::iter::repeat;
// Simple 8-bit grayscale image
struct ImageGray8 {
width: usize,
... | let width = width_in.trim().parse::<usize>().unwrap();
let height: usize = height_in.trim().parse::<usize>().unwrap();
println!("Reading pgm file {}: {} x {}", filename, width, height);
// Create image and allocate buffer
let mut img = ImageGray8 {
width: width,
height: height,
... | {
// Open file
let mut file = BufReader::new(File::open(filename).unwrap());
// Read header
let mut magic_in = String::new();
let _ = file.read_line(&mut magic_in).unwrap();
let mut width_in = String::new();
let _ = file.read_line(&mut width_in).unwrap();
let mut height_in = String::ne... | identifier_body |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... | (parameters: WebVRStageParameters, global: &GlobalScope) -> Root<VRStageParameters> {
reflect_dom_object(box VRStageParameters::new_inherited(parameters, global),
global,
VRStageParametersBinding::Wrap)
}
#[allow(unsafe_code)]
pub fn update(&sel... | new | identifier_name |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... |
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizez
fn SizeZ(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_z)
}
}
| {
Finite::wrap(self.parameters.borrow().size_x)
} | identifier_body |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... | }
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new(self.transform.get())
}
/... | }
*self.parameters.borrow_mut() = parameters.clone();
} | random_line_split |
settings.py | """
Django settings for example project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... | CUSTOM_THEME_LOOKUP_ATTR = "name"
PIMPMYTHEME_FOLDER = os.path.join(BASE_DIR, "pimp_theme")
LOGGING = {
'version': 1,
'formatters': {
'oneline': {
'format': '%(asctime)s %(levelname)-8s %(name)s %(message)s',
},
},
'handlers': {
'console': {
'class': 'l... |
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
CUSTOM_THEME_LOOKUP_OBJECT = "example.models.PimpSite" | random_line_split |
deque.rs | used. Deques
/// will only use this structure when allocating a new buffer or deallocating a
/// previous one.
pub struct BufferPool<T> {
pool: Arc<Exclusive<Vec<Box<Buffer<T>>>>>,
}
/// An internal buffer used by the chase-lev deque. This structure is actually
/// implemented as a circular buffer, and is used as... | else {
self.bottom.store(t + 1, SeqCst);
forget(data); // someone else stole this value
return None;
}
}
unsafe fn steal(&self) -> Stolen<T> {
let t = self.top.load(SeqCst);
let old = self.array.load(SeqCst);
let b = self.bottom.load(SeqCst);... | {
self.bottom.store(t + 1, SeqCst);
return Some(data);
} | conditional_block |
deque.rs | used. Deques
/// will only use this structure when allocating a new buffer or deallocating a
/// previous one.
pub struct BufferPool<T> {
pool: Arc<Exclusive<Vec<Box<Buffer<T>>>>>,
}
/// An internal buffer used by the chase-lev deque. This structure is actually
/// implemented as a circular buffer, and is used as... | () -> BufferPool<T> {
BufferPool { pool: Arc::new(Exclusive::new(Vec::new())) }
}
/// Allocates a new work-stealing deque which will send/receiving memory to
/// and from this buffer pool.
pub fn deque(&self) -> (Worker<T>, Stealer<T>) {
let a = Arc::new(Deque::new(self.clone()));
... | new | identifier_name |
deque.rs |
/// deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Stealer<T> {
/// Steals work off the end of the queue (opposite of the worker's end)
pub fn steal(&self) -> Stolen<T> {
unsafe { self.deque.steal() }
}
/// Gets access to the buf... | {
let pool = BufferPool::new();
let (w, s) = pool.deque();
assert_eq!(w.pop(), None);
assert_eq!(s.steal(), Empty);
w.push(1i);
assert_eq!(w.pop(), Some(1));
w.push(1);
assert_eq!(s.steal(), Data(1));
w.push(1);
assert_eq!(s.clone().steal()... | identifier_body | |
deque.rs | to manually run
/// destructors for values in this buffer (on drop) because the bounds
/// are defined by the deque it's owned by.
///
/// 2. We can certainly avoid bounds checks using *T instead of Vec<T>, although
/// LLVM is probably pretty good at doing this already.
struct Buffer<T> {
storage... |
// Apparently LLVM cannot optimize (foo % (1 << bar)) into this implicitly
fn mask(&self) -> int { (1 << self.log_size) - 1 }
| random_line_split | |
__init__.py | ,
Articulation,
BarLine,
BeamCount,
BendAfter,
BreathMark,
Clef,
ColorFingering,
Fermata,
Glissando,
KeyCluster,
KeySignature,
LaissezVibrer,
MarginMarkup,
MetronomeMark,
Mode,
Ottava,
RehearsalMark,
Repeat,
RepeatTie,
StaffChange,
Staf... | "Parentage",
"ParentageError",
"Parser",
| "Ottava",
"OverrideInterface", | random_line_split |
compression_op.py | taken from spec.
"""
raise NotImplementedError()
class LowRankDecompMatrixCompressor(MatrixCompressorInferface):
"""Low rank decomposition compressor.
Implements matrix compression interface for the low rank decomposition
algorithm.
"""
def __init__(self, spec):
"""Initializer.
Args:
... |
self.b_matrix_tfvar = layer.add_weight(
'b_matrix',
shape=b_matrix.shape,
initializer=layer.kernel_initializer,
regularizer=layer.kernel_regularizer,
constraint=layer.kernel_constraint,
dtype=layer.dtype,
trainable=True)
self.c_matrix_tfvar = layer.add_we... | """Create compressed layer weight matrices."""
self.matrix_compressor = matrix_compressor
a_matrix = np.zeros(shape=a_matrix_tfvar.shape)
[b_matrix, c_matrix] = matrix_compressor.static_matrix_compressor(a_matrix) | random_line_split |
compression_op.py | compressed_size = tf.size(a_matrix)
self.compressed_size = b_matrix.size + c_matrix.size
return [b_matrix, c_matrix]
class CompressionOpInterface(object):
"""Interface for a compression op.
Class to take a matrix compression algorithm and create a tensorflow
compression operator to inject that compres... | raise ValueError('Illegal value for begin_compression_step') | conditional_block | |
compression_op.py | c_matrix = vh[:rank, :]
s_mat = np.diag(np.sqrt(s[:rank]))
b_matrix = np.matmul(b_matrix, s_mat)
c_matrix = np.matmul(s_mat, c_matrix)
logging.info(
'Inside static_matrix_compressor: a_matrix,b_matrix,c_matrix shapes '
'are: %s, %s, %s', a_matrix.shape, b_matrix.shape, c_matrix.shape)
... | _compressor_and_alpha_update_op | identifier_name | |
compression_op.py | taken from spec.
"""
raise NotImplementedError()
class LowRankDecompMatrixCompressor(MatrixCompressorInferface):
"""Low rank decomposition compressor.
Implements matrix compression interface for the low rank decomposition
algorithm.
"""
def __init__(self, spec):
|
def get_spec(self):
return self._spec
@staticmethod
def get_default_hparams():
"""Get a tf.HParams object with the default values for the hyperparameters.
name: string
name of the low-rank matrix decompressor specification.
rank: integer
rank of the low-rank decomposition t... | """Initializer.
Args:
spec: hparams object with default value given by
self.get_default_hparams().
"""
super(LowRankDecompMatrixCompressor, self).__init__(spec)
self._spec = spec
self.uncompressed_size = 0
self.compressed_size = 0 | identifier_body |
__init__.py | # This file is part of quichem.
#
# quichem 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.
#
# quichem is distributed in the ho... | # along with quichem. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from quichem.compilers.compiler import Compiler, tokened_strings
from quichem.compilers.display import fragments
class DisplayCompiler(Compiler):
"""Generic compiler for rendering to displayable text for... | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License | random_line_split |
__init__.py | # This file is part of quichem.
#
# quichem 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.
#
# quichem is distributed in the ho... |
def handle(self, token):
return self.token_fragments[next(x for x in self.token_fragments if isinstance(token, x))].render(token)
| """Compile a `quichem` AST into a string of the compiled
tokens.
"""
return ''.join(Compiler.compile(self, ast)) | identifier_body |
__init__.py | # This file is part of quichem.
#
# quichem 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.
#
# quichem is distributed in the ho... | (self):
Compiler.__init__(self)
self.fragments = {
'separator': fragments.Separator(),
'element': fragments.Element(),
'coefficient': fragments.Coefficient(),
'charge': fragments.Charge(),
'state': fragments.State(),
'counter': frag... | __init__ | identifier_name |
local.py | """
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build path... | WSGI_APPLICATION = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject... | },
},
]
| random_line_split |
pg-combo-asset.ts | module Animate
{
/**
* This represents a combo property for assets that the user can select from a list.
*/
export class PGComboAsset extends PropertyGridEditor
{
constructor( grid: PropertyGrid )
|
/**
* Checks a property to see if it can edit it
* @param {Prop<any>} prop The property being edited
* @returns {boolean}
*/
canEdit(prop: Prop<any>): boolean
{
if (prop instanceof PropAsset && prop.type == PropertyType.ASSET)
return ... | {
super( grid );
} | identifier_body |
pg-combo-asset.ts | module Animate
{
/**
* This represents a combo property for assets that the user can select from a list.
*/
export class PGComboAsset extends PropertyGridEditor
{
constructor( grid: PropertyGrid )
{
super( grid );
}
/**
* Checks a property to see if it can edit it
* @param {Pro... | (prop: Prop<any>): boolean
{
if (prop instanceof PropAsset && prop.type == PropertyType.ASSET)
return true;
else
return false;
}
/**
* Given a property, the grid editor must produce HTML that can be used to edit the property
* @param {Prop<a... | canEdit | identifier_name |
pg-combo-asset.ts | module Animate
{
/**
* This represents a combo property for assets that the user can select from a list.
*/
export class PGComboAsset extends PropertyGridEditor
{
constructor( grid: PropertyGrid )
{
super( grid );
}
/**
* Checks a property to see if it can edit it
* @param {Pro... |
// When we select a new asset
var onSelect = function (e: JQueryEventObject )
{
var val = parseFloat(selector.val());
var asset: Asset = User.get.project.getResourceByShallowID<Asset>(val, ResourceType.ASSET);
p.setVal(asset);
};
... | var len: number = nodes.length;
for ( var i = 0; i < len; i++ )
selector.append(`<option title='${nodes[i].resource.entry.shallowId + " : " + nodes[i].resource.entry.className}' value='${nodes[i].resource.entry.shallowId}' ${(selectedID == nodes[i].resource.entry.shallowId ? "selected='selected'" ... | random_line_split |
TestRunnerDetector.ts | import { TestRunnerAdapter } from '@serenity-js/core/lib/io';
import { Config as ProtractorConfig } from 'protractor';
import { TestRunnerLoader } from './TestRunnerLoader';
/**
* @desc
* Detects the {@link @serenity-js/core/lib/io~TestRunnerAdapter} to use,
* based on Protractor configuration.
*
* @public
*/... | {
static cucumberOpts = 'cucumberOpts';
static jasmineNodeOpts = 'jasmineNodeOpts';
static mochaOpts = 'mochaOpts';
static protractorCliOptions(): string[] {
return [
TestRunnerDetector.cucumberOpts,
TestRunnerDetector.jasmineNodeOpts,
TestRunnerDetector.mo... | TestRunnerDetector | identifier_name |
TestRunnerDetector.ts | import { TestRunnerAdapter } from '@serenity-js/core/lib/io';
import { Config as ProtractorConfig } from 'protractor';
import { TestRunnerLoader } from './TestRunnerLoader';
/**
* @desc
* Detects the {@link @serenity-js/core/lib/io~TestRunnerAdapter} to use,
* based on Protractor configuration.
*
* @public
*/... |
/**
* @param {TestRunnerLoader} testRunnerLoader
*/
constructor(private readonly testRunnerLoader: TestRunnerLoader) {
}
/**
* @param {protractor~ProtractorConfig} config
* @returns {TestRunnerAdapter}
*/
runnerFor(config: ProtractorConfig): TestRunnerAdapter {
c... | {
return [
TestRunnerDetector.cucumberOpts,
TestRunnerDetector.jasmineNodeOpts,
TestRunnerDetector.mochaOpts,
];
} | identifier_body |
TestRunnerDetector.ts | import { TestRunnerAdapter } from '@serenity-js/core/lib/io';
import { Config as ProtractorConfig } from 'protractor';
|
/**
* @desc
* Detects the {@link @serenity-js/core/lib/io~TestRunnerAdapter} to use,
* based on Protractor configuration.
*
* @public
*/
export class TestRunnerDetector {
static cucumberOpts = 'cucumberOpts';
static jasmineNodeOpts = 'jasmineNodeOpts';
static mochaOpts = 'mochaOpts';
static p... | import { TestRunnerLoader } from './TestRunnerLoader'; | random_line_split |
dataforms.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="de" sourcelanguage="en">
<context>
<name>DataFormWidget</name>
<message>
<source>Page %1</source>
<translation>Seite %1</translation>
</message>
<message>
<source>The are %1 field(s) with invalid val... | <message>
<source>Supports the layouting of the form, including the layout of form fields, pages and sections</source>
<translation>Unterstützt das Gestalten eines Formulars, einschließlich des Layouts von Formularfeldern, -seiten und -sektionen</translation>
</message>
<message>
<so... | </message> | random_line_split |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SafetyAssertionMode {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<Safe... | }
} | match self {
SafetyAssertionMode::None => true,
_ => false,
} | random_line_split |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum | {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<SafetyAssertionMode, String> {
use self::SafetyAssertionMode::*;
match name {
"none" => Ok(None),
"skip" => Ok(Skip),
"in-ma... | SafetyAssertionMode | identifier_name |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SafetyAssertionMode {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<Safe... |
for par in ¶ms.rust_parameters {
let c_par = ¶ms.c_parameters[par.ind_c];
match *env.library.type_(c_par.typ) {
Class(..) | Interface(..)
if !*c_par.nullable && c_par.typ.ns_id == library::MAIN_NAMESPACE =>
{
... | {
return None;
} | conditional_block |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SafetyAssertionMode {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<Safe... |
InMainThread
}
pub fn is_none(self) -> bool {
match self {
SafetyAssertionMode::None => true,
_ => false,
}
}
}
| {
use self::SafetyAssertionMode::*;
use crate::library::Type::*;
if !env.config.generate_safety_asserts {
return None;
}
if is_method {
return None;
}
for par in ¶ms.rust_parameters {
let c_par = ¶ms.c_parameters[par.ind... | identifier_body |
mod.rs | // Each closure instance has its own unique anonymous type: that is, even if two closures have
// the same signature, their types are still considered to be different.
//
// Closures can capture values from environment by (1) moving, (2) borrow immutably, and (3) borrow
// mutably
// (1) Encoded as FnOnce trait. FnOnce... | assert!(equal_to_x(y));
let y = vec![1, 2, 3];
assert!(equal_to_x(y));
} | // let equal_to_x: (FnOnce(Vec<i32>) -> bool) = move |z| z == x;
let equal_to_x = move |z| z == x;
// This is no longer allowed.
// println!("can't use x here: {:?}", x);
let y = vec![1, 2, 3]; | random_line_split |
mod.rs | // Each closure instance has its own unique anonymous type: that is, even if two closures have
// the same signature, their types are still considered to be different.
//
// Closures can capture values from environment by (1) moving, (2) borrow immutably, and (3) borrow
// mutably
// (1) Encoded as FnOnce trait. FnOnce... | ensity: i32, random_number: i32) {
// Type annotations are not neccessary for closures, but can be added for clarity.
let mut expensive_result = Cacher::new(|nums: i32| -> i32 {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
nums
});
if intensity < 25 {... | rate_workout(int | identifier_name |
mod.rs | // Each closure instance has its own unique anonymous type: that is, even if two closures have
// the same signature, their types are still considered to be different.
//
// Closures can capture values from environment by (1) moving, (2) borrow immutably, and (3) borrow
// mutably
// (1) Encoded as FnOnce trait. FnOnce... | e {
println!("Today, run for {} minutes!", expensive_result.value(intensity));
}
}
}
fn capture() {
let x = 4;
// Closures can capture their dynamic environment, but at a cost -> memory
let equal_to_x = |z| z == x;
// Functions cannot do so. Following is illegal.
// fn equal... | println!("Take a break today! Remember to stay hydrated!");
} els | conditional_block |
cssrulelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... | (&self) {
for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| DomRoot::upcast(r).deparent());
}
}
pub fn item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.dom_rules.borrow().get(idx as usize).map(|rule| {
rule.or_init(|| {
let p... | deparent_all | identifier_name |
cssrulelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... |
}
}
// Remove parent stylesheets from all children
pub fn deparent_all(&self) {
for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| DomRoot::upcast(r).deparent());
}
}
pub fn item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.dom_rules... | {
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
kf.write_with(&mut guard).keyframes.remove(i... | conditional_block |
cssrulelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... | unsafe_no_jsmanaged_fields!(RulesSource);
unsafe_no_jsmanaged_fields!(CssRules);
impl From<RulesMutateError> for Error {
fn from(other: RulesMutateError) -> Self {
match other {
RulesMutateError::Syntax => Error::Syntax,
RulesMutateError::IndexSize => Error::IndexSize,
... |
#[allow(unsafe_code)] | random_line_split |
cssrulelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... |
}
impl CSSRuleListMethods for CSSRuleList {
// https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1
fn Item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.item(idx)
}
// https://drafts.csswg.org/cssom/#dom-cssrulelist-length
fn Length(&self) -> u32 {
self.dom_rules.... | {
if let RulesSource::Rules(..) = self.rules {
panic!("Can only call append_lazy_rule with keyframes-backed CSSRules");
}
self.dom_rules.borrow_mut().push(MutNullableDom::new(None));
} | identifier_body |
input-base.ts | this.setControlCss(item, inputControl);
}
// Set the control classes on the native input
if (nativeInput && inputControl) {
this.setControlCss(nativeInput, inputControl);
}
}
setControlCss(element: any, control: NgControl) {
element.setElementClass('ng-untouched', control.untouched... |
// focus this input if the pointer hasn't moved XX pixels
// and the input doesn't already have focus
if (!hasPointerMoved(8, this._coord, endCoord) && !this.hasFocus()) {
ev.preventDefault();
ev.stopPropagation();
// begin the input focus process
this.initFocus();
... |
} else if (this._coord) {
// get where the touchend/mouseup ended
let endCoord = pointerCoord(ev); | random_line_split |
input-base.ts | this.setControlCss(item, inputControl);
}
// Set the control classes on the native input
if (nativeInput && inputControl) {
this.setControlCss(nativeInput, inputControl);
}
}
setControlCss(element: any, control: NgControl) {
element.setElementClass('ng-untouched', control.untouched... |
pointerStart(ev: any) {
// input cover touchstart
if (ev.type === 'touchstart') {
this._isTouch = true;
}
if ((this._isTouch || (!this._isTouch && ev.type === 'mousedown')) && this._app.isEnabled()) {
// remember where the touchstart/mousedown started
this._coord = pointerCoord(ev... | {
if (this._item) {
console.debug(`input-base, focusChange, inputHasFocus: ${inputHasFocus}, ${this._item.getNativeElement().nodeName}.${this._item.getNativeElement().className}`);
this._item.setElementClass('input-has-focus', inputHasFocus);
}
// If clearOnEdit is enabled and the input blurred... | identifier_body |
input-base.ts | this.setControlCss(item, inputControl);
}
// Set the control classes on the native input
if (nativeInput && inputControl) {
this.setControlCss(nativeInput, inputControl);
}
}
setControlCss(element: any, control: NgControl) {
element.setElementClass('ng-untouched', control.untouched... | }
return;
}
if (this._usePadding) {
| {
// this input is inside of a scroll view
// find out if text input should be manually scrolled into view
// get container of this input, probably an ion-item a few nodes up
let ele: HTMLElement = this._elementRef.nativeElement;
ele = <HTMLElement>ele.closest('ion-item,[ion-item]') || el... | conditional_block |
input-base.ts | text input if clearOnEdit is enabled
* @private
*/
checkClearOnEdit(inputValue: string) {
if (!this._clearOnEdit) {
return;
}
// Did the input value change after it was blurred and edited?
if (this._didBlurAfterEdit && this.hasValue()) {
// Clear the input
this.clearTextInput()... | setFocus | identifier_name | |
advent1.rs | // advent1.rs
// Manhattan lengths and segment intersection
use std::io;
use std::collections::HashSet;
type Vec2 = [i32; 2];
// unit vectors for the 4 cardinal directions
const NORTH: Vec2 = [0, 1];
#[allow(dead_code)]
const SOUTH: Vec2 = [0, -1];
#[allow(dead_code)]
const EAST: Vec2 = [1, 0];
#[allow(dead_code)]
c... | () {
assert_eq!(5, calc_manhattan_length("R2, L3"));
assert_eq!(2, calc_manhattan_length("R2, R2, R2"));
assert_eq!(12, calc_manhattan_length("R5, L5, R5, R3"));
}
// part 2
#[test]
fn test_find_first_revisited_distance() {
assert_eq!(4, find_first_revisited_distance("R8, R4, R4, R8"));
}
| test_calc_manhattan_length | identifier_name |
advent1.rs | // advent1.rs
// Manhattan lengths and segment intersection
use std::io;
use std::collections::HashSet;
type Vec2 = [i32; 2];
// unit vectors for the 4 cardinal directions
const NORTH: Vec2 = [0, 1];
#[allow(dead_code)]
const SOUTH: Vec2 = [0, -1];
#[allow(dead_code)]
const EAST: Vec2 = [1, 0];
#[allow(dead_code)]
c... | assert_eq!(12, calc_manhattan_length("R5, L5, R5, R3"));
}
// part 2
#[test]
fn test_find_first_revisited_distance() {
assert_eq!(4, find_first_revisited_distance("R8, R4, R4, R8"));
} |
#[test]
fn test_calc_manhattan_length() {
assert_eq!(5, calc_manhattan_length("R2, L3"));
assert_eq!(2, calc_manhattan_length("R2, R2, R2")); | random_line_split |
advent1.rs | // advent1.rs
// Manhattan lengths and segment intersection
use std::io;
use std::collections::HashSet;
type Vec2 = [i32; 2];
// unit vectors for the 4 cardinal directions
const NORTH: Vec2 = [0, 1];
#[allow(dead_code)]
const SOUTH: Vec2 = [0, -1];
#[allow(dead_code)]
const EAST: Vec2 = [1, 0];
#[allow(dead_code)]
c... | {
assert_eq!(4, find_first_revisited_distance("R8, R4, R4, R8"));
} | identifier_body | |
csr.ts | import { Pkcs10CertificateRequest } from "@peculiar/x509";
import * as graphene from "graphene-pk11";
import { Convert } from "pvtsutils";
import * as core from "webcrypto-core";
import { CryptoKey } from "../key";
import { Pkcs11Object } from "../p11_object";
import { CryptoCertificate, Pkcs11ImportAlgorithms } from... | if (parts[0] === "public" && parts[2] === publicKeyID) {
if (algorithm && usages) {
this.publicKey = await this.crypto.keyStorage.getItem(keyIndex, algorithm, true, usages);
} else {
this.publicKey = await this.crypto.keyStorage.getItem(keyIndex);
}
... | if (!this.publicKey) {
const publicKeyID = this.id.replace(/\w+-\w+-/i, "");
const keyIndexes = await this.crypto.keyStorage.keys();
for (const keyIndex of keyIndexes) {
const parts = keyIndex.split("-"); | random_line_split |
csr.ts | import { Pkcs10CertificateRequest } from "@peculiar/x509";
import * as graphene from "graphene-pk11";
import { Convert } from "pvtsutils";
import * as core from "webcrypto-core";
import { CryptoKey } from "../key";
import { Pkcs11Object } from "../p11_object";
import { CryptoCertificate, Pkcs11ImportAlgorithms } from... |
}
return this.publicKey;
}
protected parse(data: ArrayBuffer) {
this.csr = new Pkcs10CertificateRequest(data);
}
/**
* returns parsed ASN1 value
*/
protected getData() {
if (!this.csr) {
this.parse(this.value);
}
return this.csr!;
}
}
| {
if (algorithm && usages) {
this.publicKey = await this.getData().publicKey.export(algorithm, usages, this.crypto as globalThis.Crypto) as CryptoKey;
} else {
this.publicKey = await this.getData().publicKey.export(this.crypto as globalThis.Crypto) as CryptoKey;
}
} | conditional_block |
csr.ts | import { Pkcs10CertificateRequest } from "@peculiar/x509";
import * as graphene from "graphene-pk11";
import { Convert } from "pvtsutils";
import * as core from "webcrypto-core";
import { CryptoKey } from "../key";
import { Pkcs11Object } from "../p11_object";
import { CryptoCertificate, Pkcs11ImportAlgorithms } from... | () {
return this.getData()?.subject;
}
public type: "request" = "request";
public p11Object?: graphene.Data;
public csr?: Pkcs10CertificateRequest;
public get value(): ArrayBuffer {
Pkcs11Object.assertStorage(this.p11Object);
return new Uint8Array(this.p11Object.value).buffer as ArrayBuffer;
}... | subjectName | identifier_name |
csr.ts | import { Pkcs10CertificateRequest } from "@peculiar/x509";
import * as graphene from "graphene-pk11";
import { Convert } from "pvtsutils";
import * as core from "webcrypto-core";
import { CryptoKey } from "../key";
import { Pkcs11Object } from "../p11_object";
import { CryptoCertificate, Pkcs11ImportAlgorithms } from... |
/**
* Creates new CertificateRequest in PKCS11 session
* @param data
* @param algorithm
* @param keyUsages
*/
public async importCert(data: Buffer, algorithm: Pkcs11ImportAlgorithms, keyUsages: KeyUsage[]) {
const array = new Uint8Array(data).buffer as ArrayBuffer;
this.parse(array);
... | {
Pkcs11Object.assertStorage(this.p11Object);
return new Uint8Array(this.p11Object.value).buffer as ArrayBuffer;
} | identifier_body |
dataSlice.ts | import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import _ from 'lodash';
import SampleJson from '../../samples/simple.json';
import { Path, EditMode, EditType } from '../../types';
import { isArray } from '../../utils/is';
/**
* State of dataSlice
* @param data the data. | const getParentPathAndName = (path: Path): [Path, string] => {
let parentPath: Path = [];
let name = '';
if (path.length === 1) {
name = path[0];
} else if (path.length > 1) {
parentPath = _.initial(path);
name = _.last<string>(path)!;
} else {
}
return [parentPath, name];
};
interface State ... | * @param editPath the path of editable. `null` means no editable data.
*/
| random_line_split |
dataSlice.ts | import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import _ from 'lodash';
import SampleJson from '../../samples/simple.json';
import { Path, EditMode, EditType } from '../../types';
import { isArray } from '../../utils/is';
/**
* State of dataSlice
* @param data the data.
* @param editPath the path of e... | else {
// the traget is not root object
const targetData = _.get(data, parentPath);
if (isArray(targetData)) {
// Array
_.set(
state.data,
parentPath,
targetData.filter((_, index) => index !== parseInt(name))
);
} else {
... | {
// the traget is root object
if (isArray(data)) {
// Array
state.data = data.filter((_, index) => `${index}` !== name);
} else {
// Object
_.unset(state.data, path);
}
} | conditional_block |
withHandlers.test.js | import React from 'react'
import { mount, shallow } from 'enzyme'
import { Dummy } from './utils'
import { withHandlers } from '..'
describe('withHandlers', () => {
it('passes immutable handlers', () => {
const enhance = withHandlers({
handler: () => () => null,
})
const EnhancedDummy = enhance(Dum... |
cache = { ...initialProps }
return cache
},
}
})
const componentHandlers = []
const componentHandlers2 = []
const Component = enhance(({ handler }) => {
componentHandlers.push(handler())
return null
})
const Component2 = enhance(({ handler }) =... | {
return cache
} | conditional_block |
withHandlers.test.js | import React from 'react'
import { mount, shallow } from 'enzyme'
import { Dummy } from './utils'
import { withHandlers } from '..'
describe('withHandlers', () => {
it('passes immutable handlers', () => {
const enhance = withHandlers({
handler: () => () => null,
})
const EnhancedDummy = enhance(Dum... | 'Refer to the docs for more info.',
)
console.error = originalError
/* eslint-enable no-console */
})
it('allows handers to be a factory', () => {
const enhance = withHandlers(initialProps => {
let cache
return {
handler: () => () => {
if (cache) {
... | expect(() => wrapper.prop('foo').call()).toThrowError()
expect(console.error).toBeCalledWith(
// eslint-disable-line no-console
'withHandlers(): Expected a map of higher-order functions. ' + | random_line_split |
make_loaddata.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make_loaddata.py
Convert ken_all.csv to loaddata
"""
import argparse
import csv
def merge_separated_line(args):
"""
yields line
yields a line.
if two (or more) lines has same postalcode,
merge them.
"""
def is_dup(line, buff):
""... | uff):
""" merge address of two lines """
new_buff = []
idx = 0
for element in line:
if element[:len(buff[idx])] != buff[idx]:
new_buff.append(u''.join([buff[idx], element]))
else:
new_buff.append(buff[idx])
idx += 1
... | ne, b | identifier_name |
make_loaddata.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make_loaddata.py
Convert ken_all.csv to loaddata
"""
import argparse
import csv
def merge_separated_line(args):
"""
yields line
yields a line.
if two (or more) lines has same postalcode,
merge them.
"""
def is_dup(line, buff):
""... | if buff[8].count(u'、') != 0:
return True
return False
def merge(line, buff):
""" merge address of two lines """
new_buff = []
idx = 0
for element in line:
if element[:len(buff[idx])] != buff[idx]:
new_buff.append(u''.join([buff[idx]... | True
| conditional_block |
make_loaddata.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make_loaddata.py
Convert ken_all.csv to loaddata
"""
import argparse
import csv
def merge_separated_line(args):
"""
yields line
yields a line.
if two (or more) lines has same postalcode,
merge them.
"""
def is_dup(line, buff):
""... | ame__ == '__main__':
args = parse_args()
main(args)
| = csv.writer(open(args.area, 'w'),
delimiter=',',
quoting=csv.QUOTE_NONE)
Netdata = csv.writer(open(args.net, 'w'),
delimiter=',',
quoting=csv.QUOTE_NONE)
for line in merge_separated_line(args):
zipcod... | identifier_body |
make_loaddata.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
make_loaddata.py
Convert ken_all.csv to loaddata
"""
import argparse
import csv
def merge_separated_line(args):
"""
yields line
yields a line.
if two (or more) lines has same postalcode,
merge them.
"""
def is_dup(line, buff):
""... | if line[8].count(u'、') != 0:
return True
if buff[8].count(u'、') != 0:
return True
return False
def merge(line, buff):
""" merge address of two lines """
new_buff = []
idx = 0
for element in line:
if element[:len(buff[idx])]... | return True
if buff[5].count(u'、') != 0:
return True
# line contains touten(kanji) | random_line_split |
IPv4Address.js | import React from 'react';
import { Box, Grommet, MaskedInput } from 'grommet';
import { grommet } from 'grommet/themes';
const IPv4ElementExp = /^[0-1][0-9][0-9]$|^2[0-4][0-9]$|^25[0-5]$|^[0-9][0-9]$|^[0-9]$/;
export const IPv4MaskedInput = () => {
const [value, setValue] = React.useState('');
return (
<Gro... | export default {
title: 'Input/MaskedInput/IPv4 address',
}; | random_line_split | |
femutils.py | various places in the Fem module.
"""
__title__ = "FEM Utilities"
__author__ = "Markus Hovorka, Bernd Hahnebach"
__url__ = "https://www.freecadweb.org"
import os
import sys
import FreeCAD
if FreeCAD.GuiUp:
import FreeCADGui
from PySide import QtGui
# *****************************************************... |
def is_of_type(obj, ty):
""" Compare type of *obj* with *ty* honoring Fems typesystem.
See :py:func:`type_of_obj` for more info about the special typesystem of
the Fem module.
:returns:
``True`` if *obj* is of type *ty*, ``False`` otherwise. Type must match
exactly: Derived objects are no... | """ Return type of *obj* honoring the special typesystem of Fem.
Python objects of the Fem workbench define their type via a class member
``<Class>.Type``. Return this type if the property exists. If not return
the conventional ``TypeId`` value.
:para obj: a document object
"""
if hasattr(obj,... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.