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
ocr.py
(message)s', level=log_level, filename=log_name) # Get the access token... response = azurerm.get_ams_access_token(account_name, account_key) resjson = response.json() access_token = resjson["access_token"] #Some global vars... NAME = "movie" COUNTER = 0; ENCRYPTION = "1" # 0=None, StorageEncrypted=1, CommonEncryptio...
if (MODE == "OCR"):
random_line_split
submit_pending_offer_mutation.test.ts
import { runQuery } from "schema/v2/test/utils" import { sampleOrder } from "test/fixtures/results/sample_order" import gql from "lib/gql" import { mockxchange } from "test/fixtures/exchange/mockxchange" import exchangeOrderJSON from "test/fixtures/exchange/buy_order.json" import { OrderBuyerFields } from "./order_fiel...
} context = mockxchange(resolvers) const data = await runQuery(mutation, context) expect(data!.ecommerceSubmitPendingOffer.orderOrError.order).toEqual( sampleOrder() ) }) it("returns an error if there is one", async () => { const resolvers = { Mutation: { submitPendin...
orderOrError: { order: exchangeOrderJSON }, }), },
random_line_split
test_curses.py
, 69, 70, 71, 72) win.border('|', '!', '-', '_', '+', '\\', '#', '/') with self.assertRaises(TypeError, msg="Expected win.border() to raise TypeError"): win.border(65, 66, 67, 68, 69, [], 71, 72) ...
def test_unctrl(self): unctrl = curses.ascii.unctrl self.assertEqual(unctrl('a'), 'a') self.assertEqual(unctrl('A'), 'A') self.assertEqual(unctrl(';'), ';') self.assertEqual(unctrl(' '), ' ') self.assertEqual(unctrl('\x7f'), '^?') self.assertEqual(unctrl('\n'), '^...
identifier_body
test_curses.py
"$TERM=%r, calling initscr() may cause exit" % term) @unittest.skipIf(sys.platform == "cygwin", "cygwin's curses mostly just hangs") class TestCurses(unittest.TestCase): @classmethod def setUpClass(cls): if not sys.__stdout__.isatty(): # Temporary skip test...
term = os.environ.get('TERM') # If newterm was supported we could use it instead of initscr and not exit @unittest.skipIf(not term or term == 'unknown',
random_line_split
test_curses.py
in [stdscr.box, stdscr.clear, stdscr.clrtobot, stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch, stdscr.deleteln, stdscr.erase, stdscr.getbegyx, stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx, stdscr.getparyx, stdscr.getyx, stdscr.inch,...
test_is_term_resized
identifier_name
test_curses.py
's curses mostly just hangs") class TestCurses(unittest.TestCase): @classmethod def setUpClass(cls): if not sys.__stdout__.isatty(): # Temporary skip tests on non-tty raise unittest.SkipTest('sys.__stdout__ is not a tty') cls.tmp = tempfile.TemporaryFile() ...
for meth in [stdscr.box, stdscr.clear, stdscr.clrtobot, stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch, stdscr.deleteln, stdscr.erase, stdscr.getbegyx, stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx, stdscr.getparyx, stdscr.g...
meth(*args)
conditional_block
Plotting.py
# Name: Seline, Li, Taylor, Son # Leap Motion project import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import time mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = Axes3D(fig) theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspac...
ax.view_init(elev=10, azim=ii) plt.draw() print "drawn? " + str(ii) time.sleep(0.01)
conditional_block
Plotting.py
# Name: Seline, Li, Taylor, Son # Leap Motion project import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import time mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = Axes3D(fig) theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
ax.legend() plt.ion() plt.show() for ii in xrange(0,360,1): ax.view_init(elev=10, azim=ii) plt.draw() print "drawn? " + str(ii) time.sleep(0.01)
z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * np.cos(theta) ax.plot(x, y, z, label='parametric curve')
random_line_split
node.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // ...
match event { ::event::Event::Request{ request, our_authority, from_authority, response_token } => self.handle_request(request, our_authority, from_authority, response_token), // Event::Response{ response, our_authority, from_authority } => ...
debug!("Node: Received event {:?}", event);
random_line_split
node.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // ...
, } } fn handle_get_request(&mut self, data_request: ::data::DataRequest, our_authority: ::authority::Authority, from_authority: ::authority::Authority, response_token: Option<::SignedToken>) ...
{ debug!("Node: Delete unimplemented."); }
conditional_block
node.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // ...
() -> Node { let (sender, receiver) = ::std::sync::mpsc::channel::<::event::Event>(); let routing = ::routing::Routing::new(sender); Node { routing: routing, receiver: receiver, db: ::std::collections::BTreeMap::new(), } } pub fn run(&mut sel...
new
identifier_name
node.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // ...
pub fn run(&mut self) { while let Ok(event) = self.receiver.recv() { debug!("Node: Received event {:?}", event); match event { ::event::Event::Request{ request, our_authority, from_authority, response_token } => self.handle_request(request, our_a...
{ let (sender, receiver) = ::std::sync::mpsc::channel::<::event::Event>(); let routing = ::routing::Routing::new(sender); Node { routing: routing, receiver: receiver, db: ::std::collections::BTreeMap::new(), } }
identifier_body
npc.py
# This file is part of PARPG. # PARPG is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # PARPG is distributed in the hope ...
(self): """@rtype: fife.Location @return: NPC's position""" x = self.getX() y = self.getY() if self.state == base._AGENT_STATE_WANDER: """ Random Target Location """ l = [0, 0] for i in range(len(l)): sign = randrange(0, 2) ...
getTargetLocation
identifier_name
npc.py
# This file is part of PARPG. # PARPG is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # PARPG is distributed in the hope ...
def wander(self, location): """Nice slow movement for random walking. @type location: fife.Location @param location: Where the NPC will walk to. @return: None""" self.agent.move('walk', location, self.speed) coords = location.getMapCoordinates()
self.animate('stand', self.pc.getLocation())
conditional_block
npc.py
# This file is part of PARPG. # PARPG is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version.
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with PARPG. If not, see <http://www.gnu.org/licenses/>. ...
# PARPG is distributed in the hope that it will be useful,
random_line_split
npc.py
# This file is part of PARPG. # PARPG is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # PARPG is distributed in the hope ...
def onInstanceActionFinished(self, instance, action): """What the NPC does when it has finished an action. Called by the engine and required for InstanceActionListeners. @type instance: fife.Instance @param instance: self.agent @type action: ??? @para...
"""@rtype: fife.Location @return: NPC's position""" x = self.getX() y = self.getY() if self.state == base._AGENT_STATE_WANDER: """ Random Target Location """ l = [0, 0] for i in range(len(l)): sign = randrange(0, 2) d...
identifier_body
configure_websites.py
import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html...
print(command_template % (site_name, site_name, wildcard, site_name)) return True
global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) ...
identifier_body
configure_websites.py
import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html...
elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add...
add_website()
conditional_block
configure_websites.py
import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html...
(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name...
add_ssl
identifier_name
configure_websites.py
import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format
sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environmen...
sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html
random_line_split
LdapUserGroups.tsx
import React, { FC } from 'react'; import { Tooltip, Icon } from '@grafana/ui'; import { LdapRole } from 'app/types'; interface Props { groups: LdapRole[]; showAttributeMapping?: boolean; } export const LdapUserGroups: FC<Props> = ({ groups, showAttributeMapping }) => { const items = showAttributeMapping ? grou...
<> <td>{group.groupDN}</td> {!group.orgRole && ( <> <td /> <td> <span className="text-warning"> No match ...
<tr key={`${group.orgId}-${index}`}> {showAttributeMapping && (
random_line_split
router-extensions.service.ts
import { Injectable } from '@angular/core'; import { LocationStrategy } from '@angular/common'; import { Router, UrlTree, NavigationExtras } from '@angular/router'; export interface ExtendedNavigationExtras extends NavigationExtras { // Options for nativescript clearHistory?: boolean; animated?: boolean; trans...
}
random_line_split
router-extensions.service.ts
import { Injectable } from '@angular/core'; import { LocationStrategy } from '@angular/common'; import { Router, UrlTree, NavigationExtras } from '@angular/router'; export interface ExtendedNavigationExtras extends NavigationExtras { // Options for nativescript clearHistory?: boolean; animated?: boolean; tran...
public back() { this.locationStrategy.back(); } }
{ return this.router.navigateByUrl(url); }
identifier_body
router-extensions.service.ts
import { Injectable } from '@angular/core'; import { LocationStrategy } from '@angular/common'; import { Router, UrlTree, NavigationExtras } from '@angular/router'; export interface ExtendedNavigationExtras extends NavigationExtras { // Options for nativescript clearHistory?: boolean; animated?: boolean; tran...
implements IRouterExtensions { constructor(public router: Router, private locationStrategy: LocationStrategy) { } public navigate(commands: Array<any>, extras?: ExtendedNavigationExtras): Promise<boolean> { return this.router.navigate(commands, extras); } public navigateByUrl(url: string | UrlTree, opti...
RouterExtensions
identifier_name
gradient.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import logging import numpy as np from numpy import ma from cotede.qctests import QCCheckVar try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: PANDAS_AVAILABLE = Fa...
return curvature(x) def _curvature_pandas(x): """Equivalent to curvature() but using pandas It looks like the numpy implementation is faster even for larger datasets, so the default is with numpy. Note ---- - In the future this will be useful to handle specific window widths. """ ...
random_line_split
gradient.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import logging import numpy as np from numpy import ma from cotede.qctests import QCCheckVar try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: PANDAS_AVAILABLE = Fa...
def test(self): self.flags = {} try: threshold = self.cfg["threshold"] except KeyError: module_logger.debug( "Deprecated cfg format. It should contain a threshold item." ) threshold = self.cfg assert ( (np...
self.features = {"gradient": curvature(self.data[self.varname])}
identifier_body
gradient.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import logging import numpy as np from numpy import ma from cotede.qctests import QCCheckVar try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: PANDAS_AVAILABLE = Fa...
(self): self.features = {"gradient": curvature(self.data[self.varname])} def test(self): self.flags = {} try: threshold = self.cfg["threshold"] except KeyError: module_logger.debug( "Deprecated cfg format. It should contain a threshold item." ...
set_features
identifier_name
gradient.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import logging import numpy as np from numpy import ma from cotede.qctests import QCCheckVar try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: PANDAS_AVAILABLE = Fa...
if PANDAS_AVAILABLE and isinstance(x, pd.Series): return _curvature_pandas(x) x = np.atleast_1d(x) y = np.nan * x y[1:-1] = x[1:-1] - (x[:-2] + x[2:]) / 2.0 return y class Gradient(QCCheckVar): def set_features(self): self.features = {"gradient": curvature(self.data[self.var...
x[x.mask] = np.nan x = x.data
conditional_block
minimizer.py
import beanstalkc import sqlite3 import os import msgpack from time import sleep import zlib class SeedMinimizer: def __init__(self, config): self.sql = sqlite3.connect(config['db_path'], check_same_thread=False) self.c = self.sql.cursor() self.min_dir = os.path.join(config['output_path']...
if self.job: return True else: return False def insert_seeds(self): print "[ +D+ ] - Begin seed insertion for minimization" bs = beanstalkc.Connection(host='127.0.0.1', port=11300) bs.use('min-queue') try: self.c.execute('''SELEC...
self.job = self.bs.reserve(20) if self.job: break else: self.job = self.bs.reserve(20)
random_line_split
minimizer.py
import beanstalkc import sqlite3 import os import msgpack from time import sleep import zlib class
: def __init__(self, config): self.sql = sqlite3.connect(config['db_path'], check_same_thread=False) self.c = self.sql.cursor() self.min_dir = os.path.join(config['output_path'], "minimized") self.seed_dir = config['seed_path'] self.job = None def is_minimized(self, se...
SeedMinimizer
identifier_name
minimizer.py
import beanstalkc import sqlite3 import os import msgpack from time import sleep import zlib class SeedMinimizer: def __init__(self, config): self.sql = sqlite3.connect(config['db_path'], check_same_thread=False) self.c = self.sql.cursor() self.min_dir = os.path.join(config['output_path']...
seed = msgpack.unpackb(zlib.decompress(self.job.body)) name = seed['seed_name'] data = seed['data'] filename = os.path.join(self.min_dir, name) with open(filename, 'wb') as f: f.write(data)
conditional_block
minimizer.py
import beanstalkc import sqlite3 import os import msgpack from time import sleep import zlib class SeedMinimizer: def __init__(self, config):
def is_minimized(self, seed_name): min_name = os.path.join(self.min_dir, seed_name) if os.path.isfile(min_name): return True else: return False def get_job(self): self.bs.watch('min-results') while 'min-queue' in self.bs.tubes(): sel...
self.sql = sqlite3.connect(config['db_path'], check_same_thread=False) self.c = self.sql.cursor() self.min_dir = os.path.join(config['output_path'], "minimized") self.seed_dir = config['seed_path'] self.job = None
identifier_body
ember-template-compiler.js
@submodule ember-handlebars-compiler */ // Eliminate dependency on any Ember to simplify precompilation workflow var objectCreate = Object.create || function(parent) { function F() {} F.prototype = parent; return new F(); }; var Handlebars = (Ember.imports && Ember.imports.Handlebars) || (this && this.Handleba...
else { var id = new Handlebars.AST.IdNode([{ part: '_triageMustache' }]); // Update the mustache node to include a hash value indicating whether the original node // was escaped. This will allow us to properly escape values when the underlying value // changes and we need to re-render the value. i...
{ // no changes required }
conditional_block
ember-template-compiler.js
@submodule ember-handlebars-compiler */ // Eliminate dependency on any Ember to simplify precompilation workflow var objectCreate = Object.create || function(parent) { function
() {} F.prototype = parent; return new F(); }; var Handlebars = (Ember.imports && Ember.imports.Handlebars) || (this && this.Handlebars); if (!Handlebars && typeof require === 'function') { Handlebars = require('handlebars'); } Ember.assert("Ember Handlebars requires Handlebars version 1.0 or 1.1. Include " + ...
F
identifier_name
ember-template-compiler.js
@submodule ember-handlebars-compiler */ // Eliminate dependency on any Ember to simplify precompilation workflow var objectCreate = Object.create || function(parent) { function F() {} F.prototype = parent; return new F(); }; var Handlebars = (Ember.imports && Ember.imports.Handlebars) || (this && this.Handleba...
Ember.assert("Ember Handlebars requires Handlebars version 1.0 or 1.1. Include " + "a SCRIPT tag in the HTML HEAD linking to the Handlebars file " + "before you link to Ember.", Handlebars); Ember.assert("Ember Handlebars requires Handlebars version 1.0 or 1.1, " + "COMPILER_REV...
Handlebars = require('handlebars'); }
random_line_split
ember-template-compiler.js
@submodule ember-handlebars-compiler */ // Eliminate dependency on any Ember to simplify precompilation workflow var objectCreate = Object.create || function(parent) { function F()
F.prototype = parent; return new F(); }; var Handlebars = (Ember.imports && Ember.imports.Handlebars) || (this && this.Handlebars); if (!Handlebars && typeof require === 'function') { Handlebars = require('handlebars'); } Ember.assert("Ember Handlebars requires Handlebars version 1.0 or 1.1. Include " + ...
{}
identifier_body
scripting.py
#!/usr/bin/env python2 import os, shutil, glob from functools import wraps def print_warning(message, *args, **kwargs): from . import colortext if args or kwargs: message = message.format(*args, **kwargs) colortext.write(message + '\n', color='red') def print_error_and_die(message, *args, **kwargs): ...
# Bread'n'butter shell commands. def mkdir(newdir): if os.path.isdir(newdir): pass elif os.path.isfile(newdir): raise OSError("a file with the same name as the desired " \ "dir, '%s', already exists." % newdir) else: os.makedirs(newdir) def touch(path): w...
if os.path.exists(link_name): os.remove(link_name) os.symlink(rel_target, link_name)
random_line_split
scripting.py
#!/usr/bin/env python2 import os, shutil, glob from functools import wraps def print_warning(message, *args, **kwargs): from . import colortext if args or kwargs: message = message.format(*args, **kwargs) colortext.write(message + '\n', color='red') def print_error_and_die(message, *args, **kwargs): ...
(target, link_name): """Make a symlink to target using the shortest possible relative path.""" link_name = os.path.abspath(link_name) abs_target = os.path.abspath(target) rel_target = os.path.relpath(target, os.path.dirname(link_name)) if os.path.exists(link_name): os.remove(link_name) ...
relative_symlink
identifier_name
scripting.py
#!/usr/bin/env python2 import os, shutil, glob from functools import wraps def print_warning(message, *args, **kwargs): from . import colortext if args or kwargs: message = message.format(*args, **kwargs) colortext.write(message + '\n', color='red') def print_error_and_die(message, *args, **kwargs): ...
def touch(path): with open(path, 'w'): pass
os.makedirs(newdir)
conditional_block
scripting.py
#!/usr/bin/env python2 import os, shutil, glob from functools import wraps def print_warning(message, *args, **kwargs): from . import colortext if args or kwargs: message = message.format(*args, **kwargs) colortext.write(message + '\n', color='red') def print_error_and_die(message, *args, **kwargs): ...
return wrapper def use_path_completion(): import readline readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(path_completer) def path_completer(text, state): globs = glob.glob(os.path.expanduser(text) + '*') + [None] add_slash = la...
with self: return function(*args, **kwargs)
identifier_body
bg.rs
use crate::builtins::utils::print_stderr_with_capture; use crate::jobc; use crate::libc; use crate::shell::Shell; use crate::types::{CommandResult, CommandLine, Command}; pub fn run(sh: &mut Shell, cl: &CommandLine, cmd: &Command, capture: bool) -> CommandResult
if job_str.starts_with("%") { job_str = job_str.trim_start_matches('%').to_string(); } match job_str.parse::<i32>() { Ok(n) => job_id = n, Err(_) => { let info = "cicada: bg: invalid job id"; print_stderr_with_capture(info, &mu...
{ let tokens = cmd.tokens.clone(); let mut cr = CommandResult::new(); if sh.jobs.is_empty() { let info = "cicada: bg: no job found"; print_stderr_with_capture(info, &mut cr, cl, cmd, capture); return cr; } let mut job_id = -1; if tokens.len() == 1 { for (gid, _)...
identifier_body
bg.rs
use crate::builtins::utils::print_stderr_with_capture; use crate::jobc; use crate::libc; use crate::shell::Shell; use crate::types::{CommandResult, CommandLine, Command}; pub fn
(sh: &mut Shell, cl: &CommandLine, cmd: &Command, capture: bool) -> CommandResult { let tokens = cmd.tokens.clone(); let mut cr = CommandResult::new(); if sh.jobs.is_empty() { let info = "cicada: bg: no job found"; print_stderr_with_capture(info, &mut cr, cl, cmd, capture); ...
run
identifier_name
bg.rs
use crate::builtins::utils::print_stderr_with_capture; use crate::jobc; use crate::libc; use crate::shell::Shell; use crate::types::{CommandResult, CommandLine, Command}; pub fn run(sh: &mut Shell, cl: &CommandLine, cmd: &Command, capture: bool) -> CommandResult { let tokens = cmd.tokens.clone(); le...
}
random_line_split
admin.py
from django.contrib import admin from .models import Batch, Event, PreClaim, Claim, Department, Student from django.contrib.admin.models import LogEntry # Register your models here. def js_approve(modeladmin, request, queryset): queryset.update(js_approved = True) js_approve.short_description = 'Joint Sec Approve...
if not request.user.has_perm('attendance.claim_sis_approve'): del actions['sis_approve'] return actions admin.site.register(Batch) admin.site.register(Event) admin.site.register(Department) #admin.site.register(Student) admin.site.register(LogEntry) admin.site.site_header = "KMC Office" ...
del actions['js_approve']
conditional_block
admin.py
from django.contrib import admin from .models import Batch, Event, PreClaim, Claim, Department, Student from django.contrib.admin.models import LogEntry # Register your models here. def js_approve(modeladmin, request, queryset): queryset.update(js_approved = True) js_approve.short_description = 'Joint Sec Approve...
@admin.register(Claim) class ClaimAdmin(admin.ModelAdmin): exclude = ('sis_approved',) list_display = ('student','name','period','date','event','pre_claim_approved','js_approved','sis_approved') actions = [js_approve,sis_approve] search_fields = ['student__name','student__roll_no','period__department_...
exclude = ('students','dean_approved') list_display = ('event','dean_approved') actions = [dean_approve,] def get_actions(self,request): actions = super(PreClaimAdmin, self).get_actions(request) if not request.user.has_perm('attendance.preclaim_dean_approve'): del actions['d...
identifier_body
admin.py
from django.contrib import admin from .models import Batch, Event, PreClaim, Claim, Department, Student from django.contrib.admin.models import LogEntry # Register your models here. def js_approve(modeladmin, request, queryset): queryset.update(js_approved = True) js_approve.short_description = 'Joint Sec Approve...
(self,request): actions = super(ClaimAdmin, self).get_actions(request) if not request.user.has_perm('attendance.claim_js_approve'): del actions['js_approve'] if not request.user.has_perm('attendance.claim_sis_approve'): del actions['sis_approve'] return actions a...
get_actions
identifier_name
admin.py
from django.contrib import admin from .models import Batch, Event, PreClaim, Claim, Department, Student from django.contrib.admin.models import LogEntry # Register your models here. def js_approve(modeladmin, request, queryset): queryset.update(js_approved = True) js_approve.short_description = 'Joint Sec Approve...
@admin.register(Claim) class ClaimAdmin(admin.ModelAdmin): exclude = ('sis_approved',) list_display = ('student','name','period','date','event','pre_claim_approved','js_approved','sis_approved') actions = [js_approve,sis_approve] search_fields = ['student__name','student__roll_no','period__department__...
return actions
random_line_split
home.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { User } from '../_models/index'; import { UserService, AlertService, SimpleRegistrationService } from '../_services/index'; import {VgAPI} from "videogular2/core"; @Component({ selector: 'app-home', ...
else { this.loading = false; // return the play button } }, error => { this.alertService.error(error); this.loading = false; }); } playVideoPlayer() { this.api.play(); } }
{ this.videoUrl = data.url; this.loaded = true; }
conditional_block
home.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { User } from '../_models/index'; import { UserService, AlertService, SimpleRegistrationService } from '../_services/index'; import {VgAPI} from "videogular2/core"; @Component({ selector: 'app-home', ...
}
random_line_split
home.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { User } from '../_models/index'; import { UserService, AlertService, SimpleRegistrationService } from '../_services/index'; import {VgAPI} from "videogular2/core"; @Component({ selector: 'app-home', ...
ngOnInit() { } onPlayerReady(api: VgAPI) { this.api = api; this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe( this.playVideoPlayer.bind(this) ); } playVideo() { this.loading = true; this.simpleRegistrationService.getPreSignedURL(this.video) .subscribe( ...
{ this.currentUser = JSON.parse(localStorage.getItem('currentUser')); }
identifier_body
home.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { User } from '../_models/index'; import { UserService, AlertService, SimpleRegistrationService } from '../_services/index'; import {VgAPI} from "videogular2/core"; @Component({ selector: 'app-home', ...
(api: VgAPI) { this.api = api; this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe( this.playVideoPlayer.bind(this) ); } playVideo() { this.loading = true; this.simpleRegistrationService.getPreSignedURL(this.video) .subscribe( data => { if (data.valid...
onPlayerReady
identifier_name
grid-tile.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Component, ViewEncapsulation, ElementRef, Input, Optional, ContentChildren, QueryList, After...
@Directive({ selector: 'mat-grid-tile-header', host: {'class': 'mat-grid-tile-header'} }) export class MatGridTileHeaderCssMatStyler {} /** * Directive whose purpose is to add the mat- CSS styling to this selector. * @docs-private */ @Directive({ selector: 'mat-grid-tile-footer', host: {'class': 'mat-grid-t...
/** * Directive whose purpose is to add the mat- CSS styling to this selector. * @docs-private */
random_line_split
grid-tile.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Component, ViewEncapsulation, ElementRef, Input, Optional, ContentChildren, QueryList, After...
set colspan(value: number) { this._colspan = Math.round(coerceNumberProperty(value)); } /** * Sets the style of the grid-tile element. Needs to be set manually to avoid * "Changed after checked" errors that would occur with HostBinding. */ _setStyle(property: string, value: any): void { (this._ele...
{ return this._colspan; }
identifier_body
grid-tile.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Component, ViewEncapsulation, ElementRef, Input, Optional, ContentChildren, QueryList, After...
(): number { return this._rowspan; } set rowspan(value: number) { this._rowspan = Math.round(coerceNumberProperty(value)); } /** Amount of columns that the grid tile takes up. */ @Input() get colspan(): number { return this._colspan; } set colspan(value: number) { this._colspan = Math.round(coerceNumberPrope...
rowspan
identifier_name
choose_one_species_cluster.py
import sys import seq import os from logger import Logger """ right now this just chooses the longest BEWARE, this writes over the file """ if __name__ == "__main__": if len(sys.argv) != 4 and len(sys.argv) != 5: print("python "+sys.argv[0]+" table clusterdir fending [logfile]") sys.exit(0) f...
seqs[i] = [longest] fn = open(dirr+"/"+o,"w") for i in seqs: for j in seqs[i]: fn.write(j.get_fasta()) fn.close() log.c()
if len(j.seq) > longestn: longest = j longestn = len(j.seq)
conditional_block
choose_one_species_cluster.py
import sys import seq import os from logger import Logger """ right now this just chooses the longest BEWARE, this writes over the file """ if __name__ == "__main__": if len(sys.argv) != 4 and len(sys.argv) != 5: print("python "+sys.argv[0]+" table clusterdir fending [logfile]") sys.exit(0) f...
log.c()
fn.close()
random_line_split
const.py
"""Constants for Google Assistant.""" from homeassistant.components import ( binary_sensor, camera, climate, cover, fan, group, input_boolean, light, lock, media_player, scene, script, sensor, switch, vacuum, ) DOMAIN = "google_assistant" GOOGLE_ASSISTANT_AP...
REQUEST_SYNC_BASE_URL = HOMEGRAPH_URL + "v1/devices:requestSync" # Error codes used for SmartHomeError class # https://developers.google.com/actions/reference/smarthome/errors-exceptions ERR_DEVICE_OFFLINE = "deviceOffline" ERR_DEVICE_NOT_FOUND = "deviceNotFound" ERR_VALUE_OUT_OF_RANGE = "valueOutOfRange" ERR_NOT_SUPP...
TYPE_SPEAKER = PREFIX_TYPES + "SPEAKER" SERVICE_REQUEST_SYNC = "request_sync" HOMEGRAPH_URL = "https://homegraph.googleapis.com/"
random_line_split
i18n-loading.service.ts
import { HttpClient } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { I18n, I18nInjectionToken } from 'app/i18n/i18n'; import { I18nMeta } from 'app/i18n/i18n-meta'; import { isDevServer } from 'app/shared/helper'; import { BehaviorSubject, Observable, Subscription } from 'rxjs...
*/ subscribeForLocale(next?: (locale: string) => void, error?: (error: any) => void, complete?: () => void): Subscription { return this.locale$.subscribe(next, error, complete); } /** * Sets the locale and translation values. * Shouldn't be called by regular components, only by initializations. *...
* The event is only triggered when the translations are fetched
random_line_split
i18n-loading.service.ts
import { HttpClient } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { I18n, I18nInjectionToken } from 'app/i18n/i18n'; import { I18nMeta } from 'app/i18n/i18n-meta'; import { isDevServer } from 'app/shared/helper'; import { BehaviorSubject, Observable, Subscription } from 'rxjs...
( @Inject(I18nInjectionToken) private i18n: I18n, private http: HttpClient) { } /** * Called just after the application setup. Basically checks for a static locale */ initialize(i18nRoot: string, params: { resourceCacheKey?: string, locale?: string; }) { this.i18nRoot = i18nRoot; this.resou...
constructor
identifier_name
i18n-loading.service.ts
import { HttpClient } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { I18n, I18nInjectionToken } from 'app/i18n/i18n'; import { I18nMeta } from 'app/i18n/i18n-meta'; import { isDevServer } from 'app/shared/helper'; import { BehaviorSubject, Observable, Subscription } from 'rxjs...
else { return this.load(params.locale); } } /** * Loads the translation for the given locale */ private load(localeParam = 'en'): Observable<I18n> { // Figure out the locale to use, according to the available ones let locale: string; if (this.locales.includes(localeParam)) { lo...
{ const hash = I18nMeta.contentHash('en'); return this.http.get(`${i18nRoot}/i18n.json?h=${hash}`).pipe( switchMap((defaultValues) => { this.i18n.$defaults(defaultValues); return this.load(params.locale); })); }
conditional_block
i18n-loading.service.ts
import { HttpClient } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { I18n, I18nInjectionToken } from 'app/i18n/i18n'; import { I18nMeta } from 'app/i18n/i18n-meta'; import { isDevServer } from 'app/shared/helper'; import { BehaviorSubject, Observable, Subscription } from 'rxjs...
/** * Loads the translation for the given locale */ private load(localeParam = 'en'): Observable<I18n> { // Figure out the locale to use, according to the available ones let locale: string; if (this.locales.includes(localeParam)) { locale = localeParam; } else { const parts = loc...
{ this.i18nRoot = i18nRoot; this.resourceCacheKey = params.resourceCacheKey; // If running in development mode, read the default translations first if (isDevServer()) { const hash = I18nMeta.contentHash('en'); return this.http.get(`${i18nRoot}/i18n.json?h=${hash}`).pipe( switchMap((d...
identifier_body
jquery.ui.datepicker-no.js
/* Norwegian initialisation for the jQuery UI date picker plugin. */ /* Written by Naimdjon Takhirov (naimdjon@gmail.com). */ jQuery(function($){ $.datepicker.regional['no'] = { closeText: 'Lukk', prevText: '&laquo;Forrige', nextText: 'Neste&raquo;', currentText: 'I dag', monthNames: ['j...
$.datepicker.setDefaults($.datepicker.regional['no']); });
random_line_split
index.js
this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg)...
back = null; } }
random_line_split
index.js
(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); }...
resume
identifier_name
index.js
mobx.isObservableObject; break; case "Map": mobxChecker = mobx.isObservableMap; break; default: throw new Error("Unexpected mobxType: " + mobxType); } var propValue = props[propName];...
{ isUsingStaticRendering = useStaticRendering; }
identifier_body
index.js
; } return false; } // Copied from React.PropTypes function getPropType(propValue) { var propType = typeof propValue === "undefined" ? "undefined" : _typeof(propValue); if (Array.isArray(propValue)) { return "array"; } if (propValue instanceof RegExp) { // Old webkits (at least...
{ storeNames[i] = arguments[i]; }
conditional_block
config.js
'use strict'; var yaml = require('js-yaml'); var fs = require('hexo-fs'); var pathFn = require('path'); function configConsole(args){ /* jshint validthis: true */ var key = args._[0]; var value = args._[1]; var self = this; if (!key){ console.log(this.config); return; } if (!value){ value ...
function castValue(value){ switch (value){ case 'true': return true; case 'false': return false; case 'null': return null; case 'undefined': return undefined; } var num = Number(value); if (!isNaN(num)) return num; return value; } module.exports = configConsole;
{ var split = key.split('.'); var cursor = obj; var name = ''; var lastKey = split.pop(); for (var i = 0, len = split.length; i < len; i++){ name = split[i]; cursor = cursor[name] = cursor[name] || {}; } cursor[lastKey] = value; }
identifier_body
config.js
'use strict'; var yaml = require('js-yaml'); var fs = require('hexo-fs'); var pathFn = require('path'); function configConsole(args){ /* jshint validthis: true */ var key = args._[0]; var value = args._[1]; var self = this; if (!key){ console.log(this.config); return; } if (!value){ value ...
(obj, key){ var split = key.split('.'); var result = obj[split[0]]; for (var i = 1, len = split.length; i < len; i++){ result = result[split[i]]; } return result; } function setProperty(obj, key, value){ var split = key.split('.'); var cursor = obj; var name = ''; var lastKey = split.pop(); ...
getProperty
identifier_name
config.js
'use strict'; var yaml = require('js-yaml'); var fs = require('hexo-fs'); var pathFn = require('path'); function configConsole(args){ /* jshint validthis: true */ var key = args._[0]; var value = args._[1]; var self = this; if (!key){ console.log(this.config); return; } if (!value){ value ...
return fs.exists(configPath).then(function(exist){ if (!exist) return {}; return self.render.render({path: configPath}); }).then(function(config){ if (!config) config = {}; var result = ''; setProperty(config, key, castValue(value)); if (extname === '.json'){ result = JSON.stringify...
} var configPath = this.config_path; var extname = pathFn.extname(configPath);
random_line_split
BrowserPopout.js
import EventEmitter from '../utils/EventEmitter' import ConfigMinifier from '../utils/ConfigMinifier' import { fnBind, getUniqueId, } from '../utils/utils' import $ from 'jquery' /** * Pops a content item out into a new browser window. * This is achieved by * * - Creating a new configuration with the co...
() { this._popoutWindow.moveTo(this._dimensions.left, this._dimensions.top); this._popoutWindow.focus(); } /** * Callback when the new window is opened and the GoldenLayout instance * within it is initialised * * @returns {void} */ _onInitialised() { this.is...
_positionWindow
identifier_name
BrowserPopout.js
import EventEmitter from '../utils/EventEmitter' import ConfigMinifier from '../utils/ConfigMinifier' import { fnBind, getUniqueId, } from '../utils/utils' import $ from 'jquery' /** * Pops a content item out into a new browser window. * This is achieved by * * - Creating a new configuration with the co...
}
{ setTimeout(fnBind(this.emit, this, ['closed']), 50); }
identifier_body
BrowserPopout.js
import EventEmitter from '../utils/EventEmitter' import ConfigMinifier from '../utils/ConfigMinifier' import { fnBind, getUniqueId, } from '../utils/utils' import $ from 'jquery' /** * Pops a content item out into a new browser window. * This is achieved by * * - Creating a new configuration with the co...
localStorage.setItem(storageKey, JSON.stringify(config)); } catch (e) { throw new Error('Error while writing to localStorage ' + e.toString()); } urlParts = document.location.href.split('?'); // URL doesn't contain GET-parameters if (urlParts.length === ...
config = (new ConfigMinifier()).minifyConfig(config); try {
random_line_split
BrowserPopout.js
import EventEmitter from '../utils/EventEmitter' import ConfigMinifier from '../utils/ConfigMinifier' import { fnBind, getUniqueId, } from '../utils/utils' import $ from 'jquery' /** * Pops a content item out into a new browser window. * This is achieved by * * - Creating a new configuration with the co...
} /** * Returns the popped out item to its original position. If the original * parent isn't available anymore it falls back to the layout's topmost element */ popIn() { var childConfig, parentItem, index = this._indexInParent; if (this._parentId) { ...
{ try { this.getWindow().close(); } catch (e) { // } }
conditional_block
background.js
Array.prototype.equals = function(array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { // Check if we have nested arrays if ...
var prevVersion = localStorage['version']; function init() { const TWEETDECK_WEB_URL = 'https://tweetdeck.twitter.com'; /** * Step 2: Collate a list of all the open tabs. */ function gatherTabs(urls, itemInfos) { var allTheTabs = []; var windowsChecked = 0; console.log("gatherTabs", itemInfo...
{ localStorage['version'] = currVersion; }
conditional_block
background.js
Array.prototype.equals = function(array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { // Check if we have nested arrays if ...
function getVersion() { var details = chrome.app.getDetails(); return details.version; } var currVersion = getVersion(); if (!localStorage['version']) { localStorage['version'] = currVersion; } var prevVersion = localStorage['version']; function init() { const TWEETDECK_WEB_URL = 'https://tweetdeck.twitte...
{ chrome.tabs.create({ url: "options/options.html#updated" }); }
identifier_body
background.js
Array.prototype.equals = function(array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { // Check if we have nested arrays if ...
} for (var provider in DefaultSettings["providers"]) { if (currentOptions["providers"][provider] == undefined) { console.log("Adding", provider, "as a new provider with value", DefaultSettings["providers"][provider]); currentOptions["providers"][provider] = DefaultSettings["providers"][pr...
if (!(prevVersion.split(".")[0] == currVersion.split(".")[0] && prevVersion.split(".")[1] == currVersion.split(".")[1])) { onUpdate(); } localStorage['version'] = currVersion;
random_line_split
background.js
Array.prototype.equals = function(array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { // Check if we have nested arrays if ...
() { const TWEETDECK_WEB_URL = 'https://tweetdeck.twitter.com'; /** * Step 2: Collate a list of all the open tabs. */ function gatherTabs(urls, itemInfos) { var allTheTabs = []; var windowsChecked = 0; console.log("gatherTabs", itemInfos.timestamp); // First get all the windows... chro...
init
identifier_name
client.rs
extern crate getopts; use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt}; use std::string::{String}; use std::os; use std::str; use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; fn parse_int (input: &String) -> u32 { let val = match from_str::<u32>(input.as_slice()) { Some(0) =...
let socket = create_client_socket (&address, &port); //let response = make_request (socket); make_request (socket); }
random_line_split
client.rs
extern crate getopts; use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt}; use std::string::{String}; use std::os; use std::str; use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; fn parse_int (input: &String) -> u32 { let val = match from_str::<u32>(input.as_slice()) { Some(0) =...
() { let args = os::args(); let program = args.get(0).clone(); let opts = get_program_opts (); // bind the program options to arguments and then check // and set parameters in the program let matches = match getopts (args.as_slice(), opts.as_slice()) { Ok (m) => { if m.opt_present ("h") { print_usage (...
main
identifier_name
client.rs
extern crate getopts; use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt}; use std::string::{String}; use std::os; use std::str; use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; fn parse_int (input: &String) -> u32 { let val = match from_str::<u32>(input.as_slice()) { Some(0) =...
}; let port = match matches.opt_str("p") { Some (x) => x, None => fail!("Failed to read the port value.") }; let address = if matches.opt_present("a") { matches.opt_str("a").unwrap() } else { let k = String::from_str(""); println!("Address is Nil, settingo setting it too: {}", k); k }; let socket ...
{ fail!("Failed: {}", f); }
conditional_block
client.rs
extern crate getopts; use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt}; use std::string::{String}; use std::os; use std::str; use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; fn parse_int (input: &String) -> u32 { let val = match from_str::<u32>(input.as_slice()) { Some(0) =...
fn print_usage(program : String, optgroups: &[OptGroup]) { /* print a generated usage statement for this program 1) create the formated usage statement with the program name 2) use the str array of the resulting usage format and array of options from the OptGroup to create the help statement. */ let gener...
{ // Create an array of options that will be used by // this utility let opts /*-> Vec<getopts::OptGroup >*/ = vec![ reqopt("p", "port", "port to listen on", "PORT"), reqopt("a", "address", "interface to listen on", "ADDRESS"), optflag("h", "help", "print this help menu") ]; return opts; }
identifier_body
IUser.ts
import { UserStatus } from './UserStatus'; import { IRocketChatRecord } from './IRocketChatRecord'; export interface ILoginToken { hashedToken: string; twoFactorAuthorizedUntil?: Date; twoFactorAuthorizedHash?: string; } export interface IMeteorLoginToken extends ILoginToken { when: Date; } export interface IPer...
when: Date; } export interface IUserEmailCode { code: string; expire: Date; } type LoginToken = IMeteorLoginToken & IPersonalAccessToken; export type Username = string; export interface IUserServices { password?: { bcrypt: string; }; passwordHistory?: string[]; email?: { verificationTokens?: IUserEmailVer...
export interface IUserEmailVerificationToken { token: string; address: string;
random_line_split
lib.rs
#![crate_name = "bindgen"] #![crate_type = "dylib"] #![feature(quote, plugin_registrar, unboxed_closures, rustc_private, libc, std_misc, core)] extern crate syntax; extern crate rustc; extern crate libc; #[macro_use] extern crate log; use std::collections::HashSet; use std::default::Default; use std::io::{Write, self...
parser::parse(clang_opts, logger) } fn builtin_names() -> HashSet<String> { let mut names = HashSet::new(); let keys = [ "__va_list_tag", "__va_list", "__builtin_va_list", ]; keys.iter().all(|s| { names.insert(s.to_string()); true }); return names;...
override_enum_ty: str_to_ikind(&options.override_enum_ty[..]), clang_args: options.clang_args.clone(), };
random_line_split
lib.rs
#![crate_name = "bindgen"] #![crate_type = "dylib"] #![feature(quote, plugin_registrar, unboxed_closures, rustc_private, libc, std_misc, core)] extern crate syntax; extern crate rustc; extern crate libc; #[macro_use] extern crate log; use std::collections::HashSet; use std::default::Default; use std::io::{Write, self...
(self) -> Vec<P<ast::Item>> { self.module.items } pub fn to_string(&self) -> String { pprust::to_string(|s| { s.s = pp::mk_printer(Box::new(Vec::new()), 80); try!(s.print_mod(&self.module, &[])); s.print_remaining_comments() }) } pub fn writ...
into_ast
identifier_name
lib.rs
#![crate_name = "bindgen"] #![crate_type = "dylib"] #![feature(quote, plugin_registrar, unboxed_closures, rustc_private, libc, std_misc, core)] extern crate syntax; extern crate rustc; extern crate libc; #[macro_use] extern crate log; use std::collections::HashSet; use std::default::Default; use std::io::{Write, self...
pub fn to_string(&self) -> String { pprust::to_string(|s| { s.s = pp::mk_printer(Box::new(Vec::new()), 80); try!(s.print_mod(&self.module, &[])); s.print_remaining_comments() }) } pub fn write(&self, writer: &mut (Write + 'static)) -> io::Result<()> { ...
{ self.module.items }
identifier_body
bounding_box.rs
use crate::cube::Cube; use glium; use glium::{Display, Program, Surface, implement_vertex}; use glium::index::{IndexBuffer, PrimitiveType}; use std::rc::Rc; pub fn solid_fill_program(display: &Display) -> Program { let vertex_shader_src = include_str!("shaders/solid.vert"); let fragment_shader_src = include_st...
} } pub fn draw<U>(&self, frame: &mut glium::Frame, uniforms: &U) where U: glium::uniforms::Uniforms { let params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ...
{ let vertex_data = [ Vertex { position: [c.xmin, c.ymin, c.zmin] }, Vertex { position: [c.xmax, c.ymin, c.zmin] }, Vertex { position: [c.xmax, c.ymax, c.zmin] }, Vertex { position: [c.xmin, c.ymax, c.zmin] }, Vertex { position: [c.xmin, c.ymin, c.zmax...
identifier_body
bounding_box.rs
use crate::cube::Cube; use glium; use glium::{Display, Program, Surface, implement_vertex}; use glium::index::{IndexBuffer, PrimitiveType}; use std::rc::Rc; pub fn solid_fill_program(display: &Display) -> Program { let vertex_shader_src = include_str!("shaders/solid.vert"); let fragment_shader_src = include_st...
vertexes: glium::VertexBuffer<Vertex>, program: Rc<Program>, indices: IndexBuffer<u16>, } impl BoundingBox { pub fn new(display: &Display, c: &Cube, program: Rc<Program>) -> BoundingBox { let vertex_data = [ Vertex { position: [c.xmin, c.ymin, c.zmin] }, Vertex { positio...
pub struct BoundingBox {
random_line_split
bounding_box.rs
use crate::cube::Cube; use glium; use glium::{Display, Program, Surface, implement_vertex}; use glium::index::{IndexBuffer, PrimitiveType}; use std::rc::Rc; pub fn solid_fill_program(display: &Display) -> Program { let vertex_shader_src = include_str!("shaders/solid.vert"); let fragment_shader_src = include_st...
{ vertexes: glium::VertexBuffer<Vertex>, program: Rc<Program>, indices: IndexBuffer<u16>, } impl BoundingBox { pub fn new(display: &Display, c: &Cube, program: Rc<Program>) -> BoundingBox { let vertex_data = [ Vertex { position: [c.xmin, c.ymin, c.zmin] }, Vertex { posi...
BoundingBox
identifier_name
views.py
# -*- coding: utf-8 -*- """displays the root page""" ############################################################ # # Copyright 2010, 2014 Mohammed El-Afifi # This file is part of yabe. # # yabe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # ...
"""Display the site root page. `request` is the request invoking this view. """ return shortcuts.render_to_response('index.html')
identifier_body
views.py
# -*- coding: utf-8 -*- """displays the root page""" ############################################################ # # Copyright 2010, 2014 Mohammed El-Afifi # This file is part of yabe. # # yabe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # ...
(request): """Display the site root page. `request` is the request invoking this view. """ return shortcuts.render_to_response('index.html')
index
identifier_name
views.py
# -*- coding: utf-8 -*- """displays the root page""" ############################################################ # # Copyright 2010, 2014 Mohammed El-Afifi # This file is part of yabe. # # yabe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # ...
""" return shortcuts.render_to_response('index.html')
"""Display the site root page. `request` is the request invoking this view.
random_line_split
mlp.py
# -*- coding: utf-8 -*- import sys, os sys.path.insert(0, os.path.abspath('../..')) import unittest, pandas, numpy, datetime, itertools, mlp from sklearn import cross_validation, preprocessing class MLP(unittest.TestCase): """Test cases for Ibovespa tendency problem.""" grid_search = True def test_1(sel...
# Removes rows with NaN columns train.dropna(axis=0, how='any', inplace=True) test.dropna(axis=0, how='any', inplace=True) X_train = train[train.columns.tolist()[:-1]].as_matrix() y_train = train[train.columns.tolist()[-1:]].as_matrix() X_test = test[test.columns.tolist(...
nd = 0 if ibovespa_data["Close"] < ibovespa_data["Open"] else 1 start_date = ibovespa_data["Date"] + pandas.Timedelta('-1 days') end_date = ibovespa_data["Date"] + pandas.Timedelta('-1 days') mask = (stock_data['Date'] >= start_date) & (stock_data['Date'] <= end_date) st...
conditional_block
mlp.py
# -*- coding: utf-8 -*- import sys, os sys.path.insert(0, os.path.abspath('../..')) import unittest, pandas, numpy, datetime, itertools, mlp from sklearn import cross_validation, preprocessing class
(unittest.TestCase): """Test cases for Ibovespa tendency problem.""" grid_search = True def test_1(self): """Tests the accuracy of a MLP using k-folds validation method.""" # Read data from CSV files X_train, X_test, y_train, y_test = self.read_data() # Rescales data ...
MLP
identifier_name
mlp.py
# -*- coding: utf-8 -*- import sys, os sys.path.insert(0, os.path.abspath('../..')) import unittest, pandas, numpy, datetime, itertools, mlp from sklearn import cross_validation, preprocessing class MLP(unittest.TestCase): """Test cases for Ibovespa tendency problem.""" grid_search = True def test_1(sel...
def progress(self, percent): """Prints progress in stdout""" bar_length = 20 hashes = '#' * int(round(percent * bar_length)) spaces = ' ' * (bar_length - len(hashes)) sys.stdout.write("\rPerforming 5-folds grid search: [{0}] {1}%".format(hashes + spaces, int(round(percent * 10...
Hiperparameters for MLP""" hidden_layer_size = [{'hidden_layer_size':3},{'hidden_layer_size':5},{'hidden_layer_size':7}] learning_rate = [{'learning_rate':0.1},{'learning_rate':0.3},{'learning_rate':1}] grid = [] for hiperparams in itertools.product(hidden_layer_size, learning_r...
identifier_body
mlp.py
# -*- coding: utf-8 -*- import sys, os sys.path.insert(0, os.path.abspath('../..')) import unittest, pandas, numpy, datetime, itertools, mlp from sklearn import cross_validation, preprocessing class MLP(unittest.TestCase): """Test cases for Ibovespa tendency problem.""" grid_search = True def test_1(sel...
n_folds = 5 accuracies = map(lambda x: 0, self.hipergrid()) for idx, hiperparams in enumerate(self.hipergrid()): skf = cross_validation.StratifiedKFold(y_train.flatten(), n_folds=n_folds) for fold, (train_index, test_index) in enumerate(skf): self.progre...
random_line_split
regions-infer-paramd-indirect.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, b: @b<'self>) { self.f = b; } fn set_f_bad(&self, b: @b) { self.f = b; //~ ERROR mismatched types: expected `@@&'self int` but found `@@&int` } } fn main() {}
set_f_ok
identifier_name
regions-infer-paramd-indirect.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
type a<'self> = &'self int; type b<'self> = @a<'self>; struct c<'self> { f: @b<'self> } trait set_f { fn set_f_ok(&self, b: @b<'self>); fn set_f_bad(&self, b: @b); } impl<'self> set_f for c<'self> { fn set_f_ok(&self, b: @b<'self>) { self.f = b; } fn set_f_bad(&self, b: @b) { ...
random_line_split
regions-infer-paramd-indirect.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{}
identifier_body
server.rs
use chrono::prelude::*; use serde::{Deserialize, Serialize}; // use eyre::{ // // eyre, // Result, // // Context as _, // }; use printspool_json_store::{ Record }; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Server { pub id: crate::DbId, pub version: i32, pub created_at: DateTime...
fn deleted_at_mut(&mut self) -> &mut Option<DateTime<Utc>> { &mut self.deleted_at } }
random_line_split
server.rs
use chrono::prelude::*; use serde::{Deserialize, Serialize}; // use eyre::{ // // eyre, // Result, // // Context as _, // }; use printspool_json_store::{ Record }; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct
{ pub id: crate::DbId, pub version: i32, pub created_at: DateTime<Utc>, pub deleted_at: Option<DateTime<Utc>>, // Foreign Keys // Props pub name: String, /// True if the server row is the self-reference to this instance pub is_self: bool, } #[async_trait::async_trait] impl Record f...
Server
identifier_name