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 |
|---|---|---|---|---|
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... |
/// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial.
fn crc32c_slice16(mut buf: &[u8]) -> u32 {
let tab = &*TABLE;
let tab16 = &*TABLE16;
let mut crc: u32 = !0;
while buf.len() >= 16 {
crc ^= LE::read_u32(&buf[0..4]);
crc = tab16[0][buf[15] as usize]
^ t... | {
// I can't measure any difference between slice8 and slice16.
crc32c_slice8(buf)
} | identifier_body |
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... | let mut crc = tab[0][i];
for j in 1..16 {
crc = (crc >> 8) ^ tab[0][crc as u8 as usize];
tab[j][i] = crc;
}
}
tab
};
}
/// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial.
pub fn crc32c(buf: &[u8]) -> u32 {
... | for i in 0..256 { | random_line_split |
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... | (buf: &[u8]) -> u32 {
let tab = &*TABLE;
let mut crc: u32 = !0;
for &b in buf {
crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8);
}
!crc
}
/// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial.
fn crc32c_bitwise(buf: &[u8]) -> u32 {
let mut crc: u32 = !0;
for &b ... | crc32c_multiple | identifier_name |
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... |
}
tab[i as usize] = crc;
}
tab
}
| {
crc >>= 1;
} | conditional_block |
app.js | /***
* Copyright (c) 2013 John Krauss.
*
* This file is part of Crashmapper.
*
* Crashmapper 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 yo... | *
* You should have received a copy of the GNU General Public License
* along with Crashmapper. If not, see <http://www.gnu.org/licenses/>.
*
***/
/*jslint browser: true, nomen: true, sloppy: true*/
/*globals Backbone, Crashmapper */
/**
* @param {Object} options
* @constructor
* @extends Backbone.... | * Crashmapper 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 |
hmac_prf_key_manager.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | /// Validates the given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat).
fn validate_key_format(format: &tink_proto::HmacPrfKeyFormat) -> Result<(), TinkError> {
let params = format
.params
.as_ref()
.ok_or_else(|| TinkError::new("no params"))?;
let hash = HashType::from_i32(params.ha... | }
| random_line_split |
hmac_prf_key_manager.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
/// Validate the given [`HmacPrfKey`](tink_proto::HmacPrfKey). It only validates the version of the
/// key because other parameters will be validated in primitive construction.
fn validate_key(
key: &tink_proto::HmacPrfKey,
) -> Result<(tink_proto::HmacPrfParams, HashType), TinkError> {
tink_core::keyset::... | {
tink_proto::key_data::KeyMaterialType::Symmetric
} | identifier_body |
hmac_prf_key_manager.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> {
if serialized_key.is_empty() {
return Err("HmacPrfKeyManager: invalid key".into());
}
let key = tink_proto::HmacPrfKey::decode(serialized_key)
.map_err(|_| TinkError::new("HmacPrfKeyManager: inval... | primitive | identifier_name |
dock.py | import docker
from cargo.container import Container
from cargo.image import Image
# this is a hack to get `__getattribute__` working for a few reserved properties
RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop']
class Dock(object):
"""Wrapper class for `docker-py` Client instances"""... | (self):
return self._client.info()
@property
def total_num_containers(self):
info = self.info
return int(info.get('Containers'))
@property
def total_num_images(self):
info = self.info
return int(info.get('Images'))
@property
def total_num_goroutines(self):
info = self.info
ret... | info | identifier_name |
dock.py | import docker
from cargo.container import Container
from cargo.image import Image
# this is a hack to get `__getattribute__` working for a few reserved properties
RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop']
class Dock(object):
"""Wrapper class for `docker-py` Client instances"""... | def debug(self):
info = self.info
return info.get('Debug')
def running(self, container):
"""Returns True if dock is running container, else False
Accepts container id's and Container objects
"""
container_ids = [x.container_id for x in self.containers]
if isinstance(container, Containe... | random_line_split | |
dock.py | import docker
from cargo.container import Container
from cargo.image import Image
# this is a hack to get `__getattribute__` working for a few reserved properties
RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop']
class Dock(object):
"""Wrapper class for `docker-py` Client instances"""... |
raise TypeError('expected container id as string or Container object.')
def start(self, container, *args, **kw):
if isinstance(container, Container):
cid = container.container_id
elif isinstance(container, basestring):
cid = container
return self._client.start(cid, *args, **kw)
... | return container in container_ids | conditional_block |
dock.py | import docker
from cargo.container import Container
from cargo.image import Image
# this is a hack to get `__getattribute__` working for a few reserved properties
RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop']
class Dock(object):
"""Wrapper class for `docker-py` Client instances"""... |
@property
def total_num_goroutines(self):
info = self.info
return int(info.get('NGoroutines'))
@property
def memory_limit(self):
info = self.info
return info.get('MemoryLimit')
@property
def debug(self):
info = self.info
return info.get('Debug')
def running(self, container):
... | info = self.info
return int(info.get('Images')) | identifier_body |
user-socket.routes.spec.ts | import * as io from "socket.io-client";
import {UserSocketRoutes} from "./user-socket.routes";
import {SocketServer} from "../../../socketio/socket.server";
import {Server} from "../../../core/server";
import {UserComponent} from "../component/user.component";
import {Query, QueryParameter, QueryElement, QueryOperator... |
update(request: SocketRequest<UserModel>): void {
request.socket.emit(UserRoutes.update, request.value);
}
test(request: SocketRequest<any>): void {
request.socket.emit("ping", request.value);
}
}
describe("User routes for SocketIO", () => {
let server: Server = new SocketServer(... | {
request.socket.emit(UserRoutes.add, request.value);
} | identifier_body |
user-socket.routes.spec.ts | import * as io from "socket.io-client";
import {UserSocketRoutes} from "./user-socket.routes";
import {SocketServer} from "../../../socketio/socket.server";
import {Server} from "../../../core/server";
import {UserComponent} from "../component/user.component";
import {Query, QueryParameter, QueryElement, QueryOperator... | (request: SocketRequest<Query>): void {
request.socket.emit(UserRoutes.get, request.value);
}
add(request: SocketRequest<UserModel>): void {
request.socket.emit(UserRoutes.add, request.value);
}
update(request: SocketRequest<UserModel>): void {
request.socket.emit(UserRoutes.up... | get | identifier_name |
user-socket.routes.spec.ts | import * as io from "socket.io-client";
import {UserSocketRoutes} from "./user-socket.routes";
import {SocketServer} from "../../../socketio/socket.server";
import {Server} from "../../../core/server";
import {UserComponent} from "../component/user.component";
import {Query, QueryParameter, QueryElement, QueryOperator... |
beforeEach(done => {
server.start().then(() => {
userRoute = new UserSocketRoutes(server, new MockUserComponent());
done();
});
});
afterEach(done => {
clientSocket.on("disconnect", () => {
server.stop()
.then(done);
});
... |
describe("User routes for SocketIO", () => {
let server: Server = new SocketServer();
let userRoute: UserSocketRoutes;
let clientSocket: SocketIOClient.Socket; | random_line_split |
eStore-ajax.js | jQuery(document).ready(function($){
$(function(){
//$('.eStore_add_to_cart_button').click(function(){
$('.eStore-button-form').on('submit', function() {
//check if the advanced variation addon is active
if (typeof(eStore_AVUI_JS) != "undefined"){
return;
}
var $thisbuttonform = $(this);
var prod... | });
var eStore_shipping_var_needs_update = false;
if(shipping_var_warning_class.is(":visible")){eStore_shipping_var_needs_update = true;}
else if(shipping_var_warning_default_class.is(":visible")){eStore_shipping_var_needs_update = true;}
$(".eStore_paypal_checkout_button").click(function(e){//Check if s... | $('.shipping_variation').change(function(){
shipping_var_warning_default_class.hide();
shipping_var_warning_class.show();
| random_line_split |
eStore-ajax.js | jQuery(document).ready(function($){
$(function(){
//$('.eStore_add_to_cart_button').click(function(){
$('.eStore-button-form').on('submit', function() {
//check if the advanced variation addon is active
if (typeof(eStore_AVUI_JS) != "undefined"){
return;
}
var $thisbuttonform = $(this);
var prod... | (){
if ($('.t-and-c').length ) {
//Terms and condtions is being used so apply t and c validation
$('.t_and_c_error').hide();
$(".t-and-c").click(function(){
if($(".t-and-c").is(':checked')){
$.cookie("eStore_submit_payment","true",{path: '/'});
$('.t_and_c_error').hide(); ... | estore_update_cart_validation | identifier_name |
eStore-ajax.js | jQuery(document).ready(function($){
$(function(){
//$('.eStore_add_to_cart_button').click(function(){
$('.eStore-button-form').on('submit', function() {
//check if the advanced variation addon is active
if (typeof(eStore_AVUI_JS) != "undefined"){
return;
}
var $thisbuttonform = $(this);
var prod... | //Shipping var changed
var shipping_var_warning_class = $('.shipping_var_changed');
var shipping_var_warning_default_class = $('.shipping_var_changed_default');
shipping_var_warning_class.hide();
$('.shipping_variation').change(function(){
shipping_var_warning_default_class.hide();
shipping_var... | {
if ($('.t-and-c').length ) {
//Terms and condtions is being used so apply t and c validation
$('.t_and_c_error').hide();
$(".t-and-c").click(function(){
if($(".t-and-c").is(':checked')){
$.cookie("eStore_submit_payment","true",{path: '/'});
$('.t_and_c_error').hide();
... | identifier_body |
eStore-ajax.js | jQuery(document).ready(function($){
$(function(){
//$('.eStore_add_to_cart_button').click(function(){
$('.eStore-button-form').on('submit', function() {
//check if the advanced variation addon is active
if (typeof(eStore_AVUI_JS) != "undefined"){
return;
}
var $thisbuttonform = $(this);
var prod... | else if(response.status == "error") {
var msg = response.output;
$.blockUI({
message: msg,
css: {width:'350px',border:'none',padding:'15px',backgroundColor:'#000',opacity:0.8},
showOverlay: false,
fadeIn: 700,
fadeOut: 700,
... | {
//alert("Success from the server!");
$(".eStore_classic_cart_wrapper").html(response.output);
estore_update_cart_validation();
} | conditional_block |
run_cem_cartpole.py | from __future__ import print_function
from collections import deque
import numpy as np
import gym
env_name = 'CartPole-v0'
env = gym.make(env_name)
def observation_to_action(ob, theta):
# define policy neural network
W1 = theta[:-1]
b1 = theta[-1]
return int((ob.dot(W1) + b1) < 0)
def theta_rollout(env, thet... | if render: env.render()
if done: break
return total_rewards, t
MAX_EPISODES = 10000
MAX_STEPS = 200
batch_size = 25
top_per = 0.2 # percentage of theta with highest score selected from all the theta
std = 1 # scale of standard deviation
# initialize
theta_mean = np.zeros(env.observation_s... | observation, reward, done, _ = env.step(action)
total_rewards += reward | random_line_split |
run_cem_cartpole.py | from __future__ import print_function
from collections import deque
import numpy as np
import gym
env_name = 'CartPole-v0'
env = gym.make(env_name)
def observation_to_action(ob, theta):
# define policy neural network
W1 = theta[:-1]
b1 = theta[-1]
return int((ob.dot(W1) + b1) < 0)
def theta_rollout(env, thet... |
MAX_EPISODES = 10000
MAX_STEPS = 200
batch_size = 25
top_per = 0.2 # percentage of theta with highest score selected from all the theta
std = 1 # scale of standard deviation
# initialize
theta_mean = np.zeros(env.observation_space.shape[0] + 1)
theta_std = np.ones_like(theta_mean) * std
episode_h... | total_rewards = 0
observation = env.reset()
for t in range(num_steps):
action = observation_to_action(observation, theta)
observation, reward, done, _ = env.step(action)
total_rewards += reward
if render: env.render()
if done: break
return total_rewards, t | identifier_body |
run_cem_cartpole.py | from __future__ import print_function
from collections import deque
import numpy as np
import gym
env_name = 'CartPole-v0'
env = gym.make(env_name)
def observation_to_action(ob, theta):
# define policy neural network
W1 = theta[:-1]
b1 = theta[-1]
return int((ob.dot(W1) + b1) < 0)
def theta_rollout(env, thet... | print("Environment {} solved after {} episodes".format(env_name, i_episode+1))
break | conditional_block | |
run_cem_cartpole.py | from __future__ import print_function
from collections import deque
import numpy as np
import gym
env_name = 'CartPole-v0'
env = gym.make(env_name)
def | (ob, theta):
# define policy neural network
W1 = theta[:-1]
b1 = theta[-1]
return int((ob.dot(W1) + b1) < 0)
def theta_rollout(env, theta, num_steps, render = False):
total_rewards = 0
observation = env.reset()
for t in range(num_steps):
action = observation_to_action(observation, theta)
observat... | observation_to_action | identifier_name |
SwipeVertical.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
| exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M1 3.5h2.02C1.13 5.82 0 8.78 0 12s1.13 6.18 3.02 8.5H1V22h5v-5H4.5v2.9... | Object.defineProperty(exports, "__esModule", {
value: true
}); | random_line_split |
admin.py | # coding: utf-8
from __future__ import unicode_literals
from django.contrib import admin
from core.admin import SubcategoryAdmin, DetailAdmin
from .models import FinishDetail, FinishSubcategory
class | (SubcategoryAdmin):
def get_form(self, request, obj=None, **kwargs):
from . import DETAIL_TYPE
form = super(FinishSubcategoryAdmin, self).get_form(request, obj, **kwargs)
if 'category' in form.base_fields:
field = form.base_fields['category']
field.queryset = field.q... | FinishSubcategoryAdmin | identifier_name |
admin.py | # coding: utf-8
from __future__ import unicode_literals
from django.contrib import admin
from core.admin import SubcategoryAdmin, DetailAdmin
from .models import FinishDetail, FinishSubcategory
class FinishSubcategoryAdmin(SubcategoryAdmin):
def get_form(self, request, obj=None, **kwargs):
from . impor... |
return form
admin.site.register(FinishDetail, FinishDetailAdmin) | field = form.base_fields['subcategory']
field.queryset = field.queryset.filter(type=DETAIL_TYPE) | conditional_block |
admin.py | # coding: utf-8
from __future__ import unicode_literals
from django.contrib import admin
from core.admin import SubcategoryAdmin, DetailAdmin
from .models import FinishDetail, FinishSubcategory
class FinishSubcategoryAdmin(SubcategoryAdmin):
def get_form(self, request, obj=None, **kwargs):
from . impor... |
admin.site.register(FinishDetail, FinishDetailAdmin) | from . import DETAIL_TYPE
form = super(FinishDetailAdmin, self).get_form(request, obj, **kwargs)
if 'subcategory' in form.base_fields:
field = form.base_fields['subcategory']
field.queryset = field.queryset.filter(type=DETAIL_TYPE)
return form | identifier_body |
admin.py | # coding: utf-8
from __future__ import unicode_literals
|
class FinishSubcategoryAdmin(SubcategoryAdmin):
def get_form(self, request, obj=None, **kwargs):
from . import DETAIL_TYPE
form = super(FinishSubcategoryAdmin, self).get_form(request, obj, **kwargs)
if 'category' in form.base_fields:
field = form.base_fields['category']
... | from django.contrib import admin
from core.admin import SubcategoryAdmin, DetailAdmin
from .models import FinishDetail, FinishSubcategory | random_line_split |
infinite_emnist_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | (self):
raw_client_data = tff.simulation.datasets.emnist.get_synthetic()
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 5)
self.assertEqual(raw_client_data.element_type_structure,
inf_client_data.element_type_structure)
def test_pseudo_client_count(self):
raw_cli... | test_element_type_structure_preserved | identifier_name |
infinite_emnist_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def test_transform_modifies_data(self):
data = infinite_emnist.get_infinite(
tff.simulation.datasets.emnist.get_synthetic(), 3)
datasets = [data.dataset_computation(id) for id in data.client_ids]
lengths = [_compute_dataset_length(datasets[i]) for i in [0, 1, 2]]
self.assertEqual(lengths[0],... | self.assertAllClose(raw_batch, inf_batch) | conditional_block |
infinite_emnist_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | for raw_batch, inf_batch in zip(raw_dataset, inf_dataset):
self.assertAllClose(raw_batch, inf_batch)
def test_transform_modifies_data(self):
data = infinite_emnist.get_infinite(
tff.simulation.datasets.emnist.get_synthetic(), 3)
datasets = [data.dataset_computation(id) for id in data.client... | self.assertEqual(length1, length2) | random_line_split |
infinite_emnist_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def test_pseudo_client_count(self):
raw_client_data = tff.simulation.datasets.emnist.get_synthetic()
self.assertLen(raw_client_data.client_ids, 1)
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 10)
self.assertLen(inf_client_data.client_ids, 10)
def test_first_pseudo_client_preser... | raw_client_data = tff.simulation.datasets.emnist.get_synthetic()
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 5)
self.assertEqual(raw_client_data.element_type_structure,
inf_client_data.element_type_structure) | identifier_body |
cp437.rs | 0x80) {
::std::str::from_utf8(self).unwrap().into()
} else {
self.iter().map(|c| to_char(*c)).collect::<String>().into()
}
}
}
impl FromCp437 for Vec<u8> {
type Target = String;
fn from_cp437(self) -> Self::Target {
if self.iter().all(|c| *c < 0x80) {
... | {
for i in 0x00..0x80 {
assert_eq!(super::to_char(i), i as char);
}
} | identifier_body | |
cp437.rs | ::borrow::Cow<'a, str>;
fn from_cp437(self) -> Self::Target {
if self.iter().all(|c| *c < 0x80) {
::std::str::from_utf8(self).unwrap().into()
} else {
self.iter().map(|c| to_char(*c)).collect::<String>().into()
}
}
}
impl FromCp437 for Vec<u8> {
type Target ... | ascii | identifier_name | |
cp437.rs | from_cp437(self) -> Self::Target;
}
impl<'a> FromCp437 for &'a [u8] {
type Target = ::std::borrow::Cow<'a, str>;
fn from_cp437(self) -> Self::Target {
if self.iter().all(|c| *c < 0x80) {
::std::str::from_utf8(self).unwrap().into()
} else { |
impl FromCp437 for Vec<u8> {
type Target = String;
fn from_cp437(self) -> Self::Target {
if self.iter().all(|c| *c < 0x80) {
String::from_utf8(self).unwrap()
} else {
self.into_iter().map(to_char).collect()
}
}
}
fn to_char(input: u8) -> char {
let outp... | self.iter().map(|c| to_char(*c)).collect::<String>().into()
}
}
} | random_line_split |
models_original.py | """Models for SQLAlchemy.
This file contains the original models definitions before schema tracking was
implemented. It is used to test the schema migration logic.
"""
import json
from datetime import datetime
import logging
from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer,
... | (self):
"""Convert to an HA state object."""
try:
return State(
self.entity_id, self.state,
json.loads(self.attributes),
_process_timestamp(self.last_changed),
_process_timestamp(self.last_updated)
)
except V... | to_native | identifier_name |
models_original.py | """Models for SQLAlchemy.
This file contains the original models definitions before schema tracking was
implemented. It is used to test the schema migration logic.
"""
import json
from datetime import datetime
import logging
from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer,
... |
elif ts.tzinfo is None:
return dt_util.UTC.localize(ts)
else:
return dt_util.as_utc(ts)
| return None | conditional_block |
models_original.py | """Models for SQLAlchemy.
This file contains the original models definitions before schema tracking was
implemented. It is used to test the schema migration logic.
"""
import json
from datetime import datetime
import logging
from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer,
... | dbstate.attributes = '{}'
dbstate.last_changed = event.time_fired
dbstate.last_updated = event.time_fired
else:
dbstate.domain = state.domain
dbstate.state = state.state
dbstate.attributes = json.dumps(dict(state.attributes),
... | dbstate.state = ''
dbstate.domain = split_entity_id(entity_id)[0] | random_line_split |
models_original.py | """Models for SQLAlchemy.
This file contains the original models definitions before schema tracking was
implemented. It is used to test the schema migration logic.
"""
import json
from datetime import datetime
import logging
from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer,
... | """Process a timestamp into datetime object."""
if ts is None:
return None
elif ts.tzinfo is None:
return dt_util.UTC.localize(ts)
else:
return dt_util.as_utc(ts) | identifier_body | |
todo.component.ts | import { Component, OnInit } from '@angular/core';
import { Todo } from './todo.model';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css'],
providers: [TodoService]
})
export class TodoComponent implements O... |
}
| {
this.service
.getTodos()
.then(todos => this.todos = [...todos]);
} | identifier_body |
todo.component.ts | import { Component, OnInit } from '@angular/core';
import { Todo } from './todo.model';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css'],
providers: [TodoService]
})
export class TodoComponent implements O... | this.service
.toggleTodo(todo)
.then(t => {
this.todos = [
...this.todos.slice(0,i),
t,
...this.todos.slice(i+1)
];
});
}
removeTodo(todo: Todo) {
const i = this.todos.indexOf(todo);
this.service
.deleteTodoById(todo.id)
.then... |
toggleTodo(todo: Todo) {
const i = this.todos.indexOf(todo); | random_line_split |
todo.component.ts | import { Component, OnInit } from '@angular/core';
import { Todo } from './todo.model';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css'],
providers: [TodoService]
})
export class TodoComponent implements O... | (): void {
this.service
.getTodos()
.then(todos => this.todos = [...todos]);
}
}
| getTodos | identifier_name |
postcount.py | """
niascape.usecase.postcount
投稿件数ユースケース
"""
import niascape
from niascape.repository import postcount
from niascape.utility.database import get_db
def day(option: dict) -> list:
with get_db(niascape | ase']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.month(db, **option)
def hour(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.hour(db, **option)
def week(option: dict) -> list:
with get... | .ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.day(db, **option)
def month(option: dict) -> list:
with get_db(niascape.ini['datab | identifier_body |
postcount.py | """
niascape.usecase.postcount
投稿件数ユースケース
"""
import niascape
from niascape.repository import postcount
from niascape.utility.database import get_db
def day(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.day(db, **option)
... | with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.week(db, **option)
def tag(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.tag(db, **option) | with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.hour(db, **option)
def week(option: dict) -> list: | random_line_split |
postcount.py | """
niascape.usecase.postcount
投稿件数ユースケース
"""
import niascape
from niascape.repository import postcount
from niascape.utility.database import get_db
def day(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.day(db, **option)
... | : # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.month(db, **option)
def hour(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.hour(db, **option)
def week(option: dict) -> list:
with get_db(niascape... | as db | identifier_name |
computer_doctor_pane.py | #coding: utf-8
#
# Ailurus - a simple application installer and GNOME tweaker
#
# Copyright (C) 2009-2010, Ailurus developers and Ailurus contributors
# Copyright (C) 2007-2010, Trusted Digital Technology Laboratory, Shanghai Jiao Tong University, China.
#
# Ailurus is free software; you can redistribute it and/or modi... | (self, model, iter1, iter2):
obj1 = model.get_value(iter1, 1)
obj2 = model.get_value(iter2, 1)
if obj1 and obj2:
return cmp(obj1.type, obj2.type) or cmp(obj1.__doc__, obj2.__doc__)
else:
return 0
def sort_by_text(self, model, iter1, iter2):
obj1 = mode... | sort_by_type | identifier_name |
computer_doctor_pane.py | #coding: utf-8
#
# Ailurus - a simple application installer and GNOME tweaker
#
# Copyright (C) 2009-2010, Ailurus developers and Ailurus contributors
# Copyright (C) 2007-2010, Trusted Digital Technology Laboratory, Shanghai Jiao Tong University, China.
#
# Ailurus is free software; you can redistribute it and/or modi... | text += _('Found %s errors in your system.') % must_fix
text += ' '
text += _('There is a total of %s suggestions.') % len(self.liststore)
else:
text = _('Found no error :)')
self.show_text(text)
def apply(self):
success = 0
for... | if must_fix: | random_line_split |
computer_doctor_pane.py | #coding: utf-8
#
# Ailurus - a simple application installer and GNOME tweaker
#
# Copyright (C) 2009-2010, Ailurus developers and Ailurus contributors
# Copyright (C) 2007-2010, Trusted Digital Technology Laboratory, Shanghai Jiao Tong University, China.
#
# Ailurus is free software; you can redistribute it and/or modi... |
text += _('There is a total of %s suggestions.') % len(self.liststore)
else:
text = _('Found no error :)')
self.show_text(text)
def apply(self):
success = 0
for row in self.liststore:
apply = row[0]
if apply:
obj = row[... | text += _('Found %s errors in your system.') % must_fix
text += ' ' | conditional_block |
computer_doctor_pane.py | #coding: utf-8
#
# Ailurus - a simple application installer and GNOME tweaker
#
# Copyright (C) 2009-2010, Ailurus developers and Ailurus contributors
# Copyright (C) 2007-2010, Trusted Digital Technology Laboratory, Shanghai Jiao Tong University, China.
#
# Ailurus is free software; you can redistribute it and/or modi... |
def refresh(self):
self.liststore.clear()
for obj in self.cure_objs:
if obj.exists():
self.liststore.append([False, obj])
self.sortedstore.set_sort_column_id(1000, gtk.SORT_ASCENDING)
self.button_apply.set_sensitive(False)
self.show_text('')
... | obj1 = model.get_value(iter1, 1)
obj2 = model.get_value(iter2, 1)
if obj1 and obj2:
return cmp(obj1.__doc__, obj2.__doc__)
else:
return 0 | identifier_body |
callback.rs | ;
use user32;
use shell32;
use winapi;
/// There's no parameters passed to the callback function, so it needs to get
/// its context (the HWND, the Sender for events, etc.) stashed in
/// a thread-local variable.
thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None));
pub stru... | ,
winapi::WM_SIZE => {
use events::Event::Resized;
let w = winapi::LOWORD(lparam as winapi::DWORD) as u32;
let h = winapi::HIWORD(lparam as winapi::DWORD) as u32;
send_event(window, Resized(w, h));
0
},
winapi::WM_MOVE => {
... | {
1
} | conditional_block |
callback.rs | ;
use user32;
use shell32;
use winapi;
/// There's no parameters passed to the callback function, so it needs to get
/// its context (the HWND, the Sender for events, etc.) stashed in
/// a thread-local variable.
thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None));
pub stru... | (window: winapi::HWND, msg: winapi::UINT,
wparam: winapi::WPARAM, lparam: winapi::LPARAM)
-> winapi::LRESULT
{
match msg {
winapi::WM_DESTROY => {
use events::Event::Closed;
CONTEXT_STASH.with(|context_sta... | callback | identifier_name |
callback.rs | ;
use user32;
use shell32;
use winapi;
/// There's no parameters passed to the callback function, so it needs to get
/// its context (the HWND, the Sender for events, etc.) stashed in
/// a thread-local variable.
thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None));
pub stru... |
winapi::WM_RBUTTONUP => {
use events::Event::MouseInput;
use events::MouseButton::Right;
use events::ElementState::Released;
send_event(window, MouseInput(Released, Right));
0
},
winapi::WM_MBUTTONDOWN => {
use events::Eve... | send_event(window, MouseInput(Pressed, Right));
0
}, | random_line_split |
index.story.js | import React from 'react';
import {
header,
tabs,
tab,
description,
importExample,
title,
columns,
divider,
example,
playground,
api,
testkit,
} from 'wix-storybook-utils/Sections';
import { storySettings } from '../test/storySettings';
import BasicExample from '!raw-loader!./examples/BasicExa... | }),
tabs([
tab({
title: 'Description',
sections: [
columns([
description({
title: 'Description',
text:
'Use this component inside a Modal component to display content in this layout. You may place a title and/or a footer wi... | sourceUrl:
'https://github.com/wix/wix-style-react/tree/master/src/CustomModalLayout/', | random_line_split |
list-product.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { ListProductModel } from '../list-product/list-product.model';
import { LogServiceProvider } from '../../providers/log-service/log-service';
/*
Generated class for the Li... | });
optionsURL = new RequestOptions({
headers: this.headers
});
constructor(public http: Http, public log: LogServiceProvider) {
this.log.info('Hello ListProductServiceProvider Provider');
}
postDataCategory(cateId): Promise<any> {
return new Promise((resolve, reject) => {
this.http.g... | random_line_split | |
list-product.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { ListProductModel } from '../list-product/list-product.model';
import { LogServiceProvider } from '../../providers/log-service/log-service';
/*
Generated class for the Li... | (cateId): Promise<any> {
return new Promise((resolve, reject) => {
this.http.get(this.apiUrl + 'api/products/cate/'+ cateId ).map(res => {
return res.json();
}).subscribe(data => {
resolve(data);
}, (error) => {
reject(error);
});
})
}
}
| postDataCategory | identifier_name |
_common.py | import sys
import click
from globus_cli.termio import FORMAT_SILENT, formatted_print
from ..services.transfer import CustomTransferClient
def transfer_task_wait_with_io(
transfer_client: CustomTransferClient,
meow,
heartbeat,
polling_interval,
timeout,
task_id,
timeout_exit_code,
) -> N... | if heartbeat:
click.echo("", err=True)
# meowing tasks wake up!
if meow:
click.echo(
r"""
_..
/}_{\ /.-'
( a a )-.___...-'/
==._.== ;
\ i _..._ /,
{_;/ {_//""",
... | """
Options are the core "task wait" options, including the `--meow` easter
egg.
This does the core "task wait" loop, including all of the IO.
It *does exit* on behalf of the caller. (We can enhance with a
`noabort=True` param or somesuch in the future if necessary.)
"""
def timed_out(wait... | identifier_body |
_common.py | import sys
import click
from globus_cli.termio import FORMAT_SILENT, formatted_print
| meow,
heartbeat,
polling_interval,
timeout,
task_id,
timeout_exit_code,
) -> None:
"""
Options are the core "task wait" options, including the `--meow` easter
egg.
This does the core "task wait" loop, including all of the IO.
It *does exit* on behalf of the caller. (We can e... | from ..services.transfer import CustomTransferClient
def transfer_task_wait_with_io(
transfer_client: CustomTransferClient, | random_line_split |
_common.py | import sys
import click
from globus_cli.termio import FORMAT_SILENT, formatted_print
from ..services.transfer import CustomTransferClient
def transfer_task_wait_with_io(
transfer_client: CustomTransferClient,
meow,
heartbeat,
polling_interval,
timeout,
task_id,
timeout_exit_code,
) -> N... | (waited_time):
if timeout is None:
return False
else:
return waited_time >= timeout
def check_completed():
completed = transfer_client.task_wait(
task_id, timeout=polling_interval, polling_interval=polling_interval
)
if completed:
... | timed_out | identifier_name |
_common.py | import sys
import click
from globus_cli.termio import FORMAT_SILENT, formatted_print
from ..services.transfer import CustomTransferClient
def transfer_task_wait_with_io(
transfer_client: CustomTransferClient,
meow,
heartbeat,
polling_interval,
timeout,
task_id,
timeout_exit_code,
) -> N... |
def check_completed():
completed = transfer_client.task_wait(
task_id, timeout=polling_interval, polling_interval=polling_interval
)
if completed:
if heartbeat:
click.echo("", err=True)
# meowing tasks wake up!
if meow:
... | return waited_time >= timeout | conditional_block |
index.rs | //! Index for finding Project Gutenberg texts by subject, author, or title.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as... | (&self, s: &str) -> Vec<ScoredResult> {
let mut results = Vec::new();
for key in s.split(' ').map( encode_strict ) {
self.accept_or_merge_postings(&mut results, &key);
}
// Sort results by score, decreasing.
results.sort_by( |l,r| {
match l.1.partial_cmp(&... | get_entries | identifier_name |
index.rs | //! Index for finding Project Gutenberg texts by subject, author, or title.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as... |
fn accept_or_merge_postings(&self, results: &mut Vec<ScoredResult>, key: &String) {
match self.index.get(key) {
Some(postings) => {
if results.len() == 0 {
for posting in postings.iter() {
results.push(posting.clone());
... | {
let mut results = Vec::new();
for key in s.split(' ').map( encode_strict ) {
self.accept_or_merge_postings(&mut results, &key);
}
// Sort results by score, decreasing.
results.sort_by( |l,r| {
match l.1.partial_cmp(&r.1) {
Some(o) => o.re... | identifier_body |
index.rs | //! Index for finding Project Gutenberg texts by subject, author, or title.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as... | * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
use std::cmp::{Ord,Ordering};
use std::collections::HashMap;
use iterator_utilities::equivalence_class::equivalence_classes;
use metadata::Metadata;
use nysiis::encod... | * You should have received a copy of the GNU General Public License | random_line_split |
public-profile.component.spec.ts | /*
* Copyright (C) 2017 - 2019 DataSwift Ltd - All Rights Reserved
* 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/.
* Written by Augustinas Markevicius <augustinas.m... | expect(component).toBeTruthy();
});
}); | random_line_split | |
boss.rs | // Copyright 2015 SiegeLord
//
// See LICENSE for terms.
use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE};
use dollar::new_dollar;
use std::f32::consts::PI;
use rand::{self, Rng};
use allegro::*;
pub fn new_boss(parent: usize, dollar_spawn_color: Color, state: &mut GameState) ... | {
let n = 13;
for i in 0..n
{
let theta = 2.0 * PI * (i as f32) / (n as f32);
let dollar = new_dollar(obj.parent, obj.dollar_spawn_color, obj.x, obj.y, theta.cos() * 256.0, theta.sin() * 256.0, state);
state.add_object(dollar);
}
}
}
} | if rng.gen::<f32>() < 0.2 * DT | random_line_split |
boss.rs | // Copyright 2015 SiegeLord
//
// See LICENSE for terms.
use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE};
use dollar::new_dollar;
use std::f32::consts::PI;
use rand::{self, Rng};
use allegro::*;
pub fn | (parent: usize, dollar_spawn_color: Color, state: &mut GameState) -> Object
{
let mut obj = Object::new(state.new_id());
obj.is_boss = true;
obj.has_pos = true;
obj.x = BOSS_RX;
obj.y = -DEATH;
obj.parent = parent;
obj.start_time = state.time;
obj.sprite = Some(state.bitmap_manager.load(&state.core, "data/boss.... | new_boss | identifier_name |
boss.rs | // Copyright 2015 SiegeLord
//
// See LICENSE for terms.
use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE};
use dollar::new_dollar;
use std::f32::consts::PI;
use rand::{self, Rng};
use allegro::*;
pub fn new_boss(parent: usize, dollar_spawn_color: Color, state: &mut GameState) ... |
simple_behavior!
{
BossLogic[obj.is_boss] |obj, state|
{
let theta = 2.0 * PI * (state.time - obj.start_time) / BOSS_RATE;
obj.x = BOSS_RX * theta.cos();
obj.y = BOSS_RY * theta.sin() - DEATH;
let mut rng = rand::thread_rng();
if rng.gen::<f32>() < 0.2 * DT
{
let n = 13;
for i in 0..n
{
... | {
let mut obj = Object::new(state.new_id());
obj.is_boss = true;
obj.has_pos = true;
obj.x = BOSS_RX;
obj.y = -DEATH;
obj.parent = parent;
obj.start_time = state.time;
obj.sprite = Some(state.bitmap_manager.load(&state.core, "data/boss.png").unwrap());
obj.color = random_color();
obj.size = 32.0;
obj.dollar_... | identifier_body |
componentMethodsJsDocHandler.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import ... | } | random_line_split | |
componentMethodsJsDocHandler.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import ... | (
documentation: Documentation
) {
let methods = documentation.get('methods');
if (!methods) {
return;
}
methods = methods.map(method => {
if (!method.docblock) {
return method;
}
const jsDoc = parseJsDoc(method.docblock);
const returns = merge(jsDoc.returns, method.returns);
... | componentMethodsJsDocHandler | identifier_name |
componentMethodsJsDocHandler.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import ... | ...method,
description: jsDoc.description || null,
returns,
params,
};
});
documentation.set('methods', methods);
}
| {
let methods = documentation.get('methods');
if (!methods) {
return;
}
methods = methods.map(method => {
if (!method.docblock) {
return method;
}
const jsDoc = parseJsDoc(method.docblock);
const returns = merge(jsDoc.returns, method.returns);
const params = method.params.map(pa... | identifier_body |
componentMethodsJsDocHandler.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import ... |
}
return merged;
}
/**
* Extract info from the methods jsdoc blocks. Must be run after
* flowComponentMethodsHandler.
*/
export default function componentMethodsJsDocHandler(
documentation: Documentation
) {
let methods = documentation.get('methods');
if (!methods) {
return;
}
methods = methods.m... | {
merged[prop] = obj2[prop];
} | conditional_block |
agilog.controller.js | (function() {
'use strict';
/**
* @name RootController
* @description The root controller that contains some rootScope accessible methods
* @memberof ag
*/
angular.module('ag').controller('RootController', getRootController);
var inject = ['$rootScope'];
getRootController.$in... | $rootScope.root.loadingQueue++;
};
// Method visible in the entire app and
// allows to stop the loading spinner
$rootScope.endLoading = function() {
$rootScope.root.loadingQueue--;
// Prevent bad call of the function
if ($rootScope.root.l... | random_line_split | |
agilog.controller.js | (function() {
'use strict';
/**
* @name RootController
* @description The root controller that contains some rootScope accessible methods
* @memberof ag
*/
angular.module('ag').controller('RootController', getRootController);
var inject = ['$rootScope'];
getRootController.$in... |
if ($rootScope.root.loadingQueue === 0) {
$rootScope.root.loading = false;
}
};
}
})(); | {
$rootScope.root.loadingQueue = 0;
} | conditional_block |
agilog.controller.js | (function() {
'use strict';
/**
* @name RootController
* @description The root controller that contains some rootScope accessible methods
* @memberof ag
*/
angular.module('ag').controller('RootController', getRootController);
var inject = ['$rootScope'];
getRootController.$in... | };
}
})(); | {
// Method visible in the entire app and
// allows to start the loading spinner
$rootScope.startLoading = function() {
$rootScope.root.loading = true;
$rootScope.root.loadingQueue++;
};
// Method visible in the entire app and
// allows to stop t... | identifier_body |
agilog.controller.js | (function() {
'use strict';
/**
* @name RootController
* @description The root controller that contains some rootScope accessible methods
* @memberof ag
*/
angular.module('ag').controller('RootController', getRootController);
var inject = ['$rootScope'];
getRootController.$in... | ($rootScope) {
// Method visible in the entire app and
// allows to start the loading spinner
$rootScope.startLoading = function() {
$rootScope.root.loading = true;
$rootScope.root.loadingQueue++;
};
// Method visible in the entire app and
// all... | getRootController | identifier_name |
__init__.py | #
# -*- coding: utf-8 -*-
#
# Copyright © 2013 Kimmo Parviainen-Jalanko <k@77.fi> | # in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and... | #
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal | random_line_split |
HoverProvider.ts | // import * as vscode from 'vscode';
import {
HoverProvider,
TextDocument,
Position,
CancellationToken,
Hover,
window,
Range,
MarkdownString,
ProviderResult,
} from 'vscode';
import { BsvInfoProviderManger } from '../BsvProvider';
import { Ctags, CtagsManager, Symbol } from '../ctags... |
}
this.logger.log('Hover object not found', Log_Severity.Warn);
return;
}
}
export class BsvHoverProvider implements HoverProvider {
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
provideHover(
document: TextDocument,
... | {
let codeRange = new Range(
i.startPosition,
new Position(i.startPosition.line, Number.MAX_VALUE)
);
let code = document.getText(codeRange).trim();
let hoverText: MarkdownString = new MarkdownString();
... | conditional_block |
HoverProvider.ts | // import * as vscode from 'vscode';
import {
HoverProvider,
TextDocument,
Position,
CancellationToken,
Hover,
window,
Range,
MarkdownString,
ProviderResult,
} from 'vscode';
import { BsvInfoProviderManger } from '../BsvProvider';
import { Ctags, CtagsManager, Symbol } from '../ctags... | (logger: Logger) {
this.logger = logger;
}
public async provideHover(
document: TextDocument,
position: Position,
token: CancellationToken
): Promise<Hover | undefined> {
this.logger.log('Hover requested');
// get word start and end
let textRange = do... | constructor | identifier_name |
HoverProvider.ts | // import * as vscode from 'vscode';
import {
HoverProvider,
TextDocument,
Position,
CancellationToken,
Hover,
window,
Range,
MarkdownString,
ProviderResult,
} from 'vscode';
import { BsvInfoProviderManger } from '../BsvProvider';
import { Ctags, CtagsManager, Symbol } from '../ctags... | // find symbol
for (let i of symbols) {
// returns the first found tag. Disregards others
// TODO: very basic hover implementation. Can be extended
if (i.name === targetText) {
let codeRange = new Range(
i.startPosition,
... | let textRange = document.getWordRangeAtPosition(position);
if (!textRange || textRange.isEmpty) return;
// hover word
let targetText = document.getText(textRange);
let symbols: Symbol[] = await CtagsManager.getSymbols(document); | random_line_split |
forms.ts | import { IState } from '../../models/state';
import { IProduct } from '../../models/product';
import { IFormData } from '../../models/form-data';
import { ActionContext } from 'vuex';
import { Promise } from 'es6-promise';
const initialForm: IFormData = {
};
const state: IState = {
formData: initialForm
};
const... |
state.formData = Object.assign({}, state.formData, { address });
}
};
const actions = {
setName(context: ActionContext<IState, IState>, name: string) {
context.commit('setName', name);
}
}
export default {
state,
actions,
mutations
} | {
return;
} | conditional_block |
forms.ts | import { IState } from '../../models/state';
import { IProduct } from '../../models/product';
import { IFormData } from '../../models/form-data';
import { ActionContext } from 'vuex';
import { Promise } from 'es6-promise';
const initialForm: IFormData = {
};
const state: IState = {
formData: initialForm
};
const... |
}
export default {
state,
actions,
mutations
} | {
context.commit('setName', name);
} | identifier_body |
forms.ts | import { IState } from '../../models/state';
import { IProduct } from '../../models/product';
import { IFormData } from '../../models/form-data';
import { ActionContext } from 'vuex';
import { Promise } from 'es6-promise';
const initialForm: IFormData = {
};
const state: IState = {
formData: initialForm
};
const... | return;
}
state.formData = Object.assign({}, state.formData, { email });
},
setZip: (state: IState, zip: number): void => {
if (!state.formData) {
return;
}
state.formData = Object.assign({}, state.formData, { zip });
},
setAddress: (stat... | if (!state.formData) { | random_line_split |
forms.ts | import { IState } from '../../models/state';
import { IProduct } from '../../models/product';
import { IFormData } from '../../models/form-data';
import { ActionContext } from 'vuex';
import { Promise } from 'es6-promise';
const initialForm: IFormData = {
};
const state: IState = {
formData: initialForm
};
const... | (context: ActionContext<IState, IState>, name: string) {
context.commit('setName', name);
}
}
export default {
state,
actions,
mutations
} | setName | identifier_name |
utils.rs | }
// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
const DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0;
/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals ... | pub fn new() -> GlobalStaticData {
GlobalStaticData {
windowproxy_handler: browsercontext::new_window_proxy_handler(),
}
} | random_line_split | |
utils.rs | JSContext, GlobalRef, Box<T>) -> Temporary<T>)
-> Temporary<T> {
wrap_fn(global.get_cx(), global, obj)
}
/// A struct to store a reference to the reflector of a DOM object.
// Allowing unused_attribute because the lint sometimes doesn't run in order
#[allow(raw_pointer_derive, unrooted_must_root, unused_... | delete_property_by_id | identifier_name | |
utils.rs | = boxed::into_raw(proto_array);
JS_SetReservedSlot(global,
DOM_PROTOTYPE_SLOT,
PrivateValue(box_ as *const libc::c_void));
}
}
/// A trait to provide access to the `Reflector` for a DOM object.
pub trait Reflectable {
/// Returns the receiver's ref... | {
JS_ObjectToOuterObject(cx, obj)
} | identifier_body | |
tutorial03-curved_polys.py | p2 = Point(3.23537580547, 42.1395946309)
p4 = Point(28.5119375629, 38.1285583893)
q1 = Point(73.1545885714, 21.8120805369)
q3 = Point(93.6244457143, 38.4228187919)
q5 = Point(66.4133738602, 33.8755592617)
q6 = Point(94.2249240122, 24.9089847651)
q7 = Point(84.8024316109, 26.7326948322)
q2 = Tri(q5, Point(70.1344457143,... | #!PYRTIST:VERSION:0:0:1
from pyrtist.lib2d import Point, Tri
#!PYRTIST:REFPOINTS:BEGIN
bbox1 = Point(0.0, 50.0); bbox2 = Point(100.0, 12.5838926174)
p1 = Point(3.15540458874, 46.942241204) | random_line_split | |
basic_sentiment.py | matutils
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import theano
theano.config.openmp = True
from sklearn.linear_model import LogisticRegression
#OMP_NUM_THREADS=24 python sentiment.py
def read_data(file_path, w2v_model, max_len = 300, hidden_dim = 32):
X = []
with open(... |
def generate(self, shape):
noise = self.generate_noise(shape)
gen_X = self.G.predict(noise)
return gen_X
def save(self, file_path):
self.G.save_weights(file_path+".G.h5")
self.D.save_weights(file_path+ ".D.h5")
self.GAN.save_weights(file_path+ ".GA... | G_loss = []
D_loss = []
for index in range(0, len(X), batch_size):
batch = X[index:index+batch_size]
Y = [1]*len(batch) + [0]*len(batch)
Y = np_utils.to_categorical(Y, nb_classes = 2)
noise = self.generate_noise(batch.shape)
gen_batch = self.G.predict... | identifier_body |
basic_sentiment.py | matutils
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import theano
theano.config.openmp = True
from sklearn.linear_model import LogisticRegression
#OMP_NUM_THREADS=24 python sentiment.py
def read_data(file_path, w2v_model, max_len = 300, hidden_dim = 32):
X = []
with open(... | (self, X, batch_size = 128):
print "Pre-train G ..."
L = []
for index in range(0, len(X), batch_size):
batch = X[index:index+batch_size]
noise = self.generate_noise(batch.shape)
loss = self.G.train_on_batch(noise, batch)
L.append(loss)
prin... | pre_trainG | identifier_name |
basic_sentiment.py | matutils
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import theano
theano.config.openmp = True
from sklearn.linear_model import LogisticRegression
#OMP_NUM_THREADS=24 python sentiment.py
def read_data(file_path, w2v_model, max_len = 300, hidden_dim = 32):
X = []
with open(... | def evaluate(self, testX, testY):
#print testX
#print self.CLF.predict(testX)
print "Accuracy on testing data :", self.CLF.score(testX, testY)
def save(self, file_path):
pass
def load(self, file_path):
pass
if __name__ == "__main__":
#RNN
np.random.se... | random_line_split | |
basic_sentiment.py | matutils
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import theano
theano.config.openmp = True
from sklearn.linear_model import LogisticRegression
#OMP_NUM_THREADS=24 python sentiment.py
def read_data(file_path, w2v_model, max_len = 300, hidden_dim = 32):
X = []
with open(... |
x /= index
X.append(x)
return np.array(X)
def normalize(word):
word = re.sub(r'[^\w\s]' , "", word.decode("utf-8"), re.UNICODE)
word = word.lower()
return word
class Generator:
def __init__(self, max_len = 300, hidden_dim = 32):
self.max_len = max_len
self... | if token in w2v_model:
x += w2v_model[token]
index += 1
if index >= max_len:
break | conditional_block |
test_h5r.py | #+
#
# This file is part of h5py, a low-level Python interface to the HDF5 library.
#
# Copyright (C) 2008 Andrew Collette
# http://h5py.alfven.org
# License: BSD (See LICENSE.txt for full license)
#
# $Date$
#
#-
from h5py import tests
from h5py import *
class TestBasic(tests.HTest):
def setUp(self):
... | self.assertEqual(h5r.dereference(ref, self.fid), self.did)
sid2 = h5r.get_region(ref, self.id)
self.assertIsInstance(sid, h5s.SpaceID)
self.assertEqual(sid2.get_select_bounds(), sid.get_select_bounds())
def test_create_exc(self):
""" (H5R) RegionReference w/no dataspace rais... | """ (H5R) Region reference round-trip """
sid = self.did.get_space()
ref = h5r.create(self.did, '.', h5r.DATASET_REGION, sid)
self.assertIsInstance(ref, h5r.RegionReference) | random_line_split |
test_h5r.py | #+
#
# This file is part of h5py, a low-level Python interface to the HDF5 library.
#
# Copyright (C) 2008 Andrew Collette
# http://h5py.alfven.org
# License: BSD (See LICENSE.txt for full license)
#
# $Date$
#
#-
from h5py import tests
from h5py import *
class TestBasic(tests.HTest):
def setUp(self):
... |
@tests.require(api=18)
def test_obj(self):
""" (H5R) get_name() on object reference """
ref = h5r.create(self.id, '/', h5r.OBJECT)
self.assertEqual(h5r.get_name(ref, self.fid), '/')
| """ (H5R) RegionReference w/no dataspace raises ValueError """
self.assertRaises(ValueError, h5r.create, self.did, '.', h5r.DATASET_REGION) | identifier_body |
test_h5r.py | #+
#
# This file is part of h5py, a low-level Python interface to the HDF5 library.
#
# Copyright (C) 2008 Andrew Collette
# http://h5py.alfven.org
# License: BSD (See LICENSE.txt for full license)
#
# $Date$
#
#-
from h5py import tests
from h5py import *
class TestBasic(tests.HTest):
def setUp(self):
... | (self):
""" (H5R) Region reference round-trip """
sid = self.did.get_space()
ref = h5r.create(self.did, '.', h5r.DATASET_REGION, sid)
self.assertIsInstance(ref, h5r.RegionReference)
self.assertEqual(h5r.dereference(ref, self.fid), self.did)
sid2 = h5r.get_region(ref, self... | test_reg | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... | (opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>,
... | create_constellation | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... |
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
}
fn create_constellation(opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler... | {
self.compositor.pinch_zoom_level()
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... |
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = CompositorTask::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
co... | {
webdriver(port, constellation_chan.clone());
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... |
pub use _util as util;
pub use export::canvas;
pub use export::canvas_traits;
pub use export::compositing;
pub use export::devtools;
pub use export::devtools_traits;
pub use export::euclid;
pub use export::gfx;
pub use export::gleam::gl;
pub use export::layers;
pub use export::layout;
pub use export::msg;
pub use expo... | use std::rc::Rc;
use std::sync::mpsc::Sender;
use util::opts; | random_line_split |
index.js | 'use strict';
const expect = require('chai').expect;
const deepfind = require('../index');
const simpleFixture = {
'key': 'value'
};
const complexFixture = {
'key1': {
'key': 'value1'
},
'key2': {
'key': 'value2'
},
'key3': {
'key': 'value3'
}
};
describe('deepfind', () => {
it('should ... |
it('should throw an error when given no key', () => {
expect(() => deepfind({}, null)).to.throw('deepfind must be supplied a key');
});
it('should return an empty array when no key is found', () => {
expect(deepfind({}, 'key')).to.be.an.array;
expect(deepfind({}, 'key')).to.be.empty;
});
it('sh... | expect(() => deepfind(null, 'key')).to.throw('deepfind must be supplied an object');
}); | random_line_split |
log-json-syntax-tree.js | const csound = require('bindings')('csound-api.node');
const stringify = require('json-stable-stringify');
const Csound = csound.Create();
const ASTRoot = csound.ParseOrc(Csound, `
0dbfs = 1
giFunctionTableID ftgen 0, 0, 16384, 10, 1
instr A440
outc oscili(0.5 * 0dbfs, 440, giFunctionTableID)
endin
`);
//... | if (result !== null) return result;
result = compareKeys(b.key, a.key);
return (result !== null) ? -result : a.key.localeCompare(b.key);
},
replacer: (key, value) => (key === 'next') ? undefined : value,
space: ' '
})); | }
return null;
}
let result = compareKeys(a.key, b.key); | random_line_split |
log-json-syntax-tree.js | const csound = require('bindings')('csound-api.node');
const stringify = require('json-stable-stringify');
const Csound = csound.Create();
const ASTRoot = csound.ParseOrc(Csound, `
0dbfs = 1
giFunctionTableID ftgen 0, 0, 16384, 10, 1
instr A440
outc oscili(0.5 * 0dbfs, 440, giFunctionTableID)
endin
`);
//... | (ASTObject, depth) {
const depthPlus1 = depth + 1;
ASTObjectsForDepths[depthPlus1] = ASTObject;
if (ASTObject.left)
addNextNodes(ASTObject.left, depthPlus1);
if (ASTObject.right)
addNextNodes(ASTObject.right, depthPlus1);
if (ASTObject.next) {
const ASTObjectForDepth = ASTObjectsFo... | addNextNodes | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.