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 |
|---|---|---|---|---|
Gridbox.tsx | import {
Box,
Button,
Card,
Checkbox,
Chip,
styled,
Typography,
} from "@material-ui/core";
import { fetchResolver } from "@penrose/components";
import {
compileTrio,
evalEnergy,
PenroseState,
prepareState,
prettySubstance,
RenderStatic,
resample,
showError,
showMutations,
stepUntilCon... |
async componentDidUpdate(prevProps: GridboxProps) {
if (this.props.substance.prog !== prevProps.substance.prog) {
await this.update();
}
}
toggleView = () => {
this.setState({ showDiagram: !this.state.showDiagram });
};
checkboxClick = () => {
this.setState({ isSelected: !this.state.... | {
await this.update();
} | identifier_body |
number.py | """Configure number in a device through MQTT topic."""
from __future__ import annotations
import functools
import logging
import voluptuous as vol
from homeassistant.components import number
from homeassistant.components.number import (
DEFAULT_MAX_VALUE,
DEFAULT_MIN_VALUE,
DEFAULT_STEP,
NumberEntity... |
return config
_PLATFORM_SCHEMA_BASE = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_COMMAND_TEMPLATE): cv.template,
vol.Optional(CONF_MAX, default=DEFAULT_MAX_VALUE): vol.Coerce(float),
vol.Optional(CONF_MIN, default=DEFAULT_MIN_VALUE): vol.Coerce(float),
vol.Optio... | raise vol.Invalid(f"'{CONF_MAX}' must be > '{CONF_MIN}'") | conditional_block |
number.py | """Configure number in a device through MQTT topic."""
from __future__ import annotations
import functools
import logging
import voluptuous as vol
from homeassistant.components import number
from homeassistant.components.number import (
DEFAULT_MAX_VALUE,
DEFAULT_MIN_VALUE,
DEFAULT_STEP,
NumberEntity... | ):
_LOGGER.error(
"Invalid value for %s: %s (range %s - %s)",
self.entity_id,
num_value,
self.min_value,
self.max_value,
)
return
self._current_num... | if num_value is not None and (
num_value < self.min_value or num_value > self.max_value | random_line_split |
number.py | """Configure number in a device through MQTT topic."""
from __future__ import annotations
import functools
import logging
import voluptuous as vol
from homeassistant.components import number
from homeassistant.components.number import (
DEFAULT_MAX_VALUE,
DEFAULT_MIN_VALUE,
DEFAULT_STEP,
NumberEntity... |
class MqttNumber(MqttEntity, NumberEntity, RestoreEntity):
"""representation of an MQTT number."""
_entity_id_format = number.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_NUMBER_ATTRIBUTES_BLOCKED
def __init__(self, hass, config, config_entry, discovery_data):
"""Initialize the MQTT Nu... | """Set up the MQTT number."""
async_add_entities([MqttNumber(hass, config, config_entry, discovery_data)]) | identifier_body |
number.py | """Configure number in a device through MQTT topic."""
from __future__ import annotations
import functools
import logging
import voluptuous as vol
from homeassistant.components import number
from homeassistant.components.number import (
DEFAULT_MAX_VALUE,
DEFAULT_MIN_VALUE,
DEFAULT_STEP,
NumberEntity... | (self) -> float:
"""Return the increment/decrement step."""
return self._config[CONF_STEP]
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit of measurement."""
return self._config.get(CONF_UNIT_OF_MEASUREMENT)
@property
def value(self):
"... | step | identifier_name |
dynamic.py | '''
@Summary: Utility Methods for dynamic actions during program operation.
@Author: devopsec
'''
import os, sys, socket, inspect
def getWorkingDirs():
''' Returns project dir, parent dir, and current dir of calling script as dict'''
project_dir, parent_dir, current_dir = None
if os.path.exists(os.path.d... | ''' Sets project path to current calling script location or provided dir and move to it '''
if not dir == None and os.path.exists(dir):
proj_path = os.path.abspath(dir)
os.chdir(proj_path)
sys.path.append(proj_path)
print("Project path set to: " + proj_path)
else:
if... | def setProjectPath(dir=None): | random_line_split |
dynamic.py | '''
@Summary: Utility Methods for dynamic actions during program operation.
@Author: devopsec
'''
import os, sys, socket, inspect
def getWorkingDirs():
| 'current_dir' : current_dir
}
def setProjectPath(dir=None):
''' Sets project path to current calling script location or provided dir and move to it '''
if not dir == None and os.path.exists(dir):
proj_path = os.path.abspath(dir)
os.chdir(proj_path)
sys.path.append(proj_pat... | ''' Returns project dir, parent dir, and current dir of calling script as dict'''
project_dir, parent_dir, current_dir = None
if os.path.exists(os.path.dirname(__file__)):
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__... | identifier_body |
dynamic.py | '''
@Summary: Utility Methods for dynamic actions during program operation.
@Author: devopsec
'''
import os, sys, socket, inspect
def getWorkingDirs():
''' Returns project dir, parent dir, and current dir of calling script as dict'''
project_dir, parent_dir, current_dir = None
if os.path.exists(os.path.d... | ():
''' Returns hostname of current host '''
if socket.gethostname().find('.') >= 0:
return socket.gethostname()
else:
return socket.gethostbyaddr(socket.gethostname())[0]
def script_info():
'''
Returns a dictionary with information about the running top level Python
----------... | get_hostname | identifier_name |
dynamic.py | '''
@Summary: Utility Methods for dynamic actions during program operation.
@Author: devopsec
'''
import os, sys, socket, inspect
def getWorkingDirs():
''' Returns project dir, parent dir, and current dir of calling script as dict'''
project_dir, parent_dir, current_dir = None
if os.path.exists(os.path.d... |
else:
if os.path.exists(os.path.dirname(__file__)):
proj_path = os.path.abspath(os.path.dirname(__file__))
os.chdir(proj_path)
sys.path.append(proj_path)
else:
proj_path = os.path.abspath(os.getcwd())
os.chdir(proj_path)
sys.p... | proj_path = os.path.abspath(dir)
os.chdir(proj_path)
sys.path.append(proj_path)
print("Project path set to: " + proj_path) | conditional_block |
main.rs | const BONOMEN_BANNER: &'static str = r"
======= ======= == == ======= ========== ====== == ==
|| // || || ||\\ || || || ||\\ //|| || ||\\ ||
||==== || || || \\ || || || || || || ||==== || \\ ||
|| \\ || || || \\|| || || || || || || || \\||
======... | {
let mut susp_procs: u32 = 0;
for sys_proc in sys_procs_vec.iter() {
if *verb_mode {
terminal.fg(term::color::BRIGHT_GREEN).unwrap();
println!("> Checking system process: {}", sys_proc.name);
println!("> system process executable absolute path: {}", sys_proc.exe_pat... | identifier_body | |
main.rs | ::minwindef::DWORD;
#[cfg(windows)]
use winapi::minwindef::FALSE;
#[cfg(windows)]
use winapi::psapi::LIST_MODULES_ALL;
#[cfg(windows)]
use kernel32::OpenProcess;
#[cfg(windows)]
use kernel32::K32EnumProcessModulesEx;
#[cfg(windows)]
use kernel32::K32GetModuleBaseNameW;
#[cfg(windows)]
use kernel32::K32EnumProcesses;
#... |
// Read whole file line by line, and unwrap each line
let reader = BufReader::new(file);
let lines = reader.lines().map(|l| l.unwrap());
for line in lines {
// Split each line into a vector
let v: Vec<_> = line.split(';').map(|s| s.to_string()).collect();
assert!(v.len() >= 3,... | Ok(file) => file,
};
let mut procs = Vec::new(); | random_line_split |
main.rs | || || ||==== || \\ ||
|| \\ || || || \\|| || || || || || || || \\||
======= ======= == == ======= == == == ====== == ==";
const DEFAULT_FILE: &'static str = "default_procs.txt";
fn main() {
// Handle command line arguments
let matches = App::new(BONOMEN_BANNER)
.v... | unix_check_procs_impers | identifier_name | |
main.rs | (Arg::with_name("verbose")
.short("v")
.long("verbose")
.help("Verbose mode"))
.get_matches();
let mut terminal = term::stdout().unwrap();
if terminal.supports_attr(term::Attr::Bold) {
match terminal.attr(term::Attr::Bold) {
Ok(ok) => ok,
... | {
terminal.fg(term::color::BRIGHT_GREEN).unwrap();
println!("> Checking system process: {}", sys_proc.comm);
println!("> system process executable absolute path: {}", exe_path.to_str().unwrap());
} | conditional_block | |
foreign-object.ts | import { HasOpacity, Length } from "../../attributes/base";
import { XMLNS } from "../../constants";
import { Context } from "../../context";
import { AbstractRenderable, Containers_Attributes } from "../renderable";
export interface ForeignObject_Attributes extends Containers_Attributes, HasOpacity {
x: Length;
y... | (context: Context, attrs?: Partial<ForeignObject_Attributes>, html?: HTMLElement): ForeignObject {
const foreignObject = new ForeignObject(context, context.window.document.createElementNS(XMLNS.SVG, "foreignObject"), attrs);
if (html) {
foreignObject.addHTML(html);
}
return foreignObject;
}
pu... | create | identifier_name |
foreign-object.ts | import { HasOpacity, Length } from "../../attributes/base";
import { XMLNS } from "../../constants";
import { Context } from "../../context";
import { AbstractRenderable, Containers_Attributes } from "../renderable";
export interface ForeignObject_Attributes extends Containers_Attributes, HasOpacity {
x: Length;
y... |
}
| {
this._node.removeChild(html);
} | identifier_body |
foreign-object.ts | import { HasOpacity, Length } from "../../attributes/base";
import { XMLNS } from "../../constants";
import { Context } from "../../context";
import { AbstractRenderable, Containers_Attributes } from "../renderable";
export interface ForeignObject_Attributes extends Containers_Attributes, HasOpacity {
x: Length;
y... |
return foreignObject;
}
public addHTML(html: HTMLElement): void {
this._node.appendChild(html);
}
public remove(html: HTMLElement): void {
this._node.removeChild(html);
}
}
| {
foreignObject.addHTML(html);
} | conditional_block |
foreign-object.ts | import { HasOpacity, Length } from "../../attributes/base";
import { XMLNS } from "../../constants";
import { Context } from "../../context";
import { AbstractRenderable, Containers_Attributes } from "../renderable";
export interface ForeignObject_Attributes extends Containers_Attributes, HasOpacity {
x: Length;
y... | const foreignObject = new ForeignObject(context, context.window.document.createElementNS(XMLNS.SVG, "foreignObject"), attrs);
if (html) {
foreignObject.addHTML(html);
}
return foreignObject;
}
public addHTML(html: HTMLElement): void {
this._node.appendChild(html);
}
public remove(html:... |
export class ForeignObject extends AbstractRenderable<SVGForeignObjectElement, ForeignObject_Attributes> {
public static create(context: Context, attrs?: Partial<ForeignObject_Attributes>, html?: HTMLElement): ForeignObject { | random_line_split |
GeneralPunctuation.js | /*
* ../SourceForge/trunk/mathjax/jax/output/HTML-CSS/fonts/TeX/Main/Italic/GeneralPunctuation.js
*
* Copyright (c) 2010 Design Science, Inc.
*
* Part of the MathJax library.
* See http://www.mathjax.org for details. | */
MathJax.Unpack([
['MathJax.Hub.Insert','(MathJax.OutputJax["HTML-CSS"].','FONTDATA.FONTS["MathJax_Main-italic"],{8211:[286,-248,511,91,554],8212:[285,-248,1022,117,1038],8216',':[694,-379,','307,197,362],8217',3,'307,213,377],8220:[694,-378,514,243,606],8221',3,'514,176,538]});MathJax.Ajax.loadComplete',1,'fontD... | *
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
app-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { WelcomeComponent } from './welcome/welcome.component';
import { AdminLoginComponent } from './admin-login/admin-login.component';
const appRoutes: Routes = [
{
path: 'welcome',
component: Wel... | @NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [RouterModule]
})
export class AppRoutingModule {
} | random_line_split | |
app-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { WelcomeComponent } from './welcome/welcome.component';
import { AdminLoginComponent } from './admin-login/admin-login.component';
const appRoutes: Routes = [
{
path: 'welcome',
component: Wel... | {
} | AppRoutingModule | identifier_name |
server.rs | .0.0.1", port));
while listener.is_err() && port < p + 1000 {
port += 1;
listener = TcpListener::bind(("127.0.0.1", port));
}
match listener {
Ok(listener) => listener.local_addr().unwrap().port(),
Err(_) => 0
}
} else {
0
}
}
}
fn start_provider(... | <'a>() -> WebmachineResource<'a> {
WebmachineResource {
allowed_methods: vec!["POST"],
forbidden: callback(&|context, _| {
let options = SERVER_OPTIONS.lock().unwrap();
!context.request.has_header_value(&"Authorization".to_owned(), &format!("Bearer {}", options.borrow().server_key))
}),
pr... | shutdown_resource | identifier_name |
server.rs | 0.0.1", port));
while listener.is_err() && port < p + 1000 {
port += 1;
listener = TcpListener::bind(("127.0.0.1", port));
}
match listener {
Ok(listener) => listener.local_addr().unwrap().port(),
Err(_) => 0
}
} else {
0
}
}
}
fn start_provider(c... |
Err(err) => Err(err)
}
}),
..WebmachineResource::default()
}
}
fn mock_server_resource<'a>() -> WebmachineResource<'a> {
WebmachineResource {
allowed_methods: vec!["OPTIONS", "GET", "HEAD", "POST", "DELETE"],
resource_exists: callback(&|context, _| {
debug!("mock_server_resourc... | {
// Need to work out how to do this as the webmachine has to have a static lifetime
// shutdown.send(()).unwrap_or_default();
thread::spawn(move || {
info!("Scheduling master server to shutdown in {}ms", period);
thread::sleep(Duration::from_millis(period));
... | conditional_block |
server.rs | .0.0.1", port));
while listener.is_err() && port < p + 1000 {
port += 1;
listener = TcpListener::bind(("127.0.0.1", port));
}
match listener {
Ok(listener) => listener.local_addr().unwrap().port(),
Err(_) => 0
}
} else {
0
}
}
}
fn start_provider(... | }
}
}
},
Err(_) => Err(422)
}
}
fn shutdown_resource<'a>() -> WebmachineResource<'a> {
WebmachineResource {
allowed_methods: vec!["POST"],
forbidden: callback(&|context, _| {
let options = SERVER_OPTIONS.lock().unwrap();
!context.request.has_header_value(&"Autho... | {
let id = context.metadata.get("id").cloned().unwrap_or_default();
match verify::validate_id(&id, &SERVER_MANAGER) {
Ok(ms) => {
let mut map = btreemap!{ "mockServer" => ms.to_json() };
let mismatches = ms.mismatches();
if !mismatches.is_empty() {
map.insert("mismatches", json!(
... | identifier_body |
server.rs | self-signed.key");
let cert = include_str!("self-signed.cert");
TlsConfigBuilder::new()
.key(key.as_bytes())
.cert(cert.as_bytes())
.build()
.map_err(|err| {
format!("Failed to setup TLS using self-signed certificate - {}", ... |
match thread::spawn(start_fn).join() { | random_line_split | |
command_line.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from datetime import timedelta, date
import glob
import os
import sys
import pyinotify
from evernote.edam.error.ttypes import EDAMUserException
from tomboy2evernote.tomboy2evernote import Evernote, convert_tomboy_to_evernote
__author__ = 'Denis Kovalev... | import logging
logger = logging.getLogger(__name__)
def get_token():
try:
from settings import DEV_TOKEN
except ImportError:
DEV_TOKEN = ''
with open(CONFIG_FILE, 'w') as config_file:
config_file.write("DEV_TOKEN = ''")
if not DEV_TOKEN:
logger.error(
... | sys.path.append(CONFIG_DIR)
CONFIG_FILE = os.path.join(CONFIG_DIR, 'settings.py')
| random_line_split |
command_line.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from datetime import timedelta, date
import glob
import os
import sys
import pyinotify
from evernote.edam.error.ttypes import EDAMUserException
from tomboy2evernote.tomboy2evernote import Evernote, convert_tomboy_to_evernote
__author__ = 'Denis Kovalev... | (evernote_client):
# First we need to get all current notes and their titles to correctly handle note deletion
notes = convert_all_tomboy_notes(evernote_client)
# Configure daemon
wm = pyinotify.WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY | \
pyi... | run_as_daemon | identifier_name |
command_line.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from datetime import timedelta, date
import glob
import os
import sys
import pyinotify
from evernote.edam.error.ttypes import EDAMUserException
from tomboy2evernote.tomboy2evernote import Evernote, convert_tomboy_to_evernote
__author__ = 'Denis Kovalev... |
def process_IN_MOVED_TO(self, event):
# New note / Modify note
tomboy_note = event.pathname
if os.path.isfile(tomboy_note) and os.path.splitext(tomboy_note)[1] == '.note':
ev_note = convert_tomboy_to_evernote(tomboy_note)
if ev_note:
... | notes = convert_all_tomboy_notes(evernote_client)
# Configure daemon
wm = pyinotify.WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY | \
pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM
class EventHandler(pyinotify.ProcessEvent):
def my_init(self,... | identifier_body |
command_line.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from datetime import timedelta, date
import glob
import os
import sys
import pyinotify
from evernote.edam.error.ttypes import EDAMUserException
from tomboy2evernote.tomboy2evernote import Evernote, convert_tomboy_to_evernote
__author__ = 'Denis Kovalev... |
notes_hash[tomboy_note] = ev_note['title']
else:
print('Skipped template note')
if failed_notes:
print('The following notes failed to upload:')
for idx, note_title in enumerate(failed_notes):
print('[{}]: \'{}\''.format(idx + 1, note_title))
return no... | print('OK') | conditional_block |
ScriptEditorDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
EditScriptDialog.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*******... | canvas.setMapTool(prevMapTool) | random_line_split | |
ScriptEditorDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
EditScriptDialog.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*******... | self.btnRedo.setIcon(QgsApplication.getThemeIcon('/mActionRedo.png'))
# Connect signals and slots
self.btnSave.clicked.connect(self.save)
self.btnSaveAs.clicked.connect(self.saveAs)
self.btnEditHelp.clicked.connect(self.editHelp)
self.btnRun.clicked.connect(self.runAlgor... | QDialog.__init__(self)
self.setupUi(self)
self.setWindowFlags(Qt.WindowMinimizeButtonHint |
Qt.WindowMaximizeButtonHint |
Qt.WindowCloseButtonHint)
# Set icons
self.btnSave.setIcon(
QgsApplication.getThemeIcon('/mA... | identifier_body |
ScriptEditorDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
EditScriptDialog.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*******... |
self.filename = unicode(QFileDialog.getSaveFileName(self,
self.tr('Save script'), scriptDir,
filterName))
if self.filename:
if self.algType == self.SCRIPT_PYTHON \
and not self.filename.low... | scriptDir = RUtils.RScriptsFolder()
filterName = self.tr('Processing R script (*.rsx)') | conditional_block |
ScriptEditorDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
EditScriptDialog.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*******... | (self):
if self.algType == self.SCRIPT_PYTHON:
alg = ScriptAlgorithm(None, unicode(self.editor.text()))
alg.provider = ModelerUtils.providers['script']
if self.algType == self.SCRIPT_R:
alg = RAlgorithm(None, unicode(self.editor.text()))
alg.provider = Mod... | runAlgorithm | identifier_name |
setup.web.js | // @flow
import Bourne from '@hapi/bourne';
import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
import { browser } from '../lib-jitsi-meet';
import { parseURLParams } from '../util/parseURLParams';
import logger from './logger';
declare var APP: Object;
declare var config: Object;
/**
* Check... | () {
const urlParams = parseURLParams(window.location);
if (shouldUseHostPageLocalStorage(urlParams)) {
try {
const localStorageContent = Bourne.parse(urlParams['appData.localStorageContent']);
if (typeof localStorageContent === 'object') {
Object.keys(localStor... | setupJitsiLocalStorage | identifier_name |
setup.web.js | // @flow
import Bourne from '@hapi/bourne';
import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
import { browser } from '../lib-jitsi-meet';
import { parseURLParams } from '../util/parseURLParams';
import logger from './logger';
declare var APP: Object;
declare var config: Object;
/**
* Check... |
/**
* Checks if the local storage of the host page needs to be used instead jitsi-meet's local storage.
*
* @param {Object} urlParams - Object with parsed URL params.
* @returns {boolean} - True if the local storage of the host page needs to be used instead jitsi-meet's local storage
* and false otherwise.
*/
f... | {
APP.API.notifyLocalStorageChanged(jitsiLocalStorage.serialize());
} | identifier_body |
setup.web.js | // @flow
import Bourne from '@hapi/bourne';
import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
import { browser } from '../lib-jitsi-meet';
import { parseURLParams } from '../util/parseURLParams';
import logger from './logger';
declare var APP: Object;
declare var config: Object;
/**
* Check... | // WebKit browsers don't persist local storage for third-party iframes.
return true;
}
return false;
}
/**
* Performs initial setup of the jitsiLocalStorage.
*
* @returns {void}
*/
function setupJitsiLocalStorage() {
const urlParams = parseURLParams(window.location);
if (shouldUs... | }
if (browser.isWebKitBased() && _inIframe()) { | random_line_split |
setup.web.js | // @flow
import Bourne from '@hapi/bourne';
import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
import { browser } from '../lib-jitsi-meet';
import { parseURLParams } from '../util/parseURLParams';
import logger from './logger';
declare var APP: Object;
declare var config: Object;
/**
* Check... |
return false;
}
/**
* Performs initial setup of the jitsiLocalStorage.
*
* @returns {void}
*/
function setupJitsiLocalStorage() {
const urlParams = parseURLParams(window.location);
if (shouldUseHostPageLocalStorage(urlParams)) {
try {
const localStorageContent = Bourne.parse(urlP... | {
// WebKit browsers don't persist local storage for third-party iframes.
return true;
} | conditional_block |
extHostWebview.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public set options(newOptions: vscode.WebviewOptions) {
this.assertNotDisposed();
this.#proxy.$setOptions(this.#handle, serializeWebviewOptions(this.#extension, this.#workspace, newOptions));
this.#options = newOptions;
}
public async postMessage(message: any): Promise<boolean> {
if (this.#isDisposed) {
... | {
this.assertNotDisposed();
return this.#options;
} | identifier_body |
extHostWebview.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
this.#proxy.$setHtml(this.#handle, value);
}
}
public get options(): vscode.WebviewOptions {
this.assertNotDisposed();
return this.#options;
}
public set options(newOptions: vscode.WebviewOptions) {
this.assertNotDisposed();
this.#proxy.$setOptions(this.#handle, serializeWebviewOptions(this.#extensi... | {
this.#hasCalledAsWebviewUri = true;
this.#deprecationService.report('Webview vscode-resource: uris', this.#extension,
`Please migrate to use the 'webview.asWebviewUri' api instead: https://aka.ms/vscode-webview-use-aswebviewuri`);
} | conditional_block |
extHostWebview.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (extension: IExtensionDescription): extHostProtocol.WebviewExtensionDescription {
return { id: extension.identifier, location: extension.extensionLocation };
}
export function serializeWebviewOptions(
extension: IExtensionDescription,
workspace: IExtHostWorkspace | undefined,
options: vscode.WebviewOptions,
): ext... | toExtensionData | identifier_name |
extHostWebview.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
public get cspSource(): string {
const extensionLocation = this.#extension.extensionLocation;
if (extensionLocation.scheme === Schemas.https || extensionLocation.scheme === Schemas.http) {
// The extension is being served up from a CDN.
// Also include the CDN in the default csp.
let extensionCspRule ... | random_line_split | |
content-script.ts | import FictionpressParser from './parsers/FictionpressParser';
import ParserFactory from './ParserFactory';
import Epub from './epub/Epub';
import { IChapter } from './IChapter';
const hostname = window.location.hostname;
const href = window.location.href;
let parser = ParserFactory.getParser(hostname, docume... | {
const epub = new Epub(title, author, chapters);
// epub.export();
} | identifier_body | |
content-script.ts | import FictionpressParser from './parsers/FictionpressParser';
import ParserFactory from './ParserFactory';
import Epub from './epub/Epub';
import { IChapter } from './IChapter';
const hostname = window.location.hostname;
const href = window.location.href;
let parser = ParserFactory.getParser(hostname, docume... | });
function packEpub(title: string, author: string, chapters: IChapter[]) {
const epub = new Epub(title, author, chapters);
// epub.export();
} | xhr.send();
| random_line_split |
content-script.ts | import FictionpressParser from './parsers/FictionpressParser';
import ParserFactory from './ParserFactory';
import Epub from './epub/Epub';
import { IChapter } from './IChapter';
const hostname = window.location.hostname;
const href = window.location.href;
let parser = ParserFactory.getParser(hostname, docume... | (title: string, author: string, chapters: IChapter[]) {
const epub = new Epub(title, author, chapters);
// epub.export();
} | packEpub | identifier_name |
array.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | {
pub device_type: usize,
pub device_id: usize,
}
impl<'a> From<&'a TVMContext> for DLContext {
fn from(ctx: &'a TVMContext) -> Self {
Self {
device_type: ctx.device_type as u32,
device_id: ctx.device_id as i32,
}
}
}
impl Default for TVMContext {
fn defaul... | TVMContext | identifier_name |
array.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
let typ = TypeId::of::<T>();
(typ == TypeId::of::<i32>() && self.code == 0 && self.bits == 32)
|| (typ == TypeId::of::<i64>() && self.code == 0 && self.bits == 64)
|| (typ == TypeId::of::<u32>() && self.code == 1 && self.bits == 32)
|| (typ == TypeId::of::<u64>() && ... | {
return false;
} | conditional_block |
array.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | }
impl From<DLDataType> for DataType {
fn from(dtype: DLDataType) -> Self {
Self {
code: dtype.code as usize,
bits: dtype.bits as usize,
lanes: dtype.lanes as usize,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TVMContext {
pub device_type: ... | bits: dtype.bits as u8,
lanes: dtype.lanes as u16,
}
} | random_line_split |
array.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
pub fn code(&self) -> usize {
self.code
}
pub fn bits(&self) -> usize {
self.bits
}
pub fn lanes(&self) -> usize {
self.lanes
}
}
impl<'a> From<&'a DataType> for DLDataType {
fn from(dtype: &'a DataType) -> Self {
Self {
code: dtype.code as u8... | {
if self.lanes != 1 {
return false;
}
let typ = TypeId::of::<T>();
(typ == TypeId::of::<i32>() && self.code == 0 && self.bits == 32)
|| (typ == TypeId::of::<i64>() && self.code == 0 && self.bits == 64)
|| (typ == TypeId::of::<u32>() && self.code == 1 ... | identifier_body |
sectionFolding.js | /*
*
* Fold sections to optimize page load
*
* @author Robert Haritonov (http://rhr.me)
*
* */
define([
"jquery",
"source/load-options",
"sourceModules/utils",
"sourceModules/browser",
"sourceModules/sections",
"sourceModules/innerNavigation"
], function($, options, utils, browser, sections... | .source_main_nav_a').on({
click: function(e) {
e.preventDefault();
//Imitate hash change on click
var href = $(this).attr('href');
href = href.split('#');
href = href[href.length - 1];
... | dEventListener('popstate', function (event) {
openOnNavigation();
});
} else {
$(' | conditional_block |
sectionFolding.js | /*
*
* Fold sections to optimize page load
*
* @author Robert Haritonov (http://rhr.me)
*
* */
define([
"jquery",
"source/load-options",
"sourceModules/utils",
"sourceModules/browser",
"sourceModules/sections",
"sourceModules/innerNavigation"
], function($, options, utils, browser, sections... | }
});
});
}); | openSpoiler($(sectionsOnPage[i]), true); | random_line_split |
eventEmitter.ts | // based on https://gist.github.com/contra/2759355
// TODO: split eventEmitter and hooks into separate classes
// TODO: get rid of all the anys in this file. use new typescript feature, like
// export default class EventEmitter<LTypes> {
// private listeners: {[K in keyof LTypes]: Array<(...args: LTypes[K]) => any>... |
return obj;
}
}
| {
const transform = hooks[i];
obj = await transform(obj, info);
} | conditional_block |
eventEmitter.ts | // based on https://gist.github.com/contra/2759355
// TODO: split eventEmitter and hooks into separate classes
// TODO: get rid of all the anys in this file. use new typescript feature, like
// export default class EventEmitter<LTypes> {
// private listeners: {[K in keyof LTypes]: Array<(...args: LTypes[K]) => any>... | }
public emitAsync(event: string, ...args: Array<any>) {
return Promise.all((this.listeners[event] || []).map(async (listener) => {
return await listener.apply(listener, args);
}));
}
public addListener(event: string, listener: Listener) {
this.emit('newListener', event, listener);
if (!... | public emit(event: string, ...args: Array<any>) {
return (this.listeners[event] || []).map((listener) => {
return listener.apply(listener, args);
}); | random_line_split |
eventEmitter.ts | // based on https://gist.github.com/contra/2759355
// TODO: split eventEmitter and hooks into separate classes
// TODO: get rid of all the anys in this file. use new typescript feature, like
// export default class EventEmitter<LTypes> {
// private listeners: {[K in keyof LTypes]: Array<(...args: LTypes[K]) => any>... | (event: string, listener: Listener) {
return this.removeListener(event, listener);
}
// ordered set of hooks for mutating
// NOTE: a little weird for eventEmitter to be in charge of this
public addHook(event: string, transform: Hook) {
if (!this.hooks[event]) {
this.hooks[event] = [];
}
... | off | identifier_name |
eventEmitter.ts | // based on https://gist.github.com/contra/2759355
// TODO: split eventEmitter and hooks into separate classes
// TODO: get rid of all the anys in this file. use new typescript feature, like
// export default class EventEmitter<LTypes> {
// private listeners: {[K in keyof LTypes]: Array<(...args: LTypes[K]) => any>... |
public removeAllListeners(event: string) {
delete this.listeners[event];
return this;
}
public off(event: string, listener: Listener) {
return this.removeListener(event, listener);
}
// ordered set of hooks for mutating
// NOTE: a little weird for eventEmitter to be in charge of this
publ... | {
if (!this.listeners[event]) { return this; }
this.listeners[event] = this.listeners[event].filter((l) => l !== listener);
return this;
} | identifier_body |
unit_properties.rs | #[derive(Debug, Clone, PartialEq)]
pub struct UnitProperties {
pub name: String,
pub hero: bool,
pub wizard: bool,
pub points_per_model: f32,
pub max_unit_size: i32,
pub base_move_in: i32,
pub flying: bool,
pub save_standard: Option<i32>,
pub save_mortal: Option<i32>,
pub bravery... | impl UnitProperties {
pub fn new(
name: String,
hero: bool,
wizard: bool,
points_per_model: f32,
max_unit_size: i32,
base_move_in: i32,
flying: bool,
save_standard: Option<i32>,
save_mortal: Option<i32>,
bravery: i32,
) -> Self {
... | random_line_split | |
unit_properties.rs | #[derive(Debug, Clone, PartialEq)]
pub struct UnitProperties {
pub name: String,
pub hero: bool,
pub wizard: bool,
pub points_per_model: f32,
pub max_unit_size: i32,
pub base_move_in: i32,
pub flying: bool,
pub save_standard: Option<i32>,
pub save_mortal: Option<i32>,
pub bravery... | (
name: String,
hero: bool,
wizard: bool,
points_per_model: f32,
max_unit_size: i32,
base_move_in: i32,
flying: bool,
save_standard: Option<i32>,
save_mortal: Option<i32>,
bravery: i32,
) -> Self {
UnitProperties {
n... | new | identifier_name |
unit_properties.rs | #[derive(Debug, Clone, PartialEq)]
pub struct UnitProperties {
pub name: String,
pub hero: bool,
pub wizard: bool,
pub points_per_model: f32,
pub max_unit_size: i32,
pub base_move_in: i32,
pub flying: bool,
pub save_standard: Option<i32>,
pub save_mortal: Option<i32>,
pub bravery... |
}
| {
UnitProperties {
name: name,
hero: hero,
wizard: wizard,
points_per_model: points_per_model,
max_unit_size: max_unit_size,
base_move_in: base_move_in,
flying: flying,
save_standard: save_standard,
save_... | identifier_body |
georss.py | = self._getContext()
context['where']['srsName'] = srsName
context['where']['srsDimension'] = srsDimension
def _start_gml_point(self, attrsD):
self._parse_srs_attrs(attrsD)
self.ingeometry = 1
self.push('geometry', 0)
def _start_gml_linestring(self, attrsD):
se... | srsDimension = context['where'].get('srsDimension', 2)
swap = True
if srsName and "EPSG" in srsName:
epsg = int(srsName.split(":")[-1])
swap = bool(epsg in _geogCS)
geometry = _parse_poslist(
this, self.ingeometry, swap=swap, dims=srsDimension)
... | this = self.pop('pos')
context = self._getContext()
srsName = context['where'].get('srsName') | random_line_split |
georss.py | = self._getContext()
context['where']['srsName'] = srsName
context['where']['srsDimension'] = srsDimension
def _start_gml_point(self, attrsD):
self._parse_srs_attrs(attrsD)
self.ingeometry = 1
self.push('geometry', 0)
def _start_gml_linestring(self, attrsD):
se... |
geometry = _parse_georss_point(this, swap=swap, dims=srsDimension)
if geometry:
self._save_where(geometry)
def _start_gml_poslist(self, attrsD):
self.push('pos', 0)
def _end_gml_poslist(self):
this = self.pop('pos')
context = self._getContext()
srsN... | epsg = int(srsName.split(":")[-1])
swap = bool(epsg in _geogCS) | conditional_block |
georss.py | = self._getContext()
context['where']['srsName'] = srsName
context['where']['srsDimension'] = srsDimension
def _start_gml_point(self, attrsD):
self._parse_srs_attrs(attrsD)
self.ingeometry = 1
self.push('geometry', 0)
def _start_gml_linestring(self, attrsD):
se... | (self, attrsD):
self.push('pos', 0)
def _end_gml_poslist(self):
this = self.pop('pos')
context = self._getContext()
srsName = context['where'].get('srsName')
srsDimension = context['where'].get('srsDimension', 2)
swap = True
if srsName and "EPSG" in srsName:
... | _start_gml_poslist | identifier_name |
georss.py | = self._getContext()
context['where']['srsName'] = srsName
context['where']['srsDimension'] = srsDimension
def _start_gml_point(self, attrsD):
self._parse_srs_attrs(attrsD)
self.ingeometry = 1
self.push('geometry', 0)
def _start_gml_linestring(self, attrsD):
se... |
def _end_gml_poslist(self):
this = self.pop('pos')
context = self._getContext()
srsName = context['where'].get('srsName')
srsDimension = context['where'].get('srsDimension', 2)
swap = True
if srsName and "EPSG" in srsName:
epsg = int(srsName.split(":")[-... | self.push('pos', 0) | identifier_body |
tile2raw.js | var Jimp = require("jimp");
var fs = require("fs");
var replaceExt = require('replace-ext');
//print process.argv
// process.argv.forEach(function (val, index, array) {
// console.log(index + ': ' + val);
// });
Jimp.read(process.argv[2], function (err, image) {
var raw=[];
image.scan(0, 0, image.bitmap.width... | switch(color){
case 4278190335: // edge
raw.push(0);
break;
case 8388863: // number
raw.push(1);
break;
case 255:
case 0:
raw.push(process.argv[3]);
break;
default: // unkown color
console.log(color);
break;
}
});
fs.writeFileSync(replaceExt(process.argv[2], '.raw')... | // x, y is the position of this pixel on the image
var color = image.getPixelColor(x, y);
| random_line_split |
changelog.py | re
import urllib.request
from dataclasses import dataclass
from typing import Set, List, Optional, Dict, TextIO
# https://github.com/PyGithub/PyGithub
from github import Github
from github.Milestone import Milestone
from github.Repository import Repository
PLUGIN_REPO = "intellij-rust/intellij-rust"
MAINTAINERS = [... | description = result.group("description").strip().rstrip(".")
else:
description = issue.title
changelog_item = ChangelogItem(issue.number, description, issue.user.login)
for label in labels:
changelog.add_item(label, changelog_item)
return changelog
de... | print(f"Collecting changelog issues for `{milestone.title}` milestone")
changelog = Changelog(milestone.number)
issues = repo.get_issues(milestone=milestone, state="all")
comment_pattern = re.compile("<!--.*-->", re.RegexFlag.DOTALL)
changelog_description_pattern = re.compile("[Cc]hangelog:\\s*(?P<des... | identifier_body |
changelog.py | re
import urllib.request
from dataclasses import dataclass
from typing import Set, List, Optional, Dict, TextIO
# https://github.com/PyGithub/PyGithub
from github import Github
from github.Milestone import Milestone
from github.Repository import Repository
PLUGIN_REPO = "intellij-rust/intellij-rust"
MAINTAINERS = [... | print(c)
def collect_contributors(repo: Repository, milestone: Milestone) -> set[str]:
milestone_contributors = set()
issues = repo.get_issues(milestone=milestone, state="all")
for issue in issues:
user = issue.user
login = user.login
user_name = user.name
if user_n... |
print()
for c in sorted(contributors): | random_line_split |
changelog.py | re
import urllib.request
from dataclasses import dataclass
from typing import Set, List, Optional, Dict, TextIO
# https://github.com/PyGithub/PyGithub
from github import Github
from github.Milestone import Milestone
from github.Repository import Repository
PLUGIN_REPO = "intellij-rust/intellij-rust"
MAINTAINERS = [... |
else:
description = issue.title
changelog_item = ChangelogItem(issue.number, description, issue.user.login)
for label in labels:
changelog.add_item(label, changelog_item)
return changelog
def main():
parser = argparse.ArgumentParser()
parser.add_argument("... | description = result.group("description").strip().rstrip(".") | conditional_block |
changelog.py |
import urllib.request
from dataclasses import dataclass
from typing import Set, List, Optional, Dict, TextIO
# https://github.com/PyGithub/PyGithub
from github import Github
from github.Milestone import Milestone
from github.Repository import Repository
PLUGIN_REPO = "intellij-rust/intellij-rust"
MAINTAINERS = [
... | (username: str):
url = "https://github.com/" + username
print("checking " + url)
req = urllib.request.Request(url, method="HEAD")
with urllib.request.urlopen(req) as _:
pass # will thrown on 404
line = "[@{}]: {}\n".format(username, url)
return line
def contributor_list(args: argpars... | contributor_url | identifier_name |
blocks.rs | use ansi_term::Style;
use crate::fs::fields as f;
use crate::output::cell::TextCell;
impl f::Blocks {
pub fn render<C: Colours>(&self, colours: &C) -> TextCell {
match self {
Self::Some(blk) => TextCell::paint(colours.block_count(), blk.to_string()),
Self::None => TextCell:... |
}
| {
let blox = f::Blocks::Some(3005);
let expected = TextCell::paint_str(Red.blink(), "3005");
assert_eq!(expected, blox.render(&TestColours).into());
} | identifier_body |
blocks.rs | use ansi_term::Style;
use crate::fs::fields as f;
use crate::output::cell::TextCell;
impl f::Blocks {
pub fn render<C: Colours>(&self, colours: &C) -> TextCell {
match self {
Self::Some(blk) => TextCell::paint(colours.block_count(), blk.to_string()),
Self::None => TextCell:... | (&self) -> Style { Green.italic() }
}
#[test]
fn blocklessness() {
let blox = f::Blocks::None;
let expected = TextCell::blank(Green.italic());
assert_eq!(expected, blox.render(&TestColours).into());
}
#[test]
fn blockfulity() {
let blox = f::Blocks::Some(30... | no_blocks | identifier_name |
blocks.rs | use ansi_term::Style;
use crate::fs::fields as f;
use crate::output::cell::TextCell;
impl f::Blocks {
pub fn render<C: Colours>(&self, colours: &C) -> TextCell {
match self {
Self::Some(blk) => TextCell::paint(colours.block_count(), blk.to_string()),
Self::None => TextCell:... |
#[test]
fn blockfulity() {
let blox = f::Blocks::Some(3005);
let expected = TextCell::paint_str(Red.blink(), "3005");
assert_eq!(expected, blox.render(&TestColours).into());
}
} | }
| random_line_split |
abstractshaderclosure.js | (function (webgl) {
/**
* A ShaderClosure connects a mesh-specific GLProgram with it's Xflow data
* @param {GLContext} context
* @constructor
*/
var AbstractShaderClosure = function(context) {
/**
* @private
* @type {GLProgramObject|null}
*/
this.p... |
var programObject = new XML3D.webgl.GLProgramObject(this.context.gl, this.source);
this.program = programObject;
this.id = programObject.id;
},
bind: function() {
this.program.bind();
},
unbind: function() {
this.program.unbi... | if (!this.source.fragment || !this.source.vertex) {
XML3D.debug.logError("No source found for shader", this);
return;
} | random_line_split |
abstractshaderclosure.js | (function (webgl) {
/**
* A ShaderClosure connects a mesh-specific GLProgram with it's Xflow data
* @param {GLContext} context
* @constructor
*/
var AbstractShaderClosure = function(context) {
/**
* @private
* @type {GLProgramObject|null}
*/
this.p... |
var programObject = new XML3D.webgl.GLProgramObject(this.context.gl, this.source);
this.program = programObject;
this.id = programObject.id;
},
bind: function() {
this.program.bind();
},
unbind: function() {
this.program.unb... | {
XML3D.debug.logError("No source found for shader", this);
return;
} | conditional_block |
game.rs | () -> Game {
let mut ret = Game {
area: ~Area::new(area::Rock),
pos: Location(Point2::new(0i8, 0i8)),
seen: ~Fov::new(),
remembered: ~Fov::new(),
mobs: ~[],
player_dijkstra: None,
rng: rand::rng(),
stop: true,
... | new | identifier_name | |
game.rs | };
ret.next_level();
ret
}
pub fn player<'a>(&'a mut self) -> &'a mut Mob {
for i in self.mobs.mut_iter() {
if i.t == mob::Player {
return i;
}
}
fail!("No player mob");
}
pub fn player_idx(&self) -> uint {
... | }
}
false
}
pub fn mob_idx_at<'a>(&'a self, loc: Location) -> Option<uint> {
for (i, mob) in self.mobs.iter().enumerate() {
if mob.loc == loc && mob.is_alive() {
return Some(i);
}
}
None
}
pub fn drawable_mob_a... | return true; | random_line_split |
game.rs | _s());
} else {
mob.anim_state = mob::Dying(time::precise_time_s());
if mob.t == mob::TimeEater {
// Killed the end boss! Create a portal.
self.area.set(mob.loc, area::Portal);
}
}
}
pub fn is_walkable(&self, loc: Location) -> ... | {
self.next_level();
} | conditional_block | |
game.rs | };
ret.next_level();
ret
}
pub fn player<'a>(&'a mut self) -> &'a mut Mob {
for i in self.mobs.mut_iter() {
if i.t == mob::Player {
return i;
}
}
fail!("No player mob");
}
pub fn player_idx(&self) -> uint {
for (i... |
pub fn win_game(&mut self) {
self.update();
self.mobs[self.player_idx()].hits = -666;
self.mobs[self.player_idx()].anim_state = mob::Invisible;
}
pub fn smart_move(&mut self, dirs: &[Vec2<int>]) -> bool {
let player_idx = self.player_idx();
for d in dirs.iter() {
... | {
let player_idx = self.player_idx();
if self.mobs[player_idx].ammo < 6 {
self.msg("reload");
self.mobs[player_idx].ammo += 1;
}
self.update();
} | identifier_body |
__init__.js | /*
Qookery - Declarative UI Building for Qooxdoo
Copyright (c) Ergobyte Informatics S.A., www.ergobyte.gr
Licensed under the Apache License, Version 2.0 (the "License"); | http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions... | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
| random_line_split |
VocabularyImpl.d.ts | /*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
import { Vocabulary } from "./Vocabulary";
/**
* This class provides a default implementation of the {@link Vocabulary}
* interface.
*
... | implements Vocabulary {
/**
* Gets an empty {@link Vocabulary} instance.
*
* No literal or symbol names are assigned to token types, so
* {@link #getDisplayName(int)} returns the numeric value for all tokens
* except {@link Token#EOF}.
*/
static readonly EMPTY_VOCABULARY: ... | VocabularyImpl | identifier_name |
VocabularyImpl.d.ts | /*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
import { Vocabulary } from "./Vocabulary";
/**
* This class provides a default implementation of the {@link Vocabulary}
* interface.
*
... | /**
* Gets an empty {@link Vocabulary} instance.
*
* No literal or symbol names are assigned to token types, so
* {@link #getDisplayName(int)} returns the numeric value for all tokens
* except {@link Token#EOF}.
*/
static readonly EMPTY_VOCABULARY: VocabularyImpl;
priva... | random_line_split | |
board_menu.js | <script>
$(document).ready(function () {
function functionBind() {
$('.can-select').unbind('mouseenter').unbind('mouseleave');
$(".can-select").hover(function () {
$(this).addClass("bg-gray");
}, function () {
$(this).removeClass("bg-gray")... | });
$("#submenu_model").change(function () {
$(".can-select.bg-gray-active").attr("model", $(this).val());
$(".can-select.bg-gray-active").children("a").children("span").text($(this).children("option:checked").text());
});
$("#submenu_onlyadmin").change(function (... | });
$("#mainmenu_onlyadmin").change(function () {
$(".can-select.bg-gray-active").attr("onlyadmin", $(this).prop("checked") ? "1" : "0"); | random_line_split |
board_menu.js |
<script>
$(document).ready(function () {
function functionBind() {
$('.can-select').unbind('mouseenter').unbind('mouseleave');
$(".can-select").hover(function () {
$(this).addClass("bg-gray");
}, function () {
$(this).removeClass("bg-gray"... | else{
$(this).parent().parent().remove();
}
});
}
functionBind();
$("#btnAddMainMenu").click(function () {
$(".can-select").removeClass("bg-gray-active");
var td = $('<th class="can-select bg-gray-active mainmenu" main="1">... | {
var index=$(this).parent().index();
$(this).parent().remove();
var td=$($("#submenu_tr td")[index]);
td.remove();
} | conditional_block |
configs.py | # coding: utf-8
"""
DragonPy - Dragon 32 emulator in Python
=======================================
:created: 2013 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2014 by the DragonPy team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __fu... | if name.startswith("_"):
continue
# print name, type(value)
if not isinstance(value, (int, str, list, tuple, dict)):
continue
if isinstance(value, int):
print("%20s = %-6s in hex: %7s" % (
name, value, hex(value)
... | conditional_block | |
configs.py | # coding: utf-8
"""
DragonPy - Dragon 32 emulator in Python
=======================================
:created: 2013 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2014 by the DragonPy team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __fu... |
if cfg_dict["trace"]:
self.trace = True
else:
self.trace = False
self.verbosity = cfg_dict["verbosity"]
self.mem_info = DummyMemInfo()
self.memory_byte_middlewares = {}
self.memory_word_middlewares = {}
def _get_initial_Memory(self, size):... | self.cfg_dict = cfg_dict
self.cfg_dict["cfg_module"] = self.__module__ # FIXME: !
log.debug("cfg_dict: %s", repr(cfg_dict))
# # socket address for internal bus I/O:
# if cfg_dict["bus_socket_host"] and cfg_dict["bus_socket_port"]:
# self.bus = True
# self.bus_so... | identifier_body |
configs.py | # coding: utf-8
"""
DragonPy - Dragon 32 emulator in Python
=======================================
:created: 2013 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2014 by the DragonPy team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __fu... | """
Hold information about memory address areas which accessed via bus.
e.g.:
Interrupt vectors
Text screen
Serial/parallel devices
"""
def __init__(self, areas):
super(AddressAreas, self).__init__()
for start_addr, end_addr, txt in areas:
self.add... | class AddressAreas(dict): | random_line_split |
configs.py | # coding: utf-8
"""
DragonPy - Dragon 32 emulator in Python
=======================================
:created: 2013 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2014 by the DragonPy team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __fu... | (object):
# # http address/port number for the CPU control server
# CPU_CONTROL_ADDR = "127.0.0.1"
# CPU_CONTROL_PORT = 6809
# How many ops should be execute before make a control server update cycle?
BURST_COUNT = 10000
DEFAULT_ROMS = {}
def __init__(self, cfg_dict):
self.cfg_dic... | BaseConfig | identifier_name |
mod.rs | //! A bounded SPSC channel.
use arc::{Arc, ArcTrait};
use select::{Selectable, _Selectable};
use {Error, Sendable};
mod imp;
#[cfg(test)] mod test;
#[cfg(test)] mod bench;
/// Creates a new bounded SPSC channel.
///
/// ### Panic
///
/// Panics if `next_power_of_two(cap) * sizeof(T) >= isize::MAX`.
pub fn | <'a, T: Sendable+'a>(cap: usize) -> (Producer<'a, T>, Consumer<'a, T>) {
let packet = Arc::new(imp::Packet::new(cap));
packet.set_id(packet.unique_id());
(Producer { data: packet.clone() }, Consumer { data: packet })
}
/// The producing half of a bounded SPSC channel.
pub struct Producer<'a, T: Sendable+'a... | new | identifier_name |
mod.rs | //! A bounded SPSC channel.
use arc::{Arc, ArcTrait};
use select::{Selectable, _Selectable};
use {Error, Sendable};
mod imp;
#[cfg(test)] mod test;
#[cfg(test)] mod bench;
/// Creates a new bounded SPSC channel.
///
/// ### Panic
///
/// Panics if `next_power_of_two(cap) * sizeof(T) >= isize::MAX`.
pub fn new<'a, T:... | data: Arc<imp::Packet<'a, T>>,
}
impl<'a, T: Sendable+'a> Consumer<'a, T> {
/// Receives a message over this channel. Blocks until a message is available.
///
/// ### Errors
///
/// - `Disconnected` - No message is available and the sender has disconnected.
pub fn recv_sync(&self) -> Result... |
unsafe impl<'a, T: Sendable+'a> Send for Producer<'a, T> { }
/// The consuming half of a bounded SPSC channel.
pub struct Consumer<'a, T: Sendable+'a> { | random_line_split |
mod.rs | //! A bounded SPSC channel.
use arc::{Arc, ArcTrait};
use select::{Selectable, _Selectable};
use {Error, Sendable};
mod imp;
#[cfg(test)] mod test;
#[cfg(test)] mod bench;
/// Creates a new bounded SPSC channel.
///
/// ### Panic
///
/// Panics if `next_power_of_two(cap) * sizeof(T) >= isize::MAX`.
pub fn new<'a, T:... |
/// The producing half of a bounded SPSC channel.
pub struct Producer<'a, T: Sendable+'a> {
data: Arc<imp::Packet<'a, T>>,
}
impl<'a, T: Sendable+'a> Producer<'a, T> {
/// Sends a message over the channel. Blocks if the buffer is full.
///
/// ### Errors
///
/// - `Disconnected` - The receive... | {
let packet = Arc::new(imp::Packet::new(cap));
packet.set_id(packet.unique_id());
(Producer { data: packet.clone() }, Consumer { data: packet })
} | identifier_body |
PopupOptions.ts | import { Alignment } from "../../../viewer/enums/Alignment";
import { PopupOffset } from "./PopupOffset";
/**
* Interface for the options that define behavior and
* appearance of a popup.
*
* @interface
*/
export interface PopupOptions {
/**
* Specify if the popup should capture pointer events.
*
... | opacity?: number;
/**
* The popup position in a rectangle (does not apply to points).
* When not set the popup will change position automatically
* based on the viewport so that as much of it as possible is
* visible.
*
* @default undefined
*/
position?: Alignment;
} | * Opacity of the popup visuals.
*
* @default 1
*/ | random_line_split |
validate.py | import json
import os
import types
from . import constants
from .constants import PACKAGE_ANY
from .errorbundler import ErrorBundle
# This is necessary. Do not remove it unless you know exactly what
# you are doing.
import loader # noqa
import submain
def validate(path, format='json',
approved_applicat... | formats = {'json': lambda b: b.render_json()}
if format is not None:
return formats[format](bundle)
else:
return bundle | identifier_body | |
validate.py | import json
import os
import types
from . import constants
from .constants import PACKAGE_ANY
from .errorbundler import ErrorBundle
# This is necessary. Do not remove it unless you know exactly what
# you are doing.
import loader # noqa
import submain
def | (path, format='json',
approved_applications=os.path.join(os.path.dirname(__file__),
'app_versions.json'),
determined=True,
listed=True,
expectation=PACKAGE_ANY,
for_appversions=None,
overrides=N... | validate | identifier_name |
validate.py | import json
import os
import types
from . import constants
from .constants import PACKAGE_ANY
from .errorbundler import ErrorBundle
# This is necessary. Do not remove it unless you know exactly what
# you are doing.
import loader # noqa
import submain
def validate(path, format='json',
approved_applicat... |
return format_result(bundle, format)
def format_result(bundle, format):
# Write the results to the pipe
formats = {'json': lambda b: b.render_json()}
if format is not None:
return formats[format](bundle)
else:
return bundle | submain.prepare_package(bundle, path, expectation,
for_appversions=for_appversions,
timeout=timeout) | random_line_split |
validate.py | import json
import os
import types
from . import constants
from .constants import PACKAGE_ANY
from .errorbundler import ErrorBundle
# This is necessary. Do not remove it unless you know exactly what
# you are doing.
import loader # noqa
import submain
def validate(path, format='json',
approved_applicat... | return bundle | conditional_block | |
MMDAnimationHelper.d.ts | import {
AnimationClip,
Audio,
Camera,
Mesh,
Object3D,
SkinnedMesh
} from '../../../src/Three';
export interface MMDAnimationHelperParameter {
sync?: boolean;
afterglow?: number;
resetPhysicsOnLoop?: boolean;
}
export interface MMDAnimationHelperAddParameter {
animation?: AnimationClip | AnimationClip[];
p... | ik?: boolean;
grant?: boolean;
}
export class MMDAnimationHelper {
constructor( params?: MMDAnimationHelperParameter );
meshes: Mesh[];
camera: Camera | null;
cameraTarget: Object3D;
audio: Audio;
audioManager: AudioManager;
configuration: {
sync: boolean;
afterglow: number;
resetPhysicsOnLoop: boolean... | export interface MMDAnimationHelperPoseParameter {
resetPose?: boolean; | random_line_split |
MMDAnimationHelper.d.ts | import {
AnimationClip,
Audio,
Camera,
Mesh,
Object3D,
SkinnedMesh
} from '../../../src/Three';
export interface MMDAnimationHelperParameter {
sync?: boolean;
afterglow?: number;
resetPhysicsOnLoop?: boolean;
}
export interface MMDAnimationHelperAddParameter {
animation?: AnimationClip | AnimationClip[];
p... | {
constructor( params?: MMDAnimationHelperParameter );
meshes: Mesh[];
camera: Camera | null;
cameraTarget: Object3D;
audio: Audio;
audioManager: AudioManager;
configuration: {
sync: boolean;
afterglow: number;
resetPhysicsOnLoop: boolean;
};
enabled: {
animation: boolean;
ik: boolean;
grant: boo... | MMDAnimationHelper | identifier_name |
mod.rs | /*!
**The Conrod Guide**
## Table of Contents
1. [**What is Conrod?**][1]
- [A Brief Summary][1.1]
- [Screenshots and Videos][1.2]
- [Feature Overview][1.3]
- [Available Widgets][1.4]
- [Primitive Widgets][1.4.1]
- [Common Use Widgets][1.4.2]
- [Immediate Mode][1.5]
- [Wha... | - Making a `Button` widget
6. **Custom Graphics and Window Backends**
- Demonstration of Backend Implementation (using glium and glutin)
7. **Internals**
- The `Ui`'s Widget `Graph`
- `Ui::set_widgets` - How does it work?
8. **FAQ**
[1]: ./chapter_1/index.html
[1.1]: ./chapter_1/index.html... | random_line_split | |
.eslintrc.js | module.exports = {
env: {
browser: true,
es6: true,
'jest/globals': true,
jquery: true,
node: true
},
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 6,
ecmaFeatures: {
jsx: true
}
},
plugins: ['jest', 'flowtype', ... | 'prettier',
'prettier/react'
],
settings: {
react: {
version: 'detect'
}
},
rules: {
'no-global-assign': 'error',
'linebreak-style': ['error', 'unix'],
'no-cond-assign': 'error',
'no-console': [
'error',
... | 'plugin:jsx-a11y/recommended', | random_line_split |
he-IL.js | // If you want to suggest a new language you can use this file as a template.
// To reduce the file size you should remove the comment lines (the ones that start with // )
if(!window.calendar_languages) {
window.calendar_languages = {};
}
// Here you define the language and Country code. Replace en-US with your own.
/... | // - 'easter+1' is Easter Monday (1 day after Easter)
// - 'easter+39' is the Ascension Day
// - 'easter+49' is Pentecost
// # For holidays that are on a specific weekday after the beginning of a month: 'mm+n*w', where 'mm' is the month, 'n' is the ordinal position, 'w' is the weekday being 0: Sunday, 1: Mond... | // # For Easter: use simply 'easter'
// # For holidays that are based on the Easter date: 'easter+offset in days'.
// Some examples:
// - 'easter-2' is Good Friday (2 days before Easter) | random_line_split |
he-IL.js | // If you want to suggest a new language you can use this file as a template.
// To reduce the file size you should remove the comment lines (the ones that start with // )
if(!window.calendar_languages) |
// Here you define the language and Country code. Replace en-US with your own.
// First letters: the language code (lower case). See http://www.loc.gov/standards/iso639-2/php/code_list.php
// Last letters: the Country code (upper case). See http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_ele... | {
window.calendar_languages = {};
} | conditional_block |
svg-container.component.ts | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | *
* @param transform
* @param animate
*/
setPositionByTransform(transform: { x: number; y: number; k: number }, animate = false): void {
this.svgSelect
.transition()
.duration(animate ? 500 : 0)
.call(this.zoomController.transform, transform);
}
constructor(private el: ElementRe... | random_line_split | |
svg-container.component.ts | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | implements OnInit, AfterContentInit {
zoom = 1;
width: number;
height: number;
transform = 'translate(0, 0) scale(1)';
containerTransform = { x: 0, y: 0, k: 1 };
svgSelect: Selection<SafeAny, SafeAny, SafeAny, SafeAny>;
zoomController: ZoomBehavior<SafeAny, SafeAny>;
@ViewChild('svgContainer', { static... | SvgContainerComponent | identifier_name |
svg-container.component.ts | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
this.zoomEvent.emit(this.zoom);
this.transformEvent.emit(this.containerTransform as SafeAny);
});
this.svgSelect.call(this.zoomController).on('wheel.zoom', null);
}
ngAfterContentInit(): void {
const hostElem = this.el.nativeElement;
if (hostElem.parentNode !== null) {
cons... | {
this.transform = `translate(${this.containerTransform.x} ,${this.containerTransform.y})scale(${this.containerTransform.k})`;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.