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
savaze.py
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want wit...
quality = '1080p' if '-1080p' in u or 'bluray-2' in u else '720p' if '-720p' in u or 'bluray' in u else 'SD' r = client.request(u) r = dom_parser2.parse_dom(r, 'ul', {'class': 'download-links'}) r = dom_parser2.parse_dom(r, 'a', req=['href...
for u in url: hostDict += [('clicknupload.org')]
random_line_split
savaze.py
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want wit...
except Exception: return def sources(self, url, hostDict, hostprDict): try: sources = [] for u in url: hostDict += [('clicknupload.org')] quality = '1080p' if '-1080p' in u or 'bluray-2' in u else '720p' if '-720p' in ...
try: urls = [] lst = ['1080p','720p','bluray-2','bluray'] clean_season = season if len(season) >= 2 else '0' + season clean_episode = episode if len(episode) >= 2 else '0' + episode for i in lst: url = urlparse.urljoin(self.base_l...
identifier_body
savaze.py
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want wit...
if not urls: return return urls except Exception: return def sources(self, url, hostDict, hostprDict): try: sources = [] for u in url: hostDict += [('clicknupload.org')] quality = '1080p' if '-...
r = client.request(url) if r: urls.append(url)
conditional_block
savaze.py
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want wit...
(self, url): return url
resolve
identifier_name
index.d.ts
// Type definitions for koa-compress v2.x // Project: https://github.com/koajs/compress // Definitions by: Jerry Chin <https://github.com/hellopao> // Definitions: https://github.com/hellopao/DefinitelyTyped /* =================== USAGE =================== import compress = require("koa-compress"); var Koa = ...
/** * An optional function that checks the response content type to decide whether to compress. By default, it uses compressible. */ filter?: (content_type: string) => boolean; /** * Minimum response size in bytes to compress. Default 1024 bytes or 1kb. */ ...
random_line_split
regexes.py
You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author(s): David Shea <dshea@redhat.com> # import re # Validation expressions # The full name field can contain anything except a colon. # The empty string allowed. GECOS_VAL...
# with a period, but it can end with one. # This regex uses negative lookahead and lookback assertions to enforce the # hyphen rules and make it way more confusing HOSTNAME_PATTERN_WITHOUT_ANCHORS = r'(?:(?!-)[A-Za-z0-9-]{1,63}(?<!-)(?:\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))*\.?)' # URL Hostname # This matches any hostname, ...
# must be between 1 and 63 characters, contain only alphanumeric characters or # hyphens, and may not start or end with a hyphen. The whole string cannot start
random_line_split
util.ts
import * as $ from 'jquery'; import { Timestamp } from 'index'; export const endlessWaiting = new Promise<void>(() => {}); export function waitDOMContentLoaded(): Promise<void> { return new Promise(resolve => { switch (document.readyState) { case 'interactive': case 'complete': { resolve(); break;...
export function clearStyles(element: HTMLElement | Node) { if ('jquery' in element) { throw new Error('`clearStyles` 함수는 인자로 DOM element만 받습니다.'); } const ele = element as HTMLElement; try { for (const child of Array.from(ele.querySelectorAll('*[style]'))) { child.removeAtt...
{ return new Promise(resolve => setTimeout(resolve, ms)); }
identifier_body
util.ts
import * as $ from 'jquery'; import { Timestamp } from 'index'; export const endlessWaiting = new Promise<void>(() => {}); export function waitDOMContentLoaded(): Promise<void> { return new Promise(resolve => { switch (document.readyState) { case 'interactive': case 'complete': { resolve(); break;...
export function matchAll(text: string, regex: RegExp) { const result = []; let match; do { match = regex.exec(text); if (match) result.push(match); } while (match); return result; }
random_line_split
util.ts
import * as $ from 'jquery'; import { Timestamp } from 'index'; export const endlessWaiting = new Promise<void>(() => {}); export function waitDOMContentLoaded(): Promise<void> { return new Promise(resolve => { switch (document.readyState) { case 'interactive': case 'complete': { resolve(); break;...
(element: HTMLElement | Node) { if ('jquery' in element) { throw new Error('`clearStyles` 함수는 인자로 DOM element만 받습니다.'); } const ele = element as HTMLElement; try { for (const child of Array.from(ele.querySelectorAll('*[style]'))) { child.removeAttribute('style'); } ...
clearStyles
identifier_name
test_adapters.py
from nose.plugins.attrib import attr from nose.tools import eq_, ok_ from django.contrib import messages as django_messages from django.test import RequestFactory from allauth.exceptions import ImmediateHttpResponse from allauth.socialaccount.models import SocialLogin, SocialAccount from kuma.core.urlresolvers impor...
# Verify the social_login receiver over-writes the provider # stored in the session self.adapter.pre_social_login(request, sociallogin) eq_(account.provider, request.session['sociallogin_provider'], "receiver should have over-written sociallogin_provider " ...
rf = RequestFactory() def setUp(self): """ extra setUp to make a working session """ super(KumaSocialAccountAdapterTestCase, self).setUp() self.adapter = KumaSocialAccountAdapter() @attr('bug1055870') def test_pre_social_login_overwrites_session_var(self): """ https://bugzi...
identifier_body
test_adapters.py
from nose.plugins.attrib import attr from nose.tools import eq_, ok_ from django.contrib import messages as django_messages from django.test import RequestFactory from allauth.exceptions import ImmediateHttpResponse from allauth.socialaccount.models import SocialLogin, SocialAccount from kuma.core.urlresolvers impor...
(self): """ https://bugzil.la/1055870 """ # Set up a pre-existing GitHub sign-in session request = self.rf.get('/') session = self.client.session session['sociallogin_provider'] = 'github' session.save() request.session = session # Set up a Persona Social...
test_pre_social_login_overwrites_session_var
identifier_name
test_adapters.py
from nose.plugins.attrib import attr from nose.tools import eq_, ok_ from django.contrib import messages as django_messages from django.test import RequestFactory from allauth.exceptions import ImmediateHttpResponse from allauth.socialaccount.models import SocialLogin, SocialAccount from kuma.core.urlresolvers impor...
session.save() request.session = session messages = self.get_messages(request) # Set up an un-matching Persona SocialLogin for request persona_account = SocialAccount(user=self.user_model(), provider='persona', ...
user=github_account.user) request = self.rf.get('/') session = self.client.session session['socialaccount_sociallogin'] = github_login.serialize()
random_line_split
kendo.culture.ca-ES.js
/* * Kendo UI v2014.2.1008 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial lice...
return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
random_line_split
SettingsController.js
(function () { var ns = $.namespace('pskl.controller.settings'); var settings = { 'user' : { template : 'templates/settings/preferences.html', controller : ns.PreferencesController }, 'resize' : { template : 'templates/settings/resize.html', controller : ns.resize.ResizeControll...
'import' : { template : 'templates/settings/import.html', controller : ns.ImportController }, 'localstorage' : { template : 'templates/settings/localstorage.html', controller : ns.LocalStorageController }, 'save' : { template : 'templates/settings/save.html', cont...
template : 'templates/settings/export.html', controller : ns.exportimage.ExportController },
random_line_split
SettingsController.js
(function () { var ns = $.namespace('pskl.controller.settings'); var settings = { 'user' : { template : 'templates/settings/preferences.html', controller : ns.PreferencesController }, 'resize' : { template : 'templates/settings/resize.html', controller : ns.resize.ResizeControll...
evt.stopPropagation(); evt.preventDefault(); }; ns.SettingsController.prototype.onBodyClick_ = function (evt) { var target = evt.target; var isInDrawerContainer = pskl.utils.Dom.isParent(target, this.drawerContainer); var isInSettingsIcon = target.dataset.setting; var isInSettingsContain...
{ this.closeDrawer_(); }
conditional_block
count_islands.py
""" A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connec...
0 0 0 Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. 1 1 0 0 0 1 Number of islands = 2 0 0 0 Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. 1 1 0 0 0 1 Number of islands = 3 0 1 0 """ class Solution(object): def num_islands2(self, m, n, positions): ans...
0 0 0 Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. 1 1 0 0 0 0 Number of islands = 1
random_line_split
count_islands.py
""" A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connec...
ans += [islands.count] return ans class Union(object): def __init__(self): self.id = {} self.sz = {} self.count = 0 def add(self, p): self.id[p] = p self.sz[p] = 1 self.count += 1 def root(self, i): while i != self.id[i]: ...
q = (p[0] + dp[0], p[1] + dp[1]) if q in islands.id: islands.unite(p, q)
conditional_block
count_islands.py
""" A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connec...
(self, i): while i != self.id[i]: self.id[i] = self.id[self.id[i]] i = self.id[i] return i def unite(self, p, q): i, j = self.root(p), self.root(q) if i == j: return if self.sz[i] > self.sz[j]: i, j = j, i self.id[i] = ...
root
identifier_name
count_islands.py
""" A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connec...
def root(self, i): while i != self.id[i]: self.id[i] = self.id[self.id[i]] i = self.id[i] return i def unite(self, p, q): i, j = self.root(p), self.root(q) if i == j: return if self.sz[i] > self.sz[j]: i, j = j, i ...
self.id[p] = p self.sz[p] = 1 self.count += 1
identifier_body
MinervaBot.py
from getpass import getpass from selenium import webdriver from selenium.common import exceptions from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdri...
EC.presence_of_element_located((By.ID, 'myModal')) ) # Aguarda o popup estar disponivel except exceptions.TimeoutException: pass else: popup = driver.find_element_by_css_selector( '.modal-footer > button[data-dismiss="modal"]') popup.send_keys(Keys.RETURN) # Acha a secao emprestimos e a...
# Acha o botao de fechar o popup e o fecha try: WebDriverWait(driver, 10).until(
random_line_split
MinervaBot.py
from getpass import getpass from selenium import webdriver from selenium.common import exceptions from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdri...
else: salvar = False print() return inputcpf, inputpassword, salvar def ler_dados(arquivo): file = open(arquivo, 'r') read = file.read() inputlist = read.split('\n') return inputlist[0], inputlist[1] def salvar_dados(arquivo, inputcpf, inputpassword, salvar): if not s...
salvar = True
conditional_block
MinervaBot.py
from getpass import getpass from selenium import webdriver from selenium.common import exceptions from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdri...
(salvar=None): # Pergunta ao usuario CPF e senha for label in driver.find_elements_by_tag_name('label'): if label.get_attribute('for') == 'pat_id': idcpf = driver.find_element_by_name('bor_id') inputcpf = input('%s ' % label.text) elif label.get_attribute('for') == 'pat_p...
inserir_dados
identifier_name
MinervaBot.py
from getpass import getpass from selenium import webdriver from selenium.common import exceptions from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdri...
def salvar_dados(arquivo, inputcpf, inputpassword, salvar): if not salvar: return file = open(arquivo, 'w') file.write('%s\n%s' % (inputcpf, inputpassword)) # Coloca o Chrome em modo headless options = Options() options.set_headless(True) # Abre o driver e entra na minerva driver = webdriver.Chrome(chro...
file = open(arquivo, 'r') read = file.read() inputlist = read.split('\n') return inputlist[0], inputlist[1]
identifier_body
reddit-data-extractor.py
import json from urllib import request import pymongo connection = pymongo.MongoClient('mongodb://localhost') db = connection.reddit stories = db.stories # stories.drop() # req = request.Request('http://www.reddit.com/r/technology/.json') # req.add_header('User-agent', 'Mozilla/5.0') # reddit_page = request.urlopen(r...
# # print('Adding reddit posts') # for item in parsed_reddit['data']['children']: # stories.insert_one(item['data']) # # print('Finished adding reddit posts') def find(): print('Keyword search started') query = {'title': {'$regex': 'apple|google', '$options': 'i'}} projection = {'title': 1, '_id': 0}...
# # parsed_reddit = json.loads(reddit_page.read().decode())
random_line_split
reddit-data-extractor.py
import json from urllib import request import pymongo connection = pymongo.MongoClient('mongodb://localhost') db = connection.reddit stories = db.stories # stories.drop() # req = request.Request('http://www.reddit.com/r/technology/.json') # req.add_header('User-agent', 'Mozilla/5.0') # reddit_page = request.urlopen(...
(): print('Keyword search started') query = {'title': {'$regex': 'apple|google', '$options': 'i'}} projection = {'title': 1, '_id': 0} try: cursor = stories.find(query, projection) except Exception as e: print('Unexpected error', type(e), e) for post in cursor: print(p...
find
identifier_name
reddit-data-extractor.py
import json from urllib import request import pymongo connection = pymongo.MongoClient('mongodb://localhost') db = connection.reddit stories = db.stories # stories.drop() # req = request.Request('http://www.reddit.com/r/technology/.json') # req.add_header('User-agent', 'Mozilla/5.0') # reddit_page = request.urlopen(...
find()
print('Keyword search started') query = {'title': {'$regex': 'apple|google', '$options': 'i'}} projection = {'title': 1, '_id': 0} try: cursor = stories.find(query, projection) except Exception as e: print('Unexpected error', type(e), e) for post in cursor: print(post)
identifier_body
reddit-data-extractor.py
import json from urllib import request import pymongo connection = pymongo.MongoClient('mongodb://localhost') db = connection.reddit stories = db.stories # stories.drop() # req = request.Request('http://www.reddit.com/r/technology/.json') # req.add_header('User-agent', 'Mozilla/5.0') # reddit_page = request.urlopen(...
find()
print(post)
conditional_block
iCellEditor.ts
import { Column } from "../entities/column"; import { RowNode } from "../entities/rowNode"; import { GridApi } from "../gridApi"; import { ColumnApi } from "../columnController/columnApi"; import { ColDef } from "../entities/colDef"; import { IPopupComponent } from "./iPopupComponent"; export interface ICellEditor { ...
// Callback to tell grid to stop editing the current cell. pass 'false' to prevent // navigation moving to the next cell if grid property enterMovesDownAfterEdit=true stopEditing: (suppressNavigateAfterEdit?: boolean) => void; // A reference to the DOM element representing the grid cell that your compon...
// callback to tell grid a key was pressed - useful to pass control key events (tab, // arrows etc) back to grid - however you do onKeyDown: (event: KeyboardEvent) => void;
random_line_split
data-table.js
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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...
var table; var headings; headings = getTableHeader(tableHeadings); $('#placeholder').html(template(headings)); var dataTableOptions = {}; dataTableOptions['data'] = tableData; dataTableOptions['order'] = [orderColumn]; if (!applist) { dataTableOptions['aoColumns'] = [ ...
var tableData = data.data; var tableHeadings = data.headings; var orderColumn = data.orderColumn; var applist = data.applist || undefined;
random_line_split
data-table.js
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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...
{'sWidth': '20%'} ]; } table = $('#table').dataTable(dataTableOptions); if (applist) { registerWebappSelect(table); } } function registerWebappSelect(table) { table.find('tbody').on('click', 'tr', function () { if ($(this).hasClass('selected')) { $...
{ var tableData = data.data; var tableHeadings = data.headings; var orderColumn = data.orderColumn; var applist = data.applist || undefined; var table; var headings; headings = getTableHeader(tableHeadings); $('#placeholder').html(template(headings)); var dataTableOptions = {}; ...
identifier_body
data-table.js
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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...
(startTime, endTime) { var url = pref.getString('dataSource'); var data = { start_time: start, end_time: end, node: node, action: pref.getString('appStatType') }; var appname = pref.getString('appname'); if (appname != '') { data.appname = appname; } ...
fetchData
identifier_name
data-table.js
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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...
else { th.colSpan = tableHeadings[i]["sub"].length; th.text = tableHeadings[i]['parent']; } row.push(th); } headingArray.push(row); if (rowSpan > 1) { row = []; for (i = 0, len = tableHeadings.length; i < len; i++) { if (tableHeadings[i]...
{ th.rowSpan = rowSpan; th.text = tableHeadings[i]; }
conditional_block
MonsterListStorageService.js
import MonsterData from '../../data/MonsterData'; import MonsterEncounterData from '../../data/MonsterEncounterData'; import MonsterEncounterStorageService from "./MonsterEncounterStorageService"; import MonsterListData from '../../data/MonsterListData'; import Prefix from "./Prefix"; import Q from "./Q"; import ...
if (!lists || lists.length === 0) continue; lists = lists.sort((a: MonsterListData, b: MonsterListData) => a.name.localeCompare(b.name)); lists.forEach((list, idx) => { list.order = idx; toSaveLists.push(list); ...
for (var encounterId of listMap.keys()) { let lists = listMap.get(encounterId);
random_line_split
MonsterListStorageService.js
import MonsterData from '../../data/MonsterData'; import MonsterEncounterData from '../../data/MonsterEncounterData'; import MonsterEncounterStorageService from "./MonsterEncounterStorageService"; import MonsterListData from '../../data/MonsterListData'; import Prefix from "./Prefix"; import Q from "./Q"; import ...
static createCustomList(name: string, hpexp: string, encounter: MonsterEncounterData): Promise<MonsterListData> { const newLisId = Prefix.createStorageId("MonsterListData"); const customMonsterId = Prefix.createCustomMonsterId(); const newList = new MonsterListData(newLisId, encounter...
{ const newList = new MonsterListData(null, encounterId, monsterId, name, 0); newList.order = getCurrentOrderValue(encounterId, storageData); return SyncStorageService.createData("MonsterListData", newList); }
identifier_body
MonsterListStorageService.js
import MonsterData from '../../data/MonsterData'; import MonsterEncounterData from '../../data/MonsterEncounterData'; import MonsterEncounterStorageService from "./MonsterEncounterStorageService"; import MonsterListData from '../../data/MonsterListData'; import Prefix from "./Prefix"; import Q from "./Q"; import ...
(name: string, hpexp: string, encounter: MonsterEncounterData): Promise<MonsterListData> { const newLisId = Prefix.createStorageId("MonsterListData"); const customMonsterId = Prefix.createCustomMonsterId(); const newList = new MonsterListData(newLisId, encounter.storageId, customMonsterId, na...
createCustomList
identifier_name
Peer.ts
import {EventEmitter} from "eventemitter3"; import {v4 as uuid} from "uuid"; import {ICall, RemotePeer} from "./RemotePeer"; export type RPCFn<T, Params, Response> = (client: T, params: Params) => Response; export const RESERVED_METHOD_NAMES = ["call", "open", "close"]; export abstract class Peer<T extends RemotePe...
try { const ret = this.methods[data.method](peer, data.params); if (ret && typeof ret.then === "function") { const prom = ret as Promise<any>; return prom.then((promRet) => { peer.respond(data.id, promRet); }, (err) =...
{ // Don't error if someone was listening at least if (this.listeners(data.method).length > 0) { return peer.respond(data.id, null); } return peer.error(data.id, `no such method ${data.method}`); }
conditional_block
Peer.ts
import {EventEmitter} from "eventemitter3"; import {v4 as uuid} from "uuid"; import {ICall, RemotePeer} from "./RemotePeer"; export type RPCFn<T, Params, Response> = (client: T, params: Params) => Response; export const RESERVED_METHOD_NAMES = ["call", "open", "close"]; export abstract class Peer<T extends RemotePe...
private onCall(peer: T, data: ICall) { if (data.method in RESERVED_METHOD_NAMES) { return peer.error(data.id, "no such method"); } // notify listeners for the method. these can't return anything this.emit(data.method, data.params); if (!(data.method in this.me...
{ this.methods[name] = method; }
identifier_body
Peer.ts
import {EventEmitter} from "eventemitter3"; import {v4 as uuid} from "uuid"; import {ICall, RemotePeer} from "./RemotePeer"; export type RPCFn<T, Params, Response> = (client: T, params: Params) => Response; export const RESERVED_METHOD_NAMES = ["call", "open", "close"]; export abstract class Peer<T extends RemotePe...
(peer: T) { delete this.peers[peer.id]; peer.removeListener("call"); peer.removeListener("close"); } public register<Params, Response>(name: string, method: RPCFn<T, Params, Response>) { this.methods[name] = method; } private onCall(peer: T, data: ICall) { if (...
removePeer
identifier_name
Peer.ts
import {EventEmitter} from "eventemitter3"; import {v4 as uuid} from "uuid"; import {ICall, RemotePeer} from "./RemotePeer"; export type RPCFn<T, Params, Response> = (client: T, params: Params) => Response; export const RESERVED_METHOD_NAMES = ["call", "open", "close"]; export abstract class Peer<T extends RemotePe...
if (this.listeners(data.method).length > 0) { return peer.respond(data.id, null); } return peer.error(data.id, `no such method ${data.method}`); } try { const ret = this.methods[data.method](peer, data.params); if (ret && typ...
// notify listeners for the method. these can't return anything this.emit(data.method, data.params); if (!(data.method in this.methods)) { // Don't error if someone was listening at least
random_line_split
xml_name.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of t...
def name(self, tag): return "{%s}%s" % (self._namespace, tag) class XmlNamer(object): """Initialize me with a DOM node or a DOM document node (the toplevel node you get when parsing an XML file). Then use me to generate fully qualified XML names. >>> xml = '<office:document-styles xmlns...
self._namespace = namespace
identifier_body
xml_name.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of t...
>>> xml = '<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"></office>' >>> from lxml import etree >>> namer = XmlNamer(etree.fromstring(xml)) >>> namer.name('office', 'blah') {urn:oasis:names:tc:opendocument:xmlns:office:1.0}blah >>> namer.name('office:bla...
toplevel node you get when parsing an XML file). Then use me to generate fully qualified XML names.
random_line_split
xml_name.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of t...
(self, namespace_shortcut, tag=None): # If the user doesn't pass an argument into 'tag' # then namespace_shortcut contains a tag of the form # 'short-namespace:tag' if tag is None: try: namespace_shortcut, tag = namespace_shortcut.split(':') except...
name
identifier_name
xml_name.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of t...
return "{%s}%s" % (self.nsmap[namespace_shortcut], tag) def namespace(self, namespace_shortcut): return XmlNamespace(self.nsmap[namespace_shortcut])
try: namespace_shortcut, tag = namespace_shortcut.split(':') except ValueError: # If there is no namespace in namespace_shortcut. tag = namespace_shortcut.lstrip("{}") return tag
conditional_block
urls.py
from __future__ import print_function from cms.sitemaps import CMSSitemap from django.conf.urls import * # NOQA from django.conf.urls.i18n import i18n_patterns from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.conf import settings from ImmOrbit.api import...
urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) + staticfiles_urlpatterns() + urlpatterns # NOQA
conditional_block
urls.py
from __future__ import print_function from cms.sitemaps import CMSSitemap from django.conf.urls import * # NOQA from django.conf.urls.i18n import i18n_patterns from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.conf import settings from ImmOrbit.api import...
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^select2/', include('django_select2.urls')), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^', include('...
urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), # NOQA
random_line_split
utils.py
"""Copyright 2008 Orbitz WorldWide 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, softwa...
raise KeyError def __contains__(self, key): try: self[key] return True except KeyError: return False def get(self, key, default=None): try: return self[key] except KeyError: return default def getlist(self...
if key in request.form: return request.form.getlist(key)[-1] if key in request.args: return request.args.getlist(key)[-1]
random_line_split
utils.py
"""Copyright 2008 Orbitz WorldWide 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, softwa...
return value if key in request.form: return request.form.getlist(key) return request.args.getlist(key) RequestParams = RequestParams() def hash_request(): keys = set() if request.json: keys.update(request.json.keys()) if request.form: keys.update(re...
value = [value]
conditional_block
utils.py
"""Copyright 2008 Orbitz WorldWide 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, softwa...
(delta): return abs(delta.seconds + delta.days * 86400) def epoch(dt): """ Returns the epoch timestamp of a timezone-aware datetime object. """ return calendar.timegm(dt.astimezone(pytz.utc).timetuple())
to_seconds
identifier_name
utils.py
"""Copyright 2008 Orbitz WorldWide 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, softwa...
def epoch(dt): """ Returns the epoch timestamp of a timezone-aware datetime object. """ return calendar.timegm(dt.astimezone(pytz.utc).timetuple())
return abs(delta.seconds + delta.days * 86400)
identifier_body
random_sources.py
# -*- coding: utf-8 -*- # -*- mode: python -*- """Sources of random data Copyright (C) 2013 Dan Meliza <dmeliza@uchicago.edu> Created Wed May 29 14:50:02 2013 """ from mspikes import util from mspikes.types import DataBlock, Source, Node, tag_set from numpy.random import RandomState class rand_samples(Source): ...
(self): t = 0 while t < self.nsamples: data = self.data(t) Node.send(self, data) yield data t += self.chunk_size ## TODO random_events # Variables: # End:
__iter__
identifier_name
random_sources.py
# -*- coding: utf-8 -*- # -*- mode: python -*- """Sources of random data Copyright (C) 2013 Dan Meliza <dmeliza@uchicago.edu> Created Wed May 29 14:50:02 2013 """ from mspikes import util from mspikes.types import DataBlock, Source, Node, tag_set from numpy.random import RandomState class rand_samples(Source): ...
## TODO random_events # Variables: # End:
t = 0 while t < self.nsamples: data = self.data(t) Node.send(self, data) yield data t += self.chunk_size
identifier_body
random_sources.py
# -*- coding: utf-8 -*- # -*- mode: python -*- """Sources of random data Copyright (C) 2013 Dan Meliza <dmeliza@uchicago.edu> Created Wed May 29 14:50:02 2013 """ from mspikes import util from mspikes.types import DataBlock, Source, Node, tag_set from numpy.random import RandomState class rand_samples(Source): ...
## TODO random_events # Variables: # End:
data = self.data(t) Node.send(self, data) yield data t += self.chunk_size
conditional_block
random_sources.py
# -*- coding: utf-8 -*- # -*- mode: python -*- """Sources of random data Copyright (C) 2013 Dan Meliza <dmeliza@uchicago.edu> Created Wed May 29 14:50:02 2013 """
class rand_samples(Source): """Generates random values from N(0,1)""" seed = 1 nsamples = 4096 def __init__(self, **options): util.set_option_attributes(self, options, seed=1, nsamples=4096) self.chunk_size = 1024 self.channel = "random" self.sampling_rate = 1 ...
from mspikes import util from mspikes.types import DataBlock, Source, Node, tag_set from numpy.random import RandomState
random_line_split
num_format.rs
::format_field::{FormatField, FieldType}; use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base}; use super::formatters::intf::Intf; use super::formatters::floatf::Floatf; use super::formatters::cninetyninehexfloatf::CninetyNineHexFloatf; use super::formatters::scif::Scif; use super::formatters::decf::Decf;...
} // if decimal, keep last zero if one exists // (it's possible for last zero to // not exist at this branch if we're in hex input) '.' => break, // other digit, etc. ...
{ ret.offset += 1; }
conditional_block
num_format.rs
::format_field::{FormatField, FieldType}; use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base}; use super::formatters::intf::Intf; use super::formatters::floatf::Floatf; use super::formatters::cninetyninehexfloatf::CninetyNineHexFloatf; use super::formatters::scif::Scif; use super::formatters::decf::Decf;...
(str_in_opt: Option<&String>) -> Option<u8> { const C_S_QUOTE: u8 = 39; const C_D_QUOTE: u8 = 34; match str_in_opt { Some(str_in) => { let mut byte_it = str_in.bytes(); if let Some(qchar) = byte_it.next() { match qchar { C_S_QUOTE | C_D_QUO...
get_provided
identifier_name
num_format.rs
super::format_field::{FormatField, FieldType}; use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base}; use super::formatters::intf::Intf; use super::formatters::floatf::Floatf; use super::formatters::cninetyninehexfloatf::CninetyNineHexFloatf; use super::formatters::scif::Scif; use super::formatters::decf:...
// whereas at that point octal knows its // current offset is not the final offset. match ch_zero { '0' => { if !(is_hex && first) { ret.offset += 1; ...
// first zero it does not move its offset // forward because it does not know for sure // that it's current offset (of that zero) // is not the final offset,
random_line_split
num_format.rs
::format_field::{FormatField, FieldType}; use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base}; use super::formatters::intf::Intf; use super::formatters::floatf::Floatf; use super::formatters::cninetyninehexfloatf::CninetyNineHexFloatf; use super::formatters::scif::Scif; use super::formatters::decf::Decf;...
// this function looks at the first few // characters of an argument and returns a value if we can learn // a value from that (e.g. no argument? return 0, char constant? ret value) fn get_provided(str_in_opt: Option<&String>) -> Option<u8> { const C_S_QUOTE: u8 = 39; const C_D_QUOTE: u8 = 34; match str_in...
{ match env::var("POSIXLY_CORRECT") { Ok(_) => {} Err(e) => { match e { env::VarError::NotPresent => { cli::err_msg(&format!("warning: {:?}: character(s) following character \ constant have been ignored", ...
identifier_body
main.rs
use std::env; // Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit. static DIGITS: [char; 26] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; fn main() { let inp...
fn has_straight_and_pairs(candidate: &Vec<char>) -> bool { let mut idx = 0; let mut pairs = 0; let mut straight = false; while idx < candidate.len() { straight |= is_straight(candidate, idx); if idx > 0 && candidate[idx] == candidate[idx - 1] { pairs += 1; idx +...
{ let chars : Vec<_> = candidate.chars().collect(); !candidate.contains('i') && !candidate.contains('o') && !candidate.contains('l') && has_straight_and_pairs(&chars) }
identifier_body
main.rs
use std::env; // Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit. static DIGITS: [char; 26] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; fn main() { let inp...
}; let next = find_next_password(&input); println!("found next valid password: {}", next); let next_next = find_next_password(&input); println!("found next next valid password: {}", next_next); } fn find_next_password(input: &str) -> String { let mut candidate = increment_string(&input); ...
{ println!("usage: day11 <input value>"); return }
conditional_block
main.rs
use std::env; // Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit. static DIGITS: [char; 26] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; fn main() { let inp...
pairs += 1; idx += 1; } idx += 1; } straight && pairs > 1 } fn is_straight(candidate: &Vec<char>, idx: usize) -> bool { idx > 1 && { let c = candidate[idx]; candidate[idx - 1] == std::char::from_u32(c as u32 - 1).unwrap() && candidate[idx ...
let mut straight = false; while idx < candidate.len() { straight |= is_straight(candidate, idx); if idx > 0 && candidate[idx] == candidate[idx - 1] {
random_line_split
main.rs
use std::env; // Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit. static DIGITS: [char; 26] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; fn main() { let inp...
(candidate: &str) -> bool { let chars : Vec<_> = candidate.chars().collect(); !candidate.contains('i') && !candidate.contains('o') && !candidate.contains('l') && has_straight_and_pairs(&chars) } fn has_straight_and_pairs(candidate: &Vec<char>) -> bool { let mut idx = 0; let mut ...
is_acceptable_password
identifier_name
event.rs
StreamServerCertificate, EventStreamToken}; use habitat_core::{package::ident::PackageIdent, service::HealthCheckInterval}; use nats_message_stream::{NatsMessage, NatsMessageStream}; use prost_types::Duration as ProstDuration; use rants::{Address,...
() { let (tx, rx) = futures_mpsc::unbounded(); NATS_MESSAGE_STREAM.set(NatsMessageStream(tx)); EVENT_CORE.set(EventCore { supervisor_id: String::from("supervisor_id"), ip_address: "127.0.0.1:8080".parse().unwrap(), fqdn: ...
health_check_event
identifier_name
event.rs
StreamServerCertificate, EventStreamToken}; use habitat_core::{package::ident::PackageIdent, service::HealthCheckInterval}; use nats_message_stream::{NatsMessage, NatsMessageStream}; use prost_types::Duration as ProstDuration; use rants::{Address,...
/// Publish an event. This is the main interface that client code will /// use. /// /// If `init_stream` has not been called already, this function will /// be a no-op. fn publish(subject: &'static Subject, mut event: impl EventMessage) { if let Some(stream) = NATS_MESSAGE_STREAM.try_get() { // TODO (CM):...
{ NATS_MESSAGE_STREAM.try_get().is_some() }
identifier_body
event.rs
StreamServerCertificate, EventStreamToken}; use habitat_core::{package::ident::PackageIdent, service::HealthCheckInterval}; use nats_message_stream::{NatsMessage, NatsMessageStream}; use prost_types::Duration as ProstDuration; use rants::{Address,...
} #[cfg(test)] mod tests { use super::{nats_message_stream::NatsMessageStream, *}; use crate::prost::Message; use futures::{channel::mpsc as futures_mpsc, stream::StreamExt}; #[cfg(windows)] use habitat_core::os::process::windows_child::ExitStatus; use habitat...
{ // TODO (CM): Yeah... this is looking pretty gross. The // intention is to be able to timestamp the events right as // they go out. // // We *could* set the time when we convert the EventCore to a // EventMetadata struct, but that seems odd. // // It pro...
conditional_block
event.rs
this can be avoided. #[derive(Clone, Debug, PartialEq)] pub struct EventStreamConfig { pub environment: String, pub application: String, pub site: Option<String>, pub meta: EventStreamMetadata, pub token: EventStreamToken, pub url: ...
random_line_split
server.js
'use strict'; // Dependencies const env = require('envalid'), express = require('express'), path = require('path'), app = express(); env.validate(process.env, { PORT: {required: false, parse: env.toNumber}, DOCKER_REGISTRY_HOST: {required: true},
app.set('port', port); const oneDay = 86400000; app.use(express.static(path.join(__dirname, 'public'), {maxAge: oneDay})); app.use((error, req, res, next) => { if (error) { res.json('Error validating json'); } else { next(); } }); app.use('/api', require('./api')); app.use((err, req...
DOCKER_REGISTRY_PORT: {required: true} }); const port = process.env.PORT || 3000;
random_line_split
server.js
'use strict'; // Dependencies const env = require('envalid'), express = require('express'), path = require('path'), app = express(); env.validate(process.env, { PORT: {required: false, parse: env.toNumber}, DOCKER_REGISTRY_HOST: {required: true}, DOCKER_REGISTRY_PORT: {required: true} }); con...
else { next(); } }); app.use('/api', require('./api')); app.use((err, req, res, next) => { console.error(err.stack); res.sendStatus(500); }); app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')); });
{ res.json('Error validating json'); }
conditional_block
express.js
var express = require('express'); bodyParser = require('body-parser'); cookieParser = require('cookie-parser'); methodOverride = require('method-override'); morgan = require('morgan'); compression = require('compression'); path = require('path'), jwt = require('jsonwebtoken'); request = ...
process.on('uncaughtException', function(err) { console.log(err); }); //configure express middleware app.use(express.static(path.join(__dirname,'../app/public'))); app.use(bodyParser.urlencoded({ extended:false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(co...
//json webtoken secret process.env.JWT_SECRET = 'SuperSecretGreenShoeCapital';
random_line_split
output.ts
/** * Copyright 2018 Google 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/licenses/LICENSE-2.0 * * Unless required by appli...
function getColorFromType(type: string, detectionString: string): string { const severity = typeTable[type]; switch (severity) { case 1: return chalk.greenBright(detectionString); case 2: return chalk.yellowBright(detectionString); case 3: return chalk.redBright(detectionString); ...
{ if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } if (semver.valid(a.version) && semver.valid(b.version)) { return semver.compare(a.version, b.version); } else { return a.version.localeCompare(b.version); } }
identifier_body
output.ts
/** * Copyright 2018 Google 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/licenses/LICENSE-2.0 * * Unless required by appli...
} function getColorFromType(type: string, detectionString: string): string { const severity = typeTable[type]; switch (severity) { case 1: return chalk.greenBright(detectionString); case 2: return chalk.yellowBright(detectionString); case 3: return chalk.redBright(detectionString); ...
{ return a.version.localeCompare(b.version); }
conditional_block
output.ts
/** * Copyright 2018 Google 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/licenses/LICENSE-2.0 * * Unless required by appli...
if (packageGraph.data.length > 0) { arrOfStrings.push(` Detected Patterns:`); const squashedDetections = squashDetections(packageGraph); for (const type of squashedDetections) { if (type[1] > 1) { arrOfStrings.push(getColorFromType( type[0], ` ${t...
` ${dataPoint.type} found in ${ dataPoint.fileName.split( 'node_modules/')[1]}:${dataPoint.position.lineStart}`)); }); } else {
random_line_split
output.ts
/** * Copyright 2018 Google 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/licenses/LICENSE-2.0 * * Unless required by appli...
( packageGraphs: Array<PackageGraph<PointOfInterest[]>>, verbose: boolean): string { const arrOfStrings: string[] = []; packageGraphs.forEach((packageGraph) => { arrOfStrings.push( `${packageGraph.name} ${packageGraph.version} Detections: ${ packageGraph.data.length} Immediate ${ ...
output
identifier_name
core_json.js
/* @author Zakai Hamilton @component CoreJson */ screens.core.json = function CoreJson(me, { core, storage }) { me.init = function () { if (me.platform === "server") { me.request = require("request"); } }; me.loadComponent = async function (path, useCache = true) { ...
} let item = me.traverse(root, path); if (item.found) { var value = item.value; if (typeof value === "object") { value = JSON.stringify(value); } return value; } return ""; ...
{ var info = core.property.split(object, path); let item = me.traverse(root, info.value); if (item.found) { return core.property.get(object, info.name, item.value); } return ""; }
conditional_block
core_json.js
/* @author Zakai Hamilton @component CoreJson */ screens.core.json = function CoreJson(me, { core, storage }) { me.init = function () { if (me.platform === "server") { me.request = require("request"); } }; me.loadComponent = async function (path, useCache = true) { ...
return json; }; me.compare = function (source, target) { if (typeof source !== typeof target) { return false; } if (source === target) { return true; } if (!source && !target) { return true; } if (!source || !tar...
if (buffer) { json = JSON.parse(buffer); } await storage.local.db.set(me.id, path, json);
random_line_split
tar.gz_test.js
"use strict"; /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) tes...
exports["targz"] = { setUp: function(done) { // setup here done(); }, "targz sqlite3": function(test) { test.expect(1); var actual; actual = fs.statSync("tmp/node_sqlite3.node"); test.equal(actual.size, 831488); test.done(); } };
random_line_split
detect_faces_tinyface.py
import matplotlib.pyplot as plt from bob.io.base import load from bob.io.base.test_utils import datafile from bob.io.image import imshow from bob.ip.facedetect.tinyface import TinyFacesDetector from matplotlib.patches import Rectangle # load colored test image color_image = load(datafile("test_image_multi_face.png", "...
else: # detect all faces detector = TinyFacesDetector() detections = detector.detect(color_image) imshow(color_image) plt.axis("off") for annotations in detections: topleft = annotations["topleft"] bottomright = annotations["bottomright"] size = bottomright[0] - tople...
imshow(color_image)
conditional_block
detect_faces_tinyface.py
import matplotlib.pyplot as plt from bob.io.base import load from bob.io.base.test_utils import datafile from bob.io.image import imshow from bob.ip.facedetect.tinyface import TinyFacesDetector from matplotlib.patches import Rectangle # load colored test image color_image = load(datafile("test_image_multi_face.png", "...
else: # detect all faces detector = TinyFacesDetector() detections = detector.detect(color_image) imshow(color_image) plt.axis("off") for annotations in detections: topleft = annotations["topleft"] bottomright = annotations["bottomright"] size = bottomright[0] - toplef...
imshow(color_image)
random_line_split
ycam.js
'); var isMobile = require('is-mobile'); // Import YCAM GRP Libraries var cam = require('nsc')( canvas, { position: [ 0.0, 2.5, -30.0 ], rotation: mat4.fromQuat( mat4.create(), quat.rotationTo( quat.create(), [ 0, 0, 1 ], [ 0, -0.25, 0 ] ) ), } ); var cga = require('cga'); var lgp = require('lgp'); var mda = requi...
// Setup Matricies var projection = mat4.create(); var normalm4 = mat4.create(); var normalm3 = mat3.create(); var view = mat4.create(); // Setup Shaders var vertexShader = glslify( './shaders/shader.vert' ); var fragmentShader = glslify( './shaders/shader.frag' ); var shader = glShader( gl, vertexShader, fragmentShad...
window.addEventListener( 'resize', fit( canvas, null, dpr ), false );
random_line_split
ycam.js
var isMobile = require('is-mobile'); // Import YCAM GRP Libraries var cam = require('nsc')( canvas, { position: [ 0.0, 2.5, -30.0 ], rotation: mat4.fromQuat( mat4.create(), quat.rotationTo( quat.create(), [ 0, 0, 1 ], [ 0, -0.25, 0 ] ) ), } ); var cga = require('cga'); var lgp = require('lgp'); var mda = require('...
() { // CatmullClarkOperator( meshOut ); TriangulateOperator( meshOut ); LoopSmoothOperator( meshOut ); buildGeometry(); } function createGeo( positions, cells ) { var newPositions = []; var newNormals = []; for( var i = 0; i < cells.length; i++ ) { var a = positions[ cells[ i ][ 0 ] ]; var b = ...
smooth
identifier_name
ycam.js
var isMobile = require('is-mobile'); // Import YCAM GRP Libraries var cam = require('nsc')( canvas, { position: [ 0.0, 2.5, -30.0 ], rotation: mat4.fromQuat( mat4.create(), quat.rotationTo( quat.create(), [ 0, 0, 1 ], [ 0, -0.25, 0 ] ) ), } ); var cga = require('cga'); var lgp = require('lgp'); var mda = require('...
// Set the canvas size to fill the window and its pixel density var mobile = isMobile( navigator.userAgent ); var dpr = mobile ? 1 : ( window.devicePixelRatio || 1 ); window.addEventListener( 'resize', fit( canvas, null, dpr ), false ); // Setup Matricies var projection = mat4.create(); var normalm4 = mat4.create();...
{ var geoPoints = glGeometry( gl ); geoPoints.attr( 'aPosition', positions ); return geoPoints; }
identifier_body
ycam.js
var isMobile = require('is-mobile'); // Import YCAM GRP Libraries var cam = require('nsc')( canvas, { position: [ 0.0, 2.5, -30.0 ], rotation: mat4.fromQuat( mat4.create(), quat.rotationTo( quat.create(), [ 0, 0, 1 ], [ 0, -0.25, 0 ] ) ), } ); var cga = require('cga'); var lgp = require('lgp'); var mda = require('...
shader.uniforms.uPointSize = 1.0; shader.uniforms.uProjection = projection; shader.uniforms.uView = view; shader.uniforms.uNormalMatrix = normalm3; shader.uniforms.uModel = model; shader.uniforms.uColor = color; geo.draw( gl.TRIANGLES ); geo.unbind(); } } function drawGeoPoints( geoP...
{ shader.uniforms.dpr = dpr; }
conditional_block
brand-list.component.ts
/** * Created by Deakin on 2017/5/8 0008. */ import {Component, ElementRef, OnInit} from '@angular/core'; import {Router, ActivatedRoute, Params} from '@angular/router'; import {FuncServer} from '../../../serv/func.server'; import {ApiCall} from '../../../http/api-call'; import {CityPickerServer} from '../../../com/c...
toreGoodsBrandInfo( this.goodsTypeId, this.modalData.name, this.modalData.e_name, this.modalData.file_id, this.modalData.url, this.modalData.story, this.modalData.described, () => { layer.msg("添加成功"); this.getStoreGoodsBrandList(1); this.toggleModa...
this.apiCall.addS
identifier_name
brand-list.component.ts
/** * Created by Deakin on 2017/5/8 0008. */ import {Component, ElementRef, OnInit} from '@angular/core'; import {Router, ActivatedRoute, Params} from '@angular/router'; import {FuncServer} from '../../../serv/func.server'; import {ApiCall} from '../../../http/api-call'; import {CityPickerServer} from '../../../com/c...
andList(curPageIndex?): void { if (curPageIndex) { this.curPageIndex = curPageIndex; } this.apiCall.getStoreGoodsBrandList( this.goodsTypeId, this.curPageIndex, this.perPageSize, (list, total) => { this.tableList = list; this.total = total; } ); } ...
this.funcServer.getContentHeight(this.elRef); this.perPageSize = this.funcServer.getPerPageSize(this.contentHeight); window.addEventListener('resize', () => { this.contentHeight = this.funcServer.getContentHeight(this.elRef); this.perPageSize = this.funcServer.getPerPageSize(this.contentHeight); ...
identifier_body
brand-list.component.ts
/** * Created by Deakin on 2017/5/8 0008. */ import {Component, ElementRef, OnInit} from '@angular/core'; import {Router, ActivatedRoute, Params} from '@angular/router'; import {FuncServer} from '../../../serv/func.server'; import {ApiCall} from '../../../http/api-call'; import {CityPickerServer} from '../../../com/c...
alShow; if (!this.modalShow) { this.modalData = { goods_brand_id: '', goods_type_id: '', type_name: '', name: '', e_name: '', file_id: '', url: '', story: '', described: '' } } } public addStoreGoodsBrandInfo(): void { ...
ncServer.deepCopy(item); } this.modalShow = !this.mod
conditional_block
brand-list.component.ts
/** * Created by Deakin on 2017/5/8 0008. */ import {Component, ElementRef, OnInit} from '@angular/core'; import {Router, ActivatedRoute, Params} from '@angular/router'; import {FuncServer} from '../../../serv/func.server'; import {ApiCall} from '../../../http/api-call'; import {CityPickerServer} from '../../../com/c...
} } }
}
random_line_split
server.js
import express from 'express'; import path from 'path'; let app = express(); /*** Webpack imports ***/ import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import config from './webpack.config.js'; const webpackOptions = { publicPath: config.output.publicPath, ...
module.exports = app;
console.log(`Listening on port: ${port}`); }); }
random_line_split
server.js
import express from 'express'; import path from 'path'; let app = express(); /*** Webpack imports ***/ import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import config from './webpack.config.js'; const webpackOptions = { publicPath: config.output.publicPath, ...
console.log(`Listening on port: ${port}`); }); } module.exports = app;
{ console.log(err); }
conditional_block
location.ts
import {LocationStrategy} from './location_strategy'; import {StringWrapper, isPresent, CONST_EXPR} from 'angular2/src/core/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async'; import {BaseException, isBlank} from 'angular2/src/core/facade/lang'; import {OpaqueToken, Injectable,...
function stripIndexHtml(url: string): string { if (/\/index.html$/g.test(url)) { // '/index.html'.length == 11 return url.substring(0, url.length - 11); } return url; } function stripTrailingSlash(url: string): string { if (/\/$/g.test(url)) { url = url.substring(0, url.length - 1); } return ...
{ if (!url.startsWith(baseHref)) { return baseHref + url; } return url; }
identifier_body
location.ts
import {LocationStrategy} from './location_strategy'; import {StringWrapper, isPresent, CONST_EXPR} from 'angular2/src/core/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async'; import {BaseException, isBlank} from 'angular2/src/core/facade/lang'; import {OpaqueToken, Injectable,...
forward(): void { this.platformStrategy.forward(); } back(): void { this.platformStrategy.back(); } subscribe(onNext: (value: any) => void, onThrow: (exception: any) => void = null, onReturn: () => void = null): void { ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); } }...
random_line_split
location.ts
import {LocationStrategy} from './location_strategy'; import {StringWrapper, isPresent, CONST_EXPR} from 'angular2/src/core/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async'; import {BaseException, isBlank} from 'angular2/src/core/facade/lang'; import {OpaqueToken, Injectable,...
this._baseHref = stripTrailingSlash(stripIndexHtml(browserBaseHref)); this.platformStrategy.onPopState( (_) => { ObservableWrapper.callNext(this._subject, {'url': this.path(), 'pop': true}); }); } path(): string { return this.normalize(this.platformStrategy.path()); } normalize(url: string): s...
{ throw new BaseException( `No base href set. Either provide a binding to "appBaseHrefToken" or add a base element.`); }
conditional_block
location.ts
import {LocationStrategy} from './location_strategy'; import {StringWrapper, isPresent, CONST_EXPR} from 'angular2/src/core/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async'; import {BaseException, isBlank} from 'angular2/src/core/facade/lang'; import {OpaqueToken, Injectable,...
(baseHref: string, url: string): string { if (baseHref.length > 0 && url.startsWith(baseHref)) { return url.substring(baseHref.length); } return url; } function _addBaseHref(baseHref: string, url: string): string { if (!url.startsWith(baseHref)) { return baseHref + url; } return url; } function st...
_stripBaseHref
identifier_name
previews.test.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
import { getPreviews } from './previews'; describe('previews', function () { it('should work', () => { const previews = getPreviews(); const keys = Array.from(previews.keys()).sort(); const valuesCount = keys.map((k) => previews.get(k)?.length); expect(keys).toEqual(['Arrows', 'Emojis', 'Geometries'...
random_line_split
commit_unittest.py
# Copyright (C) 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
from webkitpy.common.system.outputcapture import OutputCapture from webkitpy.common.system.executive import ScriptError from webkitpy.common.system.executive_mock import MockExecutive from webkitpy.tool.mocktool import MockOptions, MockTool from webkitpy.tool.steps.commit import Commit class CommitTest(unittest.Test...
import unittest
random_line_split
commit_unittest.py
# Copyright (C) 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
(unittest.TestCase): def _test_check_test_expectations(self, filename): capture = OutputCapture() options = MockOptions() options.git_commit = "" options.non_interactive = True tool = MockTool() tool.user = None # Will cause any access of tool.user to raise an excep...
CommitTest
identifier_name
commit_unittest.py
# Copyright (C) 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
expected_logs = """MOCK run_and_throw_if_fail: ['mock-check-webkit-style', '--diff-files', 'platform/chromium/%s'], cwd=/mock-checkout Committed r49824: <http://trac.webkit.org/changeset/49824> """ % filename capture.assert_outputs(self, step.run, [state], expected_logs=expected_logs) tool.exec...
def _test_check_test_expectations(self, filename): capture = OutputCapture() options = MockOptions() options.git_commit = "" options.non_interactive = True tool = MockTool() tool.user = None # Will cause any access of tool.user to raise an exception. step = Comm...
identifier_body
CAM-resnet.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: CAM-resnet.py import cv2 import sys import argparse import numpy as np import os import multiprocessing import tensorflow as tf from tensorpack import * from tensorpack.dataflow import dataset from tensorpack.tfutils import optimizer, gradproc from tensorpack.tfu...
def viz_cam(model_file, data_dir): ds = get_data('val') pred_config = PredictConfig( model=Model(), session_init=get_model_loader(model_file), input_names=['input', 'label'], output_names=['wrong-top1', 'group3new/bnlast/Relu', 'linearnew/W'], return_input=True ) ...
dataset_train = get_data('train') dataset_val = get_data('val') return TrainConfig( model=Model(), dataflow=dataset_train, callbacks=[ ModelSaver(), PeriodicTrigger(InferenceRunner(dataset_val, [ ClassificationError('wrong-top1', 'val-error-top1')...
identifier_body
CAM-resnet.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: CAM-resnet.py import cv2 import sys import argparse import numpy as np import os import multiprocessing import tensorflow as tf from tensorpack import * from tensorpack.dataflow import dataset from tensorpack.tfutils import optimizer, gradproc from tensorpack.tfu...
ds = BatchData(ds, BATCH_SIZE, remainder=not isTrain) return ds def get_config(): dataset_train = get_data('train') dataset_val = get_data('val') return TrainConfig( model=Model(), dataflow=dataset_train, callbacks=[ ModelSaver(), PeriodicTrigger(I...
ds = PrefetchDataZMQ(ds, min(25, multiprocessing.cpu_count()))
conditional_block
CAM-resnet.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: CAM-resnet.py import cv2 import sys import argparse import numpy as np import os import multiprocessing import tensorflow as tf from tensorpack import * from tensorpack.dataflow import dataset from tensorpack.tfutils import optimizer, gradproc from tensorpack.tfu...
images, labels = inp wrongs, convmaps, W = outp batch = wrongs.shape[0] for i in range(batch): if wrongs[i]: continue weight = W[:, [labels[i]]].T # 512x1 convmap = convmaps[i, :, :, :] # 512xhxw mergedmap = np.matmul(we...
random_line_split
CAM-resnet.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: CAM-resnet.py import cv2 import sys import argparse import numpy as np import os import multiprocessing import tensorflow as tf from tensorpack import * from tensorpack.dataflow import dataset from tensorpack.tfutils import optimizer, gradproc from tensorpack.tfu...
(ImageNetModel): def get_logits(self, image): cfg = { 18: ([2, 2, 2, 2], preresnet_basicblock), 34: ([3, 4, 6, 3], preresnet_basicblock), } defs, block_func = cfg[DEPTH] with argscope(Conv2D, use_bias=False, kernel_initializer=tf.varian...
Model
identifier_name
shortanswer.module.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
}
{ questionDelegate.registerHandler(handler); }
identifier_body