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 |
|---|---|---|---|---|
github.py | from gitmostwanted.app import celery, db
from gitmostwanted.lib.github.api import user_starred, user_starred_star
from gitmostwanted.models.repo import Repo
from gitmostwanted.models.user import UserAttitude
@celery.task()
def repo_starred_star(user_id: int, access_token: str):
starred, code = user_starred(access... | (repo_name: str, uid: int):
repo = Repo.get_one_by_full_name(repo_name)
if not repo:
return None
db.session.merge(UserAttitude.like(uid, repo.id))
db.session.commit()
return repo.id
| repo_like | identifier_name |
github.py | from gitmostwanted.app import celery, db
from gitmostwanted.lib.github.api import user_starred, user_starred_star
from gitmostwanted.models.repo import Repo
from gitmostwanted.models.user import UserAttitude
@celery.task()
def repo_starred_star(user_id: int, access_token: str):
|
def repo_like(repo_name: str, uid: int):
repo = Repo.get_one_by_full_name(repo_name)
if not repo:
return None
db.session.merge(UserAttitude.like(uid, repo.id))
db.session.commit()
return repo.id
| starred, code = user_starred(access_token)
if not starred:
return False
attitudes = UserAttitude.list_liked_by_user(user_id)
lst_in = [repo_like(s['full_name'], user_id) for s in starred
if not [a for a in attitudes if s['full_name'] == a.repo.full_name]]
lst_out = [user_starred... | identifier_body |
github.py | from gitmostwanted.app import celery, db
from gitmostwanted.lib.github.api import user_starred, user_starred_star
from gitmostwanted.models.repo import Repo
from gitmostwanted.models.user import UserAttitude
@celery.task()
def repo_starred_star(user_id: int, access_token: str):
starred, code = user_starred(access... |
db.session.merge(UserAttitude.like(uid, repo.id))
db.session.commit()
return repo.id
| return None | conditional_block |
github.py | from gitmostwanted.app import celery, db
from gitmostwanted.lib.github.api import user_starred, user_starred_star
from gitmostwanted.models.repo import Repo
from gitmostwanted.models.user import UserAttitude
@celery.task()
def repo_starred_star(user_id: int, access_token: str): |
lst_in = [repo_like(s['full_name'], user_id) for s in starred
if not [a for a in attitudes if s['full_name'] == a.repo.full_name]]
lst_out = [user_starred_star(r.repo.full_name, access_token) for r in attitudes
if not [x for x in starred if x['full_name'] == r.repo.full_name]]
... | starred, code = user_starred(access_token)
if not starred:
return False
attitudes = UserAttitude.list_liked_by_user(user_id) | random_line_split |
synom.rs | //! # extern crate syn;
//! #
//! # extern crate proc_macro2;
//! # use proc_macro2::TokenStream;
//! #
//! use syn::synom::Parser;
//! use syn::punctuated::Punctuated;
//! use syn::{PathSegment, Expr, Attribute};
//!
//! # fn run_parsers() -> Result<(), syn::synom::ParseError> {
//! # let tokens = TokenStream::new... | parse_str | identifier_name | |
synom.rs | unctuated::<Expr, Token![,]>::parse_terminated;
//! let args = parser.parse(tokens)?;
//!
//! # let tokens = TokenStream::new().into();
//! // Parse zero or more outer attributes but not inner attributes.
//! named!(outer_attrs -> Vec<Attribute>, many0!(Attribute::parse_outer));
//! let attrs = outer_attrs.parse(to... | Err(ParseError::new("failed to parse anything"))
} else {
Err(ParseError::new("failed to parse all tokens"))
}
} | random_line_split | |
synom.rs | Expr, Attribute};
//!
//! # fn run_parsers() -> Result<(), syn::synom::ParseError> {
//! # let tokens = TokenStream::new().into();
//! // Parse a nonempty sequence of path segments separated by `::` punctuation
//! // with no trailing punctuation.
//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separ... | {
match s.parse() {
Ok(tts) => self.parse2(tts),
Err(_) => Err(ParseError::new("error while lexing input string")),
}
} | identifier_body | |
FeatureBasicHeader.test.tsx | import { mockTracking } from "Artsy/Analytics"
import {
FeatureBasicArticle,
FeatureBasicVideoArticle,
} from "Components/Publishing/Fixtures/Articles"
import { EditableChild } from "Components/Publishing/Fixtures/Helpers"
import { Video } from "Components/Publishing/Sections/Video"
import { mount } from "enzyme"
i... |
expect(dispatch).toBeCalledWith({
action: "Click",
label: "Basic feature video click",
impression_type: "sa_basic_feature_video",
context_type: "article_fixed",
})
})
it("Renders editImage", () => {
testProps.editImage = EditableChild("Image")
const component = getWrapper(t... | const component = mount(<Component article={FeatureBasicVideoArticle} />)
component
.find(VideoContainer)
.at(0)
.simulate("click") | random_line_split |
visit.py | #
# Copyright (C) 2014 Jonathan Finlay <jfinlay@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
return 1
def check_duration(self, cr, uid, id, context=None):
"""
Check the consistency of the visit duration
:param cr:
:param uid:
:param id:
:param context:
:return:
"""
return {}
def onchange_consulting_room(self, cr, uid, id... | return room[0] | conditional_block |
visit.py | #
# Copyright (C) 2014 Jonathan Finlay <jfinlay@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
def check_duration(self, cr, uid, id, context=None):
"""
Check the consistency of the visit duration
:param cr:
:param uid:
:param id:
:param context:
:return:
"""
return {}
def onchange_consulting_room(self, cr, uid, id, consulting_room... | consulroom_obj = self.pool.get('consulting.room')
room = consulroom_obj.search(cr, uid, [('default', '=', '1')])
if room:
return room[0]
return 1 | identifier_body |
visit.py | #
# Copyright (C) 2014 Jonathan Finlay <jfinlay@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... | 'duration': fields.float('Standard duration',
help='Visit standard duration time in minutes'),
'price': fields.float('Price',
help='Standard consultation fee'),
'address': fields.text('Address'),
'default': fields.boolean('... | _description = 'Consulting rooms configuration module'
_columns = {
'name': fields.char('Name'), | random_line_split |
visit.py | #
# Copyright (C) 2014 Jonathan Finlay <jfinlay@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... | (osv.osv):
""" Consulting rooms """
_name = 'consulting.room'
_description = 'Consulting rooms configuration module'
_columns = {
'name': fields.char('Name'),
'duration': fields.float('Standard duration',
help='Visit standard duration time in minutes')... | ConsultingRoom | identifier_name |
index.ts | import { key, CustomLocale } from "../types/locale";
import { Arabic as ar } from "./ar";
import { Bulgarian as bg } from "./bg";
import { Bangla as bn } from "./bn";
import { Catalan as cat } from "./cat";
import { Czech as cs } from "./cs";
import { Welsh as cy } from "./cy";
import { Danish as da } from "./da";
imp... | th,
tr,
uk,
vn,
zh,
};
export default l10n; | sk,
sl,
sq,
sr,
sv, | random_line_split |
chunk.rs | use std::cell::RefCell;
use std::collections::HashMap;
use crate::array::*;
use crate::shader::Vertex;
use gfx;
#[derive(Copy, Clone)]
pub struct BlockState {
pub value: u16,
}
pub const EMPTY_BLOCK: BlockState = BlockState { value: 0 };
#[derive(Copy, Clone)]
pub struct BiomeId {
pub value: u8,
}
#[derive... |
pub const SIZE: usize = 16;
/// A chunk of SIZE x SIZE x SIZE blocks, in YZX order.
#[derive(Copy, Clone)]
pub struct Chunk {
pub blocks: [[[BlockState; SIZE]; SIZE]; SIZE],
pub light_levels: [[[LightLevel; SIZE]; SIZE]; SIZE],
}
// TODO: Change to const pointer.
pub const EMPTY_CHUNK: &Chunk = &Chunk {
... | random_line_split | |
chunk.rs | use std::cell::RefCell;
use std::collections::HashMap;
use crate::array::*;
use crate::shader::Vertex;
use gfx;
#[derive(Copy, Clone)]
pub struct BlockState {
pub value: u16,
}
pub const EMPTY_BLOCK: BlockState = BlockState { value: 0 };
#[derive(Copy, Clone)]
pub struct BiomeId {
pub value: u8,
}
#[derive... | (self) -> u8 {
self.value & 0xf
}
pub fn sky_light(self) -> u8 {
self.value >> 4
}
}
pub const SIZE: usize = 16;
/// A chunk of SIZE x SIZE x SIZE blocks, in YZX order.
#[derive(Copy, Clone)]
pub struct Chunk {
pub blocks: [[[BlockState; SIZE]; SIZE]; SIZE],
pub light_levels: [[[Li... | block_light | identifier_name |
__manifest__.py | ##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | 'base_currency_inverse_rate',
# 'l10n_ar_aeroo_purchase',
# 'l10n_ar_aeroo_sale',
# 'l10n_ar_aeroo_stock',
# 'l10n_ar_aeroo_payment_group',
'l10n_ar_bank',
# 'product_catalog_aeroo_report_public_categ',
# 'product_price_taxes_included',
'purchase_q... | random_line_split | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file was generated with PyScaffold 3.0.2.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: http://pyscaffold.org/
"""
import sys
from setuptools import setup
import versioneer
# Add here console scripts and oth... | setup_package() | conditional_block | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file was generated with PyScaffold 3.0.2.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: http://pyscaffold.org/
"""
import sys
from setuptools import setup
import versioneer
# Add here console scripts and oth... | ():
needs_sphinx = {'build_sphinx', 'upload_docs'}.intersection(sys.argv)
sphinx = ['sphinx'] if needs_sphinx else []
setup(setup_requires=['pyscaffold>=3.0a0,<3.1a0'] + sphinx,
entry_points=entry_points,
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
... | setup_package | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file was generated with PyScaffold 3.0.2.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: http://pyscaffold.org/
"""
import sys
from setuptools import setup
import versioneer
# Add here console scripts and oth... |
if __name__ == "__main__":
setup_package()
| needs_sphinx = {'build_sphinx', 'upload_docs'}.intersection(sys.argv)
sphinx = ['sphinx'] if needs_sphinx else []
setup(setup_requires=['pyscaffold>=3.0a0,<3.1a0'] + sphinx,
entry_points=entry_points,
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
u... | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file was generated with PyScaffold 3.0.2.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: http://pyscaffold.org/
"""
import sys
from setuptools import setup
import versioneer
# Add here console scripts and oth... |
def setup_package():
needs_sphinx = {'build_sphinx', 'upload_docs'}.intersection(sys.argv)
sphinx = ['sphinx'] if needs_sphinx else []
setup(setup_requires=['pyscaffold>=3.0a0,<3.1a0'] + sphinx,
entry_points=entry_points,
version=versioneer.get_version(),
cmdclass=versioneer.... | qrl_measure = qrl.measure:main
qrl_walletd = qrl.daemon.walletd:main
qrl_generate_genesis = qrl.tools.generate_genesis:main
""" | random_line_split |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
def centres(request): | def upload(request):
#文件上传
return render(request, 'centres/upload.html')
def uploadfile(request):
import os
if request.method == "POST": # 请求方法为POST时,进行处理
myFile =request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None
if not myFile:
#return HttpResponse("no files for upload!")
return... | #Python练习项目管理中心Center
return render(request, 'centres/centres.html')
| random_line_split |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
def centres(request):
#Python练习项目管理中心Center
return render(request, 'cen... | r!'}) | {'what':'upload ove | conditional_block |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
def centres(request):
#Python练习项目管理中心Center
return render(re | uest):
#文件上传
return render(request, 'centres/upload.html')
def uploadfile(request):
import os
if request.method == "POST": # 请求方法为POST时,进行处理
myFile =request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None
if not myFile:
#return HttpResponse("no files for upload!")
return render(reques... | quest, 'centres/centres.html')
def upload(req | identifier_body |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
def centres(request):
#Python练习项目管理中心Center
return render(request, 'cen... | 传
return render(request, 'centres/upload.html')
def uploadfile(request):
import os
if request.method == "POST": # 请求方法为POST时,进行处理
myFile =request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None
if not myFile:
#return HttpResponse("no files for upload!")
return render(request, 'centres/... |
#文件上 | identifier_name |
get_capabilities.rs | //! `GET /_matrix/client/*/capabilities`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3capabilities
use ruma_common::api::ruma_api;
use crate::capabilities::Capabilities;
ruma_api! {
metadata: {
descript... | (capabilities: Capabilities) -> Self {
Self { capabilities }
}
}
impl From<Capabilities> for Response {
fn from(capabilities: Capabilities) -> Self {
Self::new(capabilities)
}
}
}
| new | identifier_name |
get_capabilities.rs | //! `GET /_matrix/client/*/capabilities`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3capabilities
use ruma_common::api::ruma_api;
use crate::capabilities::Capabilities;
ruma_api! {
metadata: {
descript... |
}
impl Response {
/// Creates a new `Response` with the given capabilities.
pub fn new(capabilities: Capabilities) -> Self {
Self { capabilities }
}
}
impl From<Capabilities> for Response {
fn from(capabilities: Capabilities) -> Self {
Self::new... | {
Self {}
} | identifier_body |
get_capabilities.rs | //! `GET /_matrix/client/*/capabilities`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3capabilities
use ruma_common::api::ruma_api;
use crate::capabilities::Capabilities;
ruma_api! {
metadata: {
descript... | }
impl Request {
/// Creates an empty `Request`.
pub fn new() -> Self {
Self {}
}
}
impl Response {
/// Creates a new `Response` with the given capabilities.
pub fn new(capabilities: Capabilities) -> Self {
Self { capabilities }
}... |
error: crate::Error | random_line_split |
engine.py | # Copyright (c) 2014 OpenStack Foundation
#
# 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 ... |
def _get_instance_if_running(self, job_execution):
pid, inst_id = self._get_pid_and_inst_id(job_execution.oozie_job_id)
if not pid or not inst_id or (
job_execution.info['status'] in edp.JOB_STATUSES_TERMINATED):
return None, None
# TODO(tmckay): well, if there is a ... | try:
pid, inst_id = job_id.split("@", 1)
if pid and inst_id:
return (pid, inst_id)
except Exception:
pass
return "", "" | identifier_body |
engine.py | # Copyright (c) 2014 OpenStack Foundation
#
# 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 ... |
# SIGINT will yield either -2 or 130
elif exit_status in ["-2", "130"]:
return {"status": edp.JOB_STATUS_KILLED}
# Well, process is done and result is missing or unexpected
return {"status": edp.JOB_STATUS_DONEWITHERROR}
def cancel_job(self, job_execution):... | return {"status": edp.JOB_STATUS_SUCCEEDED} | conditional_block |
engine.py | # Copyright (c) 2014 OpenStack Foundation
#
# 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 ... | pid, job_execution)
def get_job_status(self, job_execution):
pid, instance = self._get_instance_if_running(job_execution)
if instance is not None:
with remote.get_remote(instance) as r:
return self._get_job_stat... | random_line_split | |
engine.py | # Copyright (c) 2014 OpenStack Foundation
#
# 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 ... | (self, cluster, job, data):
j.check_main_class_present(data, job)
@staticmethod
def get_possible_job_config(job_type):
return {'job_config': {'configs': [], 'args': []}}
@staticmethod
def get_supported_job_types():
return [edp.JOB_TYPE_SPARK]
| validate_job_execution | identifier_name |
state_manager.rs | use status::*;
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone)]
pub struct StateManager {
current_state: Status,
prev_state: Status,
is_web_requesting: bool,
is_bg_requesting: bool,
tx_state: Sender<(Status,Status)>,
to_print_scre... |
}
pub fn get_state(&self) -> Status {
self.current_state
}
pub fn is_to_print_screen(&self) -> bool {
(*self.to_print_screen.clone()).load(Ordering::Relaxed)
}
pub fn set_to_print_screen(&mut self, value: bool) {
(*self.to_print_screen).store(value, Ordering::Relaxed)... | {
let prev_state_tmp = self.prev_state.clone();
let current_state_tmp = self.current_state.clone();
self.prev_state = self.current_state;
self.current_state = value;
self.tx_state.send((prev_state_tmp, current_state_tmp));
} | conditional_block |
state_manager.rs | use status::*;
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone)]
pub struct StateManager {
current_state: Status,
prev_state: Status,
is_web_requesting: bool,
is_bg_requesting: bool,
tx_state: Sender<(Status,Status)>,
to_print_scre... | self.current_state
}
pub fn is_to_print_screen(&self) -> bool {
(*self.to_print_screen.clone()).load(Ordering::Relaxed)
}
pub fn set_to_print_screen(&mut self, value: bool) {
(*self.to_print_screen).store(value, Ordering::Relaxed)
}
} | random_line_split | |
state_manager.rs | use status::*;
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone)]
pub struct StateManager {
current_state: Status,
prev_state: Status,
is_web_requesting: bool,
is_bg_requesting: bool,
tx_state: Sender<(Status,Status)>,
to_print_scre... |
pub fn is_bg_request (&self) -> bool {
self.is_bg_requesting
}
pub fn set_bg_request(&mut self, value: bool) {
self.is_bg_requesting = value;
}
pub fn update_state(&mut self, value: Status) {
if self.current_state != value {
let prev_state_tmp = self.prev_state... | {
self.is_web_requesting = value;
} | identifier_body |
state_manager.rs | use status::*;
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone)]
pub struct StateManager {
current_state: Status,
prev_state: Status,
is_web_requesting: bool,
is_bg_requesting: bool,
tx_state: Sender<(Status,Status)>,
to_print_scre... | (&self) -> Status {
self.current_state
}
pub fn is_to_print_screen(&self) -> bool {
(*self.to_print_screen.clone()).load(Ordering::Relaxed)
}
pub fn set_to_print_screen(&mut self, value: bool) {
(*self.to_print_screen).store(value, Ordering::Relaxed)
}
}
| get_state | identifier_name |
doc.py | from __future__ import absolute_import
from builtins import object
from .error import CreateFolderError, FileNotWritableError, RemoveFolderError
import grace.py27.pyjsdoc
import os
from shutil import rmtree
class Doc(object):
def __init__(self, config):
self._cwd = os.getcwd()
self._config = confi... | if with_libs:
jsdoc = pyjsdoc.CodeBaseDoc([source, self._lib_path])
else:
jsdoc = pyjsdoc.CodeBaseDoc([source])
try:
jsdoc.save_docs(output_dir=dest)
except:
raise FileNotWritableError('Could not write the docs to the build directory.')
... | source = os.path.join(self._cwd, 'src', 'javascript')
dest = os.path.join(self._cwd, 'build', 'JSDocs')
if not os.path.exists(self._config['build_path']):
try:
os.makedirs(self._config['build_path'])
except:
raise CreateFolderError('Could not crea... | identifier_body |
doc.py | from __future__ import absolute_import
from builtins import object
from .error import CreateFolderError, FileNotWritableError, RemoveFolderError
import grace.py27.pyjsdoc
import os
from shutil import rmtree
class Doc(object):
def __init__(self, config):
self._cwd = os.getcwd()
self._config = confi... |
if os.path.exists(dest):
try:
rmtree(dest)
except:
raise RemoveFolderError('Could not remove the JSDoc folder.')
try:
os.makedirs(dest)
except:
raise CreateFolderError('Could not create the doc folder in your buil... | try:
os.makedirs(self._config['build_path'])
except:
raise CreateFolderError('Could not create the project folder.') | conditional_block |
doc.py | from __future__ import absolute_import
from builtins import object
from .error import CreateFolderError, FileNotWritableError, RemoveFolderError
import grace.py27.pyjsdoc
import os
from shutil import rmtree
class Doc(object):
def __init__(self, config):
self._cwd = os.getcwd()
self._config = confi... | try:
jsdoc.save_docs(output_dir=dest)
except:
raise FileNotWritableError('Could not write the docs to the build directory.')
if self._doc_path is not None:
if os.path.exists(self._doc_path):
try:
rmtree(self._doc_path)
... | else:
jsdoc = pyjsdoc.CodeBaseDoc([source])
| random_line_split |
doc.py | from __future__ import absolute_import
from builtins import object
from .error import CreateFolderError, FileNotWritableError, RemoveFolderError
import grace.py27.pyjsdoc
import os
from shutil import rmtree
class Doc(object):
def __init__(self, config):
self._cwd = os.getcwd()
self._config = confi... | (self, with_libs=False):
source = os.path.join(self._cwd, 'src', 'javascript')
dest = os.path.join(self._cwd, 'build', 'JSDocs')
if not os.path.exists(self._config['build_path']):
try:
os.makedirs(self._config['build_path'])
except:
raise ... | run | identifier_name |
vec.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... |
}
| {
self.iter().any(|e| e == p)
} | identifier_body |
vec.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | (&self, p: &T) -> bool {
self.iter().any(|e| e == p)
}
}
| contains | identifier_name |
vec.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | You should have received a copy of the GNU General Public License
along with Precached. If not, see <http://www.gnu.org/licenses/>.
*/
use rayon::prelude::*;
use std::cmp::PartialEq;
pub trait Contains<T> {
fn contains(&self, p: &T) -> bool;
}
impl<T: PartialEq> Contains<T> for Vec<T> {
fn contains(... | random_line_split | |
commands.py | ServiceDescription(**kw)
if options.address is True:
raise RuntimeError, 'WS-Address w/twisted currently unsupported, edit the "factory" attribute by hand'
else:
# TODO: make all this handler arch
if options.address is True:
ss = ServiceDescriptionWSA()
else:... | random_line_split | ||
commands.py | .getServiceModuleName()+'.py'
fd = open( join(options.output_dir, file_name), 'w+')
ss.write(fd)
fd.close()
return file_name
class _XMLSchemaAdapter:
"""Adapts an obj XMLSchema.XMLSchema to look like a WSDLTools.WSDL,
just setting a couple attributes code expects to see.
"""
def _... | os.makedirs(doc) | conditional_block | |
commands.py | dl2dispatch(options, reader.loadFromURL(args[0]))
def _wsdl2py(options, wsdl):
if options.twisted:
from ZSI.generate.containers import ServiceHeaderContainer
try:
ServiceHeaderContainer.imports.remove('from ZSI import client')
except ValueError:
pass
Servic... | """Produce HTML documentation for a class object."""
realname = object.__name__
name = name or realname
bases = object.__bases__
object, name = pydoc.resolve(object, forceload)
contents = []
push = contents.append
if name == realname:
title = '<a name=... | identifier_body | |
commands.py | of typecodes")
# Use Twisted
op.add_option("-w", "--twisted",
action="store_true", dest='twisted', default=False,
help="generate a twisted.web client/server, dependencies python>=2.4, Twisted>=2.0.0, TwistedWeb>=0.5.0")
op.add_option("-o", "--output-dir",
... | _writeclientdoc | identifier_name | |
DropdownFilter.tsx | /*
Copyright (C) 2017 Cloudbase Solutions SRL
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distribute... |
return (
<List
onMouseDown={() => { this.itemMouseDown = true }}
onMouseUp={() => { this.itemMouseDown = false }}
data-test-id="dropdownFilter-list"
>
<Tip />
<ListItems>
<SearchInput
width="100%"
alwaysOpen
placehol... | {
return null
} | conditional_block |
DropdownFilter.tsx | /*
Copyright (C) 2017 Cloudbase Solutions SRL
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distribute... | extends React.Component<Props, State> {
static defaultProps = {
searchPlaceholder: 'Filter',
}
state: State = {
showDropdownList: false,
}
itemMouseDown: boolean | undefined
componentDidMount() {
window.addEventListener('mousedown', this.handlePageClick, false)
}
componentWillUnmount() ... | DropdownFilter | identifier_name |
DropdownFilter.tsx | /*
Copyright (C) 2017 Cloudbase Solutions SRL
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distribute... | <Wrapper>
{this.renderButton()}
{this.renderList()}
</Wrapper>
)
}
}
export default DropdownFilter | return ( | random_line_split |
animator_server.py | #!/usr/bin/env python
import glob
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32
import rospkg
import sys
class Animation:
def __init__(self, directory):
self.fnames = [fname for fname in glob.glob("%s/*" % directory)]
self.fnames... |
def main():
rospy.init_node('animator_server', anonymous=True)
rate = rospy.Rate(30)
rospack = rospkg.RosPack()
path = sys.argv[1]
Animation(path)
while not rospy.is_shutdown():
rate.sleep()
if __name__ == "__main__":
main()
| print "target", self.current_target, self.current_value
if self.current_target < self.current_value:
self.set_value(self.current_value - 1)
elif self.current_target > self.current_value:
self.set_value(self.current_value + 1)
elif self.current_target =... | conditional_block |
animator_server.py | #!/usr/bin/env python
import glob
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32
import rospkg
import sys
class Animation:
def __init__(self, directory):
self.fnames = [fname for fname in glob.glob("%s/*" % directory)]
self.fnames... | (self):
assert 0 <= self.current_idx < len(self.images), self.current_idx
assert 0 <= self.current_value < 100, self.current_value
assert self.current_target == None or (0 <= self.current_target < 100), self.current_target
def publish_image(self):
msg = cv_bridge.CvBridge().cv2_to_im... | checkrep | identifier_name |
animator_server.py | #!/usr/bin/env python
import glob
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32
import rospkg
import sys
class Animation:
| queue_size=10)
self.target_publisher = rospy.Publisher("/confusion/target/state", Int32,
queue_size=10)
self.timer = rospy.Timer(rospy.Duration(self.velocity), self.timer_cb)
def set_velocity(self, vel... | def __init__(self, directory):
self.fnames = [fname for fname in glob.glob("%s/*" % directory)]
self.fnames.sort()
self.images = [cv2.imread(path) for path in self.fnames]
self.animation_timer = None
self.current_value = 0
self.current_idx = 0
self.set_velocity(1/... | identifier_body |
animator_server.py | #!/usr/bin/env python
import glob
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32
import rospkg
import sys
class Animation:
def __init__(self, directory):
self.fnames = [fname for fname in glob.glob("%s/*" % directory)]
self.fnames... | def set_velocity(self, velocity):
if isinstance(velocity, Float32):
velocity = velocity.data
self.velocity = velocity
if (self.animation_timer != None):
self.animation_timer.shutdown()
def set_idx(self, idx):
self.current_idx = idx;
self.current_... | self.timer = rospy.Timer(rospy.Duration(self.velocity), self.timer_cb)
| random_line_split |
app.js | // Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
ap... |
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
$rootScope.user = {};
}])
.config([ '$stateProvider','$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views... | {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
} | conditional_block |
app.js | // Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
ap... | 'menuContent': {
templateUrl: 'views/restaurant/restaurant.html',
controller: 'RestaurantCtrl'
}
}
})
.state('app.picture', {
url: '/picture',
views: {
'menuContent': {
templateUrl: 'views/pictures/pictures.html',
controller: 'PicturesCtrl'
}
}
})
.state('app.se... | url: '/restaurant',
views: { | random_line_split |
base.py | import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, "bin", "ssh-connect")
def __init__(self, workspace, url, username=None):
se... |
def clone(self):
raise NotImplementedError
def update(self):
raise NotImplementedError
def checkout(self, ref):
raise NotImplementedError
def get_sha(self, ref):
"""
Given a `ref` return the fully qualified version.
"""
raise NotImplementedErr... | if self.exists():
self.update()
else:
self.clone() | identifier_body |
base.py | import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, "bin", "ssh-connect")
def __init__(self, workspace, url, username=None):
se... |
if capture:
handler = workspace.capture
else:
handler = workspace.run
rv = handler(command, *args, **kwargs)
if isinstance(rv, bytes):
rv = rv.decode("utf8")
if isinstance(rv, str):
return rv.strip()
return rv
def exi... | random_line_split | |
base.py | import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, "bin", "ssh-connect")
def __init__(self, workspace, url, username=None):
se... | (self):
raise NotImplementedError
def update(self):
raise NotImplementedError
def checkout(self, ref):
raise NotImplementedError
def get_sha(self, ref):
"""
Given a `ref` return the fully qualified version.
"""
raise NotImplementedError
def get... | clone | identifier_name |
base.py | import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, "bin", "ssh-connect")
def __init__(self, workspace, url, username=None):
se... |
else:
handler = workspace.run
rv = handler(command, *args, **kwargs)
if isinstance(rv, bytes):
rv = rv.decode("utf8")
if isinstance(rv, str):
return rv.strip()
return rv
def exists(self, workspace=None):
if workspace is None:
... | handler = workspace.capture | conditional_block |
index.js | var http = require("http");
var express = require("express");
var app = express();
var fs = require("fs");
var path = require("path");
var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080;
var mongoClient = require('mongodb').MongoClient,
assert = require('assert');
//var mongodb = "mongodb:/... | });
});
//res.send(url);
});
app.listen(port);
console.log('Server running on http://%s:%s', ip, port);
module.exports = app;
var addDocument = function(db, document, callback) {
var collection = db.collection('shorturls');
collection.insertOne(document, function(err, result) {
console.log("... | res.redirect(callback[0].url);
}
| conditional_block |
index.js | var http = require("http");
var express = require("express");
var app = express();
var fs = require("fs");
var path = require("path");
var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080;
var mongoClient = require('mongodb').MongoClient,
assert = require('assert');
//var mongodb = "mongodb:/... | }
String.prototype.hashCode = function() {
var hash = 0,
i, chr, len;
if (this.length === 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;... | "url": url
}).toArray(function(err, docs) {
assert.equal(err, null);
callback(docs);
}); | random_line_split |
video_detector.js | /**
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This file requires the functions defined in test_functions.js.
var gFingerprints = [];
// Public interface.
/**
* Starts capturing fram... |
/** @private */
function fingerprint_(canvasContext, width, height) {
var imageData = canvasContext.getImageData(0, 0, width, height);
var pixels = imageData.data;
var fingerprint = 0;
for (var i = 0; i < pixels.length; i++) {
fingerprint += pixels[i];
}
return fingerprint;
}
| {
canvasContext.drawImage(video, 0, 0, width, height);
} | identifier_body |
video_detector.js | /**
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This file requires the functions defined in test_functions.js.
var gFingerprints = [];
// Public interface.
/**
* Starts capturing fram... |
}
} catch (exception) {
throw failTest('Failed to detect video: ' + exception.message);
}
returnToTest('video-not-playing');
}
// Internals.
/** @private */
function allElementsRoughlyEqualTo_(elements, element_to_compare) {
if (elements.length == 0)
return false;
var PIXEL_DIFF_TOLERANCE = 10... | {
returnToTest('video-playing');
return;
} | conditional_block |
video_detector.js | /**
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This file requires the functions defined in test_functions.js.
var gFingerprints = [];
// Public interface.
/**
* Starts capturing fram... |
/** @private */
function allElementsRoughlyEqualTo_(elements, element_to_compare) {
if (elements.length == 0)
return false;
var PIXEL_DIFF_TOLERANCE = 100;
for (var i = 0; i < elements.length; i++) {
if (Math.abs(elements[i] - element_to_compare) > PIXEL_DIFF_TOLERANCE) {
return false;
}
}
... | }
// Internals. | random_line_split |
video_detector.js | /**
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This file requires the functions defined in test_functions.js.
var gFingerprints = [];
// Public interface.
/**
* Starts capturing fram... | (canvasContext, width, height) {
var imageData = canvasContext.getImageData(0, 0, width, height);
var pixels = imageData.data;
var fingerprint = 0;
for (var i = 0; i < pixels.length; i++) {
fingerprint += pixels[i];
}
return fingerprint;
}
| fingerprint_ | identifier_name |
pc-display.tsx | /// <reference path="current-party.tsx" />
namespace TPP.Display.Elements.RunStatus {
export class PC extends React.Component<{ pc: TPP.Tv.CombinedPCData }, {}> {
render() {
if (!this.props.pc || !this.props.pc.boxes)
return null;
return <div>
<h2>{pok... |
className="pokemon-hud pc-box">
<ul className="party">
{boxContents.length > 0 ?
boxContents.map(p => <Pokemon pokemon={p} key={p.box_slot || p.personality_value} />)
:
<li className="empty">Empt... | {
const boxNum = this.props.boxNumber;
const boxName = this.props.boxName;
const boxContents = this.props.boxContents;
return <PokeBox title={`${boxNum ? `#${boxNum}: ` : ""}${boxName} (${boxContents.length})`} | identifier_body |
pc-display.tsx | /// <reference path="current-party.tsx" />
namespace TPP.Display.Elements.RunStatus {
export class PC extends React.Component<{ pc: TPP.Tv.CombinedPCData }, {}> {
render() {
if (!this.props.pc || !this.props.pc.boxes)
return null;
return <div>
<h2>{pok... | () {
const boxNum = this.props.boxNumber;
const boxName = this.props.boxName;
const boxContents = this.props.boxContents;
return <PokeBox title={`${boxNum ? `#${boxNum}: ` : ""}${boxName} (${boxContents.length})`}
className="pokemon-hud pc-box">
... | render | identifier_name |
pc-display.tsx | /// <reference path="current-party.tsx" />
namespace TPP.Display.Elements.RunStatus {
export class PC extends React.Component<{ pc: TPP.Tv.CombinedPCData }, {}> {
render() {
if (!this.props.pc || !this.props.pc.boxes)
return null;
return <div>
<h2>{pok... | }
}
} | </ul>
</PokeBox>; | random_line_split |
artelim.js | /**
* Created by FredAdmin on 11/16/13.
*/
var buildPhotoGrid = function() {
var html = '';
html += '<ul class="grid">';
for (var i = 0; i < artwork.artwork.length; i++) |
html += '</ul>';
return html;
};
var buildArtEliminator = function() {
var html = '' +
'<body>' +
'<div class="artElimContainer">' +
'<h1>Art Eliminator</h1>' +
'<p>Click on the artwork that you like the least and it ' +
'will be eliminated. When only your favor... | {
var piece = artwork.artwork[i];
html += '<li class="photo"><img src="img/art/' + piece.thumbnail + '"' +
' alt="' + piece.title + ' ' +
'" data-artist="' + piece.artist +
'"/></li>';
} | conditional_block |
artelim.js | /**
* Created by FredAdmin on 11/16/13.
*/
var buildPhotoGrid = function() {
var html = '';
html += '<ul class="grid">';
for (var i = 0; i < artwork.artwork.length; i++) {
var piece = artwork.artwork[i];
html += '<li class="photo"><img src="img/art/' + piece.thumbnail + '"' +
' alt="' + piece.... | "filename": "Lorenzo_Garcia_01.jpg",
"thumbnail": "Lorenzo_Garcia_01_tn.jpg",
"title": "Sink Hole"
},
{
"artist": "Lorenzo Garcia",
"filename": "Lorenzo_Garcia_03.jpg",
"thumbnail": "Lorenzo_Garcia_03_tn.jpg",
"title": "Ambition"
}
]
}; | },
{
"artist": "Lorenzo Garcia", | random_line_split |
lib.rs | raw_status: raw_status,
body: body,
}
}
}
#[derive(Clone, Deserialize, Serialize)]
pub struct CustomResponseMediator {
pub response_chan: IpcSender<Option<CustomResponse>>,
pub load_url: ServoUrl,
}
/// [Policies](https://w3c.github.io/webappsec-referrer-policy/#referrer-po... |
impl CustomResponse {
pub fn new(headers: Headers, raw_status: RawStatus, body: Vec<u8>) -> CustomResponse {
CustomResponse {
headers: headers, | random_line_split | |
lib.rs | .glob.uno/?c=mozilla%23servo&s=16+May+2016&e=16+May+2016#c430412
// See also: https://github.com/servo/servo/blob/735480/components/script/script_thread.rs#L313
#[derive(Clone, Serialize, Deserialize)]
pub struct ResourceThreads {
core_thread: CoreResourceThread,
storage_thread: IpcSender<StorageThreadMsg>,
}
... | trim_http_whitespace | identifier_name | |
maximum_element.py |
class ArrayStack:
def __init__(self):
self._data = []
self.max = 0
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def get_max(self):
return self.max
def push(self, e):
self._data.append(e)
if self.max < e:
self.max = e
def pop(self):
if self.i... | oprval = input().rstrip().split()
opr = int(oprval[0])
if opr == 1:
val = int(oprval[1])
stack.push(val)
elif opr ==2:
stack.pop()
elif opr == 3:
print(stack.get_max()) | conditional_block | |
maximum_element.py |
class ArrayStack:
def __init__(self):
self._data = []
self.max = 0
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def get_max(self):
return self.max
def push(self, e):
self._data.append(e)
if self.max < e:
self.max = e
def pop(self):
if self.i... | (self):
self.max = 0
for elem in self._data:
if self.max < elem:
self.max = elem
def print_stack(self):
print(self._data)
if __name__ == "__main__":
"""
stack = ArrayStack()
stack.push(10)
stack.push(20)
stack.pop()
stack.print_stack()
stack.push(92)
stack.push(1)
stack.print_stack()
print(... | _cal_max | identifier_name |
maximum_element.py | class ArrayStack:
def __init__(self):
self._data = []
self.max = 0
def __len__(self):
return len(self._data) |
def get_max(self):
return self.max
def push(self, e):
self._data.append(e)
if self.max < e:
self.max = e
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
else:
delelem = self._data[-1]
del(self._data[-1])
if self.is_empty():
self.max = 0
elif self.max == delelem:
... |
def is_empty(self):
return len(self._data) == 0 | random_line_split |
maximum_element.py |
class ArrayStack:
def __init__(self):
self._data = []
self.max = 0
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def get_max(self):
return self.max
def push(self, e):
self._data.append(e)
if self.max < e:
self.max = e
def pop(self):
if self.i... |
def print_stack(self):
print(self._data)
if __name__ == "__main__":
"""
stack = ArrayStack()
stack.push(10)
stack.push(20)
stack.pop()
stack.print_stack()
stack.push(92)
stack.push(1)
stack.print_stack()
print(stack.get_max())
"""
n = int(input())
stack = ArrayStack()
for i in range(n):
oprv... | self.max = 0
for elem in self._data:
if self.max < elem:
self.max = elem | identifier_body |
AskSpRiderWebPart.ts | import {
BaseClientSideWebPart,
IPropertyPaneSettings,
IWebPartContext,
PropertyPaneTextField
} from '@microsoft/sp-client-preview';
import styles from './AskSpRider.module.scss';
import * as strings from 'askSpRiderStrings';
import { IAskSpRiderWebPartProps } from './IAskSpRiderWebPartProps';
export default ... |
protected get propertyPaneSettings(): IPropertyPaneSettings {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
... | {
this.domElement.innerHTML = `
<div class="${styles.askSpRider}">
<div class="${styles.container}">
<iframe src="https://webchat.botframework.com/embed/${this.properties.botname}?s=${this.properties.secretkey}" width="100%" height="400px"></iframe>
</div>
</div>`;
} | identifier_body |
AskSpRiderWebPart.ts | import {
BaseClientSideWebPart,
IPropertyPaneSettings,
IWebPartContext,
PropertyPaneTextField
} from '@microsoft/sp-client-preview';
import styles from './AskSpRider.module.scss';
import * as strings from 'askSpRiderStrings';
import { IAskSpRiderWebPartProps } from './IAskSpRiderWebPartProps';
export default ... | protected get propertyPaneSettings(): IPropertyPaneSettings {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
... | random_line_split | |
AskSpRiderWebPart.ts | import {
BaseClientSideWebPart,
IPropertyPaneSettings,
IWebPartContext,
PropertyPaneTextField
} from '@microsoft/sp-client-preview';
import styles from './AskSpRider.module.scss';
import * as strings from 'askSpRiderStrings';
import { IAskSpRiderWebPartProps } from './IAskSpRiderWebPartProps';
export default ... | (context: IWebPartContext) {
super(context);
}
public render(): void {
this.domElement.innerHTML = `
<div class="${styles.askSpRider}">
<div class="${styles.container}">
<iframe src="https://webchat.botframework.com/embed/${this.properties.botname}?s=${this.properties.secretkey}" wi... | constructor | identifier_name |
binrec.js | dojo.provide("dojox.lang.functional.binrec");
dojo.require("dojox.lang.functional.lambda");
dojo.require("dojox.lang.functional.util");
// This module provides recursion combinators:
// - a binary recursion combinator.
// Acknoledgements:
// - recursion combinators are inspired by Manfred von Thun's article
// "Rec... | a = df.lambda(after);
as = "_a.call(this, _z.r, _r, _z.a)";
dict2["_a=_t.a"] = 1;
}
var locals1 = df.keys(dict1), locals2 = df.keys(dict2),
f = new Function([], "var _x=arguments,_y,_z,_r".concat( // Function
locals1.length ? "," + locals1.join(",") : "",
locals2.length ? ",_t=_x.callee," + loca... | }
if(typeof after == "string"){
as = inline(after, _z_r_r_z_a, add2dict);
}else{ | random_line_split |
binrec.js | dojo.provide("dojox.lang.functional.binrec");
dojo.require("dojox.lang.functional.lambda");
dojo.require("dojox.lang.functional.util");
// This module provides recursion combinators:
// - a binary recursion combinator.
// Acknoledgements:
// - recursion combinators are inspired by Manfred von Thun's article
// "Rec... |
var locals1 = df.keys(dict1), locals2 = df.keys(dict2),
f = new Function([], "var _x=arguments,_y,_z,_r".concat( // Function
locals1.length ? "," + locals1.join(",") : "",
locals2.length ? ",_t=_x.callee," + locals2.join(",") : "",
t ? (locals2.length ? ",_t=_t.t" : "_t=_x.callee.t") : "",
";while... | {
a = df.lambda(after);
as = "_a.call(this, _z.r, _r, _z.a)";
dict2["_a=_t.a"] = 1;
} | conditional_block |
day.py | # -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module... | if kwargs.get('instance'):
kwargs['initial']['start_datetime'] = kwargs['instance'].start
kwargs['initial']['stop_datetime'] = kwargs['instance'].stop
return kwargs
def init_fields(self, *args, **kwargs):
self.fields['start_datetime'] = forms.SplitDateTi... | # clone with SplitDateTimeField via initial datas | random_line_split |
day.py | # -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module... |
# Init some special fields
kwargs = self.init_fields(*args, **kwargs)
def clean(self):
cleaned_data = super(DayBaseFormMixin, self).clean()
content = cleaned_data.get("content")
vacation = cleaned_data.get("vacation")
# Content text is only required when... | """
DayEntry form
"""
def __init__(self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('nex... | identifier_body |
day.py | # -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module... |
else:
return content
def clean_start_datetime(self):
start = self.cleaned_data['start_datetime']
# Day entry can't start before the targeted day date
if start and start.date() < self.daydate:
raise forms.ValidationError(_("You can't start a day before it... | return validation_helper(self, content) | conditional_block |
day.py | # -*- coding: utf-8 -*-
"""
Forms for day forms
"""
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from arrow import Arrow
from datebook.models import DayEntry
from datebook.forms import CrispyFormMixin
from datebook.utils.imports import safe_import_module... | (self, datebook, day, *args, **kwargs):
self.datebook = datebook
self.daydate = datebook.period.replace(day=day)
# Args to give to the form layout method
self.crispy_form_helper_kwargs.update({
'next_day': kwargs.pop('next_day', None),
'day_to_model_url':... | __init__ | identifier_name |
discourse_location.js | /**
@module Discourse
*/
var get = Ember.get, set = Ember.set;
var popstateFired = false;
var supportsHistoryState = window.history && 'state' in window.history;
// Thanks: https://gist.github.com/kares/956897
var re = /([^&=]+)=?([^&]*)/g;
var decode = function(str) {
return decodeURIComponent(str.replace(/\+/g,... |
}
return params;
};
/**
`Ember.DiscourseLocation` implements the location API using the browser's
`history.pushState` API.
@class DiscourseLocation
@namespace Discourse
@extends Ember.Object
*/
Ember.DiscourseLocation = Ember.Object.extend({
init: function() {
set(this, 'location', get(this... | {
var k = decode(e[1]);
var v = decode(e[2]);
if (params[k] !== undefined) {
if (!$.isArray(params[k])) {
params[k] = [params[k]];
}
params[k].push(v);
} else {
params[k] = v;
... | conditional_block |
discourse_location.js | /**
@module Discourse
*/
var get = Ember.get, set = Ember.set;
var popstateFired = false;
var supportsHistoryState = window.history && 'state' in window.history;
// Thanks: https://gist.github.com/kares/956897
var re = /([^&=]+)=?([^&]*)/g;
var decode = function(str) {
return decodeURIComponent(str.replace(/\+/g,... | @method replaceState
@param path {String}
*/
replaceState: function(path) {
var state = { path: path };
// store state if browser doesn't support `history.state`
if (!supportsHistoryState) {
this._historyState = state;
} else {
get(this, 'history').replaceState(state, null, path);... |
Replaces the current state
| random_line_split |
2b_data_preparation_logarithm.py | import numpy as np
import pandas as pd
import scipy as sp
import pickle
from scipy import fft
from time import localtime, strftime
import matplotlib.pyplot as plt
from skimage.feature import match_template
import wave
###########################
# Folder Name Setting
###########################
folder = 'J:/DATAMININ... | Log_Segment_Row.append(np.max(result))
TRAIN_LOG_SPEC_FEATURES.append(Log_Segment_Row)
TRAIN_LOG_SPEC_FEATURES = np.array(TRAIN_LOG_SPEC_FEATURES)
# SAVE THE LOG-FEATURES for the TRAINING SET
output = open(dp_folder + 'TRAIN_LOG_SPEC_FEATURES_freq5.pkl', 'wb')
pickle.dump(TRA... | else:
y_max_5 = 199
spectrogram_part = mypic_rev_log_gauss[y_min_5:y_max_5+1,:]
result = match_template(spectrogram_part, segment) | random_line_split |
2b_data_preparation_logarithm.py |
import numpy as np
import pandas as pd
import scipy as sp
import pickle
from scipy import fft
from time import localtime, strftime
import matplotlib.pyplot as plt
from skimage.feature import match_template
import wave
###########################
# Folder Name Setting
###########################
folder = 'J:/DATAMIN... |
###############################
## Create the Spectrograms
## Train + Test
###############################
print strftime("%a, %d %b %Y %H:%M:%S +0000", localtime())
for file_idx in range(len(label)):
test_flag = label.irow(file_idx)['fold']
fname = label.irow(file_idx)['filename']
species_on_pic =... | s = wave.open(filename,'r')
strsig = s.readframes(s.getnframes())
y = np.fromstring(strsig, np.short)
s.close()
return y | identifier_body |
2b_data_preparation_logarithm.py |
import numpy as np
import pandas as pd
import scipy as sp
import pickle
from scipy import fft
from time import localtime, strftime
import matplotlib.pyplot as plt
from skimage.feature import match_template
import wave
###########################
# Folder Name Setting
###########################
folder = 'J:/DATAMIN... | (filename):
s = wave.open(filename,'r')
strsig = s.readframes(s.getnframes())
y = np.fromstring(strsig, np.short)
s.close()
return y
###############################
## Create the Spectrograms
## Train + Test
###############################
print strftime("%a, %d %b %Y %H:%M:%S +0000", localtime(... | wav_to_floats | identifier_name |
2b_data_preparation_logarithm.py |
import numpy as np
import pandas as pd
import scipy as sp
import pickle
from scipy import fft
from time import localtime, strftime
import matplotlib.pyplot as plt
from skimage.feature import match_template
import wave
###########################
# Folder Name Setting
###########################
folder = 'J:/DATAMIN... |
label = pd.DataFrame(label)
label['rec_id'] = cv.rec_id
label['fold'] = cv.fold
label['filename'] = rec2f.filename
# Imbalanced training set
# training species 1%--5%--20%
spec_avg = label[label.fold ==0][range(num_species)].mean()
spec_avg.sort()
plt.plot(spec_avg,'go')
# Read the audio files
# /src_wavs
# This... | label[i,c] = 1 | conditional_block |
GameRoutes.ts |
import * as express from "express";
import { GameDashboardController } from "../controllers/GameDashboardController";
import { GameLobbyController } from "../controllers/GameLobbyController";
var router = express.Router();
export class GameRoutes {
private gameDashboardController: GameDashboardController;
pri... | () {
router.get("/games", this.gameDashboardController.retrieve);
router.post("/games", this.gameDashboardController.create);
router.get("/games/:id", this.gameDashboardController.findById);
router.put("/games/:id/join", this.gameLobbyController.joinGameLobby);
router.put("/game... | routes | identifier_name |
GameRoutes.ts | import * as express from "express";
import { GameDashboardController } from "../controllers/GameDashboardController";
import { GameLobbyController } from "../controllers/GameLobbyController";
var router = express.Router();
export class GameRoutes {
private gameDashboardController: GameDashboardController;
priv... |
get routes() {
router.get("/games", this.gameDashboardController.retrieve);
router.post("/games", this.gameDashboardController.create);
router.get("/games/:id", this.gameDashboardController.findById);
router.put("/games/:id/join", this.gameLobbyController.joinGameLobby);
ro... | this.gameLobbyController = new GameLobbyController();
} | random_line_split |
GameRoutes.ts |
import * as express from "express";
import { GameDashboardController } from "../controllers/GameDashboardController";
import { GameLobbyController } from "../controllers/GameLobbyController";
var router = express.Router();
export class GameRoutes {
private gameDashboardController: GameDashboardController;
pri... |
get routes() {
router.get("/games", this.gameDashboardController.retrieve);
router.post("/games", this.gameDashboardController.create);
router.get("/games/:id", this.gameDashboardController.findById);
router.put("/games/:id/join", this.gameLobbyController.joinGameLobby);
r... | {
this.gameDashboardController = new GameDashboardController();
this.gameLobbyController = new GameLobbyController();
} | identifier_body |
dqn13.py | %matplotlib inline
import torch
import torch.nn as nn
import gym
import random
import numpy as np
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torch.autograd import Variable
from collections import deque, namedtuple
env = gym.envs.make("CartPole-v0")
class Net(nn.Module):
def ... | (self, batch_size):
return random.sample(self.memory, batch_size)
def __len__(self):
return len(self.memory)
def to_tensor(ndarray, volatile=False):
return Variable(torch.from_numpy(ndarray), volatile=volatile).float()
def deep_q_learning(num_episodes=10, batch_size=100,
... | sample | identifier_name |
dqn13.py | %matplotlib inline
import torch
import torch.nn as nn
import gym
import random
import numpy as np
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torch.autograd import Variable
from collections import deque, namedtuple
env = gym.envs.make("CartPole-v0")
class Net(nn.Module):
def ... |
def make_epsilon_greedy_policy(network, epsilon, nA):
def policy(state):
sample = random.random()
if sample < (1-epsilon) + (epsilon/nA):
q_values = network(state.view(1, -1))
action = q_values.data.max(1)[1][0, 0]
else:
action = random.randrange... | out = self.fc1(x)
out = self.tanh(out)
out = self.fc2(out)
return out | identifier_body |
dqn13.py | %matplotlib inline
import torch
import torch.nn as nn
import gym
import random
import numpy as np
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torch.autograd import Variable
from collections import deque, namedtuple
env = gym.envs.make("CartPole-v0")
class Net(nn.Module):
def ... | return Variable(torch.from_numpy(ndarray), volatile=volatile).float()
def deep_q_learning(num_episodes=10, batch_size=100,
discount_factor=0.95, epsilon=0.1, epsilon_decay=0.95):
# Q-Network and memory
net = Net()
memory = ReplayMemory(10000)
# Loss and Optimizer
... |
def to_tensor(ndarray, volatile=False): | random_line_split |
dqn13.py | %matplotlib inline
import torch
import torch.nn as nn
import gym
import random
import numpy as np
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torch.autograd import Variable
from collections import deque, namedtuple
env = gym.envs.make("CartPole-v0")
class Net(nn.Module):
def ... | print ('episode: %d, time: %d, loss: %.4f' %(i_episode, t, loss.data[0])) | conditional_block | |
car-detail.component.ts | /**
* Created by admin on 2017/3/8.
*/
import {Component,OnInit} from '@angular/core';
import {ActivatedRoute,Params} from '@angular/router'
import {Location} from '@angular/common'
import {Car} from './Car';
import {CarService} from './car-service'
import 'rxjs/add/operator/switchMap'
@Component({
moduleId:modul... | goBack():void{
this.location.back();
}
save():void{
this.carService.update(this.car)
}
} | ngOnInit():void{
//id是数字,而路由参数的值总是字符串。 所以我们需要通过 JavaScript 的 (+) 操作符把路由参数的值转成数字。
this.route.params.switchMap((params:Params)=>this.carService.getCar(+params['id']))
.subscribe(car=>this.car=car);
} | random_line_split |
car-detail.component.ts | /**
* Created by admin on 2017/3/8.
*/
import {Component,OnInit} from '@angular/core';
import {ActivatedRoute,Params} from '@angular/router'
import {Location} from '@angular/common'
import {Car} from './Car';
import {CarService} from './car-service'
import 'rxjs/add/operator/switchMap'
@Component({
moduleId:modul... | ():void{
//id是数字,而路由参数的值总是字符串。 所以我们需要通过 JavaScript 的 (+) 操作符把路由参数的值转成数字。
this.route.params.switchMap((params:Params)=>this.carService.getCar(+params['id']))
.subscribe(car=>this.car=car);
}
goBack():void{
this.location.back();
}
save():void{
this.carService.update(this.car)
}
}
| ngOnInit | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.