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 |
|---|---|---|---|---|
configurations.py | # This file is part of JST.
#
# JST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# | # You should have received a copy of the GNU General Public License
# along with JST. If not, see <http://www.gnu.org/licenses/>.
# This file was made to prevent circular dependencies, if we can do something better, let's do it
import mips.registers as mr
SPILL_MEM_LABEL = 'SPILL_MEMORY'
SPILL_MEM_SIZE = 64 # byt... | # JST is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# | random_line_split |
functions_2.js | var searchData=
[
['checkerror',['CheckError',['../vix__errglobals_8h.html#a03486e2efafef6911389c4e76a25492f',1,'vix_errglobals.h']]],
['close',['Close',['../classVixen_1_1File.html#a3f1848aba4558bd98714c528c3fe0b73',1,'Vixen::File::Close()'],['../classVixen_1_1IFile.html#ae22fba81f1a450f94bbaa993e342d28b',1,'Vixen... | ['consolewriteerr',['ConsoleWriteErr',['../namespaceVixen.html#ae5d8286e89335780589abef43cffe82b',1,'Vixen']]]
]; | random_line_split | |
index.ts | import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
/**
* Index user's by placing their displayName into the users_public collection
* @param change - Database event from function being
* @param change.before - Snapshot of data before change
* @param change.after - Snapshot of d... |
console.log(
`Display Name for userId: ${userId} changed, updating user index...`
)
// Update displayName within public profile
try {
await publicProfileRef.update({
displayName: change.after.val()
})
} catch(err) {
console.error(
`Error running updating displayName index for pr... | {
console.log(
`displayName removed from profile with userId: ${userId}, removing from index...`
)
try {
await publicProfileRef.remove()
console.log(`Successfully removed displayName from index for userId: ${userId}`)
return null
} catch(err) {
console.error(
`Error... | conditional_block |
index.ts | import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
/**
* Index user's by placing their displayName into the users_public collection
* @param change - Database event from function being
* @param change.before - Snapshot of data before change
* @param change.after - Snapshot of d... | export default functions.database
.ref('/users/{userId}/displayName')
.onWrite(indexUser) | * to users_public path.
* @type {functions.CloudFunction}
*/ | random_line_split |
index.ts | import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
/**
* Index user's by placing their displayName into the users_public collection
* @param change - Database event from function being
* @param change.before - Snapshot of data before change
* @param change.after - Snapshot of d... | (
change: functions.Change<admin.database.Snapshot>,
context: functions.EventContext
): Promise<null> {
const { userId } = context.params || {}
const publicProfileRef = admin.database().ref(`users_public/${userId}`)
// Display Name being deleted
if (!change.after.val()) {
console.log(
`displayNam... | indexUser | identifier_name |
index.ts | import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
/**
* Index user's by placing their displayName into the users_public collection
* @param change - Database event from function being
* @param change.before - Snapshot of data before change
* @param change.after - Snapshot of d... | }
console.log(
`Display Name for userId: ${userId} changed, updating user index...`
)
// Update displayName within public profile
try {
await publicProfileRef.update({
displayName: change.after.val()
})
} catch(err) {
console.error(
`Error running updating displayName index for... | {
const { userId } = context.params || {}
const publicProfileRef = admin.database().ref(`users_public/${userId}`)
// Display Name being deleted
if (!change.after.val()) {
console.log(
`displayName removed from profile with userId: ${userId}, removing from index...`
)
try {
await publicP... | identifier_body |
notifications.rs | use crate::AppState;
use actix_web::{HttpResponse, Json, State};
use log::{debug, warn};
use potboiler_common::{db, types::Log};
use serde_derive::Deserialize;
use std::{
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
thread,
};
use url::Url;
#[derive(Clone, Debug)]
pub struct Notifications {
notifiers: ... | });
}
}
}
#[derive(Deserialize)]
pub struct UrlJson {
url: String,
}
pub fn log_register(state: State<AppState>, body: Json<UrlJson>) -> HttpResponse {
let conn = state.pool.get().unwrap();
let url = &body.url;
debug!("Registering {:?}", url);
match Url::parse(url) {
... | }
Err(val) => {
warn!("Failed to notify {:?}: {:?}", &local_notifier, val);
}
}; | random_line_split |
notifications.rs | use crate::AppState;
use actix_web::{HttpResponse, Json, State};
use log::{debug, warn};
use potboiler_common::{db, types::Log};
use serde_derive::Deserialize;
use std::{
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
thread,
};
use url::Url;
#[derive(Clone, Debug)]
pub struct | {
notifiers: Arc<RwLock<Vec<String>>>,
}
impl Notifications {
pub fn new(conn: &db::Connection) -> Notifications {
let mut notifiers = Vec::new();
for row in &conn
.query("select url from notifications")
.expect("notifications select works")
{
let ur... | Notifications | identifier_name |
notifications.rs | use crate::AppState;
use actix_web::{HttpResponse, Json, State};
use log::{debug, warn};
use potboiler_common::{db, types::Log};
use serde_derive::Deserialize;
use std::{
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
thread,
};
use url::Url;
#[derive(Clone, Debug)]
pub struct Notifications {
notifiers: ... | else {
HttpResponse::NotFound().finish()
}
}
| {
HttpResponse::NoContent().finish()
} | conditional_block |
package.js | Package.describe({
summary: "Login service for Slack accounts",
version: "1.1.1",
git: "https://github.com/efounders/meteor-accounts-slack.git",
name: "acemtp:accounts-slack"
});
Package.on_use(function(api) {
api.versionsFrom("METEOR@0.9.0");
api.use('oauth2', ['client', 'server']);
api.use('oauth', ['c... | api.use('templating', 'client');
api.use('underscore', 'client');
api.use('random', 'client');
api.use('service-configuration', ['client', 'server']);
api.use('accounts-base', ['client', 'server']);
api.use('accounts-oauth', ['client', 'server']);
api.add_files('slack_server.js', 'server');
api.add_fi... | random_line_split | |
admin.py | from django.contrib import admin
from django.forms import ModelForm
from django.urls import reverse
from .models import Ballot, LoggedAction, PartySet
class LoggedActionAdminForm(ModelForm):
pass
@admin.register(LoggedAction)
class LoggedActionAdmin(admin.ModelAdmin):
form = LoggedActionAdminForm
searc... | "user",
"ip_address",
"action_type",
"popit_person_new_version",
"person_link",
"created",
"updated",
"source",
]
ordering = ("-created",)
def person_link(self, o):
if not o.person:
return ""
url = reverse("person-v... | "ip_address",
"source",
)
list_filter = ("action_type",)
list_display = [ | random_line_split |
admin.py | from django.contrib import admin
from django.forms import ModelForm
from django.urls import reverse
from .models import Ballot, LoggedAction, PartySet
class LoggedActionAdminForm(ModelForm):
pass
@admin.register(LoggedAction)
class LoggedActionAdmin(admin.ModelAdmin):
form = LoggedActionAdminForm
searc... |
@admin.register(Ballot)
class BallotAdmin(admin.ModelAdmin):
list_display = ["post", "election", "winner_count"]
list_filter = ("election__name", "election__current")
raw_id_fields = ("post", "election")
ordering = ("election", "post__label")
| form = PartySetAdminForm | identifier_body |
admin.py | from django.contrib import admin
from django.forms import ModelForm
from django.urls import reverse
from .models import Ballot, LoggedAction, PartySet
class LoggedActionAdminForm(ModelForm):
pass
@admin.register(LoggedAction)
class LoggedActionAdmin(admin.ModelAdmin):
form = LoggedActionAdminForm
searc... |
url = reverse("person-view", kwargs={"person_id": o.person.id})
return '<a href="{}">{}</a>'.format(url, o.person.name)
person_link.allow_tags = True
class PartySetAdminForm(ModelForm):
pass
@admin.register(PartySet)
class PartySetAdmin(admin.ModelAdmin):
form = PartySetAdminForm
@ad... | return "" | conditional_block |
admin.py | from django.contrib import admin
from django.forms import ModelForm
from django.urls import reverse
from .models import Ballot, LoggedAction, PartySet
class LoggedActionAdminForm(ModelForm):
pass
@admin.register(LoggedAction)
class LoggedActionAdmin(admin.ModelAdmin):
form = LoggedActionAdminForm
searc... | (self, o):
if not o.person:
return ""
url = reverse("person-view", kwargs={"person_id": o.person.id})
return '<a href="{}">{}</a>'.format(url, o.person.name)
person_link.allow_tags = True
class PartySetAdminForm(ModelForm):
pass
@admin.register(PartySet)
class PartySetAd... | person_link | identifier_name |
atomic_fence_acq.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_fence_acq;
use core::intrinsics::atomic_fence_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_fence_acq();
struct A<T> {
v: UnsafeCell<T>
... |
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data.clone();
thread::spawn(move || {
let ptr: *mut T = clone.v.get();
unsafe { *ptr = $value; }
unsafe { atomic_fence_rel() };
});
thread::sleep_ms(10);
unsafe { atomic_fence_acq() };
let ptr: *mut T = data... | let a: A<T> = A::<T>::new(value); | random_line_split |
atomic_fence_acq.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_fence_acq;
use core::intrinsics::atomic_fence_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_fence_acq();
struct A<T> {
v: UnsafeCell<T>
... |
}
| {
atomic_fence_acq_test!( 68, 500, 500 );
} | identifier_body |
atomic_fence_acq.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_fence_acq;
use core::intrinsics::atomic_fence_rel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_fence_acq();
struct A<T> {
v: UnsafeCell<T>
... | (v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_fence_acq_test {
($init:expr, $value:expr, $result:expr) => ({
let value: T = $init;
let a: A<T> = A::<T>::new(value);
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = dat... | new | identifier_name |
driver-set.ts | import { Component, Inject } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { CarService } from '../../car_service';
import { NativeService } from '../../../../providers/NativeService';
import { Globa... | ertCtrl.create({
title: '删除提示',
message: "你确定删除此司机的档案吗?<br/><span class='text-ios-danger'>删除后不能恢复</span>",
buttons: [
{
text: '取消',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: '删除',
handler: data =... | his.al | identifier_name |
driver-set.ts | import { Component, Inject } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { CarService } from '../../car_service';
import { NativeService } from '../../../../providers/NativeService';
import { Globa... | }
}
save(value){
if (this.isWrite){
value.Uid = this.globalData.Uid;
value.InDate = Utils.dateFormat(new Date(value.InDate), 'yyyy-MM-dd HH:mm:ss');
this.carService.driverAdd(value).subscribe((resJson) => {
if (resJson.Result){
this.navCtrl.pop();
this.nativeSe... | this.nativeService.showToast(resJson.Data, 800);
this.navCtrl.pop();
}
});
| conditional_block |
driver-set.ts | import { Component, Inject } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { CarService } from '../../car_service';
import { NativeService } from '../../../../providers/NativeService';
import { Globa... | }
}
save(value){
if (this.isWrite){
value.Uid = this.globalData.Uid;
value.InDate = Utils.dateFormat(new Date(value.InDate), 'yyyy-MM-dd HH:mm:ss');
this.carService.driverAdd(value).subscribe((resJson) => {
if (resJson.Result){
this.navCtrl.pop();
this.nativeS... | this.navCtrl.pop();
}
}); | random_line_split |
driver-set.ts | import { Component, Inject } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { CarService } from '../../car_service';
import { NativeService } from '../../../../providers/NativeService';
import { Globa... | save(val
ue){
if (this.isWrite){
value.Uid = this.globalData.Uid;
value.InDate = Utils.dateFormat(new Date(value.InDate), 'yyyy-MM-dd HH:mm:ss');
this.carService.driverAdd(value).subscribe((resJson) => {
if (resJson.Result){
this.navCtrl.pop();
this.nativeService.sho... | his.isWrite){
this.carService.getDriverDetails(this.navParams.get("Id")).subscribe((resJson) => {
if (resJson.Result && typeof(resJson.Data) !== "string"){
let data = resJson.Data;
this.id = data.Id;
this.addForm.setValue({
"Name": data.Name,
"Sex": da... | identifier_body |
raw.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub st_ino: c_ulonglong,
} | pub st_atime_nsec: c_ulong,
pub st_mtime: time_t,
pub st_mtime_nsec: c_ulong,
pub st_ctime: time_t,
pub st_ctime_nsec: c_ulong, | random_line_split |
raw.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
pub st_dev: c_ulonglong,
pub __pad0: [c_uchar; 4],
pub __st_ino: ino_t,
pub st_mode: c_uint,
pub st_nlink: c_uint,
pub st_uid: uid_t,
pub st_gid: gid_t,
pub st_rdev: c_ulonglong,
pub __pad3: [c_uchar; 4],
pub st_size: c_longlong,
pub st_blksize: blksize_t,
pub st_block... | stat | identifier_name |
eventLimitText.ts | import frLocale from '@fullcalendar/core/locales/fr'
import { DayGridViewWrapper } from '../lib/wrappers/DayGridViewWrapper'
describe('moreLinkText', () => { // TODO: rename file
pushOptions({
initialDate: '2014-08-01', // important that it is the first week, so works w/ month + week views
initialView: 'dayG... | expect(dayGridWrapper.getMoreEl()).toHaveText('+2 extra')
})
it('allows a function', () => {
let calendar = initCalendar({
moreLinkText(n) {
expect(typeof n).toBe('number')
return 'there are ' + n + ' more events!'
},
})
let dayGridWrapper = new DayGridViewWrapper(calend... | })
let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid | random_line_split |
eventLimitText.ts | import frLocale from '@fullcalendar/core/locales/fr'
import { DayGridViewWrapper } from '../lib/wrappers/DayGridViewWrapper'
describe('moreLinkText', () => { // TODO: rename file
pushOptions({
initialDate: '2014-08-01', // important that it is the first week, so works w/ month + week views
initialView: 'dayG... | (n) {
expect(typeof n).toBe('number')
return 'there are ' + n + ' more events!'
},
})
let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid
expect(dayGridWrapper.getMoreEl()).toHaveText('there are 2 more events!')
})
it('has a default value that is affected by the custom l... | moreLinkText | identifier_name |
eventLimitText.ts | import frLocale from '@fullcalendar/core/locales/fr'
import { DayGridViewWrapper } from '../lib/wrappers/DayGridViewWrapper'
describe('moreLinkText', () => { // TODO: rename file
pushOptions({
initialDate: '2014-08-01', // important that it is the first week, so works w/ month + week views
initialView: 'dayG... | ,
})
let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid
expect(dayGridWrapper.getMoreEl()).toHaveText('there are 2 more events!')
})
it('has a default value that is affected by the custom locale', () => {
let calendar = initCalendar({
locale: frLocale,
})
let dayGridWrapper... | {
expect(typeof n).toBe('number')
return 'there are ' + n + ' more events!'
} | identifier_body |
sys.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Rudimentary system stats collection using ``psutil``.
"""
import time
from switchy import event_callback, utils
def... |
raise
def prepost(self, collect_rate=2, storer=None):
self.storer = storer
self.count = 0
self._collect_period = 1. / collect_rate
self._last_collect_time = 0
@property
def collect_rate(self):
return 1. / self._collect_period
@collect_rate.setter
... | self.log.warn("resetting rypc connection...")
self._conn = conn = self.rpyc.classic_connect()
self._psutil = conn.modules.psutil
return self._psutil | conditional_block |
sys.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Rudimentary system stats collection using ``psutil``.
"""
import time
from switchy import event_callback, utils
def... | (self, sess):
now = time.time()
if sess.is_outbound():
# rate limiting
if (now - self._last_collect_time) >= self._collect_period:
# XXX important to keep this here for performance and
# avoiding thread racing
self._last_collect_tim... | on_create | identifier_name |
sys.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Rudimentary system stats collection using ``psutil``.
"""
import time
from switchy import event_callback, utils
def... |
@event_callback("CHANNEL_CREATE")
def on_create(self, sess):
now = time.time()
if sess.is_outbound():
# rate limiting
if (now - self._last_collect_time) >= self._collect_period:
# XXX important to keep this here for performance and
# avoi... | self._collect_period = 1. / rate | identifier_body |
sys.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Rudimentary system stats collection using ``psutil``.
"""
import time
from switchy import event_callback, utils
def... | raise
def prepost(self, collect_rate=2, storer=None):
self.storer = storer
self.count = 0
self._collect_period = 1. / collect_rate
self._last_collect_time = 0
@property
def collect_rate(self):
return 1. / self._collect_period
@collect_rate.setter
... | self._psutil = conn.modules.psutil
return self._psutil | random_line_split |
analysis.py | /phrase tagger, and as many NER taggers and dictionaries as desired.
I.e., the tokenizer and PoS tagger must be set, while NER taggers and dictionaries may be
omitted.
"""
logger = logging.getLogger("TextAnalytics")
def __init__(self, tokenizer, pos_tagger, tag_all_nouns=0, use_greek_letters=False... | (self, text):
"""
Analyze a piece of text using the configured tokenizer, dictionary, and taggers.
Most commonly, a piece of text is a sentence, but this depends on the used taggers.
:return a triple of (tokens, [ner_tags..], [normalizations...]);
if no NER tagger was s... | analyze | identifier_name |
analysis.py | phrase tagger, and as many NER taggers and dictionaries as desired.
I.e., the tokenizer and PoS tagger must be set, while NER taggers and dictionaries may be
omitted.
"""
logger = logging.getLogger("TextAnalytics")
def __init__(self, tokenizer, pos_tagger, tag_all_nouns=0, use_greek_letters=False)... |
else:
raise AssertionError('cannot rescue with next word "%s"' % next_word)
except:
raise RuntimeError('no alignment of tag %s to word "%s" found' % (repr(tag), word))
index += 1
assert len(tokens) == len(aligned_tags... | rescue = Token(word, word, *tags[index-1][2:])
self.logger.info(
"word '%s' not recognized by tagger (probably due to NERSuite's "
"shortcoming of only working with ASCII); assigning it the "
"last token: %s", wo... | conditional_block |
analysis.py | /phrase tagger, and as many NER taggers and dictionaries as desired.
I.e., the tokenizer and PoS tagger must be set, while NER taggers and dictionaries may be
omitted.
"""
logger = logging.getLogger("TextAnalytics")
def __init__(self, tokenizer, pos_tagger, tag_all_nouns=0, use_greek_letters=False... | for tagger in self._ner_taggers:
tagger.send(part_of_speech)
entities = list(tagger)
if len(entities) != len(tokens):
entities = self._alignToTokens(entities, tokens)
ner_tags.append(entities)
# DICTIONARY NORMALIZATION
mappings ... | random_line_split | |
analysis.py | /phrase tagger, and as many NER taggers and dictionaries as desired.
I.e., the tokenizer and PoS tagger must be set, while NER taggers and dictionaries may be
omitted.
"""
logger = logging.getLogger("TextAnalytics")
def __init__(self, tokenizer, pos_tagger, tag_all_nouns=0, use_greek_letters=False... |
for tagger in self._ner_taggers:
tagger.send(part_of_speech)
entities = list(tagger)
if len(entities) != len(tokens):
entities = self._alignToTokens(entities, tokens)
ner_tags.append(entities)
# DICTIONARY NORMALIZATION
mappings... | """
Analyze a piece of text using the configured tokenizer, dictionary, and taggers.
Most commonly, a piece of text is a sentence, but this depends on the used taggers.
:return a triple of (tokens, [ner_tags..], [normalizations...]);
if no NER tagger was set, the PoS tagger's t... | identifier_body |
version.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015, 2018 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your optio... | # Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ... | # | random_line_split |
EigentransformWavefunction.py | """The WaveBlocks Project
Compute the transformation to the eigen basis for wavefunction.
@author: R. Bourquin
@copyright: Copyright (C) 2012, 2016 R. Bourquin
@license: Modified BSD License
"""
from WaveBlocksND import BlockFactory
from WaveBlocksND import WaveFunction
from WaveBlocksND import BasisTransformationWF... |
# The potential used
Potential = BlockFactory().create_potential(parameters)
# Basis transformator
BT = BasisTransformationWF(Potential)
BT.set_grid(grid)
# And two empty wavefunctions
WF = WaveFunction(parameters)
WF.set_grid(grid)
# Iterate over all timesteps
for i, step in... |
# The grid on the domain
grid = BlockFactory().create_grid(parameters) | random_line_split |
EigentransformWavefunction.py | """The WaveBlocks Project
Compute the transformation to the eigen basis for wavefunction.
@author: R. Bourquin
@copyright: Copyright (C) 2012, 2016 R. Bourquin
@license: Modified BSD License
"""
from WaveBlocksND import BlockFactory
from WaveBlocksND import WaveFunction
from WaveBlocksND import BasisTransformationWF... | Potential = BlockFactory().create_potential(parameters)
# Basis transformator
BT = BasisTransformationWF(Potential)
BT.set_grid(grid)
# And two empty wavefunctions
WF = WaveFunction(parameters)
WF.set_grid(grid)
# Iterate over all timesteps
for i, step in enumerate(timesteps):
... | """Compute the transformation to the eigenbasis for a wavefunction.
Save the result back to a file.
:param iomin: An :py:class:`IOManager: instance providing the simulation data.
:param iomout: An :py:class:`IOManager: instance for saving the transformed data.
:param blockidin: The data block from whic... | identifier_body |
EigentransformWavefunction.py | """The WaveBlocks Project
Compute the transformation to the eigen basis for wavefunction.
@author: R. Bourquin
@copyright: Copyright (C) 2012, 2016 R. Bourquin
@license: Modified BSD License
"""
from WaveBlocksND import BlockFactory
from WaveBlocksND import WaveFunction
from WaveBlocksND import BasisTransformationWF... | print(" Compute eigentransform at timestep %d" % step)
# Retrieve simulation data
values = iomin.load_wavefunction(timestep=step, blockid=blockidin)
values = [values[j, ...] for j in range(parameters["ncomponents"])]
WF.set_values(values)
# Project wavefunction values to eigenb... | conditional_block | |
EigentransformWavefunction.py | """The WaveBlocks Project
Compute the transformation to the eigen basis for wavefunction.
@author: R. Bourquin
@copyright: Copyright (C) 2012, 2016 R. Bourquin
@license: Modified BSD License
"""
from WaveBlocksND import BlockFactory
from WaveBlocksND import WaveFunction
from WaveBlocksND import BasisTransformationWF... | (iomin, iomout, blockidin=0, blockidout=0):
"""Compute the transformation to the eigenbasis for a wavefunction.
Save the result back to a file.
:param iomin: An :py:class:`IOManager: instance providing the simulation data.
:param iomout: An :py:class:`IOManager: instance for saving the transformed data... | transform_wavefunction_to_eigen | identifier_name |
settings.py | """
Django settings for CELLAR project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths i... |
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'ko-kr'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
SESSION_EXPIRE... | random_line_split | |
auto_rest_duration_test_service.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (
self, base_url=None, filepath=None):
if not base_url:
base_url = 'https://localhost'
super(AutoRestDurationTestServiceConfiguration, self).__init__(base_url, filepath)
self.add_user_agent('autorestdurationtestservice/{}'.format(VERSION))
class AutoRestDurationTestS... | __init__ | identifier_name |
auto_rest_duration_test_service.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | self.config = AutoRestDurationTestServiceConfiguration(base_url, filepath)
self._client = ServiceClient(None, self.config)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(clien... | identifier_body | |
auto_rest_duration_test_service.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
super(AutoRestDurationTestServiceConfiguration, self).__init__(base_url, filepath)
self.add_user_agent('autorestdurationtestservice/{}'.format(VERSION))
class AutoRestDurationTestService(object):
"""Test Infrastructure for AutoRest
:ivar config: Configuration for client.
:vartype confi... | base_url = 'https://localhost' | conditional_block |
auto_rest_duration_test_service.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | class AutoRestDurationTestService(object):
"""Test Infrastructure for AutoRest
:ivar config: Configuration for client.
:vartype config: AutoRestDurationTestServiceConfiguration
:ivar duration: Duration operations
:vartype duration: .operations.DurationOperations
:param str base_url: Service U... |
self.add_user_agent('autorestdurationtestservice/{}'.format(VERSION))
| random_line_split |
custom.time.pipe.ts | import { Pipe,PipeTransform } from '@angular/core'
@Pipe({ name: 'customTime' })
export class CustomTimePipe implements PipeTransform {
minuteTime: number = 60 * 1000
hourTime: number = 60 * this.minuteTime
dayTime: number = 24 * this.hourTime
monthTime: number = this.dayTime * 30
yearTime: number = this.monthTim... | descTime = Math.floor(historyTime / this.yearTime) + '年前'
}else if(historyTime< this.yearTime && historyTime >= this.monthTime){
//按月算
descTime = Math.floor(historyTime / this.monthTime) + '月前'
}else if(historyTime< this.monthTime && historyTime>= this.dayTime){
//按天算
descTime = Math.floor(historyT... | let historyTime:number = this.nowTime - publishTime
let descTime:string
if(historyTime >= this.yearTime){
//按年算 | random_line_split |
custom.time.pipe.ts | import { Pipe,PipeTransform } from '@angular/core'
@Pipe({ name: 'customTime' })
export class CustomTimePipe implements PipeTransform {
minuteTime: number = 60 * 1000
hourTime: number = 60 * this.minuteTime
dayTime: number = 24 * this.hourTime
monthTime: number = this.dayTime * 30
yearTime: number = this.monthTim... | (item: string): string {
let publishTime:number = new Date(item).getTime();
let historyTime:number = this.nowTime - publishTime
let descTime:string
if(historyTime >= this.yearTime){
//按年算
descTime = Math.floor(historyTime / this.yearTime) + '年前'
}else if(historyTime< this.yearTime && historyTime >= thi... | transform | identifier_name |
custom.time.pipe.ts | import { Pipe,PipeTransform } from '@angular/core'
@Pipe({ name: 'customTime' })
export class CustomTimePipe implements PipeTransform {
minuteTime: number = 60 * 1000
hourTime: number = 60 * this.minuteTime
dayTime: number = 24 * this.hourTime
monthTime: number = this.dayTime * 30
yearTime: number = this.monthTim... | storyTime< this.yearTime && historyTime >= this.monthTime){
//按月算
descTime = Math.floor(historyTime / this.monthTime) + '月前'
}else if(historyTime< this.monthTime && historyTime>= this.dayTime){
//按天算
descTime = Math.floor(historyTime / this.dayTime) + '天前'
}else if(historyTime< this.dayTime && history... | {
//按年算
descTime = Math.floor(historyTime / this.yearTime) + '年前'
}else if(hi | conditional_block |
kobase.ts | import * as ko from "knockout";
import { Base } from "../base";
export class ImplementorBase {
private static doIterateProperties(hash: any, key: any): any {
var val = hash[key];
if (Array.isArray(val)) | else {
hash[key] = ko.observable(val);
}
}
constructor(public element: Base) {
element.iteratePropertiesHash((hash, key) => {
ImplementorBase.doIterateProperties(hash, key);
});
element.getPropertyValueCoreHandler = (hash, key) => {
if (hash[key] === undefined) {
hash[key]... | {
hash[key] = ko.observableArray(val);
(<any>val)["onArrayChanged"] = () => hash[key].notifySubscribers();
} | conditional_block |
kobase.ts | import * as ko from "knockout";
import { Base } from "../base";
export class ImplementorBase {
private static doIterateProperties(hash: any, key: any): any {
var val = hash[key];
if (Array.isArray(val)) {
hash[key] = ko.observableArray(val);
(<any>val)["onArrayChanged"] = () => hash[key].notifySu... | (public element: Base) {
element.iteratePropertiesHash((hash, key) => {
ImplementorBase.doIterateProperties(hash, key);
});
element.getPropertyValueCoreHandler = (hash, key) => {
if (hash[key] === undefined) {
hash[key] = ko.observable();
}
return ko.unwrap(hash[key]);
};... | constructor | identifier_name |
kobase.ts | import * as ko from "knockout";
import { Base } from "../base";
export class ImplementorBase {
private static doIterateProperties(hash: any, key: any): any |
constructor(public element: Base) {
element.iteratePropertiesHash((hash, key) => {
ImplementorBase.doIterateProperties(hash, key);
});
element.getPropertyValueCoreHandler = (hash, key) => {
if (hash[key] === undefined) {
hash[key] = ko.observable();
}
return ko.unwrap(hash... | {
var val = hash[key];
if (Array.isArray(val)) {
hash[key] = ko.observableArray(val);
(<any>val)["onArrayChanged"] = () => hash[key].notifySubscribers();
} else {
hash[key] = ko.observable(val);
}
} | identifier_body |
kobase.ts | import * as ko from "knockout";
import { Base } from "../base";
export class ImplementorBase {
private static doIterateProperties(hash: any, key: any): any {
var val = hash[key];
if (Array.isArray(val)) {
hash[key] = ko.observableArray(val);
(<any>val)["onArrayChanged"] = () => hash[key].notifySu... | element.setPropertyValueCoreHandler = (hash, key, val) =>
hash[key] !== undefined
? hash[key](val)
: (hash[key] = ko.observable(val));
}
} | random_line_split | |
data.ts | /// <reference types="node"/>
import ndn = require("ndn-js");
let meta = new ndn.MetaInfo();
meta = new ndn.MetaInfo(meta);
const ct: ndn.ContentType = meta.getType();
let n: number = meta.getOtherTypeCode();
n = meta.getFreshnessPeriod();
const comp: ndn.Name.Component = meta.getFinalBlockId();
meta.setType(ndn.Cont... | data = new ndn.Data(new ndn.Name("/A"));
data = new ndn.Data("/A");
data = new ndn.Data(data);
let name: ndn.Name = data.getName();
name = data.getFullName();
meta = data.getMetaInfo();
let blob: ndn.Blob = data.getContent();
const sig: ndn.Signature = data.getSignature();
n = data.getCongestionMark();
n = data.getInc... | random_line_split | |
harness_simple.py | """
The simple harness interface
"""
__author__ = """Copyright Andy Whitcroft, Martin J. Bligh 2006"""
import os, harness, time
class harness_simple(harness.harness):
"""
The simple server harness
Properties:
job
The job object for this job
"""
def __init__(self,... | (self, status, tag):
"""A test within this job is completing"""
if self.status:
for line in status.split('\n'):
# prepend status messages with
# AUTOTEST_STATUS:tag: so that we can tell
# which lines were sent by the autotest client
... | test_status | identifier_name |
harness_simple.py | """
The simple harness interface
"""
__author__ = """Copyright Andy Whitcroft, Martin J. Bligh 2006"""
import os, harness, time
class harness_simple(harness.harness):
"""
The simple server harness
Properties:
job
The job object for this job
"""
def __init__(self,... | """A test within this job is completing"""
if self.status:
for line in status.split('\n'):
# prepend status messages with
# AUTOTEST_STATUS:tag: so that we can tell
# which lines were sent by the autotest client
pre = 'AUTOTEST_STATUS:%... | identifier_body | |
harness_simple.py | """
The simple harness interface
"""
| class harness_simple(harness.harness):
"""
The simple server harness
Properties:
job
The job object for this job
"""
def __init__(self, job, harness_args):
"""
job
The job object for this job
"""
self.s... | __author__ = """Copyright Andy Whitcroft, Martin J. Bligh 2006"""
import os, harness, time
| random_line_split |
harness_simple.py | """
The simple harness interface
"""
__author__ = """Copyright Andy Whitcroft, Martin J. Bligh 2006"""
import os, harness, time
class harness_simple(harness.harness):
"""
The simple server harness
Properties:
job
The job object for this job
"""
def __init__(self,... | for line in status.split('\n'):
# prepend status messages with
# AUTOTEST_STATUS:tag: so that we can tell
# which lines were sent by the autotest client
pre = 'AUTOTEST_STATUS:%s:' % (tag,)
self.status.write(pre + line + '\n')
... | conditional_block | |
user-db.js | var _ = require("underscore"),
Util = require("../lib/util.js"),
rethinkdb = require("rethinkdb");
var defaultOptions = {
host : "localhost",
port : 28015,
dbName : "test",
tableName : "user"
}
var initializeOptions = function( options ){
if(!_.isNull(options) && _.isObject(options)){
return _.extend(defaul... | // TODO - implement connection etc in user-db.js
rethinkdb.connect( {host : optionals.host, port : optionals.port}, function(err, conn) {
if (err){
throw new Error("Unable to connect to database. " + err.stack());
}
self.connection = conn;
self.dbName = optionals.dbName;
self.tableName = optionals.table... | var User = function( options, callback ){
var self = this;
var optionals = initializeOptions( options );
| random_line_split |
user-db.js | var _ = require("underscore"),
Util = require("../lib/util.js"),
rethinkdb = require("rethinkdb");
var defaultOptions = {
host : "localhost",
port : 28015,
dbName : "test",
tableName : "user"
}
var initializeOptions = function( options ){
if(!_.isNull(options) && _.isObject(options)){
return _.extend(defaul... |
self.connection = conn;
self.dbName = optionals.dbName;
self.tableName = optionals.tableName;
Util.executeSafely(callback);
});
};
User.prototype.registerUser = function( user, callBack, options ){
Util.checkIsObject( user, "Cannot save an empty user." );
Util.checkIsFunction( callBack, "Must supply a va... | {
throw new Error("Unable to connect to database. " + err.stack());
} | conditional_block |
change.ts | import { Component, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { contentHeaders } from '../../common/headers';
import { config } from '../../common/config';
declare var jQuery: JQueryStatic;
const template = require('./change.html');
const ... | * 회원가입 수정 가이드 페이지
*/
export class Change {
jwt:string;
decodedJwt: any;
public data;
// 일반 정보
email: string;
telephones: string;
memberType: number;
// 사업주 정보
contacts:string;
companyNames:string;
ownerNames:string;
bizRegNos:string;
workPlaces:string;
mainWorkFields:string;
mainWorkArea... | random_line_split | |
change.ts | import { Component, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { contentHeaders } from '../../common/headers';
import { config } from '../../common/config';
declare var jQuery: JQueryStatic;
const template = require('./change.html');
const ... | );
}
}
}
}
| conditional_block | |
change.ts | import { Component, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { contentHeaders } from '../../common/headers';
import { config } from '../../common/config';
declare var jQuery: JQueryStatic;
const template = require('./change.html');
const ... | word": msg = "비밀번호를 입력해 주십시오."; break;
case "password_ok": msg = "비밀번호 확인을 입력해 주십시오."; break;
}
// 출력 후 종료
alert(msg); return;
}
}
//html에서의 value값
var memberType = this.memberType;
var passwords = password;
var confirmpasswords = password_ok;
var patter... | case "pass | identifier_name |
checkrust.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
0xff
}
})
}
| {
0
} | conditional_block |
checkrust.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[no_mangle]
pub unsafe extern "C" fn check_list_copy_0(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 6.28f64.floor());
continue_if!(ap.arg::<c_int>() == 16);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Skip Me!"))... | {
continue_if!(ap.arg::<c_double>().floor() == 3.14f64.floor());
continue_if!(ap.arg::<c_long>() == 12);
continue_if!(ap.arg::<c_char>() == 'a' as c_char);
continue_if!(ap.arg::<c_double>().floor() == 6.18f64.floor());
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Hello"));
continue_if!... | identifier_body |
checkrust.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | continue_if!(ap.arg::<c_int>() == 0x10000001);
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "Valid!"));
0
}
#[no_mangle]
pub unsafe extern "C" fn check_list_2(mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 3.14f64.floor());
continue_if!(ap.arg::<c_long>() == 12);
... | continue_if!(ap.arg::<c_int>() == -1);
continue_if!(ap.arg::<c_char>() == 'A' as c_char);
continue_if!(ap.arg::<c_char>() == '4' as c_char);
continue_if!(ap.arg::<c_char>() == ';' as c_char);
continue_if!(ap.arg::<c_int>() == 0x32); | random_line_split |
checkrust.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (mut ap: VaList) -> usize {
continue_if!(ap.arg::<c_double>().floor() == 3.14f64.floor());
continue_if!(ap.arg::<c_long>() == 12);
continue_if!(ap.arg::<c_char>() == 'a' as c_char);
continue_if!(ap.arg::<c_double>().floor() == 6.18f64.floor());
continue_if!(compare_c_str(ap.arg::<*const c_char>(), "... | check_list_2 | identifier_name |
sprites.py | #!/usr/bin/env python
# -*- coding: utf-8 *-*
import pygame
from const import *
class MultiSprite(object):
def __init__(self, path, res_x, res_y=None, offX=0, offY=0, gX=0, gY=0):
"""path = file path of the Multi sprite.
res_x and res_y are the X, Y size of each sub sprite.
offX and offY can specify an ... |
class CharSetMultiSprite(MultiSprite):
def __init__(self, path, res_x, res_y=None, offX=0, offY=0, gX=0, gY=0):
super(CharSetMultiSprite, self).__init__(path, res_x, res_y, offX, offY, gX, gY)
| super(TileSetMultiSprite, self).__init__(path, res_x, res_y) | identifier_body |
sprites.py | #!/usr/bin/env python
# -*- coding: utf-8 *-*
import pygame
from const import *
class MultiSprite(object):
def | (self, path, res_x, res_y=None, offX=0, offY=0, gX=0, gY=0):
"""path = file path of the Multi sprite.
res_x and res_y are the X, Y size of each sub sprite.
offX and offY can specify an internal offset which are applied inside of a field (used for char sets).
gX and gY specify global offsets (used for c... | __init__ | identifier_name |
sprites.py | #!/usr/bin/env python
# -*- coding: utf-8 *-*
import pygame
| class MultiSprite(object):
def __init__(self, path, res_x, res_y=None, offX=0, offY=0, gX=0, gY=0):
"""path = file path of the Multi sprite.
res_x and res_y are the X, Y size of each sub sprite.
offX and offY can specify an internal offset which are applied inside of a field (used for char sets).
gX a... | from const import *
| random_line_split |
mathsquiz-step2.py |
# this function will print a welcome message to the user
def welcome_message():
print("Hello! I'm going to ask you 10 maths questions.")
print("Let's see how many you can get right!")
# this function will ask a maths question and return the points awarded (1 or 0)
def ask_question(first_number, second_number)... |
print("")
return points_awarded
# this function will look at the final scores and print the results
def print_final_scores(final_score):
print("That's all the questions done. So...what was your score...?")
print("You scored", score, "points out of a possible 10.")
if score < 5:
print("Yo... | print("Wrong!")
points_awarded = 0 | conditional_block |
mathsquiz-step2.py |
# this function will print a welcome message to the user
def welcome_message():
print("Hello! I'm going to ask you 10 maths questions.")
print("Let's see how many you can get right!")
# this function will ask a maths question and return the points awarded (1 or 0)
def | (first_number, second_number):
print("What is", first_number, "x", second_number)
answer = input("Answer: ")
if int(answer) == first_number * second_number:
print("Correct!")
points_awarded = 1
else:
print("Wrong!")
points_awarded = 0
print("")
return points_awa... | ask_question | identifier_name |
mathsquiz-step2.py | # this function will print a welcome message to the user
def welcome_message():
print("Hello! I'm going to ask you 10 maths questions.")
print("Let's see how many you can get right!")
# this function will ask a maths question and return the points awarded (1 or 0)
def ask_question(first_number, second_number):... | print("That's all the questions done. So...what was your score...?")
print("You scored", score, "points out of a possible 10.")
if score < 5:
print("You need to practice your maths!")
elif score < 8:
print("That's pretty good!")
elif score < 10:
print("You did really well! Tr... | random_line_split | |
mathsquiz-step2.py |
# this function will print a welcome message to the user
def welcome_message():
print("Hello! I'm going to ask you 10 maths questions.")
print("Let's see how many you can get right!")
# this function will ask a maths question and return the points awarded (1 or 0)
def ask_question(first_number, second_number)... |
# this function will look at the final scores and print the results
def print_final_scores(final_score):
print("That's all the questions done. So...what was your score...?")
print("You scored", score, "points out of a possible 10.")
if score < 5:
print("You need to practice your maths!")
elif ... | print("What is", first_number, "x", second_number)
answer = input("Answer: ")
if int(answer) == first_number * second_number:
print("Correct!")
points_awarded = 1
else:
print("Wrong!")
points_awarded = 0
print("")
return points_awarded | identifier_body |
vendor_only_svd.py | # Put libraries such as Divisi in the PYTHONPATH.
import sys, pickle, os
sys.path = ['/stuff/openmind'] + sys.path
from csc.divisi.cnet import *
from csc.divisi.graphics import output_svg
from vendor_db import iter_info
from csamoa.corpus.models import *
from csamoa.conceptnet.models import *
# Load the OMCS language ... | (text):
windows = []
words = [x for x in text.lower().replace('&', 'and').split() if x not in swords]
for x in range(len(words)-wsize+1):
pair = " ".join(words[x:x+wsize])
if check_concept(pair): windows.append(pair)
if check_concept(words[x]): windows.append(words[x])
for c in r... | english_window | identifier_name |
vendor_only_svd.py | # Put libraries such as Divisi in the PYTHONPATH.
import sys, pickle, os
sys.path = ['/stuff/openmind'] + sys.path
from csc.divisi.cnet import *
from csc.divisi.graphics import output_svg
from vendor_db import iter_info
from csamoa.corpus.models import *
from csamoa.conceptnet.models import *
# Load the OMCS language ... | print "Adding Vendors"
for co, englist in iter_info('CFB_Cities'):
print co
for phrase in englist:
parts = english_window(phrase)
print parts
for part in parts:
matrix[co, ('sells', part)] += factor
matrix[part, ('sells_inv', co... | matrix = SparseLabeledTensor(ndim=2) | random_line_split |
vendor_only_svd.py | # Put libraries such as Divisi in the PYTHONPATH.
import sys, pickle, os
sys.path = ['/stuff/openmind'] + sys.path
from csc.divisi.cnet import *
from csc.divisi.graphics import output_svg
from vendor_db import iter_info
from csamoa.corpus.models import *
from csamoa.conceptnet.models import *
# Load the OMCS language ... |
if 'vendor_only.pickle' in os.listdir('.'):
print "Loading saved matrix."
matrix = pickle.load(open("vendor_only.pickle"))
else:
print "Creating New Tensor"
matrix = SparseLabeledTensor(ndim=2)
print "Adding Vendors"
for co, englist in iter_info('CFB_Cities'):
print co
for phra... | windows = []
words = [x for x in text.lower().replace('&', 'and').split() if x not in swords]
for x in range(len(words)-wsize+1):
pair = " ".join(words[x:x+wsize])
if check_concept(pair): windows.append(pair)
if check_concept(words[x]): windows.append(words[x])
for c in range(wsize-1... | identifier_body |
vendor_only_svd.py | # Put libraries such as Divisi in the PYTHONPATH.
import sys, pickle, os
sys.path = ['/stuff/openmind'] + sys.path
from csc.divisi.cnet import *
from csc.divisi.graphics import output_svg
from vendor_db import iter_info
from csamoa.corpus.models import *
from csamoa.conceptnet.models import *
# Load the OMCS language ... |
if check_concept(words[x]): windows.append(words[x])
for c in range(wsize-1):
if check_concept(words[c]): windows.append(words[c])
return windows
if 'vendor_only.pickle' in os.listdir('.'):
print "Loading saved matrix."
matrix = pickle.load(open("vendor_only.pickle"))
else:
print "... | windows.append(pair) | conditional_block |
systemhost_mock.py | # Copyright (c) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
# FIXME: Should this take pointers to the filesystem and the executive?
self.workspace = MockWorkspace()
self.stdin = StringIO()
self.stdout = StringIO()
self.stderr = StringIO()
def copy_current_environment(self):
return Environment({"MOCK_ENVIRON_COPY": '1'})
... | self.platform.os_version = os_version | conditional_block |
systemhost_mock.py | # Copyright (c) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) A... | # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | random_line_split |
systemhost_mock.py | # Copyright (c) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
def print_(self, *args, **kwargs):
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '\n')
stream = kwargs.get('stream', self.stdout)
stream.write(sep.join([str(arg) for arg in args]) + end)
| return Environment({"MOCK_ENVIRON_COPY": '1'}) | identifier_body |
systemhost_mock.py | # Copyright (c) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | (object):
def __init__(self, log_executive=False, executive_throws_when_run=None, os_name=None, os_version=None, executive=None, filesystem=None):
self.executable = 'python'
self.executive = executive or MockExecutive(should_log=log_executive, should_throw_when_run=executive_throws_when_run)
... | MockSystemHost | identifier_name |
strings.js | define(
({
_widgetLabel: "속성 테이블",
ok: "확인",
cancel: "취소",
unsupportQueryWarning: "속성 테이블 위젯에 표시하려면 레이어가 쿼리 작업을 지원해야 합니다. 서비스에 쿼리 기능이 켜져 있는지 확인하세요.",
exportMessage: "데이터를 CSV 파일로 내보내시겠습니까?",
exportFiles: "CSV로 내보내기",
exportSelected: "선택한 항목을 CSV로 내보내기",
exportAll: "모든 항목을 CSV로 내보내기",... | refresh: "새로고침",
features: "피처",
selected: "선택함",
transparent: "투명 모드",
indicate: "선택 항목 찾기",
columns: "열 표시/숨기기",
selectionSymbol: "선택 심볼",
closeMessage: "테이블 숨기기(하단에서 다시 확장)",
dataNotAvailable: "데이터를 사용할 수 없습니다.<br>[새로 고침] 버튼을 클릭하여 다시 시도하세요.",
openTableTip: "속성 테이블 열기",
clo... | filterByExtent: "맵 범위로 필터링",
showSelectedRecords: "선택한 레코드 표시",
showAllRecords: "모든 레코드 보기",
showRelatedRecords: "릴레이트된 레코드 표시",
noRelatedRecords: "릴레이트된 레코드 없음", | random_line_split |
SplittingIce.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer, { SELECTED_PLAYER, Options } from 'parser/core/Analyzer';
import Events, { CastEvent, DamageEvent } from 'parser/core/Events';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
impor... |
get damage() {
return this.cleaveDamage + this.boostDamage;
}
get damagePercent() {
return this.owner.getPercentageOfTotalDamageDone(this.damage);
}
get cleaveDamagePercent() {
return this.owner.getPercentageOfTotalDamageDone(this.cleaveDamage);
}
get boostDamagePercent() {
return thi... | {
const spellId = event.ability.guid;
const damageTarget = encodeTargetString(event.targetID, event.targetInstance);
if(this.castTarget === damageTarget) {
let damageBonus = SPLITTING_ICE_DAMAGE_BONUS;
if(spellId === SPELLS.GLACIAL_SPIKE_DAMAGE.id) {
damageBonus *= GLACIAL_SPIKE_DAMAGE_B... | identifier_body |
SplittingIce.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer, { SELECTED_PLAYER, Options } from 'parser/core/Analyzer';
import Events, { CastEvent, DamageEvent } from 'parser/core/Events';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
impor... | <li>Primary Target Boosted: <strong>{this.hasGlacialSpike && '≈'}{formatPercentage(this.boostDamagePercent)}%</strong></li>
<li>Secondary Target Total: <strong>{formatPercentage(this.cleaveDamagePercent)}%</strong></li>
</ul>
</>
)}
>
<BoringSpellV... | <ul> | random_line_split |
SplittingIce.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer, { SELECTED_PLAYER, Options } from 'parser/core/Analyzer';
import Events, { CastEvent, DamageEvent } from 'parser/core/Events';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
impor... | () {
return this.owner.getPercentageOfTotalDamageDone(this.damage);
}
get cleaveDamagePercent() {
return this.owner.getPercentageOfTotalDamageDone(this.cleaveDamage);
}
get boostDamagePercent() {
return this.owner.getPercentageOfTotalDamageDone(this.boostDamage);
}
statistic() {
return (
... | damagePercent | identifier_name |
SplittingIce.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer, { SELECTED_PLAYER, Options } from 'parser/core/Analyzer';
import Events, { CastEvent, DamageEvent } from 'parser/core/Events';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
impor... |
this.boostDamage += calculateEffectiveDamage(event, damageBonus);
} else {
this.cleaveDamage += event.amount + (event.absorbed || 0);
if(debug) { console.log(`Splitting Ice cleave for ${event.amount + (event.absorbed || 0)} : castTarget=${this.castTarget} damageTarget=${damageTarget}`); }
}
... | {
damageBonus *= GLACIAL_SPIKE_DAMAGE_BONUS;
} | conditional_block |
task-comm-14.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() {
let (tx, rx) = channel();
// Spawn 10 threads each sending us back one isize.
let mut i = 10;
while (i > 0) {
println!("{}", i);
let tx = tx.clone();
thread::spawn({let i = i; move|| { child(i, &tx) }});
... | #![feature(std_misc)]
| random_line_split |
task-comm-14.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (x: isize, tx: &Sender<isize>) {
println!("{}", x);
tx.send(x).unwrap();
}
| child | identifier_name |
task-comm-14.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }
println!("main thread exiting");
}
fn child(x: isize, tx: &Sender<isize>) {
println!("{}", x);
tx.send(x).unwrap();
}
| {
let (tx, rx) = channel();
// Spawn 10 threads each sending us back one isize.
let mut i = 10;
while (i > 0) {
println!("{}", i);
let tx = tx.clone();
thread::spawn({let i = i; move|| { child(i, &tx) }});
i = i - 1;
}
// Spawned threads are likely killed before... | identifier_body |
repos.rs | use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn | () -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),... | main | identifier_name |
repos.rs | use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> | });
handle.spawn(f.map_err(|_| ()));
Ok(())
}),
)?;
Ok(())
}
_ => Err("example missing GITHUB_TOKEN".into()),
}
}
| {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
... | identifier_body |
repos.rs | use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => | }),
)?;
Ok(())
}
_ => Err("example missing GITHUB_TOKEN".into()),
}
}
| {
let mut rt = Runtime::new()?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let handle = rt.executor();
rt.block_on(
github
... | conditional_block |
repos.rs | use std::env;
use futures::{Future, Stream};
use tokio::runtime::Runtime;
use hubcaps::{Credentials, Github, Result};
fn main() -> Result<()> {
pretty_env_logger::init();
match env::var("GITHUB_TOKEN").ok() {
Some(token) => {
let mut rt = Runtime::new()?;
let github = Github::... | let f = repo.languages(github.clone()).map(|langs| {
for (language, bytes_of_code) in langs {
println!("{}: {} bytes", language, bytes_of_code)
}
});
handle.spa... | println!("{}", repo.name); | random_line_split |
test_views.py | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.h... | status=200)
self.assertTrue(expect in result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=... | ):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON, | random_line_split |
test_views.py | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def | (self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
... | test_validpath | identifier_name |
test_views.py | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.h... |
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self... | self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404) | conditional_block |
test_views.py | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.h... |
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self... | for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404) | identifier_body |
sprk-checkbox-input.directive.spec.ts | import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SprkCheckboxInputDirective } from './sprk-checkbox-input.directive';
@Component({
selector: 'sprk-test',
template: `
<input
... | 'test-analytics-str',
);
});
}); | random_line_split | |
sprk-checkbox-input.directive.spec.ts | import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SprkCheckboxInputDirective } from './sprk-checkbox-input.directive';
@Component({
selector: 'sprk-test',
template: `
<input
... | {}
describe('SprkCheckboxInputDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let inputElement: DebugElement;
let itemElement: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SprkCheckboxInputDirective, TestComponent]... | TestComponent | identifier_name |
test.view.ts | /* 3rd party modules */
import { Component, OnInit, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { select } from '@angular-redux/store';
import { Observable } from 'rxjs';
/* C&C Modules */
import { AliveState } from '../../common';
/* Post module pieces */
import { PostActions } from '..... |
}
| {
this.subscribeWhileAlive(this.actions.getAll());
} | identifier_body |
test.view.ts | /* 3rd party modules */
import { Component, OnInit, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { select } from '@angular-redux/store';
import { Observable } from 'rxjs';
/* C&C Modules */
import { AliveState } from '../../common';
/* Post module pieces */
import { PostActions } from '..... | extends AliveState implements OnInit {
@select([ 'post', 'posts' ]) public posts$: Observable<Array<Post>>;
constructor(public actions: PostActions) {
super();
}
/**
* Initialize the subscription
*/
public ngOnInit(): void {
this.subscribeWhileAlive(this.actions.getAll());
}
}
| PostTestView | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.