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 |
|---|---|---|---|---|
normalize.ts | export interface EntityMap {
[key: string]: { [id: string]: any };
}
/**
* The state interface from which the app state should extend.
* Holds an instance of `NormalizedEntityState` itself.
*/
export interface NormalizedState {
/** The normalized state property */
normalized: NormalizedEntityState;
}
/**
* The... |
const parentRefs = getParentReferences(newEntities, action.payload);
/* istanbul ignore else */
if (parentRefs && parentRefs.indexOf(id) > -1) {
newEntities[parentSchemaKey][parentId][parentProperty].splice(
parentRefs.indexOf(id),
1
);
}
delete newEntities[childSchemaKey][id];
r... | {
return state;
} | conditional_block |
lib.rs | // Copyright (C) 2019 Sajeer Ahamed <ahamedsajeer.15.15@cse.mrt.ac.lk>
// Copyright (C) 2019 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Extracts release for [GStreamer](https://gstreamer.freedesktop.org) plugin meta... | crate_dir: path::PathBuf) -> Option<String> {
let mut cargo_toml = crate_dir;
cargo_toml.push("Cargo.toml");
let metadata = fs::metadata(&cargo_toml).ok()?;
let mtime = metadata.modified().ok()?;
let unix_time = mtime.duration_since(SystemTime::UNIX_EPOCH).ok()?;
let dt = chrono::Utc.timestamp(... | argo_mtime_date( | identifier_name |
lib.rs | // Copyright (C) 2019 Sajeer Ahamed <ahamedsajeer.15.15@cse.mrt.ac.lk>
// Copyright (C) 2019 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Extracts release for [GStreamer](https://gstreamer.freedesktop.org) plugin meta... | ///
/// - If extracted from a git repository, sets the `COMMIT_ID` environment variable to the short
/// commit id of the latest commit and the `BUILD_REL_DATE` environment variable to the date of the
/// commit.
///
/// - If not, `COMMIT_ID` will be set to the string `RELEASE` and the
/// `BUILD_REL_DATE` variab... | /// place as the `Cargo.toml`, or one directory up to allow for Cargo workspaces. If no
/// git repository is found, we assume this is a release. | random_line_split |
lib.rs | // Copyright (C) 2019 Sajeer Ahamed <ahamedsajeer.15.15@cse.mrt.ac.lk>
// Copyright (C) 2019 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Extracts release for [GStreamer](https://gstreamer.freedesktop.org) plugin meta... | println!("cargo:rustc-env=BUILD_REL_DATE={}", commit_date);
}
fn cargo_mtime_date(crate_dir: path::PathBuf) -> Option<String> {
let mut cargo_toml = crate_dir;
cargo_toml.push("Cargo.toml");
let metadata = fs::metadata(&cargo_toml).ok()?;
let mtime = metadata.modified().ok()?;
let unix_time = ... |
let crate_dir =
path::PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
let mut repo_dir = crate_dir.clone();
// First check for a git repository in the manifest directory and if there
// is none try one directory up in case we're in a Cargo workspace
let ... | identifier_body |
drivers.py | # coding=utf-8
import pprint
import config
import json
import urllib
import requests
class Driver(object):
def __init__(self):
self.driver_type = self.__class__.__name__
# Get credentials from conf files for CMDB
pass
def get_driver_type(self):
return self.driver_type
... |
#
#=======================================================================
class Fakeprovider(Driver):
def get_ci(self, ci):
# Simulate a driver that will provide Manager data.
# TODO a connect method must be implemented
# Assuming the connection is ok.
# Now c... | print("We are in Fakecmdb driver !")
pp.pprint(ci.data)
# Simply write a json file with ci.data content.
with open("Fakecmdb.json", "w") as jsonfile:
json.dump(ci.data, jsonfile, indent=4)
jsonfile.close() | conditional_block |
drivers.py | # coding=utf-8
import pprint
import config
import json
import urllib
import requests
class Driver(object):
def __init__(self):
self.driver_type = self.__class__.__name__
# Get credentials from conf files for CMDB
pass
def get_driver_type(self):
return self.driver_type
... | pp.pprint(ci.data)
# Simply write a json file with ci.data content.
with open("Fakecmdb.json", "w") as jsonfile:
json.dump(ci.data, jsonfile, indent=4)
jsonfile.close()
#
#===================================================================... | def set_ci(self, ci):
# Determine ci type so we can do the proper action.
pp = pprint.PrettyPrinter(indent=4)
if ci.ci_type == "Manager":
print("We are in Fakecmdb driver !") | random_line_split |
drivers.py | # coding=utf-8
import pprint
import config
import json
import urllib
import requests
class Driver(object):
def __init__(self):
self.driver_type = self.__class__.__name__
# Get credentials from conf files for CMDB
pass
def get_driver_type(self):
return self.driver_type
... | (self, ci):
username = config.alexandria.conf_file.get_driver_parameters("itop", "loginItop")
password = config.alexandria.conf_file.get_driver_parameters("itop", "passwordItop")
config.logger.debug("login : {}, password : {}".format(
... | set_ci | identifier_name |
drivers.py | # coding=utf-8
import pprint
import config
import json
import urllib
import requests
class Driver(object):
def __init__(self):
self.driver_type = self.__class__.__name__
# Get credentials from conf files for CMDB
pass
def get_driver_type(self):
return self.driver_type
... |
class Ironic(Driver):
pass
class Mondorescue(Driver):
pass
class Fakecmdb(Driver):
def set_ci(self, ci):
# Determine ci type so we can do the proper action.
pp = pprint.PrettyPrinter(indent=4)
if ci.ci_type == "Manager":
print("We are in Fakecmdb driver !")
... | print "Push to Redfish"
return True | identifier_body |
framedImage.py | #!/usr/bin/python3
# coding: utf-8
import gi
gi.require_version('CinnamonDesktop', '3.0')
from gi.repository import Gtk, GdkPixbuf, Gio, GLib, GObject, Gdk
from util import utils, trackers
MAX_IMAGE_SIZE = 320
MAX_IMAGE_SIZE_LOW_RES = 200
class FramedImage(Gtk.Image):
"""
Widget to hold the user face image... |
self.cancellable = Gio.Cancellable()
self.file.load_contents_async(self.cancellable, self.load_contents_async_callback)
def load_contents_async_callback(self, file, result, data=None):
try:
success, contents, etag_out = file.load_contents_finish(result)
except ... | self.cancellable.cancel()
self.cancellable = None | conditional_block |
framedImage.py | #!/usr/bin/python3
# coding: utf-8
import gi
gi.require_version('CinnamonDesktop', '3.0')
from gi.repository import Gtk, GdkPixbuf, Gio, GLib, GObject, Gdk
from util import utils, trackers
MAX_IMAGE_SIZE = 320
MAX_IMAGE_SIZE_LOW_RES = 200
class FramedImage(Gtk.Image):
"""
Widget to hold the user face image... |
def on_file_written(self, file, result, data=None):
try:
if file.replace_contents_finish(result):
self.set_image_internal(file.get_path())
except GLib.Error:
pass
| try:
success, contents, etag_out = file.load_contents_finish(result)
except GLib.Error:
self.clear_image()
return
if contents:
cache_name = GLib.build_filenamev([GLib.get_user_cache_dir(), "cinnamon-screensaver-albumart-temp"])
cache_file = Gi... | identifier_body |
framedImage.py | #!/usr/bin/python3
# coding: utf-8
import gi
gi.require_version('CinnamonDesktop', '3.0')
from gi.repository import Gtk, GdkPixbuf, Gio, GLib, GObject, Gdk
from util import utils, trackers
MAX_IMAGE_SIZE = 320
MAX_IMAGE_SIZE_LOW_RES = 200
class | (Gtk.Image):
"""
Widget to hold the user face image. It attempts to display an image at
its native size, up to a max sane size.
"""
__gsignals__ = {
"surface-changed": (GObject.SignalFlags.RUN_LAST, None, (object,))
}
def __init__(self, low_res=False, scale_up=False):
super(... | FramedImage | identifier_name |
framedImage.py | #!/usr/bin/python3
# coding: utf-8
import gi
gi.require_version('CinnamonDesktop', '3.0')
from gi.repository import Gtk, GdkPixbuf, Gio, GLib, GObject, Gdk
from util import utils, trackers
MAX_IMAGE_SIZE = 320
MAX_IMAGE_SIZE_LOW_RES = 200
class FramedImage(Gtk.Image):
"""
Widget to hold the user face image... | self.path = None
if self.get_realized():
self.generate_image()
def set_image_internal(self, path):
pixbuf = None
scaled_max_size = self.max_size * self.get_scale_factor()
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
except GLib.Error a... | def set_from_file(self, file):
self.file = file | random_line_split |
constants.py | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
| #
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other ... | random_line_split | |
account.component.ts | import { Component, ViewContainerRef, OnInit, ViewEncapsulation, Injector } from '@angular/core';
import { LoginService } from './login/login.service';
import { AppComponentBase } from '@shared/app-component-base';
@Component({
templateUrl: './account.component.html', | styleUrls: [
'./account.component.less'
],
encapsulation: ViewEncapsulation.None
})
export class AccountComponent extends AppComponentBase implements OnInit {
private viewContainerRef: ViewContainerRef;
versionText: string;
currentYear: number;
public constructor(
injector... | random_line_split | |
account.component.ts | import { Component, ViewContainerRef, OnInit, ViewEncapsulation, Injector } from '@angular/core';
import { LoginService } from './login/login.service';
import { AppComponentBase } from '@shared/app-component-base';
@Component({
templateUrl: './account.component.html',
styleUrls: [
'./account.component... | ngOnInit(): void {
this._loginService.init();
$('body').attr('class', 'login-page');
}
} | return abp.multiTenancy.isEnabled;
}
| identifier_body |
account.component.ts | import { Component, ViewContainerRef, OnInit, ViewEncapsulation, Injector } from '@angular/core';
import { LoginService } from './login/login.service';
import { AppComponentBase } from '@shared/app-component-base';
@Component({
templateUrl: './account.component.html',
styleUrls: [
'./account.component... | : void {
this._loginService.init();
$('body').attr('class', 'login-page');
}
} | OnInit() | identifier_name |
timer.rs | use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer i... | (&mut self, ms: u32) {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_Delay(ms) }
}
pub fn performance_counter(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn performance_frequency(&self) -> u64 {
unsafe... | delay | identifier_name |
timer.rs | use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer i... | fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_... |
#[cfg(test)] | random_line_split |
timer.rs | use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer i... | else { 0 }
}));
::std::thread::sleep_ms(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[cfg(test)]
fn test_timer_runs_at... | {
*num += 1;
20
} | conditional_block |
timer.rs | use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer i... |
#[cfg(test)]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = timer_subsystem.add_timer(20... | {
unsafe {
let f: *mut Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
} | identifier_body |
componentModelProvider.ts | import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
const cxmlExtension = ".cxml";
const graphicalFileSuffix = "_Graphical";
const graphicalFileExtension = ".xml";
export interface ComponentRawModel {
model: string;
graphical?: string;
}
export class ComponentModelProvid... |
const rawModel = this.editor.document.getText();
return {
model: rawModel,
graphical: this.getGraphicalRawModel()
};
}
private getGraphicalRawModel(): string | undefined {
const graphicalFilePath = this.getGraphicalPath();
if (fs.existsSync(gra... | {
return undefined;
} | conditional_block |
componentModelProvider.ts | import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
const cxmlExtension = ".cxml";
const graphicalFileSuffix = "_Graphical";
const graphicalFileExtension = ".xml";
export interface ComponentRawModel {
model: string;
graphical?: string;
}
export class ComponentModelProvid... | private getGraphicalPath(): string {
let parsedFile = path.parse(this.editor.document.fileName);
parsedFile.base = `${parsedFile.name}${graphicalFileSuffix}${graphicalFileExtension}`;
return path.format(parsedFile);
}
} | }
| random_line_split |
componentModelProvider.ts | import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
const cxmlExtension = ".cxml";
const graphicalFileSuffix = "_Graphical";
const graphicalFileExtension = ".xml";
export interface ComponentRawModel {
model: string;
graphical?: string;
}
export class ComponentModelProvid... |
} | {
let parsedFile = path.parse(this.editor.document.fileName);
parsedFile.base = `${parsedFile.name}${graphicalFileSuffix}${graphicalFileExtension}`;
return path.format(parsedFile);
} | identifier_body |
componentModelProvider.ts | import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
const cxmlExtension = ".cxml";
const graphicalFileSuffix = "_Graphical";
const graphicalFileExtension = ".xml";
export interface ComponentRawModel {
model: string;
graphical?: string;
}
export class ComponentModelProvid... | (): ComponentRawModel | undefined {
if (!this.isCxmlDocument()) {
return undefined;
}
const rawModel = this.editor.document.getText();
return {
model: rawModel,
graphical: this.getGraphicalRawModel()
};
}
private getGraphicalRawModel... | getRawModel | identifier_name |
hw5_task1.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
Задание 1: классный Человек.
УСЛОВИЕ:
Реализовать класс Person, который отображает запись в книге контактов.
Класс имеет 4 атрибута:
- surname - строка - фамилия контакта (обязательный)
- first_name - строка - имя контакта (обязательный)
- nickname - строк... | return str(delta)
else:
print "No correct data about person's birthday."
return "0"
def get_fullname(self):
u"""Метод выводит и возвращаем полное имя экземпляра класса Person"""
print self.surname, self.first_name
return self.surname + " " + self.fi... | res_date = None
self.surname = surname
self.first_name = first_name
self.birth_date = res_date
if nickname is not None:
self.nickname = nickname
def get_age(self):
u"""Метод класса подсчитывает и выводит количество полных лет"""
if self.birth_... | identifier_body |
hw5_task1.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
Задание 1: классный Человек.
УСЛОВИЕ:
Реализовать класс Person, который отображает запись в книге контактов.
Класс имеет 4 атрибута:
- surname - строка - фамилия контакта (обязательный)
- first_name - строка - имя контакта (обязательный)
- nickname - строк... | conditional_block | ||
hw5_task1.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
Задание 1: классный Человек.
УСЛОВИЕ:
Реализовать класс Person, который отображает запись в книге контактов.
Класс имеет 4 атрибута:
- surname - строка - фамилия контакта (обязательный)
- first_name - строка - имя контакта (обязательный)
- nickname - строк... | res_date = None
except ValueError:
print "Wrong value of birthday date!"
res_date = None
self.surname = surname
self.first_name = first_name
self.birth_date = res_date
if nickname is not None:
self.nickname = nickname
... | res_date = datetime.date(var_date.year,
var_date.month, var_date.day)
except TypeError:
print "Incorrect type of birthday date!"
| random_line_split |
hw5_task1.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
Задание 1: классный Человек.
УСЛОВИЕ:
Реализовать класс Person, который отображает запись в книге контактов.
Класс имеет 4 атрибута:
- surname - строка - фамилия контакта (обязательный)
- first_name - строка - имя контакта (обязательный)
- nickname - строк... | or:
print "Wrong value of birthday date!"
res_date = None
self.surname = surname
self.first_name = first_name
self.birth_date = res_date
if nickname is not None:
self.nickname = nickname
def get_age(self):
u"""Метод класса подсчи... | ValueErr | identifier_name |
App.js | import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.scss';
import Header from '../Header';
import Footer from '../Footer';
import Daytime from '../../models/daytime';
class App extends Component {
static propTypes = {
context: PropTypes.sh... |
render() {
const className = Daytime.isNight() ? s.containerNight : s.containerDay;
return !this.props.error ? (
<div className={className}>
<div className={s.container}>
<Header />
<main className={s.pageMain}>
{this.props.children}
</main>
<... |
componentWillUnmount() {
this.removeCss();
} | random_line_split |
App.js | import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.scss';
import Header from '../Header';
import Footer from '../Footer';
import Daytime from '../../models/daytime';
class App extends Component {
static propTypes = {
context: PropTypes.sh... |
componentWillMount() {
this.removeCss = this.props.context.insertCss(s);
}
componentWillUnmount() {
this.removeCss();
}
render() {
const className = Daytime.isNight() ? s.containerNight : s.containerDay;
return !this.props.error ? (
<div className={className}>
<div className=... | {
const context = this.props.context;
return {
insertCss: context.insertCss || emptyFunction,
onSetTitle: context.onSetTitle || emptyFunction,
onSetMeta: context.onSetMeta || emptyFunction,
onPageNotFound: context.onPageNotFound || emptyFunction,
};
} | identifier_body |
App.js | import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.scss';
import Header from '../Header';
import Footer from '../Footer';
import Daytime from '../../models/daytime';
class App extends Component {
static propTypes = {
context: PropTypes.sh... | () {
const context = this.props.context;
return {
insertCss: context.insertCss || emptyFunction,
onSetTitle: context.onSetTitle || emptyFunction,
onSetMeta: context.onSetMeta || emptyFunction,
onPageNotFound: context.onPageNotFound || emptyFunction,
};
}
componentWillMount() {
... | getChildContext | identifier_name |
build-bundle-app.js | /**
* Gulp tasks for wrapping Browserify modules.
*/
const browserify = require("browserify");
const gulp = require("gulp");
const sourcemaps = require("gulp-sourcemaps");
const uglify = require("gulp-uglify");
const path = require("path");
const through2 = require("through2");
const buffer = require("vinyl-buffer");... | autoInject: hasStyleLoader
});
bApp.transform("stringify", {
appliesTo: {
includeExtensions: uniteConfig.viewExtensions.map(ext => `.${ext}`)
}
});
bApp.transform("babelify", {
global: true,
presets: ["@babel/pre... | {
display.info("Running", "Browserify for App");
const bApp = browserify({
debug: buildConfiguration.sourcemaps,
entries: `./${path.join(uniteConfig.dirs.www.dist, "entryPoint.js")}`
});
const vendorPackages = await clientPackages.getBundleVendorPackages(uniteConf... | conditional_block |
build-bundle-app.js | /**
* Gulp tasks for wrapping Browserify modules.
*/
const browserify = require("browserify");
const gulp = require("gulp");
const sourcemaps = require("gulp-sourcemaps");
const uglify = require("gulp-uglify");
const path = require("path");
const through2 = require("through2");
const buffer = require("vinyl-buffer");... | entries: `./${path.join(uniteConfig.dirs.www.dist, "entryPoint.js")}`
});
const vendorPackages = await clientPackages.getBundleVendorPackages(uniteConfig);
let hasStyleLoader = false;
Object.keys(vendorPackages).forEach((key) => {
bApp.exclude(key);
co... | const bApp = browserify({
debug: buildConfiguration.sourcemaps, | random_line_split |
property.ts | import { PropertyMutationIndex, TransferrableMutationType } from '../../transfer/TransferrableMutation';
import { CommandExecutorInterface } from './interface';
import { NumericBoolean } from '../../utils';
export const PropertyProcessor: CommandExecutorInterface = (strings, nodeContext, workerContext, objectContext, ... | else {
console.error(`PROPERTY: getNode(${targetIndex}) is null.`);
}
}
return startPosition + PropertyMutationIndex.End;
},
print(mutations: Uint16Array, startPosition: number): {} {
const targetIndex = mutations[startPosition + PropertyMutationIndex.Target];
const t... | {
if (name && value != null) {
if (config.sanitizer) {
const mutated = config.sanitizer.setProperty(target, name, String(value));
if (!mutated) {
// TODO(choumx): Inform worker that sanitizer ignored unsafe property value change.
}
... | conditional_block |
property.ts | import { PropertyMutationIndex, TransferrableMutationType } from '../../transfer/TransferrableMutation';
import { CommandExecutorInterface } from './interface';
import { NumericBoolean } from '../../utils';
export const PropertyProcessor: CommandExecutorInterface = (strings, nodeContext, workerContext, objectContext, ... | (mutations: Uint16Array, startPosition: number, allowedMutation: boolean): number {
if (allowedExecution && allowedMutation) {
const targetIndex = mutations[startPosition + PropertyMutationIndex.Target];
const target = nodeContext.getNode(targetIndex);
const name = strings.get(mutations[st... | execute | identifier_name |
property.ts | import { PropertyMutationIndex, TransferrableMutationType } from '../../transfer/TransferrableMutation';
import { CommandExecutorInterface } from './interface';
import { NumericBoolean } from '../../utils';
export const PropertyProcessor: CommandExecutorInterface = (strings, nodeContext, workerContext, objectContext, ... | }
}
return startPosition + PropertyMutationIndex.End;
}
,
print(mutations: Uint16Array, startPosition: number): {} {
const targetIndex = mutations[startPosition + PropertyMutationIndex.Target];
const target = nodeContext.getNode(targetIndex);
const name = strings.get(mutat... | {
if (allowedExecution && allowedMutation) {
const targetIndex = mutations[startPosition + PropertyMutationIndex.Target];
const target = nodeContext.getNode(targetIndex);
const name = strings.get(mutations[startPosition + PropertyMutationIndex.Name]);
const value = getValue(mutatio... | identifier_body |
learner_profile_factory_spec.js | define(['backbone', 'jquery', 'underscore', 'js/common_helpers/ajax_helpers', 'js/common_helpers/template_helpers',
'js/spec/student_account/helpers',
'js/spec/student_profile/helpers',
'js/views/fields',
'js/student_account/models/user_account_model',
'js/student_account/models/... | AjaxHelpers.respondWithJson(requests, Helpers.createUserPreferencesData());
// sets the profile for full view.
context.accountPreferencesModel.set({account_privacy: 'all_users'});
LearnerProfileHelpers.expectProfileSectionsAndFieldsToBeRendered(learnerPro... | var context = createProfilePage(true),
learnerProfileView = context.learnerProfileView;
AjaxHelpers.respondWithJson(requests, Helpers.createAccountSettingsData()); | random_line_split |
gulpfile.js | var gulp = require('gulp'),
concat = require('gulp-concat'),
compass = require('gulp-compass'),
notify = require('gulp-notify');
function swallowError(error) |
function reportError(error) {
notify.onError().apply(this, arguments);
this.emit('end');
}
// combine js into single file
//===========================================
gulp.task('scripts', function() {
gulp.src([
'./src/js/lib/jquery.min.js',
'./src/js/lib/cssbeautify.js',
'./src/js/lib/specifici... | {
this.emit('end');
} | identifier_body |
gulpfile.js | var gulp = require('gulp'),
concat = require('gulp-concat'),
compass = require('gulp-compass'),
notify = require('gulp-notify');
function swallowError(error) {
this.emit('end');
}
function reportError(error) {
notify.onError().apply(this, arguments);
this.emit('end');
}
// com... | gulp.src('./assets/sass/*.scss')
.pipe(compass({
config_file: './config.rb',
css: './ext/css/',
sass: './assets/sass'
}))
.on('error', reportError);
});
// watch: monitor html and static assets updates
//===========================================
gulp.task('watch', function() {
//... | random_line_split | |
gulpfile.js | var gulp = require('gulp'),
concat = require('gulp-concat'),
compass = require('gulp-compass'),
notify = require('gulp-notify');
function swallowError(error) {
this.emit('end');
}
function | (error) {
notify.onError().apply(this, arguments);
this.emit('end');
}
// combine js into single file
//===========================================
gulp.task('scripts', function() {
gulp.src([
'./src/js/lib/jquery.min.js',
'./src/js/lib/cssbeautify.js',
'./src/js/lib/specificity.js',
'./src/js/... | reportError | identifier_name |
mouse.js | /**
mouse.js
Copyright (c) 2020 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
let mMouseLastX;
let mMouseLastY;
let mStartTime;
let mDragFlag = false;
let mMouseMode;
/* Show Mouse page */
function showMouse(serviceId) {
initAll();
setTitle('Mouse Profil... | te.now();
if (endTime - mStartTime < 40) {
return;
}
let original = event.originalEvent;
let x, y;
if (original.changedTouches) {
x = original.changedTouches[0].pageX;
y = original.changedTouches[0].pageY;
} else {
x = event.pageX;
y = event.pageY;
}
... | }
let endTime = Da | conditional_block |
mouse.js | /**
mouse.js
Copyright (c) 2020 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
let mMouseLastX;
let mMouseLastY;
let mStartTime;
let mDragFlag = false;
let mMouseMode;
/* Show Mouse page */
function showMouse(serviceId) {
initAll();
setTitle('Mouse Profil... |
$("#hogpBox").bind(EVENTNAME_TOUCHEND, event => {
onMouseUp(serviceId, event);
});
$("#hogpBox").bind(EVENTNAME_TOUCHMOVE, event => {
onMouseMove(serviceId, event);
event.preventDefault();
});
$("#hogpBox").bind('mouseleave', event => {
onMouseUp(serviceId, event);... | }); | random_line_split |
mouse.js | /**
mouse.js
Copyright (c) 2020 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
let mMouseLastX;
let mMouseLastY;
let mStartTime;
let mDragFlag = false;
let mMouseMode;
/* Show Mouse page */
function showMouse(serviceId) {
initAll();
setTitle('Mouse Profil... | ,
params: {
serviceId: serviceId
}
}).then(json => {
console.log('success');
console.log(json);
mMouseMode = json.mouse.type;
}).catch(e => {
console.log('Failed to get mouse info. message=' + e.errorMessage);
});
}
| identifier_body | |
mouse.js | /**
mouse.js
Copyright (c) 2020 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
let mMouseLastX;
let mMouseLastY;
let mStartTime;
let mDragFlag = false;
let mMouseMode;
/* Show Mouse page */
function showMouse(serviceId) {
initAll();
setTitle('Mouse Profil... | if (!mDragFlag) {
return;
}
let endTime = Date.now();
if (endTime - mStartTime < 40) {
return;
}
let original = event.originalEvent;
let x, y;
if (original.changedTouches) {
x = original.changedTouches[0].pageX;
y = original.changedTouches[0].pageY;
}... | event) {
| identifier_name |
automata.rs | // Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/ |
const S0:&'static str = "S0";
const S1:&'static str = "S1";
const S2:&'static str = "S2";
fn assert_state(state:&'static str,desired:&'static str) -> bool {
state == desired
}
#[allow(unused_assignments)]
fn dfa(s:&String) -> bool {
let mut state = S0;
// initializing the dfa to the start state with any... |
pub mod even_zeros_dfa { | random_line_split |
automata.rs | // Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/
pub mod even_zeros_dfa {
const S0:&'... |
}
#[test]
fn test_dfa() {
let string = "100".to_string();
if dfa(&string) {
println!("Language accepted by the dfa");
}else {
println!("Language not recognized");
}
}
}
| {println!("Language not recognized");} | conditional_block |
automata.rs | // Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/
pub mod even_zeros_dfa {
const S0:&'... |
#[allow(unused_assignments)]
fn dfa(s:&String) -> bool {
let mut state = S0;
// initializing the dfa to the start state with any symbol
if s.len() > 0 {state=S1;} else {return false;}
for i in s.chars() {
if i=='1' && assert_state(&state,S1)
{state = S1;}
else if i=='0' && asse... | {
state == desired
} | identifier_body |
automata.rs | // Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/
pub mod even_zeros_dfa {
const S0:&'... | () {
let string = "100".to_string();
if dfa(&string) {
println!("Language accepted by the dfa");
}else {
println!("Language not recognized");
}
}
}
| test_dfa | identifier_name |
index.ts | export * from "./topology_compiler";
export * from "./topology_local";
export { createSysBolt, createSysSpout } from "./topology_local_inprocess";
export * from "./topology_validation"; |
export * from "./distributed/topology_worker";
export * from "./distributed/memory/memory_storage";
export * from "./distributed/file_based/file_storage";
export * from "./distributed/http_based/http_storage_server";
export * from "./distributed/http_based/http_storage";
export * from "./distributed/gui/dashboard_serv... | export * from "./topology_interfaces"; | random_line_split |
util.rs | #![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflec... | (vec: Vector3<Float>) -> Float {
sin2_t(vec) / cos2_t(vec)
}
| tan2_t | identifier_name |
util.rs | #![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflec... |
pub fn sin_t(vec: Vector3<Float>) -> Float {
sin2_t(vec).sqrt()
}
pub fn tan2_t(vec: Vector3<Float>) -> Float {
sin2_t(vec) / cos2_t(vec)
}
| {
1.0 - cos2_t(vec)
} | identifier_body |
util.rs | #![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflec... |
let cos_tt = (1.0 - sin2_tt).sqrt();
Some(-w * eta + (eta * cos_ti - cos_tt) * wh)
}
/// Refract w around the shading normal (0, 0, 1)
pub fn refract_n(w: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Make sure normal is in the same hemisphere as w
let n = w.z.signum() * Vector3::unit... | {
return None;
} | conditional_block |
util.rs | #![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflec... | if sin2_tt >= 1.0 {
return None;
}
let cos_tt = (1.0 - sin2_tt).sqrt();
Some(-w * eta + (eta * cos_ti - cos_tt) * wh)
}
/// Refract w around the shading normal (0, 0, 1)
pub fn refract_n(w: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Make sure normal is in the same hemisp... | // Total internal reflection | random_line_split |
camera.rs | //! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two r... |
impl T {
#[allow(missing_docs)]
pub fn projection_matrix(&self) -> Matrix4<GLfloat> {
self.fov * self.rotation * self.translation
}
#[allow(missing_docs)]
pub fn translate_to(&mut self, p: Point3<f32>) {
self.position = p;
self.translation = Matrix4::from_translation(-p.to_vec());
}
/// Ro... | {
T {
position : Point3::new(0.0, 0.0, 0.0),
lateral_rotation : 0.0,
vertical_rotation : 0.0,
translation : Matrix4::one(),
rotation : Matrix4::one(),
fov : Matrix4::one(),
}
} | identifier_body |
camera.rs | //! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two r... |
/// Changes the camera pitch by `r` radians. Positive is up.
/// Angles that "flip around" (i.e. looking too far up or down)
/// are sliently rejected.
pub fn rotate_vertical(&mut self, r: GLfloat) {
let new_rotation = self.vertical_rotation + r;
if new_rotation < -PI / 2.0
|| new_rotation > PI /... | self.lateral_rotation = self.lateral_rotation + r;
self.rotate(&Vector3::new(0.0, 1.0, 0.0), r);
} | random_line_split |
camera.rs | //! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two r... |
self.vertical_rotation = new_rotation;
let axis =
Matrix3::from_axis_angle(
Vector3::new(0.0, 1.0, 0.0),
cgmath::Rad(self.lateral_rotation),
);
let axis = axis * (&Vector3::new(1.0, 0.0, 0.0));
self.rotate(&axis, r);
}
}
/// Set a shader's projection matrix to match tha... | {
return
} | conditional_block |
camera.rs | //! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two r... | (&mut self, p: Point3<f32>) {
self.position = p;
self.translation = Matrix4::from_translation(-p.to_vec());
}
/// Rotate about a given vector, by `r` radians.
fn rotate(&mut self, v: &Vector3<f32>, r: f32) {
let mat = Matrix3::from_axis_angle(*v, -cgmath::Rad(r));
let mat =
Matrix4::new(
... | translate_to | identifier_name |
modulo_one.rs | #![warn(clippy::modulo_one)]
#![allow(clippy::no_effect, clippy::unnecessary_operation)]
static STATIC_ONE: usize = 2 - 1;
static STATIC_NEG_ONE: i64 = 1 - 2;
fn main() | {
10 % 1;
10 % -1;
10 % 2;
i32::MIN % (-1); // also caught by rustc
const ONE: u32 = 1 * 1;
const NEG_ONE: i64 = 1 - 2;
const INT_MIN: i64 = i64::MIN;
2 % ONE;
5 % STATIC_ONE; // NOT caught by lint
2 % NEG_ONE;
5 % STATIC_NEG_ONE; // NOT caught by lint
INT_MIN % NEG_ONE... | identifier_body | |
modulo_one.rs | #![warn(clippy::modulo_one)]
#![allow(clippy::no_effect, clippy::unnecessary_operation)]
static STATIC_ONE: usize = 2 - 1;
static STATIC_NEG_ONE: i64 = 1 - 2;
fn | () {
10 % 1;
10 % -1;
10 % 2;
i32::MIN % (-1); // also caught by rustc
const ONE: u32 = 1 * 1;
const NEG_ONE: i64 = 1 - 2;
const INT_MIN: i64 = i64::MIN;
2 % ONE;
5 % STATIC_ONE; // NOT caught by lint
2 % NEG_ONE;
5 % STATIC_NEG_ONE; // NOT caught by lint
INT_MIN % NEG_... | main | identifier_name |
modulo_one.rs | #![warn(clippy::modulo_one)]
#![allow(clippy::no_effect, clippy::unnecessary_operation)]
static STATIC_ONE: usize = 2 - 1;
static STATIC_NEG_ONE: i64 = 1 - 2;
fn main() { | i32::MIN % (-1); // also caught by rustc
const ONE: u32 = 1 * 1;
const NEG_ONE: i64 = 1 - 2;
const INT_MIN: i64 = i64::MIN;
2 % ONE;
5 % STATIC_ONE; // NOT caught by lint
2 % NEG_ONE;
5 % STATIC_NEG_ONE; // NOT caught by lint
INT_MIN % NEG_ONE; // also caught by rustc
INT_MIN %... | 10 % 1;
10 % -1;
10 % 2; | random_line_split |
default.py | 开发者中心 -> 点击应用ID -> 基本信息 中获取 APP_ID 和 APP_TOKEN 的值
APP_ID = 'hello-world'
APP_TOKEN = 'c52de43b-ef43-49b2-8268-b53c5271750a'
# 蓝鲸智云开发者中心的域名,形如:http://paas.bking.com
BK_PAAS_HOST = 'http://paas.bking.com'
# 是否启用celery任务
IS_USE_CELERY = True
# 本地开发的 celery 的消息队列(RabbitMQ)信息
BROKER_URL_DEV = 'amqp://guest:guest@127.0.0.1:... | os.path.join(PROJECT_ROOT, 'static'),
)
STATIC_VERSION = 0.1
# 应用本地静态资源目录
STATIC_URL = '%sstatic/' % SITE_URL
ROOT_URLCONF = 'urls'
# ==============================================================================
# Templates
# ==============================================================================
# mako te... | random_line_split | |
default.py | 开发者中心 -> 点击应用ID -> 基本信息 中获取 APP_ID 和 APP_TOKEN 的值
APP_ID = 'hello-world'
APP_TOKEN = 'c52de43b-ef43-49b2-8268-b53c5271750a'
# 蓝鲸智云开发者中心的域名,形如:http://paas.bking.com
BK_PAAS_HOST = 'http://paas.bking.com'
# 是否启用celery任务
IS_USE_CELERY = True
# 本地开发的 celery 的消息队列(RabbitMQ)信息
BROKER_URL_DEV = 'amqp://guest:guest@127.0.0.1:... | os.makedirs(LOGGING_DIR)
except:
pass
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s [%(asctime)s] %(pathname)s %(lineno)d %(funcName)s %(process)d %(thread)d \n \t %(message)s \n',
'datefmt': '... |
try:
| identifier_name |
default.py | 开发者中心 -> 点击应用ID -> 基本信息 中获取 APP_ID 和 APP_TOKEN 的值
APP_ID = 'hello-world'
APP_TOKEN = 'c52de43b-ef43-49b2-8268-b53c5271750a'
# 蓝鲸智云开发者中心的域名,形如:http://paas.bking.com
BK_PAAS_HOST = 'http://paas.bking.com'
# 是否启用celery任务
IS_USE_CELERY = True
# 本地开发的 celery 的消息队列(RabbitMQ)信息
BROKER_URL_DEV = 'amqp://guest:guest@127.0.0.1:... | {
'class': LOG_CLASS,
'formatter': 'verbose',
'filename': os.path.join(LOGGING_DIR, '%s.log' % APP_ID),
'maxBytes': 1024 * 1024 * 10,
'backupCount': 5
},
'component': {
| ,
'formatter': 'simple'
},
'root': | conditional_block |
default.py | 开发者中心 -> 点击应用ID -> 基本信息 中获取 APP_ID 和 APP_TOKEN 的值
APP_ID = 'hello-world'
APP_TOKEN = 'c52de43b-ef43-49b2-8268-b53c5271750a'
# 蓝鲸智云开发者中心的域名,形如:http://paas.bking.com
BK_PAAS_HOST = 'http://paas.bking.com'
# 是否启用celery任务
IS_USE_CELERY = True
# 本地开发的 celery 的消息队列(RabbitMQ)信息
BROKER_URL_DEV = 'amqp://guest:guest@127.0.0.1:... | 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s [%(asctime)s] %(pathname)s %(lineno)d %(funcName)s %(process)d %(thread)d \n \t %(message)s \n',
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(leve... | t:
pass
LOGGING = {
'version': | identifier_body |
Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
reporter: require('jshint-stylish')
},
// when this task is run, lint the Gruntfile and all js files ilisted
build: ['Gruntfile.js', 'server.js', 'pub... | grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-concurrent');
grunt.registerTask('default', ['jshint', 'csslint', 'autoprefixer', ... | }); //closes grunt initconfig
| random_line_split |
update.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the update tool."""
from __future__ import unicode_literals
import os
import sys
import unittest
from tools import update
from tests import test_lib
@unittest.skipIf(
os.environ.get('TRAVIS_OS_NAME') == 'osx',
'TLS 1.2 not supported by macOS on Tr... | package_filenames.get(self._PROJECT_NAME, None),
'{0:s}-{1:s}.1.win32.msi'.format(
self._PROJECT_NAME, self._PROJECT_VERSION))
self.assertEqual(
package_versions.get(self._PROJECT_NAME, None),
[self._PROJECT_VERSION, '1'])
if __name__ == '__main__':
unit... | """Tests the GetPackageFilenamesAndVersions function."""
dependency_updater = update.DependencyUpdater(
preferred_machine_type='x86', preferred_operating_system='Windows')
package_filenames, package_versions = (
dependency_updater._GetPackageFilenamesAndVersions([]))
if (sys.version_info[0... | identifier_body |
update.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the update tool."""
from __future__ import unicode_literals
import os
import sys
import unittest
from tools import update
from tests import test_lib
@unittest.skipIf(
os.environ.get('TRAVIS_OS_NAME') == 'osx',
'TLS 1.2 not supported by macOS on Tr... | self.assertIsNone(package_versions)
else:
self.assertIsNotNone(package_filenames)
self.assertIsNotNone(package_versions)
self.assertEqual(
package_filenames.get(self._PROJECT_NAME, None),
'{0:s}-{1:s}.1.win32.msi'.format(
self._PROJECT_NAME, self._PROJECT_... | self.assertIsNone(package_filenames) | random_line_split |
update.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the update tool."""
from __future__ import unicode_literals
import os
import sys
import unittest
from tools import update
from tests import test_lib
@unittest.skipIf(
os.environ.get('TRAVIS_OS_NAME') == 'osx',
'TLS 1.2 not supported by macOS on Tr... | (test_lib.BaseTestCase):
"""Tests for the dependency updater class."""
# pylint: disable=protected-access
_PROJECT_NAME = 'dfvfs'
_PROJECT_VERSION = '20180510'
def testGetPackageFilenamesAndVersions(self):
"""Tests the GetPackageFilenamesAndVersions function."""
dependency_updater = update.Dependen... | DependencyUpdaterTest | identifier_name |
update.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the update tool."""
from __future__ import unicode_literals
import os
import sys
import unittest
from tools import update
from tests import test_lib
@unittest.skipIf(
os.environ.get('TRAVIS_OS_NAME') == 'osx',
'TLS 1.2 not supported by macOS on Tr... | unittest.main() | conditional_block | |
soupselect.py | """
soupselect.py - https://code.google.com/p/soupselect/
CSS selector support for BeautifulSoup.
soup = BeautifulSoup('<html>...')
select(soup, 'div')
- returns a list of div elements
select(soup, 'div#main ul a')
- returns a list of links inside a ul inside div#main
"""
import re
from bs4 import BeautifulSoup
t... | if not BeautifulSoupClass:
from BeautifulSoup import BeautifulSoup as BeautifulSoupClass
delattr(BeautifulSoupClass, 'findSelect')
def cssFind(html, selector):
"""
Parse ``html`` with class:`BeautifulSoup.BeautifulSoup` and use
:func:`.select` on the result.
Added by Espen A. Kristian... |
def unmonkeypatch(BeautifulSoupClass=None): | random_line_split |
soupselect.py | """
soupselect.py - https://code.google.com/p/soupselect/
CSS selector support for BeautifulSoup.
soup = BeautifulSoup('<html>...')
select(soup, 'div')
- returns a list of div elements
select(soup, 'div#main ul a')
- returns a list of links inside a ul inside div#main
"""
import re
from bs4 import BeautifulSoup
t... | (html):
return re.sub('(\s|\\xa0)+', ' ', html).strip()
| normalize_whitespace | identifier_name |
soupselect.py | """
soupselect.py - https://code.google.com/p/soupselect/
CSS selector support for BeautifulSoup.
soup = BeautifulSoup('<html>...')
select(soup, 'div')
- returns a list of div elements
select(soup, 'div#main ul a')
- returns a list of links inside a ul inside div#main
"""
import re
from bs4 import BeautifulSoup
t... |
found = []
for context in current_context:
found.extend(
context.findAll(tag,
{'class': lambda attr: attr and klass in attr.split()}
)
)
current_context = found
continue
... | tag = True | conditional_block |
soupselect.py | """
soupselect.py - https://code.google.com/p/soupselect/
CSS selector support for BeautifulSoup.
soup = BeautifulSoup('<html>...')
select(soup, 'div')
- returns a list of div elements
select(soup, 'div#main ul a')
- returns a list of links inside a ul inside div#main
"""
import re
from bs4 import BeautifulSoup
t... |
def select(soup, selector):
"""
soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve.
"""
tokens = selector.split()
current_context = [soup]
for token in tokens:
m = attribselect_re.match(token)
if m:
... | """
Takes an operator, attribute and optional value; returns a function that
will return True for elements that match that combination.
"""
return {
'=': lambda el: el.get(attribute) == value,
# attribute includes value as one of a set of space separated tokens
'~': lambda el: va... | identifier_body |
DesktopMonkeyPatch.ts | import fs from "fs"
import path from "path"
import {app} from "electron"
import {execSync} from "child_process"
import {last} from "@tutao/tutanota-utils"
import {neverNull} from "@tutao/tutanota-utils"
import {Logger, replaceNativeLogger} from "../api/common/Logger"
import {log, rebindDesktopLog} from "./DesktopLog"
... | rebindDesktopLog()
process.on("exit", () => {
const logDir = path.join(app.getPath("userData"), "logs")
const logFilePath = path.join(logDir, "tutanota_desktop.log")
const oldLogFilePath = path.join(logDir, "tutanota_desktop_old.log")
const entries = logger.getEntries()
fs.mkdirSync(logDir, {
recursive: true,
}... | replaceNativeLogger(global, logger, true)
// we need to bind to a new logger | random_line_split |
DesktopMonkeyPatch.ts | import fs from "fs"
import path from "path"
import {app} from "electron"
import {execSync} from "child_process"
import {last} from "@tutao/tutanota-utils"
import {neverNull} from "@tutao/tutanota-utils"
import {Logger, replaceNativeLogger} from "../api/common/Logger"
import {log, rebindDesktopLog} from "./DesktopLog"
... |
} catch (e) {
log.debug("failed to detect locale")
}
}
global.btoa = str => Buffer.from(str, "binary").toString("base64")
global.atob = b64 => Buffer.from(b64, "base64").toString("binary")
export function mp() {
log.debug("the monkey has been patched")
} | {
const locale = neverNull(last(parts)).trim()
log.debug("detected locale", locale)
process.env.LC_ALL = locale
} | conditional_block |
DesktopMonkeyPatch.ts | import fs from "fs"
import path from "path"
import {app} from "electron"
import {execSync} from "child_process"
import {last} from "@tutao/tutanota-utils"
import {neverNull} from "@tutao/tutanota-utils"
import {Logger, replaceNativeLogger} from "../api/common/Logger"
import {log, rebindDesktopLog} from "./DesktopLog"
... | () {
log.debug("the monkey has been patched")
} | mp | identifier_name |
DesktopMonkeyPatch.ts | import fs from "fs"
import path from "path"
import {app} from "electron"
import {execSync} from "child_process"
import {last} from "@tutao/tutanota-utils"
import {neverNull} from "@tutao/tutanota-utils"
import {Logger, replaceNativeLogger} from "../api/common/Logger"
import {log, rebindDesktopLog} from "./DesktopLog"
... | {
log.debug("the monkey has been patched")
} | identifier_body | |
agilent34410A.py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... | import time
import struct
from .. import ivi
from .. import dmm
from .. import scpi
class agilent34410A(scpi.dmm.Base):
"Agilent 34410A IVI DMM driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', '34410A')
super(agilent34410A, self).__init__(*a... | """
| random_line_split |
agilent34410A.py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... |
def _memory_recall(self, index):
index = int(index)
if index < 1 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("*rcl %d" % index)
def _get_memory_name(self, index):
index = int(inde... | index = int(index)
if index < 1 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("*sav %d" % index) | identifier_body |
agilent34410A.py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... | (self, index, value):
index = int(index)
value = str(value)
if index < 1 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("memory:state:name %d, \"%s\"" % (index, value))
| _set_memory_name | identifier_name |
agilent34410A.py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... |
def _memory_save(self, index):
index = int(index)
if index < 1 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("*sav %d" % index)
def _memory_recall(self, index):
i... | self.utility.reset() | conditional_block |
diary-show.component.ts | import {Component, OnInit,Input} from '@angular/core';
import {DiaryService} from '../services/painDiaries'
import {Router} from "@angular/router";
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'diary-show',
styleUrls: ['../diary/diary.style.css'],
templateUrl: 'diary-show.template.html'... |
onBack(): void {
this.router.navigate(['/diaries']);
}
}
| {
this.router.navigate(['','users', this.user_id]);
} | identifier_body |
diary-show.component.ts | import {Component, OnInit,Input} from '@angular/core';
import {DiaryService} from '../services/painDiaries'
import {Router} from "@angular/router";
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'diary-show',
styleUrls: ['../diary/diary.style.css'],
templateUrl: 'diary-show.template.html'... | painLevelCount:string;
moodLevelCount: string;
diaries = []
user_id = window.localStorage.getItem('cpms_user_id')
powers = ['Aching','Sharp','Penetrating','Throbbing','Tender','Nagging','Shooting','Burning','Numb','Stabbing','Pinching','Gnaving'];
constructor( private diaryService: DiaryService, privat... | id: string | random_line_split |
diary-show.component.ts | import {Component, OnInit,Input} from '@angular/core';
import {DiaryService} from '../services/painDiaries'
import {Router} from "@angular/router";
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'diary-show',
styleUrls: ['../diary/diary.style.css'],
templateUrl: 'diary-show.template.html'... | ( private diaryService: DiaryService, private route: ActivatedRoute, private router: Router) {
route.params.subscribe(params => { this.id = params['id']; });
this.diaryService.getDiaries()
.subscribe(
res => {this.diaries = res})
this.diaryService.getDiary(this.id)
.subscribe(res => this.dia... | constructor | identifier_name |
component.js | class Component {
/**
* Generic constructor for all components
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(classDef, el, options) {
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML El... | * @param {class} classDef
* @param {Element | NodeList | jQuery} els
* @param {Object} options
*/
static init(classDef, els, options) {
let instances = null;
if (els instanceof Element) {
instances = new classDef(els, options);
} else if (!!els && (els.jquery || els.cash || els instanceo... | /**
* Initializes components | random_line_split |
component.js | class Component {
/**
* Generic constructor for all components
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(classDef, el, options) {
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML El... |
}
| {
let instances = null;
if (els instanceof Element) {
instances = new classDef(els, options);
} else if (!!els && (els.jquery || els.cash || els instanceof NodeList)) {
let instancesArr = [];
for (let i = 0; i < els.length; i++) {
instancesArr.push(new classDef(els[i], options));
... | identifier_body |
component.js | class Component {
/**
* Generic constructor for all components
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(classDef, el, options) {
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML El... |
return instances;
}
}
| {
let instancesArr = [];
for (let i = 0; i < els.length; i++) {
instancesArr.push(new classDef(els[i], options));
}
instances = instancesArr;
} | conditional_block |
component.js | class | {
/**
* Generic constructor for all components
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(classDef, el, options) {
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML Element'));
}... | Component | identifier_name |
database.js | // Polarbot
// database.js
// handles database connection and queries
var mysql = require('mysql');
var config = require('./config/config.js');
var logger = require('./logger.js');
// Init MySql-connection
var pool = mysql.createPool({
host : config.dbHost,
port : config.dbPort,
user : config.... | {
pool.getConnection(function(err, connection) {
if (err) {
logger.log('MYSQL Error getting connection from pool: ' + err);
}
else return callback(err, connection);
});
} | identifier_body | |
database.js | // Polarbot
// database.js
// handles database connection and queries
var mysql = require('mysql');
var config = require('./config/config.js');
var logger = require('./logger.js');
// Init MySql-connection
var pool = mysql.createPool({
host : config.dbHost,
port : config.dbPort,
user : config.... | (callback) {
pool.getConnection(function(err, connection) {
if (err) {
logger.log('MYSQL Error getting connection from pool: ' + err);
}
else return callback(err, connection);
});
} | connect | identifier_name |
database.js | // Polarbot
// database.js
// handles database connection and queries
var mysql = require('mysql');
var config = require('./config/config.js');
var logger = require('./logger.js');
// Init MySql-connection
var pool = mysql.createPool({
host : config.dbHost,
port : config.dbPort,
user : config.... | if (err) {
logger.log('MYSQL Error getting connection from pool: ' + err);
}
else return callback(err, connection);
});
} |
function connect(callback) {
pool.getConnection(function(err, connection) { | random_line_split |
foo.py | from zope.interface import implements, classProvides
from twisted.internet import address
from nevow import inevow, rend, loaders, util, url
from webut.navi import inavi
from demoplugins import idemo
class FooPage(rend.Page):
implements(inavi.INavigationElement)
title = 'Foo!'
docFactory = loaders.xmlfil... | and int(addr.host.split('.')[-1])%2==0):
return None
return FooPage()
getResource = classmethod(getResource) | # IP addresses that are odd. Use 127.0.0.1 vs 127.0.0.2
# to see the difference.
addr = inevow.IRequest(ctx).getHost()
if (isinstance(addr, address.IPv4Address) | random_line_split |
foo.py | from zope.interface import implements, classProvides
from twisted.internet import address
from nevow import inevow, rend, loaders, util, url
from webut.navi import inavi
from demoplugins import idemo
class FooPage(rend.Page):
| u.netloc = ':'.join(netloc)
return u
class Foo(object):
classProvides(idemo.IDemoPlugin)
name = "foo"
priority = 20
def getResource(klass, ctx):
# demonstrate conditional plugins by only being visible on
# IP addresses that are odd. Use 127.0.0.1 vs 127.0.0.2
... | implements(inavi.INavigationElement)
title = 'Foo!'
docFactory = loaders.xmlfile(util.resource_filename('demoplugins', 'foo.html'))
def render_navigation(self, ctx, data):
return ctx.tag.clear()[idemo.IDemoNavigation(ctx)]
def render_visible(self, ctx, data):
u = url.URL.fromContext(... | identifier_body |
foo.py | from zope.interface import implements, classProvides
from twisted.internet import address
from nevow import inevow, rend, loaders, util, url
from webut.navi import inavi
from demoplugins import idemo
class FooPage(rend.Page):
implements(inavi.INavigationElement)
title = 'Foo!'
docFactory = loaders.xmlfil... |
return FooPage()
getResource = classmethod(getResource)
| return None | conditional_block |
foo.py | from zope.interface import implements, classProvides
from twisted.internet import address
from nevow import inevow, rend, loaders, util, url
from webut.navi import inavi
from demoplugins import idemo
class | (rend.Page):
implements(inavi.INavigationElement)
title = 'Foo!'
docFactory = loaders.xmlfile(util.resource_filename('demoplugins', 'foo.html'))
def render_navigation(self, ctx, data):
return ctx.tag.clear()[idemo.IDemoNavigation(ctx)]
def render_visible(self, ctx, data):
u = url... | FooPage | identifier_name |
LayersClearRounded.js | import React from 'react'; | <path d="M19.99 9.79c.51-.4.51-1.18 0-1.58l-6.76-5.26c-.72-.56-1.73-.56-2.46 0L9.41 4.02l7.88 7.88 2.7-2.11zm0 3.49l-.01-.01a.991.991 0 00-1.22 0l-.05.04 1.4 1.4c.37-.41.34-1.07-.12-1.43zm1.45 5.6L4.12 1.56a.9959.9959 0 00-1.41 0c-.39.39-.39 1.02 0 1.41l3.52 3.52-2.22 1.72c-.51.4-.51 1.18 0 1.58l6.76 5.26c.72.56 1.73... | import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon( | random_line_split |
retry.ts | /// <reference path="../../observable.ts"/>
module Rx {
export interface Observable<T> {
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an ... | (function() {
var o: Rx.Observable<number>;
o.retry();
o.retry(42);
}); | */
retry(retryCount?: number): Observable<T>;
}
}
| random_line_split |
web_driver_extension_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal';
import... | extends WebDriverExtension {
constructor(public id: string) { super(); }
supports(capabilities: {[key: string]: any}): boolean {
return capabilities['browser'] === this.id;
}
}
| MockExtension | identifier_name |
web_driver_extension_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal';
import... | }
describe('WebDriverExtension.provideFirstSupported', () => {
it('should provide the extension that matches the capabilities',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension(['m1', 'm2', 'm3'], {'browser': 'm2'}).then((m) => {
expect(m.id).toEqual('m2... | rej(e);
}
}); | random_line_split |
web_driver_extension_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal';
import... |
}
| {
return capabilities['browser'] === this.id;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.