file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
generator.py | # Copyright 2012 SINA Corporation
# Copyright 2014 Cisco Systems, Inc.
# All Rights Reserved.
#
# 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/licens... | ():
try:
csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
csock.connect(('8.8.8.8', 80))
(addr, port) = csock.getsockname()
csock.close()
return addr
except socket.error:
return None
def _sanitize_default(name, value):
"""Set up a reasonably sensible... | _get_my_ip | identifier_name |
generator.py | # Copyright 2012 SINA Corporation
# Copyright 2014 Cisco Systems, Inc.
# All Rights Reserved.
#
# 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/licens... |
elif opt_type == FLOATOPT:
assert(isinstance(opt_default, float))
print('#%s=%s' % (opt_name, opt_default))
elif opt_type == LISTOPT:
assert(isinstance(opt_default, list))
print('#%s=%s' % (opt_name, ','.join(opt_default)))
elif opt_type == DICTOP... | assert(isinstance(opt_default, int) and
not isinstance(opt_default, bool))
print('#%s=%s' % (opt_name, opt_default)) | conditional_block |
common.py | team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Es... |
def get_match_urls(response):
for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract():
yield response.urljoin(match) | match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0]
match_details = match_container.xpath(".//text()").extract()
return {
"round": match_details[1],
"venue": match_details[3],
"date": match_details[6],
"attendance": match_details[8],
"homeTea... | identifier_body |
common.py | team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Es... | (response):
match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0]
match_details = match_container.xpath(".//text()").extract()
return {
"round": match_details[1],
"venue": match_details[3],
"date": match_details[6],
"attendance": match_details[8],
... | get_match_description | identifier_name |
common.py | team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Es... | "homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()),
"awayScore": int(response.xpath("//table[1]/tr[3]/td[5]/b/text()").extract_first())
}
def get_match_urls(response):
for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract():
... | "venue": match_details[3],
"date": match_details[6],
"attendance": match_details[8],
"homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(),
"awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(), | random_line_split |
common.py | team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Es... | yield response.urljoin(match) | conditional_block | |
main.rs | extern crate event_handler;
extern crate client;
use std::net::TcpListener;
use std::thread;
use client::*;
use event_handler::*;
fn main() {
// 클라이언트의 접속을 처리할 listen port 생성
let listener = TcpListener::bind("127.0.0.1:9000").unwrap();
println!("Start to listen, ready to accept");
// 각종 이벤트를 처리... | = Client::new(new_stream, Some(_tx.clone()));
_tx.send(Signal::NewClient(new_client));
}
Err(_) => { println!("connection failed"); }
}
}
drop(listener);
} | conditional_block | |
main.rs | extern crate event_handler;
extern crate client;
use std::net::TcpListener;
use std::thread;
use client::*;
use event_handler::*;
fn main() {
// 클라이언트의 접속을 처리할 listen port 생성
let listener = TcpListener::bind("127.0.0.1:9000").unwrap();
println!("Start to listen, ready to accept");
// 각종 이벤트를 처리... | _tx.send(Signal::NewClient(new_client));
}
Err(_) => { println!("connection failed"); }
}
}
drop(listener);
} | match stream {
Ok(new_stream) => {
// 새로운 클라이언트의 연결이 생기면 이벤트 처리 스레드로 이벤트 생성, 전달
let new_client = Client::new(new_stream, Some(_tx.clone())); | random_line_split |
main.rs | extern crate event_handler;
extern crate client;
use std::net::TcpListener;
use std::thread;
use client::*;
use event_handler::*;
fn main() | {
// 클라이언트의 접속을 처리할 listen port 생성
let listener = TcpListener::bind("127.0.0.1:9000").unwrap();
println!("Start to listen, ready to accept");
// 각종 이벤트를 처리할 로직 생성
let sample_event_handler = EventHandler::new();
// 클라이언트의 접속 이벤트를 전송하기 위한 channel(Send) 할당
let _tx = sample_event_handl... | identifier_body | |
main.rs | extern crate event_handler;
extern crate client;
use std::net::TcpListener;
use std::thread;
use client::*;
use event_handler::*;
fn | () {
// 클라이언트의 접속을 처리할 listen port 생성
let listener = TcpListener::bind("127.0.0.1:9000").unwrap();
println!("Start to listen, ready to accept");
// 각종 이벤트를 처리할 로직 생성
let sample_event_handler = EventHandler::new();
// 클라이언트의 접속 이벤트를 전송하기 위한 channel(Send) 할당
let _tx = sample_event_ha... | main | identifier_name |
gsinfo.py | import discord
from discord.ext import commands
from .utils import checks
from __main__ import send_cmd_help
try:
import valve.source.a2s
import valve.source.messages
sourcequery_isinstalled = True
except:
sourcequery_isinstalled = False
import socket
import json
try:
from bs4 import BeautifulSoup
... | else:
try:
valid_ip = validate_ip(ip)
except IndexError:
valid_ip = False
if valid_ip:
msg = await self._query_server(ip,port,msgtoedit)
else:
try:
ip = socket.gethostbyname(ip)
... | random_line_split | |
gsinfo.py | import discord
from discord.ext import commands
from .utils import checks
from __main__ import send_cmd_help
try:
import valve.source.a2s
import valve.source.messages
sourcequery_isinstalled = True
except:
sourcequery_isinstalled = False
import socket
import json
try:
from bs4 import BeautifulSoup
... |
elif info["player_count"] == 0:
await self.bot.say(":no_entry: **Error!** Playercount is 0, there is nothing for me to list.")
await self.bot.delete_message(msgtoedit)
msg_return = "Join this server by clicking here --> steam://connect/"+ip+":"+str(port)
... | await self.bot.say(":warning: **Warning!** `This gameserver is not reporting it's playerlist.`\nThis is a feature in CS:GO and some other games. We cannot display the playerlist for this server.") | conditional_block |
gsinfo.py | import discord
from discord.ext import commands
from .utils import checks
from __main__ import send_cmd_help
try:
import valve.source.a2s
import valve.source.messages
sourcequery_isinstalled = True
except:
sourcequery_isinstalled = False
import socket
import json
try:
from bs4 import BeautifulSoup
... |
async def _query_server(self,ip,port,msgtoedit):
"""Internal function for querying servers, keeps it from being piled into one function."""
try:
server = valve.source.a2s.ServerQuerier([ip,port])
info = server.info()
do_players = True
try:
... | """Internal function for querying playerlists, keeps it from being piled into one function."""
try:
server = valve.source.a2s.ServerQuerier([ip,port])
info = server.info()
do_players = True
try:
players = server.players()
except valve.s... | identifier_body |
gsinfo.py | import discord
from discord.ext import commands
from .utils import checks
from __main__ import send_cmd_help
try:
import valve.source.a2s
import valve.source.messages
sourcequery_isinstalled = True
except:
sourcequery_isinstalled = False
import socket
import json
try:
from bs4 import BeautifulSoup
... | (bot):
if sourcequery_isinstalled and soupAvailable:
bot.add_cog(GSInfo(bot))
else:
if soupAvailable and not sourcequery_isinstalled:
raise RuntimeError("There's a dependancy missing, please install python-valve. Do this by running `pip3 install -U https://github.com/Holiverh/python-val... | setup | identifier_name |
GitIgnore.ts | import {TemplateInterface} from './../../TemplateInterface';
const html = require('common-tags').html;
/**
* create the RelutionHjson file for the Project
* @link [template](https://github.com/github/gitignore/blob/master/Node.gitignore)
*/
export class | implements TemplateInterface {
public publishName: string = '.gitignore';
public name: string = 'gitignore';
get template() {
return (html`
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated b... | GitIgnore | identifier_name |
GitIgnore.ts | import {TemplateInterface} from './../../TemplateInterface';
const html = require('common-tags').html;
/**
* create the RelutionHjson file for the Project
* @link [template](https://github.com/github/gitignore/blob/master/Node.gitignore)
*/
export class GitIgnore implements TemplateInterface {
public publishName... | logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt ... | # Logs | random_line_split |
trainer.py | # Copyright 2021 DeepMind Technologies Limited
#
# 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 agree... | (rng: chex.PRNGKey, minibatch: datasets.MiniBatch,
params: hk.Params, state: hk.State,
opt_state: optax.OptState) -> ModelUpdates:
grad_fn = jax.grad(loss_fn, has_aux=True)
grad, (state, scalars) = grad_fn(params, state, rng, minibatch)
grad = jax.lax.pmean(grad, axis_name=... | update_fn | identifier_name |
trainer.py | # Copyright 2021 DeepMind Technologies Limited
#
# 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 agree... |
return update_fn
def get_batch_dims(global_batch_size: int, device_count: int,
local_device_count: int) -> Sequence[int]:
"""Compute the batch dims for this host.
The global_batch_size is the number of data samples that are optimized over
in one step of the optimization. This value must b... | random_line_split | |
trainer.py | # Copyright 2021 DeepMind Technologies Limited
#
# 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 agree... |
host_batch_dims = (local_device_count, per_device_batch_size)
return host_batch_dims
| raise ValueError(
f'Cannot split batch of {global_batch_size} evenly across {local_device_count} devices.'
) | conditional_block |
trainer.py | # Copyright 2021 DeepMind Technologies Limited
#
# 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 agree... |
return update_fn
def get_batch_dims(global_batch_size: int, device_count: int,
local_device_count: int) -> Sequence[int]:
"""Compute the batch dims for this host.
The global_batch_size is the number of data samples that are optimized over
in one step of the optimization. This value must ... | grad_fn = jax.grad(loss_fn, has_aux=True)
grad, (state, scalars) = grad_fn(params, state, rng, minibatch)
grad = jax.lax.pmean(grad, axis_name='i')
scalars = jax.lax.pmean(scalars, axis_name='i')
updates, opt_state = optimizer.update(grad, opt_state, params)
params = optax.apply_updates(params, up... | identifier_body |
core.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // except according to those terms.
use rustc;
use rustc::{driver, middle};
use syntax::ast;
use syntax::diagnostic;
use syntax::parse;
use syntax;
use std::os;
use std::local_data;
use visit_ast::RustdocVisitor;
use clean;
use clean::Clean;
pub struct DocContext {
crate: @ast::Crate,
tycx: middle::ty::ctx... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
core.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
let ctxt = @get_ast_and_resolve(path, libs);
debug!("defmap:");
for (k, v) in ctxt.tycx.def_map.iter() {
debug!("%?: %?", k, v);
}
local_data::set(super::ctxtkey, ctxt);
let v = @mut RustdocVisitor::new();
v.visit(ctxt.crate);
v.clean()
} | identifier_body | |
core.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
crate: @ast::Crate,
tycx: middle::ty::ctxt,
sess: driver::session::Session
}
/// Parses, resolves, and typechecks the given crate
fn get_ast_and_resolve(cpath: &Path, libs: ~[Path]) -> DocContext {
use syntax::codemap::dummy_spanned;
use rustc::driver::driver::*;
let parsesess = parse::new_... | DocContext | identifier_name |
dataload.py | #*******************************************************************************
# Copyright (c) 2015 IBM Corp.
#
# 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/li... | import json
from helpers.dbutils import CloudantDbUtils
from helpers.acmeair_utils import AcmeAirUtils
import conftest
# get the cloudant credentials from pytest config file
test_properties = conftest.test_properties()
class DataLoader:
"""
Test data loader related functions
"""
def load_AcmeData(self, num_of... | import requests
import sys
import os | random_line_split |
dataload.py | #*******************************************************************************
# Copyright (c) 2015 IBM Corp.
#
# 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/li... | (self):
"""
Create booking data needed to test SpecCharValuePredicate
"""
try:
acmeair = AcmeAirUtils()
acmeair.start_acmeair()
# book flights AA93 and AA330
flight1 = "AA93"
flight2 = "AA330"
# Step#1 - need to find the flights generated _id required for booking
flight1_id = acmeai... | load_SpecCharValuePredicateData | identifier_name |
dataload.py | #*******************************************************************************
# Copyright (c) 2015 IBM Corp.
#
# 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/li... | """
Utility to create test databases and load data
"""
import argparse
parser = argparse.ArgumentParser(description="Utility to load AcmeAir data required for python spark-cloudant tests")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-cleanup', action='store_true', help='Drop all... | conditional_block | |
dataload.py | #*******************************************************************************
# Copyright (c) 2015 IBM Corp.
#
# 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/li... |
if __name__ =='__main__':
"""
Utility to create test databases and load data
"""
import argparse
parser = argparse.ArgumentParser(description="Utility to load AcmeAir data required for python spark-cloudant tests")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-cleanup', ac... | """
Create booking data needed to test SpecCharValuePredicate
"""
try:
acmeair = AcmeAirUtils()
acmeair.start_acmeair()
# book flights AA93 and AA330
flight1 = "AA93"
flight2 = "AA330"
# Step#1 - need to find the flights generated _id required for booking
flight1_id = acmeair.get_flig... | identifier_body |
main.controller.ts | import * as _ from 'lodash';
import { IAppService } from '../app.service';
export class ma |
title: string;
static $inject = ['$scope', '$state', 'appService', '$mdDialog'];
constructor(private $scope, private $state: ng.ui.IStateService, private appService: IAppService, private $mdDialog: ng.material.IDialogService) {
this.title = 'MAIN';
var clearEvt1 = appService.events.filter... | inCtrl { | identifier_name |
main.controller.ts | import * as _ from 'lodash';
import { IAppService } from '../app.service';
export class mainCtrl {
title: string;
static $inject = ['$scope', '$state', 'appService', '$mdDialog'];
constructor(private $scope, private $state: ng.ui.IStateService, private appService: IAppService, private $mdDialog: ng.mater... | .ok('Yes')
.textContent('The server connection is closed. Do you want to open it back?')
.clickOutsideToClose(true)
.escapeToClose(true)
//.focusOnOpen(false)
//.onComplete(() => {
// this.appService.connect();
)
... |
if (data.code === 3001) return;
this.$mdDialog.show(this.$mdDialog.confirm()
.cancel('No') | random_line_split |
main.controller.ts | import * as _ from 'lodash';
import { IAppService } from '../app.service';
export class mainCtrl {
title: string;
static $inject = ['$scope', '$state', 'appService', '$mdDialog'];
constructor(private $scope, private $state: ng.ui.IStateService, private appService: IAppService, private $mdDialog: ng.mater... | OnWSError(data) {
console.error('error: ', data);
}
OnWSClose(data) {
this.appService.permissions = '';
this.appService.username = '';
if (data.code === 3001) return;
this.$mdDialog.show(this.$mdDialog.confirm()
.cancel('No')
.ok('Yes')
... | this.title = 'MAIN';
var clearEvt1 = appService.events.filter(x => x.target === 'websocket@open').subscribe(data => this.appService.send('login', {}));
var clearEvt2 = appService.events.filter(x => x.target === 'websocket@close').subscribe(data => this.OnWSClose(data));
var clearEvt3 = ... | identifier_body |
getInspirationalQuoteOfDay.js | //
// getInspirationalQuoteOfDay.js | //
// created by Liv Erickson on 12/04/18
// Copyright 2018 High Fidelity, Inc.
// Quotes provided by 'They Said So' - https://theysaidso.com/api
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function(){
var... | random_line_split | |
getInspirationalQuoteOfDay.js | //
// getInspirationalQuoteOfDay.js
//
// created by Liv Erickson on 12/04/18
// Copyright 2018 High Fidelity, Inc.
// Quotes provided by 'They Said So' - https://theysaidso.com/api
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICE... | () {
req.request(API_URL, function(error, data) {
try {
var quote = data.contents.quotes[0].quote;
var author = data.contents.quotes[0].author;
var string = quote + " - " + author;
Entities.editEntity(myEntityID, {'text' : string});
... | getInspirationOfTheDay | identifier_name |
getInspirationalQuoteOfDay.js | //
// getInspirationalQuoteOfDay.js
//
// created by Liv Erickson on 12/04/18
// Copyright 2018 High Fidelity, Inc.
// Quotes provided by 'They Said So' - https://theysaidso.com/api
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICE... |
return new InspirationalSign();
});
| {
req.request(API_URL, function(error, data) {
try {
var quote = data.contents.quotes[0].quote;
var author = data.contents.quotes[0].author;
var string = quote + " - " + author;
Entities.editEntity(myEntityID, {'text' : string});
... | identifier_body |
getInspirationalQuoteOfDay.js | //
// getInspirationalQuoteOfDay.js
//
// created by Liv Erickson on 12/04/18
// Copyright 2018 High Fidelity, Inc.
// Quotes provided by 'They Said So' - https://theysaidso.com/api
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICE... |
}
};
function getInspirationOfTheDay() {
req.request(API_URL, function(error, data) {
try {
var quote = data.contents.quotes[0].quote;
var author = data.contents.quotes[0].author;
var string = quote + " - " + author;
... | {
Script.clearInterval(interval);
} | conditional_block |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | let &TokenString(ref s) = self;
(cx as &ExtParseUtils).parse_tts(s.clone())
}
}
pub fn add_node_dependency(node: &Rc<node::Node>, dep: &Rc<node::Node>) {
let mut depends_on = node.depends_on.borrow_mut();
depends_on.deref_mut().push(dep.downgrade());
let mut rev_depends_on = dep.rev_depends_on.borrow_... | fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> { | random_line_split |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
pub fn add_type_item(&mut self, item: P<ast::Item>) {
self.type_items.push(item);
}
fn emit_main(&self, cx: &ExtCtxt) -> P<ast::Item> {
// init stack
let init_stack_stmt = cx.stmt_expr(quote_expr!(&*cx,
zinc::hal::mem_init::init_stack();
));
// init data
let init_data_stmt = cx... | {
self.main_stmts.push(stmt);
} | identifier_body |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
}
Some(builder)
}
fn walk_mutate(builder: &mut Builder, cx: &mut ExtCtxt, node: &Rc<node::Node>) {
let maybe_mut = node.mutator.get();
if maybe_mut.is_some() {
maybe_mut.unwrap()(builder, cx, node.clone());
}
for sub in node.subnodes().iter() {
Builder::walk_mutate(builder, cx... | {
cx.parse_sess().span_diagnostic.span_err(DUMMY_SP,
"root node `mcu::clock` must be present");
} | conditional_block |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | (&self, cx: &ExtCtxt) -> P<ast::Item> {
let stmt = cx.stmt_expr(quote_expr!(&*cx,
core::intrinsics::abort()
// or
// zinc::os::task::morestack();
));
let empty_span = DUMMY_SP;
let body = cx.block(empty_span, vec!(stmt), None);
self.item_fn(cx, empty_span, "__morestack", &[],... | emit_morestack | identifier_name |
font.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/. */
use app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use platform::f... | options.flags.contains(IS_WHITESPACE_SHAPING_FLAG),
options.flags.contains(RTL_FLAG));
if self.can_do_fast_shaping(text, options) {
debug!("shape_text: Using ASCII fast path.");
self.sh... | };
let result = self.shape_cache.borrow_mut().find_or_create(lookup_key, || {
let start_time = time::precise_time_ns();
let mut glyphs = GlyphStore::new(text.len(), | random_line_split |
font.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/. */
use app_units::Au;
use euclid::{Point2D, Rect, Size2D};
use font_template::FontTemplateDescriptor;
use platform::f... | (&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
let mut prev_glyph_id = None;
for (i, byte) in text.bytes().enumerate() {
let character = byte as char;
let glyph_id = match self.glyph_index(character) {
Some(id) => id,
None... | shape_text_fast | identifier_name |
ovnclients.py | # Copyright 2018 Red Hat, Inc.
#
# 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 _restart_daemon(self):
self._stop_daemon()
return self._start_daemon()
def _create_lswitches(self, lswitch_create_args, num_switches=-1):
self.RESOURCE_NAME_FORMAT = "lswitch_XXXXXX_XXXXXX"
if (num_switches == -1):
num_switches = lswitch_create_args.get("amoun... | ovn_nbctl = self._get_ovn_controller(self.install_method)
ovn_nbctl.stop_daemon() | identifier_body |
ovnclients.py | # Copyright 2018 Red Hat, Inc.
#
# 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, ... |
ovn_nbctl.flush() # ensure all commands be run
ovn_nbctl.enable_batch_mode(False)
return lswitches
def _create_routers(self, router_create_args):
self.RESOURCE_NAME_FORMAT = "lrouter_XXXXXX_XXXXXX"
amount = router_create_args.get("amount", 1)
batch = router_create... | ovn_nbctl.flush()
flush_count = batch | conditional_block |
ovnclients.py | # Copyright 2018 Red Hat, Inc.
#
# 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, ... | flush_count = batch
lrouters = []
for i in range(amount):
name = self.generate_random_name()
lrouter = ovn_nbctl.lrouter_add(name)
lrouters.append(lrouter)
flush_count -= 1
if flush_count < 1:
ovn_nbctl.flush()
... | batch = router_create_args.get("batch", 1)
ovn_nbctl = self._get_ovn_controller(self.install_method)
ovn_nbctl.enable_batch_mode()
| random_line_split |
ovnclients.py | # Copyright 2018 Red Hat, Inc.
#
# 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):
ovn_nbctl = self._get_ovn_controller(self.install_method)
ovn_nbctl.stop_daemon()
def _restart_daemon(self):
self._stop_daemon()
return self._start_daemon()
def _create_lswitches(self, lswitch_create_args, num_switches=-1):
self.RESOURCE_NAME_FORMAT = "lswitch_X... | _stop_daemon | identifier_name |
utils.ts | import { Condition, Status, STATUS_TYPE, K8sObject } from 'kubeflow';
import { V1Container } from '@kubernetes/client-node';
import {
InferenceServiceK8s,
PredictorSpec,
PredictorExtensionSpec,
ExplainerSpec,
} from '../types/kfserving/v1beta1';
/*
* general util functions
*/
export function dictIsEmpty(obj:... | return ['Ready', 'check_circle'];
}
return [readyCondition.message, 'warning'];
}
// functions for processing the InferenceService spec
export function getPredictorType(predictor: PredictorSpec): string {
if ('tensorflow' in predictor) {
return 'Tensorflow';
}
if ('triton' in predictor) {
retur... |
if (readyCondition.status === 'True') { | random_line_split |
utils.ts | import { Condition, Status, STATUS_TYPE, K8sObject } from 'kubeflow';
import { V1Container } from '@kubernetes/client-node';
import {
InferenceServiceK8s,
PredictorSpec,
PredictorExtensionSpec,
ExplainerSpec,
} from '../types/kfserving/v1beta1';
/*
* general util functions
*/
export function dictIsEmpty(obj:... |
return [readyCondition.message, 'warning'];
}
// functions for processing the InferenceService spec
export function getPredictorType(predictor: PredictorSpec): string {
if ('tensorflow' in predictor) {
return 'Tensorflow';
}
if ('triton' in predictor) {
return 'Triton';
}
if ('sklearn' in predi... | {
return ['Ready', 'check_circle'];
} | conditional_block |
utils.ts | import { Condition, Status, STATUS_TYPE, K8sObject } from 'kubeflow';
import { V1Container } from '@kubernetes/client-node';
import {
InferenceServiceK8s,
PredictorSpec,
PredictorExtensionSpec,
ExplainerSpec,
} from '../types/kfserving/v1beta1';
/*
* general util functions
*/
export function dictIsEmpty(obj:... |
export function getPredictorExtensionSpec(
predictor: PredictorSpec,
): PredictorExtensionSpec {
if ('tensorflow' in predictor) {
return predictor.tensorflow;
}
if ('triton' in predictor) {
return predictor.triton;
}
if ('sklearn' in predictor) {
return predictor.sklearn;
}
if ('onnx' i... | {
if ('tensorflow' in predictor) {
return 'Tensorflow';
}
if ('triton' in predictor) {
return 'Triton';
}
if ('sklearn' in predictor) {
return 'SKLearn';
}
if ('onnx' in predictor) {
return 'Onnx';
}
if ('pytorch' in predictor) {
return 'PyTorch';
}
if ('xgboost' in predic... | identifier_body |
utils.ts | import { Condition, Status, STATUS_TYPE, K8sObject } from 'kubeflow';
import { V1Container } from '@kubernetes/client-node';
import {
InferenceServiceK8s,
PredictorSpec,
PredictorExtensionSpec,
ExplainerSpec,
} from '../types/kfserving/v1beta1';
/*
* general util functions
*/
export function dictIsEmpty(obj:... | (svc: InferenceServiceK8s): string[] {
const components: string[] = [];
['predictor', 'transformer', 'explainer'].forEach(c => {
if (!svcHasComponent(svc, c)) {
return;
}
components.push(c);
});
return components;
}
export function getReadyCondition(obj: K8sObject): Condition {
let cs: C... | getSvcComponents | identifier_name |
webpack.config.js | const path = require('path');
const nodeExternals = require('webpack-node-externals'); // 외부 Node.js 모듈들을 포함하지 않기 위해 로드.
const WebpackShellPlugin = require('webpack-shell-plugin');
const OutputFileName = 'aether.agent.package.js';
var serverCfg = {
context: path.resolve(__dirname, 'src'),
entry: './app.js',
target:... | };
module.exports = serverCfg; | random_line_split | |
createDrawAxes.ts | import { vec3, vec4 } from 'gl-matrix';
// tslint:disable-next-line:import-name
import REGL = require('regl');
interface Attributes {
position: vec3;
color: vec3;
}
/*
* All the information needed to be able to draw axes to the screen
*/
export interface DrawAxesProps {
positions: vec4[];
colors: ve... | (
regl: REGL.Regl
): REGL.DrawCommand<REGL.DefaultContext, DrawAxesProps> {
return regl<{}, Attributes, DrawAxesProps>({
vert: `
precision mediump float;
attribute vec4 position;
attribute vec3 color;
varying vec3 vertexColor;
void main() {
... | createDrawAxes | identifier_name |
createDrawAxes.ts | import { vec3, vec4 } from 'gl-matrix';
// tslint:disable-next-line:import-name
import REGL = require('regl');
interface Attributes {
position: vec3;
color: vec3;
}
/*
* All the information needed to be able to draw axes to the screen
*/
export interface DrawAxesProps {
positions: vec4[];
colors: ve... | {
return regl<{}, Attributes, DrawAxesProps>({
vert: `
precision mediump float;
attribute vec4 position;
attribute vec3 color;
varying vec3 vertexColor;
void main() {
gl_Position = position;
vertexColor = color;
... | identifier_body | |
createDrawAxes.ts | import { vec3, vec4 } from 'gl-matrix';
// tslint:disable-next-line:import-name
import REGL = require('regl');
interface Attributes {
position: vec3;
color: vec3;
}
/*
* All the information needed to be able to draw axes to the screen
*/
export interface DrawAxesProps {
positions: vec4[];
colors: ve... | * Shader to draw axes in the corner of the screen
*/
export function createDrawAxes(
regl: REGL.Regl
): REGL.DrawCommand<REGL.DefaultContext, DrawAxesProps> {
return regl<{}, Attributes, DrawAxesProps>({
vert: `
precision mediump float;
attribute vec4 position;
att... | random_line_split | |
test_auth_resources.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# Copyright (C) 2014-2017 Anler Hernández ... | tings.PUBLIC_REGISTER_ENABLED = True
url = reverse('auth-register')
register_data = json.dumps({
"type": "public",
"username": "test",
"password": "test",
"full_name": "test",
"email": "test@test.com",
})
result = client.post(url, register_data, content_type="ap... | identifier_body | |
test_auth_resources.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# Copyright (C) 2014-2017 Anler Hernández ... | dule):
disconnect_signals()
def teardown_module(module):
reconnect_signals()
def test_auth_create(client):
url = reverse('auth-list')
user = f.UserFactory.create()
login_data = json.dumps({
"type": "normal",
"username": user.username,
"password": user.username,
})
... | up_module(mo | identifier_name |
test_auth_resources.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> | # License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have... | # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# Copyright (C) 2014-2017 Anler Hernández <hello@anler.me>
# 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, eithe... | random_line_split |
Opportunity.tsx | import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { Options } from 'parser/core/Analyzer';
import { NumberThreshold, ThresholdStyle, When } from 'parser/core/ParseResults';
import DamageTracker... |
suggestions(when: When) {
when(this.thresholds).addSuggestion((suggest, actual, recommended) =>
suggest(
<>
You casted <SpellLink id={SPELLS.SINISTER_STRIKE.id} /> while having an{' '}
<SpellLink id={SPELLS.OPPORTUNITY.id} /> proc. Try to prioritize{' '}
<SpellLink id... | {
super(options);
options.opportunityDamageTracker.subscribeInefficientCast(
[SPELLS.SINISTER_STRIKE],
() => `Pistol Shot should be used as your builder during Opportunity`,
);
} | identifier_body |
Opportunity.tsx | import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { Options } from 'parser/core/Analyzer';
import { NumberThreshold, ThresholdStyle, When } from 'parser/core/ParseResults';
import DamageTracker... | class Opportunity extends Analyzer {
get thresholds(): NumberThreshold {
const total = this.damageTracker.getAbility(SPELLS.SINISTER_STRIKE.id);
const filtered = this.opportunityDamageTracker.getAbility(SPELLS.SINISTER_STRIKE.id);
return {
actual: filtered.casts / total.casts,
isGreaterThan: ... |
import OpportunityDamageTracker from './OpportunityDamageTracker';
| random_line_split |
Opportunity.tsx | import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { Options } from 'parser/core/Analyzer';
import { NumberThreshold, ThresholdStyle, When } from 'parser/core/ParseResults';
import DamageTracker... | (when: When) {
when(this.thresholds).addSuggestion((suggest, actual, recommended) =>
suggest(
<>
You casted <SpellLink id={SPELLS.SINISTER_STRIKE.id} /> while having an{' '}
<SpellLink id={SPELLS.OPPORTUNITY.id} /> proc. Try to prioritize{' '}
<SpellLink id={SPELLS.PISTOL... | suggestions | identifier_name |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *};
use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task;
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
schedule... | () {
let (_server, client, mut rx) = new_rpc_suite();
let (tmp, endpoint) = new_endpoint();
let engine = endpoint.engine.clone();
endpoint.region_info.set_regions(vec![
(b"".to_vec(), b"2".to_vec(), 1),
(b"2".to_vec(), b"5".to_vec(), 2),
]);
let ... | test_client_stop | identifier_name |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *}; |
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
scheduler: Scheduler<Task>,
}
impl Service {
/// Create a new backup service.
pub fn new(scheduler: Scheduler<Task>) -> Service {
Service { scheduler }
}
}
impl Backup for Service {
fn bac... | use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task; | random_line_split |
service.rs | use std::sync::atomic::*;
use futures::channel::mpsc;
use futures::{FutureExt, SinkExt, StreamExt, TryFutureExt};
use grpcio::{self, *};
use kvproto::backup::*;
use tikv_util::worker::*;
use super::Task;
/// Service handles the RPC messages for the `Backup` service.
#[derive(Clone)]
pub struct Service {
schedule... |
#[test]
fn test_client_stop() {
let (_server, client, mut rx) = new_rpc_suite();
let (tmp, endpoint) = new_endpoint();
let engine = endpoint.engine.clone();
endpoint.region_info.set_regions(vec![
(b"".to_vec(), b"2".to_vec(), 1),
(b"2".to_vec(), b"5".to... | {
let env = Arc::new(EnvBuilder::new().build());
let (scheduler, rx) = dummy_scheduler();
let backup_service = super::Service::new(scheduler);
let builder =
ServerBuilder::new(env.clone()).register_service(create_backup(backup_service));
let mut server = builder.bind(... | identifier_body |
Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: { | files: [
{expand: true, cwd: "app", src: ['**/*'], dest: '/var/www/html/status/'},
]
}
},
watch : {
files : [
'app/**'
],
tasks : ['test', 'deploy']
}
});
// concat was used at one point b... | files: ['app/js/*.js']
},
copy: {
deploy: { | random_line_split |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn test_success() |
#[test]
fn test_failure() {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, dir.path()).... | {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
util::create_file_with_content(&file2,... | identifier_body |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn test_success() {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create... | let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
assert!(libxch::xch_non_atomic(&file1, dir.path()).is_err());
assert!(util::e... | #[test]
fn test_failure() { | random_line_split |
tests.rs | use tempdir;
use libxch;
mod util;
#[test]
fn | () {
let dir = tempdir::TempDir::new("test").expect("Could not create temporary directory");
let file1 = dir.path().join("file1");
let file2 = dir.path().join("file2");
util::create_file_with_content(&file1, b"content1").expect("Could not create file in tempdir");
util::create_file_with_content(&fil... | test_success | identifier_name |
sl.js | /* Slovenian locals for flatpickr */
var flatpickr = flatpickr || { l10ns: {} };
flatpickr.l10ns.sl = {};
flatpickr.l10ns.sl.weekdays = {
shorthand: ["Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"],
longhand: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"]
};
flatpickr.l10ns.sl.months = {... | flatpickr.l10ns.sl.ordinal = function () {
return ".";
};
if (typeof module !== "undefined") module.exports = flatpickr.l10ns; |
flatpickr.l10ns.sl.firstDayOfWeek = 1;
flatpickr.l10ns.sl.rangeSeparator = " do "; | random_line_split |
eagerLoadDownRefs.ts | import { Dictionary, includes } from 'lodash';
import UnstoredStatementModel from '../../../models/UnstoredStatementModel';
import ClientModel from '../../../models/ClientModel'; | import Statement from '../../../models/Statement';
import Config from '../../Config';
import groupStatementsById from './groupStatementsById';
const getGroupedDownRefs = async (
config: Config,
models: UnstoredStatementModel[],
client: ClientModel
): Promise<Dictionary<Statement>> => {
const allIds: string[] =... | random_line_split | |
eagerLoadDownRefs.ts | import { Dictionary, includes } from 'lodash';
import UnstoredStatementModel from '../../../models/UnstoredStatementModel';
import ClientModel from '../../../models/ClientModel';
import Statement from '../../../models/Statement';
import Config from '../../Config';
import groupStatementsById from './groupStatementsById'... |
return results;
}, [] as string[]);
const targetStatements = await config.repo.getStatementsByIds({ ids: targetIds, client });
const groupedStatements = groupStatementsById(targetStatements);
return groupedStatements;
};
const getGroupedModels = (models: UnstoredStatementModel[]) => {
const statements =... | {
return [...results, model.statement.object.id];
} | conditional_block |
pipeline_info_editor_spec.tsx | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* 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 agr... | import {TestHelper} from "views/pages/spec/test_helper";
import {PipelineInfoEditor} from "../pipeline_info_editor";
const flag: (val?: boolean) => Stream<boolean> = Stream;
describe("AddPipeline: PipelineInfoEditor", () => {
const helper = new TestHelper();
let config: PipelineConfig;
beforeEach(() => {
c... | random_line_split | |
pipeline_info_editor_spec.tsx | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* 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 agr... |
// tslint:disable-next-line
invalidate() {}
contents() { return []; }
pipelineGroups() { return []; }
stages(pipeline: string) { return []; }
failureReason() { return undefined; }
failed() { return false; }
}
class EmptyTemplatesTestCache extends TemplateCache {
ready() { return true; }
// tslint:di... | {} | identifier_body |
pipeline_info_editor_spec.tsx | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* 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 agr... | () { return undefined; }
failed() { return false; }
}
| failureReason | identifier_name |
self_assessment_module.py | import json
import logging
from lxml import etree
from xmodule.capa_module import ComplexEncoder
from xmodule.progress import Progress
from xmodule.stringify import stringify_children
import openendedchild
from .combined_open_ended_rubric import CombinedOpenEndedRubric
log = logging.getLogger("edx.courseware") | submit, then see a rubric and rate themselves. Persists student supplied
hints, answers, and assessment judgment (currently only correct/incorrect).
Parses xml definition file--see below for exact format.
Sample XML format:
<selfassessment>
<hintprompt>
What hint about this pro... |
class SelfAssessmentModule(openendedchild.OpenEndedChild):
"""
A Self Assessment module that allows students to write open-ended responses, | random_line_split |
self_assessment_module.py | import json
import logging
from lxml import etree
from xmodule.capa_module import ComplexEncoder
from xmodule.progress import Progress
from xmodule.stringify import stringify_children
import openendedchild
from .combined_open_ended_rubric import CombinedOpenEndedRubric
log = logging.getLogger("edx.courseware")
cla... |
else:
# This is a dev_facing_error
raise ValueError("Self assessment module is in an illegal state '{0}'".format(self.child_state))
return system.render_template('{0}/self_assessment_rubric.html'.format(self.TEMPLATE_DIR), context)
def get_hint_html(self, system):
... | context['read_only'] = True | conditional_block |
self_assessment_module.py | import json
import logging
from lxml import etree
from xmodule.capa_module import ComplexEncoder
from xmodule.progress import Progress
from xmodule.stringify import stringify_children
import openendedchild
from .combined_open_ended_rubric import CombinedOpenEndedRubric
log = logging.getLogger("edx.courseware")
cla... |
return {}
def definition_to_xml(self, resource_fs):
'''Return an xml element representing this definition.'''
elt = etree.Element('selfassessment')
def add_child(k):
child_str = u'<{tag}>{body}</{tag}>'.format(tag=k, body=getattr(self, k))
child_node = etr... | """Assumes that xml_object has child k"""
return stringify_children(xml_object.xpath(k)[0]) | identifier_body |
self_assessment_module.py | import json
import logging
from lxml import etree
from xmodule.capa_module import ComplexEncoder
from xmodule.progress import Progress
from xmodule.stringify import stringify_children
import openendedchild
from .combined_open_ended_rubric import CombinedOpenEndedRubric
log = logging.getLogger("edx.courseware")
cla... | (self, data, _system):
'''
Not used currently, as hints have been removed from the system.
Save the hint.
Returns a dict { 'success': bool,
'message_html': message_html,
'error': error-msg,
'allow_reset': bool},
... | save_hint | identifier_name |
tag_view.js | var tag_view = Vue.component('tag_view',{
template: '<div class="col-sm-12 col-md-7 col-md-push-3">\
<div class="panel panel-default">\ | <div is="pretty_header" v-bind:title="tag"></div>\
</div>\
</div>\
<div is="post_input" v-bind:user_prop="user" v-show="auth" v-bind:prefill="mention_prefill"></div>\
<div is="post_list" v-bind:posts.sync="po... | <div class="panel-body" style="padding: 0px;">\ | random_line_split |
Main.py | #!/usr/bin/python
import feedparser | import sqlite3
import time
RssUrlList = ['http://postitforward.tumblr.com/rss','http://for-war3-blog-blog.tumblr.com/rss']
sleep=3600/len(RssUrlList)
def mkdir(path):
import os
path=path.strip()
path=path.rstrip("\\")
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
conn ... | import wget | random_line_split |
Main.py | #!/usr/bin/python
import feedparser
import wget
import sqlite3
import time
RssUrlList = ['http://postitforward.tumblr.com/rss','http://for-war3-blog-blog.tumblr.com/rss']
sleep=3600/len(RssUrlList)
def mkdir(path):
import os
path=path.strip()
path=path.rstrip("\\")
isExists=os.path.exists(path)
... | (rss_url):
feeds = feedparser.parse(rss_url)
table=rss_url[7:-15].replace('-','')
try:
conn.execute('''CREATE TABLE %s(BLOG TEXT, ADDRESS TEXT PRIMARY KEY, DATE REAL)'''% table)
conn.execute("INSERT INTO %s (BLOG ,ADDRESS, DATE) VALUES ('%s','new','0')" % (table,rss_url))
# conn... | DownloadVideo | identifier_name |
Main.py | #!/usr/bin/python
import feedparser
import wget
import sqlite3
import time
RssUrlList = ['http://postitforward.tumblr.com/rss','http://for-war3-blog-blog.tumblr.com/rss']
sleep=3600/len(RssUrlList)
def mkdir(path):
|
conn = sqlite3.connect('tumblr.db')
def DownloadVideo(rss_url):
feeds = feedparser.parse(rss_url)
table=rss_url[7:-15].replace('-','')
try:
conn.execute('''CREATE TABLE %s(BLOG TEXT, ADDRESS TEXT PRIMARY KEY, DATE REAL)'''% table)
conn.execute("INSERT INTO %s (BLOG ,ADDRESS, DATE) V... | import os
path=path.strip()
path=path.rstrip("\\")
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path) | identifier_body |
Main.py | #!/usr/bin/python
import feedparser
import wget
import sqlite3
import time
RssUrlList = ['http://postitforward.tumblr.com/rss','http://for-war3-blog-blog.tumblr.com/rss']
sleep=3600/len(RssUrlList)
def mkdir(path):
import os
path=path.strip()
path=path.rstrip("\\")
isExists=os.path.exists(path)
... | for rss_url in RssUrlList:
print("Downloading "+rss_url)
DownloadVideo(rss_url)
print("Sleep "+str(sleep)+" seconds")
time.sleep(sleep) | conditional_block | |
SheetList.ts | import { Map, Range, Record } from 'immutable';
import { RootState } from '../ducks';
import Sheet, { ISheet } from './Sheet';
export interface ISheetList {
list: Map<number, Sheet>;
}
const defaultValue: ISheetList = {
list: Map(),
};
export default class SheetList extends Record(defaultValue) {
constructor(p... |
public updateList(params: ISheet[]) {
let newList = Map<number, Sheet>();
params.forEach((sheet) => {
newList = newList.set(sheet.id, new Sheet(sheet));
});
return this.set('list', newList);
}
public whereAbility(ability: number, type: RootState['$$sheet']['type']) {
return this.list
... | {
const newList = this.list.map((sheet) => {
if (sheet.version !== version) {
return sheet;
}
return sheet.set('hide', !sheet.hide);
});
return this.set('list', newList);
} | identifier_body |
SheetList.ts | import { Map, Range, Record } from 'immutable';
import { RootState } from '../ducks';
import Sheet, { ISheet } from './Sheet';
export interface ISheetList {
list: Map<number, Sheet>;
}
const defaultValue: ISheetList = {
list: Map(),
};
export default class SheetList extends Record(defaultValue) {
constructor(p... | });
}
public chunk(list: Map<number, Sheet | undefined>, chunkSize = 5) {
return Range(0, list.count(), chunkSize).map((chunkStart) =>
list.slice(chunkStart, chunkStart + chunkSize),
);
}
} | if (sheet?.title === undefined) {
return;
}
return sheet.title.toLocaleLowerCase(); | random_line_split |
SheetList.ts | import { Map, Range, Record } from 'immutable';
import { RootState } from '../ducks';
import Sheet, { ISheet } from './Sheet';
export interface ISheetList {
list: Map<number, Sheet>;
}
const defaultValue: ISheetList = {
list: Map(),
};
export default class SheetList extends Record(defaultValue) {
constructor(p... |
return sheet;
})
.filter((sheet) => sheet !== undefined)
.sortBy((sheet) => {
if (sheet?.title === undefined) {
return;
}
return sheet.title.toLocaleLowerCase();
});
}
public chunk(list: Map<number, Sheet | undefined>, chunkSize = 5) {
return R... | {
return;
} | conditional_block |
SheetList.ts | import { Map, Range, Record } from 'immutable';
import { RootState } from '../ducks';
import Sheet, { ISheet } from './Sheet';
export interface ISheetList {
list: Map<number, Sheet>;
}
const defaultValue: ISheetList = {
list: Map(),
};
export default class SheetList extends Record(defaultValue) {
constructor(p... | (params: ISheet[]) {
let newList = Map<number, Sheet>();
params.forEach((sheet) => {
newList = newList.set(sheet.id, new Sheet(sheet));
});
return this.set('list', newList);
}
public whereAbility(ability: number, type: RootState['$$sheet']['type']) {
return this.list
.map((sheet) =>... | updateList | identifier_name |
tooltipAdvancedHelper.js | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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 ... | else {
bbDirections = {
top: true,
bottom:true
};
}
component.constraints[thisConstraint + 'pointerBox'] = lib.createRelationship({
element:pointer,
target:ttbodyNode,
type: 'bounding box',
enable: false,
boxDirections: bbDirections,
pad: 0
});
}
component.c... | {
bbDirections = {
left:true,
right:true
};
} | conditional_block |
tooltipAdvancedHelper.js | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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 ... | ['north', 'south', 'west' , 'east'].forEach(function(directions) {
component.constraints[directions].disable();
component.constraints[directions + '_pointer'].disable();
component.constraints[directions + 'pointerBox'].disable();
// Manipulating classes directly to avoid re-render:
ttWrapper.classList... | random_line_split | |
vmSearchTaxonRepository.py | # -*- coding:utf-8 -*-
from sqlalchemy import desc, func
from atlas.modeles.entities.vmSearchTaxon import VmSearchTaxon
def listeTaxons(session):
"""
revoie un tableau de dict :
label = nom latin et nom francais concatene, value = cd_ref
TODO Fonction inutile à supprimer !!!
"""
... | session, search, limit=50):
"""
Recherche dans la VmSearchTaxon en ilike
Utilisé pour l'autocomplétion de la recherche de taxon
:query SQLA_Session session
:query str search : chaine de charactere pour la recherche
:query int limit: limite des résultats
**Returns:**... | isteTaxonsSearch( | identifier_name |
vmSearchTaxonRepository.py | # -*- coding:utf-8 -*-
from sqlalchemy import desc, func
from atlas.modeles.entities.vmSearchTaxon import VmSearchTaxon
def listeTaxons(session):
"""
revoie un tableau de dict :
label = nom latin et nom francais concatene, value = cd_ref
TODO Fonction inutile à supprimer !!!
"""
... | :query str search : chaine de charactere pour la recherche
:query int limit: limite des résultats
**Returns:**
list: retourne un tableau {'label':'str': 'value': 'int'}
label = search_name
value = cd_ref
"""
req = session.query(
VmSearchTaxo... | Utilisé pour l'autocomplétion de la recherche de taxon
:query SQLA_Session session | random_line_split |
vmSearchTaxonRepository.py | # -*- coding:utf-8 -*-
from sqlalchemy import desc, func
from atlas.modeles.entities.vmSearchTaxon import VmSearchTaxon
def listeTaxons(session):
"""
revoie un tableau de dict :
label = nom latin et nom francais concatene, value = cd_ref
TODO Fonction inutile à supprimer !!!
"""
... | ""
Recherche dans la VmSearchTaxon en ilike
Utilisé pour l'autocomplétion de la recherche de taxon
:query SQLA_Session session
:query str search : chaine de charactere pour la recherche
:query int limit: limite des résultats
**Returns:**
list: retourne un t... | identifier_body | |
vmSearchTaxonRepository.py | # -*- coding:utf-8 -*-
from sqlalchemy import desc, func
from atlas.modeles.entities.vmSearchTaxon import VmSearchTaxon
def listeTaxons(session):
"""
revoie un tableau de dict :
label = nom latin et nom francais concatene, value = cd_ref
TODO Fonction inutile à supprimer !!!
"""
... | return taxonList
def listeTaxonsSearch(session, search, limit=50):
"""
Recherche dans la VmSearchTaxon en ilike
Utilisé pour l'autocomplétion de la recherche de taxon
:query SQLA_Session session
:query str search : chaine de charactere pour la recherche
:query int limi... | emp = {"label": r[0], "value": r[1]}
taxonList.append(temp)
| conditional_block |
wallpaper.tsx | import React = require('react')
import './wallpaper.less'
interface WallPaperProps {
src?: string
style?: React.CSSProperties
className?: string
}
export const defualtWallPaper = '../../assets/pattern.png'
export const defualWallpaperStyle: React.CSSProperties = {
backgroundRepeat: 'repeat',
backgroundPosit... |
ref = (el) => this.e = el
render() {
const {
style = {},
className = ''
} = this.props
return <div className={ 'wallpaper ' + className } ref={ this.ref } style={ style }>
{ this.props.children }
</div>
}
} | {
if (this.props.src) {
const bg = new Image()
bg.src = this.props.src || ''
bg.onload = () => {
this.e.style.backgroundImage = `url('${this.props.src}')`
}
}
} | identifier_body |
wallpaper.tsx | import React = require('react')
import './wallpaper.less'
interface WallPaperProps {
src?: string
style?: React.CSSProperties
className?: string
}
export const defualtWallPaper = '../../assets/pattern.png'
export const defualWallpaperStyle: React.CSSProperties = {
backgroundRepeat: 'repeat',
backgroundPosit... |
ref = (el) => this.e = el
render() {
const {
style = {},
className = ''
} = this.props
return <div className={ 'wallpaper ' + className } ref={ this.ref } style={ style }>
{ this.props.children }
</div>
}
} | this.e.style.backgroundImage = `url('${this.props.src}')`
}
}
} | random_line_split |
wallpaper.tsx | import React = require('react')
import './wallpaper.less'
interface WallPaperProps {
src?: string
style?: React.CSSProperties
className?: string
}
export const defualtWallPaper = '../../assets/pattern.png'
export const defualWallpaperStyle: React.CSSProperties = {
backgroundRepeat: 'repeat',
backgroundPosit... |
}
ref = (el) => this.e = el
render() {
const {
style = {},
className = ''
} = this.props
return <div className={ 'wallpaper ' + className } ref={ this.ref } style={ style }>
{ this.props.children }
</div>
}
} | {
const bg = new Image()
bg.src = this.props.src || ''
bg.onload = () => {
this.e.style.backgroundImage = `url('${this.props.src}')`
}
} | conditional_block |
wallpaper.tsx | import React = require('react')
import './wallpaper.less'
interface WallPaperProps {
src?: string
style?: React.CSSProperties
className?: string
}
export const defualtWallPaper = '../../assets/pattern.png'
export const defualWallpaperStyle: React.CSSProperties = {
backgroundRepeat: 'repeat',
backgroundPosit... | extends React.Component<WallPaperProps, {}> {
static defualtWallPaper = defualtWallPaper
static defualStyle = defualWallpaperStyle
private e: HTMLDivElement
constructor(props) {
super(props)
}
componentDidMount() {
if (this.props.src) {
const bg = new Image()
bg.src = this.props.src ... | WallPaper | identifier_name |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... | else {
if include_connections {
depths.push(depth);
}
while let Some(&1) = stack.last() {
stack.pop();
}
if let Some(last) = stack.last_mut() {
*last -= 1;
}
... | {
depths.push(depth);
stack.push(*inputs);
} | conditional_block |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... | (&self, id: usize) -> usize {
self.network.genome.iter().fold(0, |acc, g| {
if let GeneExtras::Input(_) = (*g).variant {
acc + ((g.id == id) as usize)
} else {
acc
}
})
}
// Returns a vector with each element being the length o... | get_input_copies | identifier_name |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... | // does not need to be implemented
fn previous_neuron_index(&self, _: usize) -> Option<usize> {
unimplemented!();
}
} | random_line_split | |
mutation_utils.rs | use std::ops;
use cge::gene::GeneExtras;
use rand::{Rng, thread_rng};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// A few convenience methods for helping with determining which mutation operators are valid
impl<T: NNFitnessFunction+ Clone> Individual<T> {
// Retur... |
pub fn random_index(&self) -> usize {
let indices = (0..self.next_id).map(|i| {
self.network.get_neuron_index(i).unwrap()
}).collect::<Vec<usize>>();
*thread_rng().choose(&indices).unwrap()
}
pub fn subnetwork_index(&self, index: usize) -> ops::Range<usize> {
... | {
let mut depths = Vec::new();
let mut stack = Vec::new();
for gene in &self.network.genome {
let depth = stack.len();
if let GeneExtras::Neuron(_, ref inputs) = gene.variant {
depths.push(depth);
stack.push(*inputs);
} else {... | identifier_body |
mod.rs | use communication::Message;
pub use self::counter::Counter;
pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must con... |
}
| { (**self).pull() } | identifier_body |
mod.rs | use communication::Message;
pub use self::counter::Counter;
pub mod counter;
/// The pullable design may need to be upgraded: right now there is no obvious connection between
/// subsequent calls to pull; although multiple calls may produce the same time, they don't need to
/// and defensive implementations must con... | (&mut self) -> Option<(&T, &mut Message<D>)> { (**self).pull() }
}
| pull | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.