prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>4_4_Using_Cpp_NSGA.py<|end_file_name|><|fim▁begin|># This file is part of DEAP. # # DEAP is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # DEAP is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with DEAP. If not, see <http://www.gnu.org/licenses/>. import random from deap import algorithms from deap import base from deap import creator from deap import tools from deap import cTools import sortingnetwork as sn INPUTS = 6 def evalEvoSN(individual, dimension): network = sn.SortingNetwork(dimension, individual) return network.assess(), network.length, network.depth def genWire(dimension): return (random.randrange(dimension), random.randrange(dimension)) def genNetwork(dimension, min_size, max_size): size = random.randint(min_size, max_size) return [genWire(dimension) for i in xrange(size)] def mutWire(individual, dimension, indpb): for index, elem in enumerate(individual): if random.random() < indpb: individual[index] = genWire(dimension) def mutAddWire(individual, dimension): index = random.randint(0, len(individual)) individual.insert(index, genWire(dimension)) def mutDelWire(individual): index = random.randrange(len(individual)) del individual[index] creator.create("FitnessMin", base.Fitness, weights=(-1.0, -1.0, -1.0)) creator.create("Individual", list, fitness=creator.FitnessMin) toolbox = base.Toolbox() # Gene initializer toolbox.register("network", genNetwork, dimension=INPUTS, min_size=9, max_size=12) # Structure initializers toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.network) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", evalEvoSN, dimension=INPUTS) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", mutWire, dimension=INPUTS, indpb=0.05) toolbox.register("addwire", mutAddWire, dimension=INPUTS) toolbox.register("delwire", mutDelWire) toolbox.register("select", cTools.selNSGA2) <|fim▁hole|> population = toolbox.population(n=300) hof = tools.ParetoFront() stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("Avg", tools.mean) stats.register("Std", tools.std) stats.register("Min", min) stats.register("Max", max) CXPB, MUTPB, ADDPB, DELPB, NGEN = 0.5, 0.2, 0.01, 0.01, 40 # Evaluate every individuals fitnesses = toolbox.map(toolbox.evaluate, population) for ind, fit in zip(population, fitnesses): ind.fitness.values = fit hof.update(population) stats.update(population) # Begin the evolution for g in xrange(NGEN): print "-- Generation %i --" % g offspring = [toolbox.clone(ind) for ind in population] # Apply crossover and mutation for ind1, ind2 in zip(offspring[::2], offspring[1::2]): if random.random() < CXPB: toolbox.mate(ind1, ind2) del ind1.fitness.values del ind2.fitness.values # Note here that we have a different sheme of mutation than in the # original algorithm, we use 3 different mutations subsequently. for ind in offspring: if random.random() < MUTPB: toolbox.mutate(ind) del ind.fitness.values if random.random() < ADDPB: toolbox.addwire(ind) del ind.fitness.values if random.random() < DELPB: toolbox.delwire(ind) del ind.fitness.values # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit print " Evaluated %i individuals" % len(invalid_ind) population = toolbox.select(population+offspring, len(offspring)) hof.update(population) stats.update(population) print " Min %s" % stats.Min[0][-1][0] print " Max %s" % stats.Max[0][-1][0] print " Avg %s" % stats.Avg[0][-1][0] print " Std %s" % stats.Std[0][-1][0] best_network = sn.SortingNetwork(INPUTS, hof[0]) print best_network print best_network.draw() print "%i errors, length %i, depth %i" % hof[0].fitness.values return population, stats, hof if __name__ == "__main__": main()<|fim▁end|>
def main(): random.seed(64)
<|file_name|>AnalogClockLCD.py<|end_file_name|><|fim▁begin|># original code is from openmips gb Team: [OMaClockLcd] Renderer # # Thx to arn354 # import math from Components.Renderer.Renderer import Renderer from skin import parseColor from enigma import eCanvas, eSize, gRGB, eRect class AnalogClockLCD(Renderer): def __init__(self): Renderer.__init__(self) self.fColor = gRGB(255, 255, 255, 0) self.fColors = gRGB(255, 0, 0, 0) self.fColorm = gRGB(255, 0, 0, 0) self.fColorh = gRGB(255, 255, 255, 0) self.bColor = gRGB(0, 0, 0, 255) self.forend = -1 self.linewidth = 1 self.positionheight = 1 self.positionwidth = 1 self.linesize = 1 GUI_WIDGET = eCanvas def applySkin(self, desktop, parent): attribs = [] for (attrib, what,) in self.skinAttributes: if (attrib == 'hColor'): self.fColorh = parseColor(what) elif (attrib == 'mColor'): self.fColorm = parseColor(what) elif (attrib == 'sColor'): self.fColors = parseColor(what) elif (attrib == 'linewidth'): self.linewidth = int(what) elif (attrib == 'positionheight'): self.positionheight = int(what) elif (attrib == 'positionwidth'): self.positionwidth = int(what) elif (attrib == 'linesize'): self.linesize = int(what) else: attribs.append((attrib, what)) self.skinAttributes = attribs return Renderer.applySkin(self, desktop, parent) def calc(self, w, r, m, m1):<|fim▁hole|> return ((m + x), (m1 - y)) def hand(self, opt): width = self.positionwidth height = self.positionheight r = (width / 2) r1 = (height / 2) if opt == 'sec': self.fColor = self.fColors elif opt == 'min': self.fColor = self.fColorm else: self.fColor = self.fColorh (endX, endY,) = self.calc(self.forend, self.linesize, r, r1) self.line_draw(r, r1, endX, endY) def line_draw(self, x0, y0, x1, y1): steep = (abs((y1 - y0)) > abs((x1 - x0))) if steep: x0, y0 = y0, x0 x1, y1 = y1, x1 if (x0 > x1): x0, x1 = x1, x0 y0, y1 = y1, y0 if (y0 < y1): ystep = 1 else: ystep = -1 deltax = (x1 - x0) deltay = abs((y1 - y0)) error = (-deltax / 2) y = int(y0) for x in range(int(x0), (int(x1) + 1)): if steep: self.instance.fillRect(eRect(y, x, self.linewidth, self.linewidth), self.fColor) else: self.instance.fillRect(eRect(x, y, self.linewidth, self.linewidth), self.fColor) error = (error + deltay) if (error > 0): y = (y + ystep) error = (error - deltax) def changed(self, what): opt = (self.source.text).split(',') try: sopt = int(opt[0]) if len(opt) < 2: opt.append('') except Exception as e: return if (what[0] == self.CHANGED_CLEAR): pass elif self.instance: self.instance.show() if (self.forend != sopt): self.forend = sopt self.instance.clear(self.bColor) self.hand(opt[1]) def parseSize(self, str): (x, y,) = str.split(',') return eSize(int(x), int(y)) def postWidgetCreate(self, instance): for (attrib, value,) in self.skinAttributes: if ((attrib == 'size') and self.instance.setSize(self.parseSize(value))): pass self.instance.clear(self.bColor)<|fim▁end|>
a = (w * 6) z = (math.pi / 180) x = int(round((r * math.sin((a * z))))) y = int(round((r * math.cos((a * z)))))
<|file_name|>index.js<|end_file_name|><|fim▁begin|>var express = require('express'); var request = require('request'); // Constants var PORT = 8080; // App var app = express(); app.get('/', function (req, res) { res.send('A prototype of a micro-service hosting service. An example can be retrieved from https://funcist.ns.mg/7c9600b9d2a5f3b991ab\n'); }); app.get('/:gist_id', function (req, res) { request({<|fim▁hole|> headers: { 'User-Agent': 'request' } }, function(error, response, body) { var files = JSON.parse(body).files; var filename = Object.keys(files)[0]; var content = files[filename].content; var m = new module.constructor(); m._compile(content, filename); res.send(m.exports); }); }); app.listen(PORT); console.log('Running on http://localhost:' + PORT);<|fim▁end|>
url: 'https://api.github.com/gists/' + req.params.gist_id,
<|file_name|>test_controller.py<|end_file_name|><|fim▁begin|>import unittest import syzoj import hashlib from random import randint class TestRegister(unittest.TestCase):<|fim▁hole|> def test_register(self): user = "tester_%d" % randint(1, int(1e9)) pw = self.md5_pass("123_%d" % randint(1, 100)) email = "84%[email protected]" % randint(1, 10000) print user, pw, email self.assertEqual(syzoj.controller.register(user, pw, email), 1) self.assertNotEqual(syzoj.controller.register(user, pw, email), 1) def test_multiple_register(self): rid = randint(1, 10000) for i in range(1, 2): pw = self.md5_pass("123_%d_%d" % (rid, i)) print i, pw self.assertEqual(syzoj.controller.register("hello_%d_%d" % (rid, i), pw, "%[email protected]" % i), 1) if __name__ == "__main__": unittest.main()<|fim▁end|>
def md5_pass(self, password): md5 = hashlib.md5() md5.update(password) return md5.hexdigest()
<|file_name|>other.d.ts<|end_file_name|><|fim▁begin|>declare module 'all:part:@sanity/base/absolutes' { const components: React.ComponentType[] export default components } declare module 'all:part:@sanity/base/component' declare module 'all:part:@sanity/desk-tool/filter-fields-fn?' { declare const filterFields: Observable[] export default filterFields } declare module 'part:@sanity/desk-tool/filter-fields-fn?' { import type {Observable} from 'rxjs' declare const filterField: Observable<{ (type: ObjectSchemaTypeWithOptions, field: ObjectField): boolean }> export default filterField } declare module 'all:part:@sanity/base/diff-resolver' { type DiffComponent = React.ComponentType<unknown> type DiffResolver = (schemaType: unknown) => DiffComponent | undefined const diffResolvers: DiffResolver[] export default diffResolvers } declare module 'all:part:@sanity/base/schema-type' declare module 'all:part:@sanity/base/tool' { const tools: { canHandleIntent?: ( intent: Record<string, any>, params: Record<string, any>, state: Record<string, any> ) => void component?: React.ComponentType<{tool: string}> icon?: React.ComponentType getIntentState?: ( intent: Record<string, any>, params: Record<string, any>, state: Record<string, any>, payload: Record<string, any> ) => void name: string title: string router?: Record<string, any> }[] export default tools } declare module 'part:@sanity/base/actions/utils' declare module 'part:@sanity/base/app-loading-screen' { const AppLoadingScreen: React.ComponentType<{text: React.ReactNode}> export default AppLoadingScreen } declare module 'part:@sanity/base/arrow-drop-down' declare module 'part:@sanity/base/arrow-right' declare module 'part:@sanity/base/asset-url-builder' declare module 'part:@sanity/base/authentication-fetcher' { interface Role { name: string title: string description: string } interface CurrentUser { id: string name: string email: string profileImage?: string provider?: string role: string | null roles: Role[] } interface Provider { name: string title: string url: string } const fetcher: { getProviders: () => Promise<Provider[]> getCurrentUser: () => Promise<CurrentUser | null> logout: () => Promise<void> } export default fetcher } declare module 'part:@sanity/base/brand-logo' { declare const BrandLogo: React.ComponentType export default BrandLogo } declare module 'part:@sanity/base/brand-logo?' { declare const BrandLogo: React.ComponentType | undefined export default BrandLogo } declare module 'part:@sanity/base/client' { import type {ClientConfig, SanityClient, SanityClient} from '@sanity/client' type StudioClient = SanityClient & {withConfig: (config: Partial<ClientConfig>) => SanityClient} declare const client: StudioClient export default client } declare module 'part:@sanity/base/client?' { import type client from 'part:@sanity/base/client' type StudioClient = SanityClient & {withConfig: (config: Partial<ClientConfig>) => SanityClient} declare const client: StudioClient | void export default maybeClient } declare module 'part:@sanity/base/configure-client?' { import type {SanityClient as OriginalSanityClient} from '@sanity/client' type Configurer = ( client: OriginalSanityClient ) => OriginalSanityClient & {withConfig: (config: Partial<ClientConfig>) => SanityClient} const configure: Configurer | undefined export default configure } declare module 'part:@sanity/base/document' declare module 'part:@sanity/base/document-actions/resolver' declare module 'part:@sanity/base/document-badges/resolver' declare module 'part:@sanity/base/initial-value-templates' declare module 'part:@sanity/base/initial-value-templates?' declare module 'part:@sanity/base/language-resolver' declare module 'part:@sanity/base/location' { declare const locationStore: { actions: {navigate: (newUrl: string, options: Record<string, any>) => void} state: Observable<any> } export default locationStore } declare module 'part:@sanity/base/login-dialog' declare module 'part:@sanity/base/login-dialog-content' declare module 'part:@sanity/base/login-wrapper?' { declare const Component: | React.ComponentType<{ LoadingScreen: React.ReactNode }> | undefined export default Component } declare module 'part:@sanity/base/new-document-structure' { declare const newDocumentStructure: Record<string, any> export default newDocumentStructure } declare module 'part:@sanity/base/new-document-structure?' { declare const newDocumentStructure: Record<string, any> | undefined export default newDocumentStructure } declare module 'part:@sanity/base/preview' { import type {ImageUrlFitMode, Reference, SanityDocument, SchemaType} from '_self_' import type {Observable} from 'rxjs' export type MediaDimensions = { width?: number height?: number fit?: ImageUrlFitMode aspect?: number dpr?: number } type PreviewLayoutKey = 'default' | 'card' | 'media' | 'detail' | 'inline' | 'block' interface PreviewProps<LayoutKey = PreviewLayoutKey> { children?: React.ReactNode extendedPreview?: unknown isPlaceholder?: boolean mediaDimensions?: MediaDimensions media?: | React.ReactNode | React.FC<{ dimensions: MediaDimensions layout: LayoutKey }> progress?: number status?: React.ReactNode | React.FC<{layout: LayoutKey}> title?: React.ReactNode | React.FC<{layout: LayoutKey}> subtitle?: React.ReactNode | React.FC<{layout: LayoutKey}> description?: React.ReactNode | React.FC<{layout: LayoutKey}> } declare const PreviewBase: React.ComponentType<{ type?: SchemaType fields?: string[] value: any children?: (props: any) => React.ComponentType layout: 'default' | 'card' | 'media' | 'detail' | 'inline' | 'block' }> type previewObserver = ( value: Reference | string, schemaType: SchemaType ) => Observable<{snapshot: {title: string}}> export const observeForPreview: previewObserver export const observePaths: (id: string, paths: string[]) => Observable<Record<string, string>> export const SanityDefaultPreview: React.ComponentType< { _renderAsBlockImage?: boolean icon?: React.ComponentType<any> | false layout?: 'default' | 'card' | 'media' | 'detail' | 'inline' | 'block' value: Partial<SanityDocument> } & PreviewProps > export const PreviewFields: React.ComponentType<{ document: SanityDocument fields: string | string[] layout?: 'inline' | 'block' | 'default' | 'card' | 'media' | 'detail' type: SchemaType children: (snapshot: SanityDocument) => React.ReactElement }> export default PreviewBase } declare module 'part:@sanity/base/preview?' { import type {SchemaType} from '_self_' const Preview: React.ComponentType<{ layout: 'default' status: React.ReactNode type: SchemaType value: Record<string, any> }> export default Preview } declare module 'part:@sanity/base/preview-resolver' declare module 'part:@sanity/base/preview-resolver?' declare module 'part:@sanity/base/project-fetcher' declare module 'part:@sanity/base/query-container' declare module 'part:@sanity/base/root' declare module 'part:@sanity/base/router' { export { IntentLink, StateLink, RouteScope, RouterProvider, Link, HOCRouter, resolvePathFromState, resolveStateFromPath, route, Router, RouterContext, useRouter, useRouterState, withRouterHOC, } from '@sanity/base/src/router' } declare module 'part:@sanity/base/sanity-logo' declare module 'part:@sanity/base/sanity-logo-alpha' declare module 'part:@sanity/base/sanity-root' declare module 'part:@sanity/base/sanity-studio-logo' declare module 'part:@sanity/base/schema' { import type {SchemaType} from '_self_' interface Schema { _validation: { path: Array<string | number | {_key: string}> problems: {message: string; severity: string}[] }[] name: string get: (typeName: string) => SchemaType | undefined has: (typeName: string) => boolean getTypeNames(): string[] } const schema: Schema export default schema } declare module 'part:@sanity/base/schema?' { import type schema from 'part:@sanity/base/schema' declare const maybeSchema: typeof schema | void export default maybeSchema } declare module 'part:@sanity/base/schema-creator' declare module 'part:@sanity/base/schema-type' declare module 'part:@sanity/base/search' { import type {Observable} from 'rxjs' declare const search: (queryStr: string) => Observable export default search } declare module 'part:@sanity/base/search/weighted' declare module 'part:@sanity/base/settings' { export interface SettingsNamespace<ValueType> { forKey: ( key: string ) => { listen: (defaultValue?: ValueType) => Observable<ValueType> set: (val: ValueType) => void } forNamespace: (namespaceKey: string | null) => SettingsNamespace<ValueType> } export interface SettingsStore { forNamespace: <ValueType>(namespaceKey: string) => SettingsNamespace<ValueType> } declare const settings: SettingsStore export default settings } declare module 'part:@sanity/base/tool' declare module 'part:@sanity/base/user' declare module 'part:@sanity/base/grants' declare module 'part:@sanity/base/util/document-action-utils' { export const isActionEnabled: (schema: Schema, actionName: string) => boolean } declare module 'part:@sanity/base/util/draft-utils' { export declare const collate: ( documents: SanityDocument[] ) => {id: string; draft?: SanityDocument; published?: SanityDocument}[] export declare const getPublishedId: (str: string) => string<|fim▁hole|> declare module 'part:@sanity/base/util/search-utils' declare module 'part:@sanity/base/version-checker' { const VersionChecker: { checkVersions: () => Promise<{ result: { outdated: { name: string latest: string severity: 'notice' | 'low' | 'medium' | 'high' version: string }[] isSupported: boolean isUpToDate: boolean } }> } export default VersionChecker } declare module 'part:@sanity/base/with-referring-documents'<|fim▁end|>
export declare const getDraftId: (str: string) => string export declare const isDraftId: (str: string) => boolean export declare const isPublishedId: (str: string) => boolean }
<|file_name|>mthreading.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 ######################################################################### # File Name: mthreading.py # Author: ly # Created Time: Wed 05 Jul 2017 08:46:57 PM CST # Description: ######################################################################### # -*- coding: utf-8 -*- import time import threading def play(name,count): for i in range(1,count): print('%s %d in %d' %(name, i, count)) time.sleep(1) return <|fim▁hole|> # 设置为守护线程 t1.setDaemon(True) t1.start() print("main") # 等待子线程结束 t1.join() exit(1)<|fim▁end|>
if __name__=='__main__': t1=threading.Thread(target=play, args=('t1',10))
<|file_name|>bitcoin_zh_TW.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_TW" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About GulfCoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;GulfCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;位元幣&lt;/b&gt;版本</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> 這是一套實驗性的軟體. 此軟體是依據 MIT/X11 軟體授權條款散布, 詳情請見附帶的 COPYING 檔案, 或是以下網站: http://www.opensource.org/licenses/mit-license.php. 此產品也包含了由 OpenSSL Project 所開發的 OpenSSL Toolkit (http://www.openssl.org/) 軟體, 由 Eric Young ([email protected]) 撰寫的加解密軟體, 以及由 Thomas Bernard 所撰寫的 UPnP 軟體.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>版權</translation> </message> <message> <location line="+0"/> <source>The GulfCoin developers</source> <translation>位元幣開發人員</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>位址簿</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>點兩下來修改位址或標記</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>產生新位址</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>複製目前選取的位址到系統剪貼簿</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>新增位址</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your GulfCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>這些是你用來收款的位元幣位址. 你可以提供不同的位址給不同的付款人, 來追蹤是誰支付給你.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>複製位址</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>顯示 &amp;QR 條碼</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a GulfCoin address</source> <translation>簽署訊息是用來證明位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>從列表中刪除目前選取的位址</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified GulfCoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>刪除</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your GulfCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>這是你用來付款的位元幣位址. 在付錢之前, 務必要檢查金額和收款位址是否正確.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>編輯</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>付錢</translation> </message> <message> <location line="+265"/> <source>Export Address Book Data</source> <translation>匯出位址簿資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號區隔資料檔 (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入檔案 %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(沒有標記)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>密碼對話視窗</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>輸入密碼</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>新的密碼</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>重複新密碼</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>輸入錢包的新密碼.&lt;br/&gt;請用&lt;b&gt;10個以上的字元&lt;/b&gt;, 或是&lt;b&gt;8個以上的單字&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>錢包加密</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>這個動作需要用你的錢包密碼來解鎖</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>錢包解鎖</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>這個動作需要用你的錢包密碼來解密</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>錢包解密</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>變更密碼</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>輸入錢包的新舊密碼.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>錢包加密確認</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>警告: 如果將錢包加密後忘記密碼, 你會&lt;b&gt;失去其中所有的位元幣&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>你確定要將錢包加密嗎?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>重要: 請改用新產生有加密的錢包檔, 來取代之前錢包檔的備份. 為了安全性的理由, 當你開始使用新的有加密的錢包時, 舊錢包的備份就不能再使用了.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>警告: 大寫字母鎖定作用中!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>錢包已加密</translation> </message> <message> <location line="-56"/> <source>GulfCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your gulfcoins from being stolen by malware infecting your computer.</source> <translation>位元幣現在要關閉以完成加密程序. 請記住, 加密錢包無法完全防止入侵電腦的惡意程式偷取你的位元幣.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>錢包加密失敗</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>錢包加密因程式內部錯誤而失敗. 你的錢包還是沒有加密.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>提供的密碼不符.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>錢包解鎖失敗</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>用來解密錢包的密碼輸入錯誤.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>錢包解密失敗</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>錢包密碼變更成功.</translation> </message> </context> <context> <name>GulfCoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+254"/> <source>Sign &amp;message...</source> <translation>訊息簽署...</translation> </message> <message> <location line="+246"/> <source>Synchronizing with network...</source> <translation>網路同步中...</translation> </message> <message> <location line="-321"/> <source>&amp;Overview</source> <translation>總覽</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>顯示錢包一般總覽</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>交易</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>瀏覽交易紀錄</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>編輯位址與標記的儲存列表</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>顯示收款位址的列表</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>結束</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>結束應用程式</translation> </message> <message> <location line="+7"/> <source>Show information about GulfCoin</source> <translation>顯示位元幣相關資訊</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>關於 &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>顯示有關於 Qt 的資訊</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>選項...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation>錢包加密...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>錢包備份...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>密碼變更...</translation> </message> <message> <location line="+251"/> <source>Importing blocks from disk...</source> <translation>從磁碟匯入區塊中...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>重建磁碟區塊索引中...</translation> </message> <message> <location line="-319"/> <source>Send coins to a GulfCoin address</source> <translation>付錢到位元幣位址</translation> </message> <message> <location line="+52"/> <source>Modify configuration options for GulfCoin</source> <translation>修改位元幣的設定選項</translation> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>將錢包備份到其它地方</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>變更錢包加密用的密碼</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>除錯視窗</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>開啓除錯與診斷主控台</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>驗證訊息...</translation> </message> <message> <location line="-183"/> <location line="+6"/> <location line="+508"/> <source>GulfCoin</source> <translation>位元幣</translation> </message> <message> <location line="-514"/> <location line="+6"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+107"/> <source>&amp;Send</source> <translation>付出</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>收受</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>位址</translation> </message> <message> <location line="+23"/> <location line="+2"/> <source>&amp;About GulfCoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+10"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation>顯示或隱藏</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>顯示或隱藏主視窗</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>將屬於你的錢包的密鑰加密</translation> </message> <message> <location line="+7"/> <source>Sign messages with your GulfCoin addresses to prove you own them</source> <translation>用位元幣位址簽署訊息來證明那是你的</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified GulfCoin addresses</source> <translation>驗證訊息來確認是用指定的位元幣位址簽署的</translation> </message><|fim▁hole|> <location line="+28"/> <source>&amp;File</source> <translation>檔案</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>設定</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>求助</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>分頁工具列</translation> </message> <message> <location line="-228"/> <location line="+288"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-5"/> <location line="+5"/> <source>GulfCoin client</source> <translation>位元幣客戶端軟體</translation> </message> <message numerus="yes"> <location line="+121"/> <source>%n active connection(s) to GulfCoin network</source> <translation><numerusform>與位元幣網路有 %n 個連線在使用中</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>目前沒有區塊來源...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>已處理了估計全部 %2 個中的 %1 個區塊的交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>已處理了 %1 個區塊的交易紀錄.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n 個小時</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n 天</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n 個星期</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>落後 %1</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>最近收到的區塊是在 %1 之前生產出來.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>會看不見在這之後的交易.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>這筆交易的資料大小超過限制了. 你還是可以付出 %1 的費用來傳送, 這筆費用會付給處理你的交易的節點, 並幫助維持整個網路. 你願意支付這項費用嗎?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>最新狀態</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>進度追趕中...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>確認交易手續費</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>付款交易</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>收款交易</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>日期: %1 金額: %2 類別: %3 位址: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI 處理</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid GulfCoin address or malformed URI parameters.</source> <translation>無法解析 URI! 也許位元幣位址無效或 URI 參數有誤.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;解鎖中&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;上鎖中&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+110"/> <source>A fatal error occurred. GulfCoin can no longer continue safely and will quit.</source> <translation>發生了致命的錯誤. 位元幣程式無法再繼續安全執行, 只好結束.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+105"/> <source>Network Alert</source> <translation>網路警報</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>編輯位址</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>標記</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>與這個位址簿項目關聯的標記</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>位址</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>與這個位址簿項目關聯的位址. 付款位址才能被更改.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>新收款位址</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>新增付款位址</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>編輯收款位址</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>編輯付款位址</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>輸入的位址&quot;%1&quot;已存在於位址簿中.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid GulfCoin address.</source> <translation>輸入的位址 &quot;%1&quot; 並不是有效的位元幣位址.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>無法將錢包解鎖.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>新密鑰產生失敗.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+61"/> <source>A new data directory will be created.</source> <translation>將會建立新的資料目錄.</translation> </message> <message> <location line="+22"/> <source>name</source> <translation>名稱</translation> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>目錄已經存在了. 如果你要在裡面建立新目錄的話, 請加上 %1.</translation> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation>已經存在該路徑了, 並且不是一個目錄.</translation> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation>無法在這裡新增資料目錄</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+517"/> <location line="+13"/> <source>GulfCoin-Qt</source> <translation>位元幣-Qt</translation> </message> <message> <location line="-13"/> <source>version</source> <translation>版本</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>使用界面選項</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>設定語言, 比如說 &quot;de_DE&quot; (預設: 系統語系)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>啓動時最小化 </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>顯示啓動畫面 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation>啓動時選擇資料目錄 (預設值: 0)</translation> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation>歡迎</translation> </message> <message> <location line="+9"/> <source>Welcome to GulfCoin-Qt.</source> <translation>歡迎使用&quot;位元幣-Qt&quot;</translation> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where GulfCoin-Qt will store its data.</source> <translation>由於這是程式第一次啓動, 你可以選擇&quot;位元幣-Qt&quot;儲存資料的地方.</translation> </message> <message> <location line="+10"/> <source>GulfCoin-Qt will download and store a copy of the GulfCoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>位元幣-Qt 會下載並儲存一份位元幣區塊鏈結的拷貝. 至少有 %1GB 的資料會儲存到這個目錄中, 並且還會持續增長. 另外錢包資料也會儲存在這個目錄.</translation> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation>用預設的資料目錄</translation> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation>用自定的資料目錄:</translation> </message> <message> <location filename="../intro.cpp" line="+100"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation>GB 可用空間</translation> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation>(需要 %1GB)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>選項</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>主要</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>非必要的交易手續費, 以 kB 為計費單位, 且有助於縮短你的交易處理時間. 大部份交易資料的大小是 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>付交易手續費</translation> </message> <message> <location line="+31"/> <source>Automatically start GulfCoin after logging in to the system.</source> <translation>在登入系統後自動啓動位元幣.</translation> </message> <message> <location line="+3"/> <source>&amp;Start GulfCoin on system login</source> <translation>系統登入時啟動位元幣</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>回復所有客戶端軟體選項成預設值.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>選項回復</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>網路</translation> </message> <message> <location line="+6"/> <source>Automatically open the GulfCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>自動在路由器上開啟 GulfCoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>用 &amp;UPnP 設定通訊埠對應</translation> </message> <message> <location line="+7"/> <source>Connect to the GulfCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>透過 SOCKS 代理伺服器連線至位元幣網路 (比如說要透過 Tor 連線).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>透過 SOCKS 代理伺服器連線:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>代理伺服器位址:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>通訊埠:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>代理伺服器的通訊埠 (比如說 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS 協定版本:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>代理伺服器的 SOCKS 協定版本 (比如說 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>視窗</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>最小化視窗後只在通知區域顯示圖示</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>最小化至通知區域而非工作列</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>關閉時最小化</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>顯示</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>使用界面語言</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting GulfCoin.</source> <translation>可以在這裡設定使用者介面的語言. 這個設定在位元幣程式重啓後才會生效.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>金額顯示單位:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>選擇操作界面與付錢時預設顯示的細分單位.</translation> </message> <message> <location line="+9"/> <source>Whether to show GulfCoin addresses in the transaction list or not.</source> <translation>是否要在交易列表中顯示位元幣位址.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>在交易列表顯示位址</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>好</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>取消</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>套用</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+54"/> <source>default</source> <translation>預設</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>確認回復選項</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>有些設定可能需要重新啓動客戶端軟體才會生效.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>你想要就做下去嗎?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting GulfCoin.</source> <translation>這個設定會在位元幣程式重啓後生效.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>提供的代理伺服器位址無效</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+50"/> <location line="+202"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the GulfCoin network after a connection is established, but this process has not completed yet.</source> <translation>顯示的資訊可能是過期的. 與位元幣網路的連線建立後, 你的錢包會自動和網路同步, 但這個步驟還沒完成.</translation> </message> <message> <location line="-131"/> <source>Unconfirmed:</source> <translation>未確認金額:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+49"/> <source>Confirmed:</source> <translation>已確認金額:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>目前可用餘額</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>尚未確認的交易的總金額, 可用餘額不包含此金額</translation> </message> <message> <location line="+13"/> <source>Immature:</source> <translation>未熟成</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>尚未熟成的開採金額</translation> </message> <message> <location line="+13"/> <source>Total:</source> <translation>總金額:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>目前全部餘額</translation> </message> <message> <location line="+53"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;最近交易&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>沒同步</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+108"/> <source>Cannot start gulfcoin: click-to-pay handler</source> <translation>無法啟動 gulfcoin 隨按隨付處理器</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+92"/> <location filename="../intro.cpp" line="-32"/> <source>GulfCoin</source> <translation>位元幣</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation>錯誤: 不存在指定的資料目錄 &quot;%1&quot;.</translation> </message> <message> <location filename="../intro.cpp" line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation>錯誤: 無法新增指定的資料目錄 &quot;%1&quot;.</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR 條碼對話視窗</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>付款單</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>金額:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>標記:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>訊息:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>儲存為...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+64"/> <source>Error encoding URI into QR Code.</source> <translation>將 URI 編碼成 QR 條碼失敗</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>輸入的金額無效, 請檢查看看.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>造出的網址太長了,請把標籤或訊息的文字縮短再試看看.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>儲存 QR 條碼</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG 圖檔 (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>客戶端軟體名稱</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+345"/> <source>N/A</source> <translation>無</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>客戶端軟體版本</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>資訊</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>使用 OpenSSL 版本</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>啓動時間</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>網路</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>連線數</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>位於測試網路</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>區塊鎖鏈</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>目前區塊數</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>估算總區塊數</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>最近區塊時間</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>開啓</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+7"/> <source>Show the GulfCoin-Qt help message to get a list with possible GulfCoin command-line options.</source> <translation>顯示&quot;位元幣-Qt&quot;的求助訊息, 來取得可用的命令列選項列表.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>顯示</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>主控台</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>建置日期</translation> </message> <message> <location line="-104"/> <source>GulfCoin - Debug window</source> <translation>位元幣 - 除錯視窗</translation> </message> <message> <location line="+25"/> <source>GulfCoin Core</source> <translation>位元幣核心</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>除錯紀錄檔</translation> </message> <message> <location line="+7"/> <source>Open the GulfCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>從目前的資料目錄下開啓位元幣的除錯紀錄檔. 當紀錄檔很大時可能要花好幾秒的時間.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>清主控台</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the GulfCoin RPC console.</source> <translation>歡迎使用位元幣 RPC 主控台.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>請用上下游標鍵來瀏覽歷史指令, 且可用 &lt;b&gt;Ctrl-L&lt;/b&gt; 來清理畫面.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>請打 &lt;b&gt;help&lt;/b&gt; 來看可用指令的簡介.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+128"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>付錢</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>一次付給多個人</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>加收款人</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>移除所有交易欄位</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>餘額:</translation> </message> <message> <location line="+10"/> <source>123.456 ABC</source> <translation>123.456 ABC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>確認付款動作</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>付出</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-62"/> <location line="+2"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; 給 %2 (%3)</translation> </message> <message> <location line="+6"/> <source>Confirm send coins</source> <translation>確認要付錢</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>確定要付出 %1 嗎?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>和</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>無效的收款位址, 請再檢查看看.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>付款金額必須大於 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>金額超過餘額了.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>包含 %1 的交易手續費後, 總金額超過你的餘額了.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>發現有重複的位址. 每個付款動作中, 只能付給個別的位址一次.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>錯誤: 交易產生失敗!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕. 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>金額:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>付給:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>付款的目標位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>輸入一個標記給這個位址, 並加到位址簿中</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>標記:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>從位址簿中選一個位址</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>去掉這個收款人</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a GulfCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>簽章 - 簽署或驗證訊息</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>你可以用自己的位址來簽署訊息, 以證明你對它的所有權. 但是請小心, 不要簽署語意含糊不清的內容, 因為釣魚式詐騙可能會用騙你簽署的手法來冒充是你. 只有在語句中的細節你都同意時才簽署.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>用來簽署訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>從位址簿選一個位址</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>在這裡輸入你想簽署的訊息</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>簽章</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>複製目前的簽章到系統剪貼簿</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this GulfCoin address</source> <translation>簽署訊息是用來證明這個位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>重置所有訊息簽署欄位</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>請在下面輸入簽署的位址, 訊息(請確認完整複製了所包含的換行, 空格, 跳位符號等等), 與簽章, 以驗證該訊息. 請小心, 除了訊息內容外, 不要對簽章本身過度解讀, 以避免被用&quot;中間人攻擊法&quot;詐騙.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>簽署該訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified GulfCoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>重置所有訊息驗證欄位</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a GulfCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>按&quot;訊息簽署&quot;來產生簽章</translation> </message> <message> <location line="+3"/> <source>Enter GulfCoin signature</source> <translation>輸入位元幣簽章</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>輸入的位址無效.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>請檢查位址是否正確後再試一次.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>輸入的位址沒有指到任何密鑰.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>錢包解鎖已取消.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>沒有所輸入位址的密鑰.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>訊息簽署失敗.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>訊息已簽署.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>無法將這個簽章解碼.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>請檢查簽章是否正確後再試一次.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>這個簽章與訊息的數位摘要不符.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>訊息驗證失敗.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>訊息已驗證.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The GulfCoin developers</source> <translation>位元幣開發人員</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/離線中</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/未確認</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>經確認 %1 次</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>狀態</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, 已公告至 %n 個節點</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>來源</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>生產出</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>來處</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>目的</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>自己的位址</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>標籤</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>入帳</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>將在 %n 個區塊產出後熟成</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>不被接受</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>出帳</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>交易手續費</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>淨額</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>訊息</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>附註</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>交易識別碼</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>生產出來的錢要再等 1 個區塊熟成之後, 才能夠花用. 當你產出區塊時, 它會被公布到網路上, 以被串連至區塊鎖鏈. 如果串連失敗了, 它的狀態就會變成&quot;不被接受&quot;, 且不能被花用. 當你產出區塊的幾秒鐘內, 也有其他節點產出區塊的話, 有時候就會發生這種情形.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>除錯資訊</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>交易</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>輸入</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>是</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>否</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, 尚未成功公告出去</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>未知</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>交易明細</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>此版面顯示交易的詳細說明</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>金額</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>離線中 (經確認 %1 次)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>未確認 (經確認 %1 次, 應確認 %2 次)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>已確認 (經確認 %1 次)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>開採金額將可在 %n 個區塊熟成後可用</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>沒有其他節點收到這個區塊, 也許它不被接受!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>生產出但不被接受</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>收受自</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>付給自己</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(不適用)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>交易狀態. 移動游標至欄位上方來顯示確認次數.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>收到交易的日期與時間.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>交易的種類.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>交易的目標位址.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>減去或加入至餘額的金額</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>全部</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>今天</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>這週</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>這個月</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>上個月</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>今年</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>指定範圍...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>給自己</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>其他</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>輸入位址或標記來搜尋</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>最小金額</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>複製位址</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>複製金額</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>複製交易識別碼</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>編輯標記</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>顯示交易明細</translation> </message> <message> <location line="+143"/> <source>Export Transaction Data</source> <translation>匯出交易資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號分隔資料檔 (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>已確認</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>識別碼</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入至 %1 檔案.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>範圍:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>至</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>付錢</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+46"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+197"/> <source>Backup Wallet</source> <translation>錢包備份</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>錢包資料檔 (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>備份失敗</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>儲存錢包資料到新的地方失敗</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>備份成功</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>錢包的資料已經成功儲存到新的地方了.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+98"/> <source>GulfCoin version</source> <translation>位元幣版本</translation> </message> <message> <location line="+104"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="-30"/> <source>Send command to -server or gulfcoind</source> <translation>送指令給 -server 或 gulfcoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>列出指令 </translation> </message> <message> <location line="-13"/> <source>Get help for a command</source> <translation>取得指令說明 </translation> </message> <message> <location line="+25"/> <source>Options:</source> <translation>選項: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: gulfcoin.conf)</source> <translation>指定設定檔 (預設: gulfcoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: gulfcoind.pid)</source> <translation>指定行程識別碼檔案 (預設: gulfcoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>指定資料目錄 </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>設定資料庫快取大小為多少百萬位元組(MB, 預設: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 12401 or testnet: 22401)</source> <translation>在通訊埠 &lt;port&gt; 聽候連線 (預設: 12401, 或若為測試網路: 22401)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>維持與節點連線數的上限為 &lt;n&gt; 個 (預設: 125)</translation> </message> <message> <location line="-49"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>連線到某個節點以取得其它節點的位址, 然後斷線</translation> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation>指定自己公開的位址</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>與亂搞的節點斷線的臨界值 (預設: 100)</translation> </message> <message> <location line="-136"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>避免與亂搞的節點連線的秒數 (預設: 86400)</translation> </message> <message> <location line="-33"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>在 IPv4 網路上以通訊埠 %u 聽取 RPC 連線時發生錯誤: %s</translation> </message> <message> <location line="+31"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 12402 or testnet: 22402)</source> <translation>在通訊埠 &lt;port&gt; 聽候 JSON-RPC 連線 (預設: 12402, 或若為測試網路: 22402)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>接受命令列與 JSON-RPC 指令 </translation> </message> <message> <location line="+77"/> <source>Run in the background as a daemon and accept commands</source> <translation>以背景程式執行並接受指令</translation> </message> <message> <location line="+38"/> <source>Use the test network</source> <translation>使用測試網路 </translation> </message> <message> <location line="-114"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>是否接受外來連線 (預設: 當沒有 -proxy 或 -connect 時預設為 1)</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=gulfcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;GulfCoin Alert&quot; [email protected] </source> <translation>%s, 你必須要在以下設定檔中設定 RPC 密碼(rpcpassword): %s 建議你使用以下隨機產生的密碼: rpcuser=gulfcoinrpc rpcpassword=%s (你不用記住這個密碼) 使用者名稱(rpcuser)和密碼(rpcpassword)不可以相同! 如果設定檔還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;. 也建議你設定警示通知, 發生問題時你才會被通知到; 比如說設定為: alertnotify=echo %%s | mail -s &quot;GulfCoin Alert&quot; [email protected] </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>設定在 IPv6 網路的通訊埠 %u 上聽候 RPC 連線失敗, 退而改用 IPv4 網路: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>和指定的位址繫結, 並總是在該位址聽候連線. IPv6 請用 &quot;[主機]:通訊埠&quot; 這種格式</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. GulfCoin is probably already running.</source> <translation>無法鎖定資料目錄 %s. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation>進入回歸測試模式, 特別的區塊鎖鏈使用中, 可以立即解出區塊. 目的是用來做回歸測試, 以及配合應用程式的開發.</translation> </message> <message> <location line="+4"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕了! 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>錯誤: 這筆交易需要至少 %s 的手續費! 因為它的金額太大, 或複雜度太高, 或是使用了最近才剛收到的款項.</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>當收到相關警示時所要執行的指令 (指令中的 %s 會被取代為警示訊息)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>當錢包有交易改變時所要執行的指令 (指令中的 %s 會被取代為交易識別碼)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>設定高優先權或低手續費的交易資料大小上限為多少位元組 (預設: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>這是尚未發表的測試版本 - 使用請自負風險 - 請不要用於開採或商業應用</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>警告: -paytxfee 設定了很高的金額! 這可是你交易付款所要付的手續費.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>警告: 顯示的交易可能不正確! 你可能需要升級, 或者需要等其它的節點升級.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong GulfCoin will not work properly.</source> <translation>警告: 請檢查電腦時間與日期是否正確! 位元幣無法在時鐘不準的情況下正常運作.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>警告: 讀取錢包檔 wallet.dat 失敗了! 所有的密鑰都正確讀取了, 但是交易資料或位址簿資料可能會缺少或不正確.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>警告: 錢包檔 wallet.dat 壞掉, 但資料被拯救回來了! 原來的 wallet.dat 會改儲存在 %s, 檔名為 wallet.{timestamp}.bak. 如果餘額或交易資料有誤, 你應該要用備份資料復原回來.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>嘗試從壞掉的錢包檔 wallet.dat 復原密鑰</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>區塊產生選項:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>只連線至指定節點(可多個)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>發現區塊資料庫壞掉了</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>找出自己的網際網路位址 (預設: 當有聽候連線且沒有 -externalip 時為 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>你要現在重建區塊資料庫嗎?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>初始化區塊資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>錢包資料庫環境 %s 初始化錯誤!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>載入區塊資料庫失敗</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>打開區塊資料庫檔案失敗</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>錯誤: 磁碟空間很少!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>錯誤: 錢包被上鎖了, 無法產生新的交易!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>錯誤: 系統錯誤:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>在任意的通訊埠聽候失敗. 如果你想的話可以用 -listen=0.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>讀取區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>讀取區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>同步區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>寫入區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>寫入區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>寫入區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>寫入檔案資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>寫入位元幣資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>寫入交易索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>寫入回復資料失敗</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>是否允許在找節點時使用域名查詢 (預設: 當沒用 -connect 時為 1)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>生產位元幣 (預設值: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>啓動時檢查的區塊數 (預設: 288, 指定 0 表示全部)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>區塊檢查的仔細程度 (0 至 4, 預設: 3)</translation> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>創世區塊不正確或找不到. 資料目錄錯了嗎?</translation> </message> <message> <location line="+18"/> <source>Not enough file descriptors available.</source> <translation>檔案描述器不足.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>從目前的區塊檔 blk000??.dat 重建鎖鏈索引</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>設定處理 RPC 服務請求的執行緒數目 (預設為 4)</translation> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation>指定錢包檔(會在資料目錄中)</translation> </message> <message> <location line="+20"/> <source>Verifying blocks...</source> <translation>驗證區塊資料中...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>驗證錢包資料中...</translation> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation>錢包檔 %s 沒有在資料目錄 %s 裡面</translation> </message> <message> <location line="+4"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>改變 -txindex 參數後, 必須要用 -reindex 參數來重建資料庫</translation> </message> <message> <location line="-76"/> <source>Imports blocks from external blk000??.dat file</source> <translation>從其它來源的 blk000??.dat 檔匯入區塊</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>設定指令碼驗證的執行緒數目 (最多為 16, 若為 0 表示程式自動決定, 小於 0 表示保留不用的處理器核心數目, 預設為 0)</translation> </message> <message> <location line="+78"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>無效的 -tor 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -minrelaytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -mintxfee=&lt;amount&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>維護全部交易的索引 (預設為 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>每個連線的接收緩衝區大小上限為 &lt;n&gt;*1000 個位元組 (預設: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>每個連線的傳送緩衝區大小上限為 &lt;n&gt;*1000 位元組 (預設: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>只接受與內建的檢查段點吻合的區塊鎖鏈 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>只和 &lt;net&gt; 網路上的節點連線 (IPv4, IPv6, 或 Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>輸出額外的除錯資訊. 包含了其它所有的 -debug* 選項</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>輸出額外的網路除錯資訊</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>在除錯輸出內容前附加時間</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the GulfCoin Wiki for SSL setup instructions)</source> <translation>SSL 選項: (SSL 設定程序請見 GulfCoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>選擇 SOCKS 代理伺服器的協定版本(4 或 5, 預設: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>在終端機顯示追蹤或除錯資訊, 而非寫到 debug.log 檔</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>輸出追蹤或除錯資訊給除錯器</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>設定區塊大小上限為多少位元組 (預設: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>設定區塊大小下限為多少位元組 (預設: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>客戶端軟體啓動時將 debug.log 檔縮小 (預設: 當沒有 -debug 時為 1)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>簽署交易失敗</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>指定連線在幾毫秒後逾時 (預設: 5000)</translation> </message> <message> <location line="+5"/> <source>System error: </source> <translation>系統錯誤:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>交易金額太小</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>交易金額必須是正的</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>交易位元量太大</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 當有聽候連線為 1)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>透過代理伺服器來使用 Tor 隱藏服務 (預設: 同 -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC 連線使用者名稱</translation> </message> <message> <location line="+5"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>警告: 這個版本已經被淘汰掉了, 必須要升級!</translation> </message> <message> <location line="+2"/> <source>wallet.dat corrupt, salvage failed</source> <translation>錢包檔 weallet.dat 壞掉了, 拯救失敗</translation> </message> <message> <location line="-52"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC 連線密碼</translation> </message> <message> <location line="-68"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>只允許從指定網路位址來的 JSON-RPC 連線</translation> </message> <message> <location line="+77"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>送指令給在 &lt;ip&gt; 的節點 (預設: 127.0.0.1) </translation> </message> <message> <location line="-121"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>當最新區塊改變時所要執行的指令 (指令中的 %s 會被取代為區塊的雜湊值)</translation> </message> <message> <location line="+149"/> <source>Upgrade wallet to latest format</source> <translation>將錢包升級成最新的格式</translation> </message> <message> <location line="-22"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>設定密鑰池大小為 &lt;n&gt; (預設: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>重新掃描區塊鎖鏈, 以尋找錢包所遺漏的交易.</translation> </message> <message> <location line="+36"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>於 JSON-RPC 連線使用 OpenSSL (https) </translation> </message> <message> <location line="-27"/> <source>Server certificate file (default: server.cert)</source> <translation>伺服器憑證檔 (預設: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>伺服器密鑰檔 (預設: server.pem) </translation> </message> <message> <location line="-156"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>可以接受的加密法 (預設: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+171"/> <source>This help message</source> <translation>此協助訊息 </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>無法和這台電腦上的 %s 繫結 (繫結回傳錯誤 %d, %s)</translation> </message> <message> <location line="-93"/> <source>Connect through socks proxy</source> <translation>透過 SOCKS 代理伺服器連線</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>允許對 -addnode, -seednode, -connect 的參數使用域名查詢 </translation> </message> <message> <location line="+56"/> <source>Loading addresses...</source> <translation>載入位址中...</translation> </message> <message> <location line="-36"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>載入檔案 wallet.dat 失敗: 錢包壞掉了</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of GulfCoin</source> <translation>載入檔案 wallet.dat 失敗: 此錢包需要新版的 GulfCoin</translation> </message> <message> <location line="+96"/> <source>Wallet needed to be rewritten: restart GulfCoin to complete</source> <translation>錢包需要重寫: 請重啟位元幣來完成</translation> </message> <message> <location line="-98"/> <source>Error loading wallet.dat</source> <translation>載入檔案 wallet.dat 失敗</translation> </message> <message> <location line="+29"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>無效的 -proxy 位址: &apos;%s&apos;</translation> </message> <message> <location line="+57"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>在 -onlynet 指定了不明的網路別: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>在 -socks 指定了不明的代理協定版本: %i</translation> </message> <message> <location line="-98"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>無法解析 -bind 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>無法解析 -externalip 位址: &apos;%s&apos;</translation> </message> <message> <location line="+45"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -paytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>無效的金額</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>累積金額不足</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>載入區塊索引中...</translation> </message> <message> <location line="-58"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>加入一個要連線的節線, 並試著保持對它的連線暢通</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. GulfCoin is probably already running.</source> <translation>無法和這台電腦上的 %s 繫結. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>交易付款時每 KB 的交易手續費</translation> </message> <message> <location line="+20"/> <source>Loading wallet...</source> <translation>載入錢包中...</translation> </message> <message> <location line="-53"/> <source>Cannot downgrade wallet</source> <translation>無法將錢包格式降級</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>無法寫入預設位址</translation> </message> <message> <location line="+65"/> <source>Rescanning...</source> <translation>重新掃描中...</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>載入完成</translation> </message> <message> <location line="+84"/> <source>To use the %s option</source> <translation>為了要使用 %s 選項</translation> </message> <message> <location line="-76"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>你必須在下列設定檔中設定 RPC 密碼(rpcpassword=&lt;password&gt;): %s 如果這個檔案還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;.</translation> </message> </context> </TS><|fim▁end|>
<message>
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # yara documentation build configuration file, created by # sphinx-quickstart on Tue Jul 8 11:04:03 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'yara' copyright = u'2014-2019, VirusTotal' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '3.9' # The full version, including alpha/beta/rc tags. release = '3.9.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. try: import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except: html_theme = "default" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True<|fim▁hole|>#html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'yaradoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'yara.tex', u'yara Documentation', u'Victor M. Alvarez', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'yara', u'yara Documentation', [u'Victor M. Alvarez'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'yara', u'yara Documentation', u'Victor M. Alvarez', 'yara', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False<|fim▁end|>
# Custom sidebar templates, maps document names to template names.
<|file_name|>ai.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 2011-2013 Bitcraze AB # # Crazyflie Nano Quadcopter Client # # This program 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 the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ Attitude indicator widget. """ import sys from PyQt4 import QtGui, QtCore __author__ = 'Bitcraze AB' __all__ = ['AttitudeIndicator'] class AttitudeIndicator(QtGui.QWidget): """Widget for showing attitude""" def __init__(self): super(AttitudeIndicator, self).__init__() self.roll = 0 self.pitch = 0 self.hover = False self.hoverASL = 0.0 self.hoverTargetASL = 0.0 self.setMinimumSize(30, 30) # self.setMaximumSize(240,240) def setRoll(self, roll): self.roll = roll self.repaint() def setPitch(self, pitch): self.pitch = pitch self.repaint() def setHover(self, target): self.hoverTargetASL = target self.hover = target > 0 self.repaint() def setBaro(self, asl): self.hoverASL = asl self.repaint() def setRollPitch(self, roll, pitch): self.roll = roll self.pitch = pitch self.repaint() def paintEvent(self, e): qp = QtGui.QPainter() qp.begin(self) self.drawWidget(qp) qp.end() def drawWidget(self, qp): size = self.size() w = size.width() h = size.height() qp.translate(w / 2, h / 2) qp.rotate(self.roll) qp.translate(0, (self.pitch * h) / 50) qp.translate(-w / 2, -h / 2) qp.setRenderHint(qp.Antialiasing) font = QtGui.QFont('Serif', 7, QtGui.QFont.Light) qp.setFont(font) # Draw the blue qp.setPen(QtGui.QColor(0, 61, 144)) qp.setBrush(QtGui.QColor(0, 61, 144)) qp.drawRect(-w, h / 2, 3 * w, -3 * h) # Draw the marron qp.setPen(QtGui.QColor(59, 41, 39)) qp.setBrush(QtGui.QColor(59, 41, 39)) qp.drawRect(-w, h / 2, 3 * w, 3 * h) pen = QtGui.QPen(QtGui.QColor(255, 255, 255), 1.5, QtCore.Qt.SolidLine) qp.setPen(pen)<|fim▁hole|> # Drawing pitch lines for ofset in [-180, 0, 180]: for i in range(-900, 900, 25): pos = (((i / 10.0) + 25 + ofset) * h / 50.0) if i % 100 == 0: length = 0.35 * w if i != 0: if ofset == 0: qp.drawText((w / 2) + (length / 2) + (w * 0.06), pos, "{}".format(-i / 10)) qp.drawText((w / 2) - (length / 2) - (w * 0.08), pos, "{}".format(-i / 10)) else: qp.drawText((w / 2) + (length / 2) + (w * 0.06), pos, "{}".format(i / 10)) qp.drawText((w / 2) - (length / 2) - (w * 0.08), pos, "{}".format(i / 10)) elif i % 50 == 0: length = 0.2 * w else: length = 0.1 * w qp.drawLine((w / 2) - (length / 2), pos, (w / 2) + (length / 2), pos) qp.setWorldMatrixEnabled(False) pen = QtGui.QPen(QtGui.QColor(0, 0, 0), 2, QtCore.Qt.SolidLine) qp.setBrush(QtGui.QColor(0, 0, 0)) qp.setPen(pen) qp.drawLine(0, h / 2, w, h / 2) # Draw Hover vs Target qp.setWorldMatrixEnabled(False) pen = QtGui.QPen(QtGui.QColor(255, 255, 255), 2, QtCore.Qt.SolidLine) qp.setBrush(QtGui.QColor(255, 255, 255)) qp.setPen(pen) fh = max(7, h / 50) font = QtGui.QFont('Sans', fh, QtGui.QFont.Light) qp.setFont(font) qp.resetTransform() qp.translate(0, h / 2) if not self.hover: # asl qp.drawText(w - fh * 10, fh / 2, str(round(self.hoverASL, 2))) if self.hover: # target asl (center) qp.drawText( w - fh * 10, fh / 2, str(round(self.hoverTargetASL, 2))) diff = round(self.hoverASL - self.hoverTargetASL, 2) pos_y = -h / 6 * diff # cap to +- 2.8m if diff < -2.8: pos_y = -h / 6 * -2.8 elif diff > 2.8: pos_y = -h / 6 * 2.8 else: pos_y = -h / 6 * diff # difference from target (moves up and down +- 2.8m) qp.drawText(w - fh * 3.8, pos_y + fh / 2, str(diff)) # vertical line qp.drawLine(w - fh * 4.5, 0, w - fh * 4.5, pos_y) # left horizontal line qp.drawLine(w - fh * 4.7, 0, w - fh * 4.5, 0) # right horizontal line qp.drawLine(w - fh * 4.2, pos_y, w - fh * 4.5, pos_y) if __name__ == "__main__": class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def updatePitch(self, pitch): self.wid.setPitch(pitch - 90) def updateRoll(self, roll): self.wid.setRoll((roll / 10.0) - 180.0) def updateTarget(self, target): self.wid.setHover(500 + target / 10.) def updateBaro(self, asl): self.wid.setBaro(500 + asl / 10.) def initUI(self): vbox = QtGui.QVBoxLayout() sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) sld.setFocusPolicy(QtCore.Qt.NoFocus) sld.setRange(0, 3600) sld.setValue(1800) vbox.addWidget(sld) self.wid = AttitudeIndicator() sld.valueChanged[int].connect(self.updateRoll) vbox.addWidget(self.wid) hbox = QtGui.QHBoxLayout() hbox.addLayout(vbox) sldPitch = QtGui.QSlider(QtCore.Qt.Vertical, self) sldPitch.setFocusPolicy(QtCore.Qt.NoFocus) sldPitch.setRange(0, 180) sldPitch.setValue(90) sldPitch.valueChanged[int].connect(self.updatePitch) hbox.addWidget(sldPitch) sldASL = QtGui.QSlider(QtCore.Qt.Vertical, self) sldASL.setFocusPolicy(QtCore.Qt.NoFocus) sldASL.setRange(-200, 200) sldASL.setValue(0) sldASL.valueChanged[int].connect(self.updateBaro) sldT = QtGui.QSlider(QtCore.Qt.Vertical, self) sldT.setFocusPolicy(QtCore.Qt.NoFocus) sldT.setRange(-200, 200) sldT.setValue(0) sldT.valueChanged[int].connect(self.updateTarget) hbox.addWidget(sldT) hbox.addWidget(sldASL) self.setLayout(hbox) self.setGeometry(50, 50, 510, 510) self.setWindowTitle('Attitude Indicator') self.show() def changeValue(self, value): self.c.updateBW.emit(value) self.wid.repaint() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()<|fim▁end|>
qp.drawLine(-w, h / 2, 3 * w, h / 2)
<|file_name|>mailTest.js<|end_file_name|><|fim▁begin|>var Component = new Brick.Component();<|fim▁hole|> ] }; Component.entryPoint = function(NS){ var Y = Brick.YUI, COMPONENT = this, SYS = Brick.mod.sys; NS.MailTestWidget = Y.Base.create('MailTestWidget', SYS.AppWidget, [], { onInitAppWidget: function(err, appInstance, options){ }, destructor: function(){ this.hideResult(); }, sendTestMail: function(){ var tp = this.template, email = tp.getValue('email'); this.set('waiting', true); this.get('appInstance').mailTestSend(email, function(err, result){ this.set('waiting', false); if (!err){ this.showResult(result.mailTestSend); } }, this); }, showResult: function(mail){ var tp = this.template; tp.show('resultPanel'); this._resultMailWidget = new NS.MailViewWidget({ srcNode: tp.append('resultMail', '<div></div>'), mail: mail }); }, hideResult: function(){ var widget = this._resultMailWidget; if (!widget){ return; } widget.destroy(); this._resultMailWidget = null; this.template.hide('resultPanel'); } }, { ATTRS: { component: {value: COMPONENT}, templateBlockName: {value: 'widget'}, }, CLICKS: { send: 'sendTestMail' }, }); };<|fim▁end|>
Component.requires = { mod: [ {name: '{C#MODNAME}', files: ['mail.js']}
<|file_name|>CWE401_Memory_Leak__new_twoIntsStruct_52b.cpp<|end_file_name|><|fim▁begin|>/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__new_twoIntsStruct_52b.cpp Label Definition File: CWE401_Memory_Leak__new.label.xml Template File: sources-sinks-52b.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: Allocate data using new * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call delete on data * BadSink : no deallocation of data * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif namespace CWE401_Memory_Leak__new_twoIntsStruct_52 { #ifndef OMITBAD /* bad function declaration */ void badSink_c(twoIntsStruct * data); void badSink_b(twoIntsStruct * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD <|fim▁hole|> void goodG2BSink_b(twoIntsStruct * data) { goodG2BSink_c(data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink_c(twoIntsStruct * data); void goodB2GSink_b(twoIntsStruct * data) { goodB2GSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */<|fim▁end|>
/* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(twoIntsStruct * data);
<|file_name|>TopicStruct.java<|end_file_name|><|fim▁begin|>package org.zarroboogs.weibo.hot.bean.hotweibo; import org.json.*; public class TopicStruct { private String topicTitle; private String topicUrl; public TopicStruct () { } public TopicStruct (JSONObject json) { this.topicTitle = json.optString("topic_title"); this.topicUrl = json.optString("topic_url"); } public String getTopicTitle() { return this.topicTitle;<|fim▁hole|> public void setTopicTitle(String topicTitle) { this.topicTitle = topicTitle; } public String getTopicUrl() { return this.topicUrl; } public void setTopicUrl(String topicUrl) { this.topicUrl = topicUrl; } }<|fim▁end|>
}
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate env_logger; extern crate glutin; extern crate gfx; extern crate gfx_window_glutin; extern crate claymore_game as game; pub fn main() { use gfx::traits::*; env_logger::init().unwrap(); println!("Initializing the window..."); let window = glutin::WindowBuilder::new() .with_title("Claymore".to_string()) .with_vsync() .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (3, 2))) .with_srgb(Some(true)) .build().unwrap(); let (mut stream, mut device, mut factory) = gfx_window_glutin::init(window); let _ = stream.out.set_gamma(gfx::Gamma::Convert); println!("Loading the game..."); let mut app = game::App::new(&mut factory); println!("Rendering..."); let (mut mouse_x, mut mouse_y) = (0, 0); 'main: loop { // quit when Esc is pressed. for event in stream.out.window.poll_events() { use glutin::{ElementState, Event, MouseButton, VirtualKeyCode}; match event { Event::Closed => break 'main, Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Escape)) => break 'main, Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::W)) => app.rotate_camera(-90.0), Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Q)) => app.rotate_camera(90.0), Event::MouseMoved((x, y)) => { mouse_x = x; mouse_y = y; }, Event::MouseInput(ElementState::Pressed, MouseButton::Left) => { let (sx, sy) = stream.out.get_size(); app.mouse_click(mouse_x as f32 / sx as f32, mouse_y as f32 / sy as f32); },<|fim▁hole|> app.render(&mut stream); stream.present(&mut device); } println!("Done."); }<|fim▁end|>
_ => (), } }
<|file_name|>descriptor.cc<|end_file_name|><|fim▁begin|>// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: [email protected] (Petar Petrov) #include <Python.h> #include <string> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/pyext/descriptor.h> #include <google/protobuf/pyext/scoped_pyobject_ptr.h> #define C(str) const_cast<char*>(str) #if PY_MAJOR_VERSION >= 3 #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #define PyInt_FromLong PyLong_FromLong #if PY_VERSION_HEX < 0x03030000 #error "Python 3.0 - 3.2 are not supported." #else #define PyString_AsString(ob) \ (PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AS_STRING(ob)) #endif #endif namespace google { namespace protobuf { namespace python { #ifndef PyVarObject_HEAD_INIT #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, #endif #ifndef Py_TYPE #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif static google::protobuf::DescriptorPool* g_descriptor_pool = NULL; namespace cfield_descriptor { static void Dealloc(CFieldDescriptor* self) { Py_CLEAR(self->descriptor_field); Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); } static PyObject* GetFullName(CFieldDescriptor* self, void *closure) { return PyString_FromStringAndSize( self->descriptor->full_name().c_str(), self->descriptor->full_name().size()); } static PyObject* GetName(CFieldDescriptor *self, void *closure) { return PyString_FromStringAndSize( self->descriptor->name().c_str(), self->descriptor->name().size()); } static PyObject* GetCppType(CFieldDescriptor *self, void *closure) { return PyInt_FromLong(self->descriptor->cpp_type()); } static PyObject* GetLabel(CFieldDescriptor *self, void *closure) { return PyInt_FromLong(self->descriptor->label()); } static PyObject* GetID(CFieldDescriptor *self, void *closure) { return PyLong_FromVoidPtr(self); } static PyGetSetDef Getters[] = { { C("full_name"), (getter)GetFullName, NULL, "Full name", NULL}, { C("name"), (getter)GetName, NULL, "last name", NULL}, { C("cpp_type"), (getter)GetCppType, NULL, "C++ Type", NULL}, { C("label"), (getter)GetLabel, NULL, "Label", NULL}, { C("id"), (getter)GetID, NULL, "ID", NULL}, {NULL} }; } // namespace cfield_descriptor PyTypeObject CFieldDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) C("google.protobuf.internal." "_net_proto2___python." "CFieldDescriptor"), // tp_name sizeof(CFieldDescriptor), // tp_basicsize 0, // tp_itemsize (destructor)cfield_descriptor::Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags C("A Field Descriptor"), // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext 0, // tp_methods 0, // tp_members cfield_descriptor::Getters, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init PyType_GenericAlloc, // tp_alloc PyType_GenericNew, // tp_new PyObject_Del, // tp_free }; namespace cdescriptor_pool { static void Dealloc(CDescriptorPool* self) { Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); } static PyObject* NewCDescriptor( const google::protobuf::FieldDescriptor* field_descriptor) { CFieldDescriptor* cfield_descriptor = PyObject_New( CFieldDescriptor, &CFieldDescriptor_Type); if (cfield_descriptor == NULL) { return NULL; } cfield_descriptor->descriptor = field_descriptor; cfield_descriptor->descriptor_field = NULL; return reinterpret_cast<PyObject*>(cfield_descriptor); } PyObject* FindFieldByName(CDescriptorPool* self, PyObject* name) { const char* full_field_name = PyString_AsString(name); if (full_field_name == NULL) { return NULL; } const google::protobuf::FieldDescriptor* field_descriptor = NULL; field_descriptor = self->pool->FindFieldByName(full_field_name); if (field_descriptor == NULL) { PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s", full_field_name); return NULL; } return NewCDescriptor(field_descriptor); } PyObject* FindExtensionByName(CDescriptorPool* self, PyObject* arg) { const char* full_field_name = PyString_AsString(arg); if (full_field_name == NULL) { return NULL; } const google::protobuf::FieldDescriptor* field_descriptor = self->pool->FindExtensionByName(full_field_name); if (field_descriptor == NULL) { PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s", full_field_name); return NULL; } return NewCDescriptor(field_descriptor); } static PyMethodDef Methods[] = { { C("FindFieldByName"), (PyCFunction)FindFieldByName, METH_O, C("Searches for a field descriptor by full name.") }, { C("FindExtensionByName"),<|fim▁hole|>}; } // namespace cdescriptor_pool PyTypeObject CDescriptorPool_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) C("google.protobuf.internal." "_net_proto2___python." "CFieldDescriptor"), // tp_name sizeof(CDescriptorPool), // tp_basicsize 0, // tp_itemsize (destructor)cdescriptor_pool::Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags C("A Descriptor Pool"), // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext cdescriptor_pool::Methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init PyType_GenericAlloc, // tp_alloc PyType_GenericNew, // tp_new PyObject_Del, // tp_free }; google::protobuf::DescriptorPool* GetDescriptorPool() { if (g_descriptor_pool == NULL) { g_descriptor_pool = new google::protobuf::DescriptorPool( google::protobuf::DescriptorPool::generated_pool()); } return g_descriptor_pool; } PyObject* Python_NewCDescriptorPool(PyObject* ignored, PyObject* args) { CDescriptorPool* cdescriptor_pool = PyObject_New( CDescriptorPool, &CDescriptorPool_Type); if (cdescriptor_pool == NULL) { return NULL; } cdescriptor_pool->pool = GetDescriptorPool(); return reinterpret_cast<PyObject*>(cdescriptor_pool); } // Collects errors that occur during proto file building to allow them to be // propagated in the python exception instead of only living in ERROR logs. class BuildFileErrorCollector : public google::protobuf::DescriptorPool::ErrorCollector { public: BuildFileErrorCollector() : error_message(""), had_errors(false) {} void AddError(const string& filename, const string& element_name, const Message* descriptor, ErrorLocation location, const string& message) { // Replicates the logging behavior that happens in the C++ implementation // when an error collector is not passed in. if (!had_errors) { error_message += ("Invalid proto descriptor for file \"" + filename + "\":\n"); } // As this only happens on failure and will result in the program not // running at all, no effort is made to optimize this string manipulation. error_message += (" " + element_name + ": " + message + "\n"); } string error_message; bool had_errors; }; PyObject* Python_BuildFile(PyObject* ignored, PyObject* arg) { char* message_type; Py_ssize_t message_len; if (PyBytes_AsStringAndSize(arg, &message_type, &message_len) < 0) { return NULL; } google::protobuf::FileDescriptorProto file_proto; if (!file_proto.ParseFromArray(message_type, message_len)) { PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!"); return NULL; } if (google::protobuf::DescriptorPool::generated_pool()->FindFileByName( file_proto.name()) != NULL) { Py_RETURN_NONE; } BuildFileErrorCollector error_collector; const google::protobuf::FileDescriptor* descriptor = GetDescriptorPool()->BuildFileCollectingErrors(file_proto, &error_collector); if (descriptor == NULL) { PyErr_Format(PyExc_TypeError, "Couldn't build proto file into descriptor pool!\n%s", error_collector.error_message.c_str()); return NULL; } Py_RETURN_NONE; } bool InitDescriptor() { CFieldDescriptor_Type.tp_new = PyType_GenericNew; if (PyType_Ready(&CFieldDescriptor_Type) < 0) return false; CDescriptorPool_Type.tp_new = PyType_GenericNew; if (PyType_Ready(&CDescriptorPool_Type) < 0) return false; return true; } } // namespace python } // namespace protobuf } // namespace google<|fim▁end|>
(PyCFunction)FindExtensionByName, METH_O, C("Searches for extension descriptor by full name.") }, {NULL}
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>/// <reference types="chai" /> declare module "chai-bytes" { function chaiBytes(chai: any, utils: any): void; export = chaiBytes; } <|fim▁hole|> interface Assertion extends LanguageChains, NumericComparison, TypeComparison { equalBytes(expected: string | Array<number> | ArrayLike<number>): void; } }<|fim▁end|>
declare namespace Chai { // For BDD API
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) <|fim▁hole|>class RDoparallel(RPackage): """Provides a parallel backend for the %dopar% function using the parallel package.""" homepage = "https://cloud.r-project.org/package=doParallel" url = "https://cloud.r-project.org/src/contrib/doParallel_1.0.10.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/doParallel" version('1.0.15', sha256='71ad7ea69616468996aefdd8d02a4a234759a21ddde9ed1657e3c537145cd86e') version('1.0.11', sha256='4ccbd2eb46d3e4f5251b0c3de4d93d9168b02bb0be493656d6aea236667ff76a') version('1.0.10', sha256='70024b6950025cc027022ee409f382e5ad3680c0a25bcd404bfc16418be8add5') depends_on('[email protected]:', type=('build', 'run')) depends_on('[email protected]:', type=('build', 'run')) depends_on('[email protected]:', type=('build', 'run'))<|fim▁end|>
from spack import *
<|file_name|>test_cert.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import unittest from cert import test_user_agent class Logger(object): """Dummy logger"""<|fim▁hole|>class TestCert(unittest.TestCase): def setUp(self): self.logger = Logger() def test_test_user_agent(self): self.assertFalse(test_user_agent("Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0", self.logger), "android") self.assertTrue(test_user_agent("Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "mobile") self.assertTrue(test_user_agent("Mozilla/5.0 (Tablet; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "tablet") self.assertTrue(test_user_agent("Mozilla/5.0 (Mobile; nnnn; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "example device") self.assertFalse(test_user_agent("Mozilla/5.0 (Mobile; nn nn; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "invalid device") self.assertFalse(test_user_agent("Mozilla/5.0 (Mobile; nn;nn; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "invalid device") self.assertFalse(test_user_agent("Mozilla/5.0 (Mobile; nn/nn; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "invalid device") self.assertFalse(test_user_agent("Mozilla/5.0 (Mobile; nn(nn; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "invalid device") self.assertFalse(test_user_agent("Mozilla/5.0 (Mobile; nn)nn; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "invalid device") self.assertTrue(test_user_agent("Mozilla/5.0 (Mobile; nnnn ; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "extra whitespace in device") self.assertTrue(test_user_agent("Mozilla/5.0 (Mobile;nnnn; rv:26.0) Gecko/26.0 Firefox/26.0", self.logger), "no whitespace in device") if __name__ == '__main__': unittest.main()<|fim▁end|>
def test_status(this, *args): pass
<|file_name|>TramoView.js<|end_file_name|><|fim▁begin|>define(function() { var TramoView = Backbone.View.extend({ <|fim▁hole|> events: {}, initialize: function() {}, render: function(index) { $(this.el).html(this.template(this.model.toJSON())) .addClass((index % 2 === 0) ? 'row1' : 'row2'); return this; } }); return TramoView; });<|fim▁end|>
tagName: 'tr', template: _.template($('#tramo-tmpl').html()),
<|file_name|>test_tree.py<|end_file_name|><|fim▁begin|>""" Testing for the tree module (sklearn.tree). """ import numpy as np from numpy.testing import assert_array_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_almost_equal from numpy.testing import assert_equal from nose.tools import assert_raises from nose.tools import assert_true from sklearn import tree from sklearn import datasets # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [-1, -1, -1, 1, 1, 1] T = [[-1, -1], [2, 2], [3, 2]] true_result = [-1, 1, 1] # also load the iris dataset # and randomly permute it iris = datasets.load_iris() rng = np.random.RandomState(1) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # also load the boston dataset # and randomly permute it boston = datasets.load_boston() perm = rng.permutation(boston.target.size) boston.data = boston.data[perm] boston.target = boston.target[perm] def test_classification_toy(): """Check classification on a toy dataset.""" clf = tree.DecisionTreeClassifier() clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) # With subsampling clf = tree.DecisionTreeClassifier(max_features=1, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) def test_regression_toy(): """Check regression on a toy dataset.""" clf = tree.DecisionTreeRegressor() clf.fit(X, y) assert_almost_equal(clf.predict(T), true_result) # With subsampling clf = tree.DecisionTreeRegressor(max_features=1, random_state=1) clf.fit(X, y) assert_almost_equal(clf.predict(T), true_result) def test_xor(): """Check on a XOR problem""" y = np.zeros((10, 10)) y[:5, :5] = 1 y[5:, 5:] = 1 gridx, gridy = np.indices(y.shape) X = np.vstack([gridx.ravel(), gridy.ravel()]).T y = y.ravel() clf = tree.DecisionTreeClassifier() clf.fit(X, y) assert_equal(clf.score(X, y), 1.0) clf = tree.DecisionTreeClassifier(max_features=1) clf.fit(X, y) assert_equal(clf.score(X, y), 1.0) clf = tree.ExtraTreeClassifier() clf.fit(X, y) assert_equal(clf.score(X, y), 1.0) clf = tree.ExtraTreeClassifier(max_features=1) clf.fit(X, y) assert_equal(clf.score(X, y), 1.0) def test_graphviz_toy(): """Check correctness of graphviz output on a toy dataset.""" clf = tree.DecisionTreeClassifier(max_depth=3, min_samples_split=1) clf.fit(X, y) from StringIO import StringIO # test export code out = StringIO() tree.export_graphviz(clf, out_file=out) contents1 = out.getvalue() tree_toy = StringIO("digraph Tree {\n" "0 [label=\"X[0] <= 0.0000\\nerror = 0.5" "\\nsamples = 6\\nvalue = [ 3. 3.]\", shape=\"box\"] ;\n" "1 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 3. 0.]\", shape=\"box\"] ;\n" "0 -> 1 ;\n" "2 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 0. 3.]\", shape=\"box\"] ;\n" "0 -> 2 ;\n" "}") contents2 = tree_toy.getvalue() assert contents1 == contents2, \ "graphviz output test failed\n: %s != %s" % (contents1, contents2) # test with feature_names out = StringIO() out = tree.export_graphviz(clf, out_file=out, feature_names=["feature1", ""]) contents1 = out.getvalue() tree_toy = StringIO("digraph Tree {\n" "0 [label=\"feature1 <= 0.0000\\nerror = 0.5" "\\nsamples = 6\\nvalue = [ 3. 3.]\", shape=\"box\"] ;\n" "1 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 3. 0.]\", shape=\"box\"] ;\n" "0 -> 1 ;\n" "2 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 0. 3.]\", shape=\"box\"] ;\n" "0 -> 2 ;\n" "}") contents2 = tree_toy.getvalue() assert contents1 == contents2, \ "graphviz output test failed\n: %s != %s" % (contents1, contents2) # test improperly formed feature_names out = StringIO() assert_raises(IndexError, tree.export_graphviz, clf, out, feature_names=[]) def test_iris(): """Check consistency on dataset iris.""" for c in ('gini', 'entropy'): clf = tree.DecisionTreeClassifier(criterion=c).fit(iris.data, iris.target) score = np.mean(clf.predict(iris.data) == iris.target) assert score > 0.9, "Failed with criterion " + c + \ " and score = " + str(score) clf = tree.DecisionTreeClassifier(criterion=c, max_features=2, random_state=1).fit(iris.data, iris.target) score = np.mean(clf.predict(iris.data) == iris.target) assert score > 0.5, "Failed with criterion " + c + \ " and score = " + str(score) def test_boston(): """Check consistency on dataset boston house prices.""" for c in ('mse',): clf = tree.DecisionTreeRegressor(criterion=c).fit(boston.data, boston.target) score = np.mean(np.power(clf.predict(boston.data) - boston.target, 2)) assert score < 1, "Failed with criterion " + c + \ " and score = " + str(score) clf = tree.DecisionTreeRegressor(criterion=c, max_features=6, random_state=1).fit(boston.data, boston.target) #using fewer features reduces the learning ability of this tree, # but reduces training time. score = np.mean(np.power(clf.predict(boston.data) - boston.target, 2)) assert score < 2, "Failed with criterion " + c + \ " and score = " + str(score) def test_probability(): """Predict probabilities using DecisionTreeClassifier.""" clf = tree.DecisionTreeClassifier(max_depth=1, max_features=1, random_state=42) clf.fit(iris.data, iris.target) prob_predict = clf.predict_proba(iris.data) assert_array_almost_equal( np.sum(prob_predict, 1), np.ones(iris.data.shape[0])) assert np.mean(np.argmax(prob_predict, 1) == clf.predict(iris.data)) > 0.9 assert_almost_equal(clf.predict_proba(iris.data), np.exp(clf.predict_log_proba(iris.data)), 8) def test_arrayrepr(): """Check the array representation.""" # Check resize clf = tree.DecisionTreeRegressor(max_depth=None) X = np.arange(10000)[:, np.newaxis] y = np.arange(10000) clf.fit(X, y) def test_pure_set(): """Check when y is pure.""" X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [1, 1, 1, 1, 1, 1] clf = tree.DecisionTreeClassifier().fit(X, y) assert_array_equal(clf.predict(X), y) clf = tree.DecisionTreeRegressor().fit(X, y) assert_array_equal(clf.predict(X), y) def test_numerical_stability(): """Check numerical stability.""" old_settings = np.geterr() np.seterr(all="raise") X = np.array([ [152.08097839, 140.40744019, 129.75102234, 159.90493774], [142.50700378, 135.81935120, 117.82884979, 162.75781250], [127.28772736, 140.40744019, 129.75102234, 159.90493774], [132.37025452, 143.71923828, 138.35694885, 157.84558105], [103.10237122, 143.71928406, 138.35696411, 157.84559631], [127.71276855, 143.71923828, 138.35694885, 157.84558105], [120.91514587, 140.40744019, 129.75102234, 159.90493774]]) y = np.array( [1., 0.70209277, 0.53896582, 0., 0.90914464, 0.48026916, 0.49622521]) dt = tree.DecisionTreeRegressor() dt.fit(X, y) dt.fit(X, -y) dt.fit(-X, y) dt.fit(-X, -y) np.seterr(**old_settings) def test_importances(): """Check variable importances.""" X, y = datasets.make_classification(n_samples=1000, n_features=10, n_informative=3, n_redundant=0, n_repeated=0, shuffle=False, random_state=0) clf = tree.DecisionTreeClassifier(compute_importances=True) clf.fit(X, y) importances = clf.feature_importances_ n_important = sum(importances > 0.1) assert_equal(importances.shape[0], 10) assert_equal(n_important, 3) X_new = clf.transform(X, threshold="mean") assert 0 < X_new.shape[1] < X.shape[1] clf = tree.DecisionTreeClassifier() clf.fit(X, y) assert_true(clf.feature_importances_ is None) def test_error(): """Test that it gives proper exception on deficient input.""" # Invalid values for parameters assert_raises(ValueError, tree.DecisionTreeClassifier(min_samples_leaf=-1).fit, X, y) assert_raises(ValueError, tree.DecisionTreeClassifier(max_depth=-1).fit, X, y) assert_raises(ValueError, tree.DecisionTreeClassifier(min_density=2.0).fit, X, y) assert_raises(ValueError, tree.DecisionTreeClassifier(max_features=42).fit, X, y) # Wrong dimensions clf = tree.DecisionTreeClassifier() y2 = y[:-1] assert_raises(ValueError, clf.fit, X, y2) # Test with arrays that are non-contiguous. Xf = np.asfortranarray(X) clf = tree.DecisionTreeClassifier() clf.fit(Xf, y) assert_array_equal(clf.predict(T), true_result) # predict before fitting clf = tree.DecisionTreeClassifier() assert_raises(Exception, clf.predict, T) # predict on vector with different dims clf.fit(X, y) t = np.asarray(T) assert_raises(ValueError, clf.predict, t[:, 1:]) # use values of max_features that are invalid clf = tree.DecisionTreeClassifier(max_features=10) assert_raises(ValueError, clf.fit, X, y) clf = tree.DecisionTreeClassifier(max_features=-1) assert_raises(ValueError, clf.fit, X, y) clf = tree.DecisionTreeClassifier(max_features="foobar") assert_raises(ValueError, clf.fit, X, y) tree.DecisionTreeClassifier(max_features="auto").fit(X, y) tree.DecisionTreeClassifier(max_features="sqrt").fit(X, y) tree.DecisionTreeClassifier(max_features="log2").fit(X, y) tree.DecisionTreeClassifier(max_features=None).fit(X, y) # predict before fit clf = tree.DecisionTreeClassifier() assert_raises(Exception, clf.predict_proba, X) clf.fit(X, y) X2 = [-2, -1, 1] # wrong feature shape for sample assert_raises(ValueError, clf.predict_proba, X2) # wrong sample shape Xt = np.array(X).T clf = tree.DecisionTreeClassifier() clf.fit(np.dot(X, Xt), y) assert_raises(ValueError, clf.predict, X) clf = tree.DecisionTreeClassifier() clf.fit(X, y) assert_raises(ValueError, clf.predict, Xt) # wrong length of sample mask clf = tree.DecisionTreeClassifier() sample_mask = np.array([1]) assert_raises(ValueError, clf.fit, X, y, sample_mask=sample_mask) # wrong length of X_argsorted clf = tree.DecisionTreeClassifier() X_argsorted = np.array([1]) assert_raises(ValueError, clf.fit, X, y, X_argsorted=X_argsorted) def test_min_samples_leaf(): """Test if leaves contain more than leaf_count training examples""" X = np.asfortranarray(iris.data.astype(tree._tree.DTYPE)) y = iris.target for tree_class in [tree.DecisionTreeClassifier, tree.ExtraTreeClassifier]: clf = tree_class(min_samples_leaf=5).fit(X, y) out = clf.tree_.apply(X) node_counts = np.bincount(out) leaf_count = node_counts[node_counts != 0] # drop inner nodes assert np.min(leaf_count) >= 5 def test_pickle(): import pickle # classification obj = tree.DecisionTreeClassifier() obj.fit(iris.data, iris.target) score = obj.score(iris.data, iris.target) s = pickle.dumps(obj) obj2 = pickle.loads(s) assert_equal(type(obj2), obj.__class__) score2 = obj2.score(iris.data, iris.target) assert score == score2, "Failed to generate same score " + \ " after pickling (classification) " # regression obj = tree.DecisionTreeRegressor() obj.fit(boston.data, boston.target) score = obj.score(boston.data, boston.target) s = pickle.dumps(obj) obj2 = pickle.loads(s) assert_equal(type(obj2), obj.__class__) score2 = obj2.score(boston.data, boston.target) assert score == score2, "Failed to generate same score " + \ " after pickling (regression) " def test_multioutput(): """Check estimators on multi-output problems.""" X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [-2, 1], [-1, 1], [-1, 2], [2, -1], [1, -1], [1, -2]] y = [[-1, 0], [-1, 0], [-1, 0], [1, 1], [1, 1], [1, 1], [-1, 2], [-1, 2], [-1, 2], [1, 3], [1, 3], [1, 3]] T = [[-1, -1], [1, 1], [-1, 1], [1, -1]] y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]] # toy classification problem clf = tree.DecisionTreeClassifier() y_hat = clf.fit(X, y).predict(T) assert_array_equal(y_hat, y_true) assert_equal(y_hat.shape, (4, 2)) proba = clf.predict_proba(T) assert_equal(len(proba), 2) assert_equal(proba[0].shape, (4, 2)) assert_equal(proba[1].shape, (4, 4)) log_proba = clf.predict_log_proba(T) assert_equal(len(log_proba), 2) assert_equal(log_proba[0].shape, (4, 2)) assert_equal(log_proba[1].shape, (4, 4)) # toy regression problem clf = tree.DecisionTreeRegressor() y_hat = clf.fit(X, y).predict(T) assert_almost_equal(y_hat, y_true) assert_equal(y_hat.shape, (4, 2)) def test_sample_mask(): """Test sample_mask argument. """ # test list sample_mask clf = tree.DecisionTreeClassifier() sample_mask = [1] * len(X) clf.fit(X, y, sample_mask=sample_mask) assert_array_equal(clf.predict(T), true_result) # test different dtype clf = tree.DecisionTreeClassifier() sample_mask = np.ones((len(X),), dtype=np.int32)<|fim▁hole|> def test_X_argsorted(): """Test X_argsorted argument. """ # test X_argsorted with different layout and dtype clf = tree.DecisionTreeClassifier() X_argsorted = np.argsort(np.array(X).T, axis=1).T clf.fit(X, y, X_argsorted=X_argsorted) assert_array_equal(clf.predict(T), true_result) def test_classes_shape(): """Test that n_classes_ and classes_ have proper shape.""" # Classification, single output clf = tree.DecisionTreeClassifier() clf.fit(X, y) assert_equal(clf.n_classes_, 2) assert_equal(clf.classes_, [-1, 1]) # Classification, multi-output _y = np.vstack((y, np.array(y) * 2)).T clf = tree.DecisionTreeClassifier() clf.fit(X, _y) assert_equal(len(clf.n_classes_), 2) assert_equal(len(clf.classes_), 2) assert_equal(clf.n_classes_, [2, 2]) assert_equal(clf.classes_, [[-1, 1], [-2, 2]]) if __name__ == "__main__": import nose nose.runmodule()<|fim▁end|>
clf.fit(X, y, sample_mask=sample_mask) assert_array_equal(clf.predict(T), true_result)
<|file_name|>_CommandFemMeshGmshFromShape.py<|end_file_name|><|fim▁begin|># *************************************************************************** # * *<|fim▁hole|># * Copyright (c) 2016 - Bernd Hahnebach <[email protected]> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** __title__ = "Command GMSH Mesh From Shape" __author__ = "Bernd Hahnebach" __url__ = "http://www.freecadweb.org" ## @package CommandFemMeshGmshFromShape # \ingroup FEM import FreeCAD from FemCommands import FemCommands import FreeCADGui import FemGui from PySide import QtCore class _CommandFemMeshGmshFromShape(FemCommands): # the FEM_MeshGmshFromShape command definition def __init__(self): super(_CommandFemMeshGmshFromShape, self).__init__() self.resources = {'Pixmap': 'fem-femmesh-gmsh-from-shape', 'MenuText': QtCore.QT_TRANSLATE_NOOP("FEM_MeshGmshFromShape", "FEM mesh from shape by GMSH"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("FEM_MeshGmshFromShape", "Create a FEM mesh from a shape by GMSH mesher")} self.is_active = 'with_part_feature' def Activated(self): FreeCAD.ActiveDocument.openTransaction("Create FEM mesh by GMSH") FreeCADGui.addModule("FemGui") sel = FreeCADGui.Selection.getSelection() if (len(sel) == 1): if(sel[0].isDerivedFrom("Part::Feature")): mesh_obj_name = sel[0].Name + "_Mesh" FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand("ObjectsFem.makeMeshGmsh('" + mesh_obj_name + "')") FreeCADGui.doCommand("App.ActiveDocument.ActiveObject.Part = App.ActiveDocument." + sel[0].Name) if FemGui.getActiveAnalysis(): FreeCADGui.addModule("FemGui") FreeCADGui.doCommand("FemGui.getActiveAnalysis().Member = FemGui.getActiveAnalysis().Member + [App.ActiveDocument.ActiveObject]") FreeCADGui.doCommand("Gui.ActiveDocument.setEdit(App.ActiveDocument.ActiveObject.Name)") FreeCADGui.Selection.clearSelection() FreeCADGui.addCommand('FEM_MeshGmshFromShape', _CommandFemMeshGmshFromShape())<|fim▁end|>
<|file_name|>file.py<|end_file_name|><|fim▁begin|>from qit.base.type import Type class File(Type): <|fim▁hole|> pass_by_value = True def build(self, builder): return "FILE*"<|fim▁end|>
<|file_name|>ops_invokevirtual.py<|end_file_name|><|fim▁begin|># PyJVM (pyjvm.org) Java Virtual Machine implemented in pure Python # Copyright (C) 2014 Andrew Romanenco ([email protected]) # # This program 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. '''Java bytecode implementation''' import logging from pyjvm.bytecode import bytecode from pyjvm.frame import Frame from pyjvm.jassert import jassert_ref from pyjvm.natives import exec_native from pyjvm.thread import SkipThreadCycle from pyjvm.utils import args_count from pyjvm.vmo import vm_obj_call logger = logging.getLogger(__name__) @bytecode(code=0xb6) def invokevirtual(frame): index = (ord(frame.code[frame.pc]) << 8) + ord(frame.code[frame.pc + 1]) frame.pc += 2 cp_item = frame.this_class.constant_pool[index] assert cp_item[0] == 10 # CONSTANT_Methodref klass_info = frame.this_class.constant_pool[cp_item[1]] assert klass_info[0] == 7 # CONSTANT_Class_info name_and_type = frame.this_class.constant_pool[cp_item[2]] assert name_and_type[0] == 12 # name_and_type_index klass_name = frame.this_class.constant_pool[klass_info[1]][1] method_name = frame.this_class.constant_pool[name_and_type[1]][1] method_signature = frame.this_class.constant_pool[name_and_type[2]][1] logger.debug("%s %s %s", klass_name, method_name, method_signature) klass = frame.vm.get_class(klass_name) method = klass.find_method(method_name, method_signature) nargs = args_count(method_signature) + 1 args = [None] * nargs while nargs > 0: value = frame.stack.pop() if type(value) is tuple and value[0] in ('long', 'double'): nargs -= 1 args[nargs - 1] = value nargs -= 1 logger.debug(frame.id) logger.debug(args) logger.debug(method_signature) jassert_ref(args[0]) if args[0] is None: frame.vm.raise_exception(frame, "java/lang/NullPointerException") return if args[0][0] == "vm_ref": # vm owned object call vm_obj_call(frame, args, method_name, method_signature) return # ignore signute polimorphic method instance = frame.vm.heap[args[0][1]] klass = instance.java_class method = None while method is None and klass is not None: if method_name in klass.methods: if method_signature in klass.methods[method_name]: method = klass.methods[method_name][method_signature] break klass = klass.super_class assert method is not None assert klass is not None if method[0] & 0x0100 > 0: # is native? exec_native(frame, args, klass, method_name, method_signature) return obj_mon = None if method[0] & 0x0020 > 0: # is sync obj_mon = frame.vm.heap[args[0][1]] if "@monitor" in obj_mon.fields:<|fim▁hole|> while index < len(args): a = args[index] if type(a) is tuple and a[0] in ('long', 'double'): index += 1 else: frame.stack.append(a) index += 1 raise SkipThreadCycle() else: obj_mon.fields["@monitor"] = frame.thread obj_mon.fields["@monitor_count"] = 1 m_args = [''] * method[1] m_args[0:len(args)] = args[0:len(args)] sub = Frame(frame.thread, klass, method, m_args, "InvVirt: %s %s in %s" % (method_name, method_signature, instance.java_class.this_name)) if obj_mon is not None: sub.monitor = obj_mon frame.thread.frame_stack.append(sub)<|fim▁end|>
if obj_mon.fields["@monitor"] == frame.thread: obj_mon.fields["@monitor_count"] += 1 else: index = 0
<|file_name|>init.go<|end_file_name|><|fim▁begin|><|fim▁hole|> "github.com/lmorg/murex/lang/stdio" "github.com/lmorg/murex/lang/types" ) func init() { // Register data type stdio.RegisterWriteArray(types.Null, newArrayWriter) }<|fim▁end|>
package null import (
<|file_name|>ActionAddClientDependencyAction.java<|end_file_name|><|fim▁begin|>// $Id: ActionAddClientDependencyAction.java 41 2010-04-03 20:04:12Z marcusvnac $ // Copyright (c) 2007 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and <|fim▁hole|>// does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui.foundation.core; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.argouml.i18n.Translator; import org.argouml.kernel.ProjectManager; import org.argouml.model.Model; import org.argouml.uml.ui.AbstractActionAddModelElement2; /** * An Action to add client dependencies to some modelelement. * * @author Michiel */ public class ActionAddClientDependencyAction extends AbstractActionAddModelElement2 { /** * The constructor. */ public ActionAddClientDependencyAction() { super(); setMultiSelect(true); } /* * Constraint: This code only deals with 1 supplier per dependency! * TODO: How to support more? * * @see org.argouml.uml.ui.AbstractActionAddModelElement#doIt(java.util.List) */ protected void doIt(Collection selected) { Set oldSet = new HashSet(getSelected()); for (Object client : selected) { if (oldSet.contains(client)) { oldSet.remove(client); //to be able to remove dependencies later } else { Model.getCoreFactory().buildDependency(getTarget(), client); } } Collection toBeDeleted = new ArrayList(); Collection dependencies = Model.getFacade().getClientDependencies( getTarget()); for (Object dependency : dependencies) { if (oldSet.containsAll(Model.getFacade().getSuppliers(dependency))) { toBeDeleted.add(dependency); } } ProjectManager.getManager().getCurrentProject() .moveToTrash(toBeDeleted); } /* * @see org.argouml.uml.ui.AbstractActionAddModelElement#getChoices() */ protected List getChoices() { List ret = new ArrayList(); Object model = ProjectManager.getManager().getCurrentProject().getModel(); if (getTarget() != null) { ret.addAll(Model.getModelManagementHelper() .getAllModelElementsOfKind(model, "org.omg.uml.foundation.core.ModelElement")); ret.remove(getTarget()); } return ret; } /* * @see org.argouml.uml.ui.AbstractActionAddModelElement#getDialogTitle() */ protected String getDialogTitle() { return Translator.localize("dialog.title.add-client-dependency"); } /* * @see org.argouml.uml.ui.AbstractActionAddModelElement#getSelected() */ protected List getSelected() { List v = new ArrayList(); Collection c = Model.getFacade().getClientDependencies(getTarget()); for (Object cd : c) { v.addAll(Model.getFacade().getSuppliers(cd)); } return v; } }<|fim▁end|>
// documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents
<|file_name|>forms.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Forms for the votes application. """ # standard library # django from django import forms # models from .models import Vote # views from base.forms import BaseModelForm class VoteForm(BaseModelForm): """ Form Vote model. """ score = forms.IntegerField(required=True) class Meta:<|fim▁hole|> widgets = { 'user': forms.HiddenInput(), 'card': forms.HiddenInput(), } exclude = ()<|fim▁end|>
model = Vote
<|file_name|>example.py<|end_file_name|><|fim▁begin|>#/usr/bin/env python from fsm import Machine states = ["q1", "q2", "q3"] alphabet = ["0","1"] transitions = { "q1": {"0": "q1", "1": "q2"},<|fim▁hole|>start = "q1" end = ["q2"] machine = Machine.from_arguments(states, alphabet, transitions, start, end) machine.run(123) # fail machine.run("") # fail machine.run("1") # pass machine.run("11") # pass machine.run("0100101") # pass<|fim▁end|>
"q2": {"0": "q3", "1": "q2"}, "q3": {"0": "q2", "1": "q2"}, }
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! Miscellaneous Rust utilities //! //! [Repository](https://github.com/spearman/rs-utils) #![feature(decl_macro)] extern crate generic_array; extern crate typenum;<|fim▁hole|>#[cfg(test)] extern crate tempdir; pub mod array; pub mod file; pub mod numeric; pub mod macros; pub use self::macros::*; #[cfg(feature = "app")] pub mod app;<|fim▁end|>
#[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate quickcheck_macros;
<|file_name|>beam.py<|end_file_name|><|fim▁begin|># pylint: disable=R0904,R0902,E1101,E1103,C0111,C0302,C0103,W0101 from six import string_types import numpy as np from numpy.linalg import norm from pyNastran.utils import integer_types from pyNastran.bdf.cards.elements.bars import CBAR, LineElement from pyNastran.bdf.bdf_interface.assign_type import ( integer, integer_or_blank, double_or_blank, integer_double_string_or_blank) from pyNastran.bdf.field_writer_8 import set_blank_if_default from pyNastran.bdf.field_writer_8 import print_card_8 from pyNastran.bdf.field_writer_16 import print_card_16 class CBEAM(CBAR): """ +-------+-----+-----+-----+-----+-----+-----+-----+----------+ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | +=======+=====+=====+=====+=====+=====+=====+=====+==========+ | CBEAM | EID | PID | GA | GB | X1 | X2 | X3 | OFFT/BIT | +-------+-----+-----+-----+-----+-----+-----+-----+----------+ | | PA | PB | W1A | W2A | W3A | W1B | W2B | W3B | +-------+-----+-----+-----+-----+-----+-----+-----+----------+ | | SA | SB | | | | | | | +-------+-----+-----+-----+-----+-----+-----+-----+----------+ or +-------+-----+-----+-----+-----+-----+-----+-----+----------+ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | +=======+=====+=====+=====+=====+=====+=====+=====+==========+ | CBEAM | EID | PID | GA | GB | G0 | | | OFFT/BIT | +-------+-----+-----+-----+-----+-----+-----+-----+----------+ | | PA | PB | W1A | W2A | W3A | W1B | W2B | W3B | +-------+-----+-----+-----+-----+-----+-----+-----+----------+ | | SA | SB | | | | | | | +-------+-----+-----+-----+-----+-----+-----+-----+----------+ offt/bit are MSC specific fields """ type = 'CBEAM' _field_map = { 1: 'eid', 2:'pid', 3:'ga', 4:'gb', #5:'x_g0', 6:'g1', 7:'g2', #8:'offt', 9:'pa', 10:'pb', 17:'sa', 18:'sb', } def _update_field_helper(self, n, value): if n == 11: self.wa[0] = value elif n == 12: self.wa[1] = value elif n == 13: self.wa[2] = value elif n == 14: self.wb[0] = value elif n == 15: self.wb[1] = value elif n == 16: self.wb[2] = value else: if self.g0 is not None: if n == 5: self.g0 = value else: # offt msg = 'Field %r=%r is an invalid %s entry or is unsupported.' % ( n, value, self.type) raise KeyError(msg) else: if n == 5: self.x[0] = value elif n == 6: self.x[1] = value elif n == 7: self.x[2] = value else: msg = 'Field %r=%r is an invalid %s entry or is unsupported.' % ( n, value, self.type) raise KeyError(msg) def __init__(self, eid, pid, ga, gb, x, g0, offt, bit, pa=0, pb=0, wa=None, wb=None, sa=0, sb=0, comment=''): """ Adds a CBEAM card Parameters ---------- pid : int property id mid : int material id ga / gb : int grid point at End A/B x : List[float, float, float] Components of orientation vector, from GA, in the displacement coordinate system at GA (default), or in the basic coordinate system g0 : int Alternate method to supply the orientation vector using grid point G0. Direction of is from GA to G0. is then transferred to End A offt : str; default='GGG' Offset vector interpretation flag None : bit is active bit : float; default=None Built-in twist of the cross-sectional axes about the beam axis <|fim▁hole|> Pin Flag at End A/B. Releases the specified DOFs wa / wb : List[float, float, float] Components of offset vectors from the grid points to the end points of the axis of the shear center sa / sb : int; default=0 Scalar or grid point identification numbers for the ends A and B, respectively. The degrees-of-freedom at these points are the warping variables . SA and SB cannot be specified for beam p-elements comment : str; default='' a comment for the card offt/bit are MSC specific fields """ LineElement.__init__(self) if comment: self.comment = comment if wa is None: wa = np.zeros(3, dtype='float64') else: wa = np.asarray(wa) if wb is None: wb = np.zeros(3, dtype='float64') else: wb = np.asarray(wb) self.eid = eid self.pid = pid self.ga = ga self.gb = gb self.x = x self.g0 = g0 self.offt = offt self.bit = bit self.pa = pa self.pb = pb self.wa = wa self.wb = wb self.sa = sa self.sb = sb self._validate_input() @classmethod def add_card(cls, card, comment=''): eid = integer(card, 1, 'eid') pid = integer_or_blank(card, 2, 'pid', eid) ga = integer(card, 3, 'ga') gb = integer(card, 4, 'gb') x, g0 = cls._init_x_g0(card, eid) offt, bit = cls._init_offt_bit(card, eid)# offt doesn't exist in NX nastran pa = integer_or_blank(card, 9, 'pa', 0) pb = integer_or_blank(card, 10, 'pb', 0) wa = np.array([double_or_blank(card, 11, 'w1a', 0.0), double_or_blank(card, 12, 'w2a', 0.0), double_or_blank(card, 13, 'w3a', 0.0)], 'float64') wb = np.array([double_or_blank(card, 14, 'w1b', 0.0), double_or_blank(card, 15, 'w2b', 0.0), double_or_blank(card, 16, 'w3b', 0.0)], 'float64') sa = integer_or_blank(card, 17, 'sa', 0) sb = integer_or_blank(card, 18, 'sb', 0) assert len(card) <= 19, 'len(CBEAM card) = %i\ncard=%s' % (len(card), card) return CBEAM(eid, pid, ga, gb, x, g0, offt, bit, pa=pa, pb=pb, wa=wa, wb=wb, sa=sa, sb=sb, comment=comment) @classmethod def add_op2_data(cls, data, f, comment=''): #: .. todo:: verify assert len(data) == 2, 'data=%s len(data)=%s' % (data, len(data)) #data = [[eid,pid,ga,gb,sa,sb, pa,pb,w1a,w2a,w3a,w1b,w2b,w3b], # [f,g0]] #data = [[eid,pid,ga,gb,sa,sb, pa,pb,w1a,w2a,w3a,w1b,w2b,w3b], # [f,x1,x2,x3]] main, aft = data flag = aft[0] assert f == flag, 'f=%s flag=%s' % (f, flag) if flag == 0: # basic cid #data_in = [[eid, pid, ga, gb, sa, sb, pa, pb, w1a, w2a, w3a, w1b, w2b, w3b], #[f, x1, x2, x3]] assert len(aft) == 4, 'f=%s aft=%s len(aft)=%s' % (f, aft, len(aft)) x1, x2, x3 = aft[1:] g0 = None x = np.array([x1, x2, x3], dtype='float64') elif flag == 1: # global cid #data_in = [[eid, pid, ga, gb, sa, sb, pa, pb, w1a, w2a, w3a, w1b, w2b, w3b], #[f, x1, x2, x3]] assert len(aft) == 4, 'f=%s aft=%s len(aft)=%s' % (f, aft, len(aft)) g0 = None x1, x2, x3 = aft[1:] x = np.array([x1, x2, x3], dtype='float64') elif flag == 2: # grid option #data_in = [[eid, pid, ga, gb, sa, sb, pa, pb, w1a, w2a, w3a, w1b, w2b, w3b], #[f, g0]] assert len(aft) == 2, 'f=%s aft=%s len(aft)=%s' % (f, aft, len(aft)) g0 = data[1][1] x = None else: raise NotImplementedError() eid = main[0] pid = main[1] ga = main[2] gb = main[3] sa = main[4] sb = main[5] #offt = str(data[6]) # GGG bit = None # ??? offt = 'GGG' #: .. todo:: is this correct??? pa = main[6] pb = main[7] wa = np.array([main[8], main[9], main[10]], 'float64') wb = np.array([main[11], main[12], main[13]], 'float64') return CBEAM(eid, pid, ga, gb, x, g0, offt, bit, pa=pa, pb=pb, wa=wa, wb=wb, sa=sa, sb=sb, comment=comment) def _validate_input(self): if self.g0 in [self.ga, self.gb]: msg = 'G0=%s cannot be GA=%s or GB=%s' % (self.g0, self.ga, self.gb) raise RuntimeError(msg) def Nodes(self): return [self.ga, self.gb] @classmethod def _init_offt_bit(cls, card, eid): """ offt doesn't exist in NX nastran """ field8 = integer_double_string_or_blank(card, 8, 'field8') if isinstance(field8, float): offt = None bit = field8 elif field8 is None: offt = 'GGG' # default bit = None elif isinstance(field8, string_types): bit = None offt = field8 msg = 'invalid offt parameter of CBEAM...offt=%s' % offt assert offt[0] in ['G', 'B', 'O', 'E'], msg assert offt[1] in ['G', 'B', 'O', 'E'], msg assert offt[2] in ['G', 'B', 'O', 'E'], msg else: msg = ('field8 on %s card is not a string(offt) or bit ' '(float)...field8=%s\n' % (cls.type, field8)) raise RuntimeError("Card Instantiation: %s" % msg) return offt, bit def Mid(self): if isinstance(self.pid, integer_types): raise RuntimeError('Element eid=%i has not been ' 'cross referenced.\n%s' % (self.eid, str(self))) return self.pid_ref.Mid() def Area(self): if isinstance(self.pid, integer_types): raise RuntimeError('Element eid=%i has not been ' 'cross referenced.\n%s' % (self.eid, str(self))) return self.pid_ref.Area() def Nsm(self): if isinstance(self.pid, integer_types): raise RuntimeError('Element eid=%i has not been ' 'cross referenced.\n%s' % (self.eid, str(self))) return self.pid_ref.Nsm() @property def is_offt(self): """is the offt flag active?""" if isinstance(self.offt, string_types): return True assert isinstance(self.bit, float), 'bit=%s type=%s' % (self.bit, type(self.bit)) return False @property def is_bit(self): """is the bit flag active?""" return not self.is_offt def get_offt_bit_defaults(self): """ offt doesn't exist in NX nastran """ if self.is_offt: field8 = set_blank_if_default(self.offt, 'GGG') else: field8 = set_blank_if_default(self.bit, 0.0) return field8 def cross_reference(self, model): """ Cross links the card so referenced cards can be extracted directly Parameters ---------- model : BDF() the BDF object """ msg = ' which is required by CBEAM eid=%s' % (self.eid) self.ga = model.Node(self.ga, msg=msg) self.ga_ref = self.ga self.gb = model.Node(self.gb, msg=msg) self.gb_ref = self.gb self.nodes = model.Nodes([self.ga.nid, self.gb.nid], msg=msg) self.nodes_ref = self.nodes self.pid = model.Property(self.pid, msg=msg) self.pid_ref = self.pid if self.g0: g0 = model.nodes[self.g0] self.g0_vector = g0.get_position() - self.ga.get_position() else: self.g0_vector = self.x if model.is_nx: assert self.offt == 'GGG', 'NX only support offt=GGG; offt=%r' % self.offt def safe_cross_reference(self, model): msg = ' which is required by CBEAM eid=%s' % (self.eid) self.ga = model.Node(self.ga, msg=msg) self.gb = model.Node(self.gb, msg=msg) self.ga_ref = self.ga self.gb_ref = self.gb try: self.pid = model.Property(self.pid, msg=msg) self.pid_ref = self.pid except KeyError: model.log.warning('pid=%s%s' % (self.pid, msg)) if self.g0: try: g0 = model.nodes[self.g0] self.g0_vector = g0.get_position() - self.ga.get_position() except KeyError: model.log.warning('Node=%s%s' % (self.g0, msg)) else: self.g0_vector = self.x def uncross_reference(self): self.pid = self.Pid() self.ga = self.Ga() self.gb = self.Gb() del self.ga_ref, self.gb_ref, self.pid_ref def raw_fields(self): (x1, x2, x3) = self.getX_G0_defaults() offt = self.getOfft_Bit_defaults() ga, gb = self.node_ids list_fields = ['CBEAM', self.eid, self.Pid(), ga, gb, x1, x2, x3, offt, self.pa, self.pb] + list(self.wa) + list(self.wb) + [self.sa, self.sb] return list_fields def repr_fields(self): w1a = set_blank_if_default(self.wa[0], 0.0) w2a = set_blank_if_default(self.wa[1], 0.0) w3a = set_blank_if_default(self.wa[2], 0.0) w1b = set_blank_if_default(self.wb[0], 0.0) w2b = set_blank_if_default(self.wb[1], 0.0) w3b = set_blank_if_default(self.wb[2], 0.0) sa = set_blank_if_default(self.sa, 0) sb = set_blank_if_default(self.sb, 0) (x1, x2, x3) = self.getX_G0_defaults() offt = self.get_offt_bit_defaults() ga, gb = self.node_ids list_fields = ['CBEAM', self.eid, self.Pid(), ga, gb, x1, x2, x3, offt, self.pa, self.pb, w1a, w2a, w3a, w1b, w2b, w3b, sa, sb] return list_fields def write_card(self, size=8, is_double=False): card = self.repr_fields() if size == 8: return self.comment + print_card_8(card) return self.comment + print_card_16(card) def write_card_16(self, is_double=False): card = self.repr_fields() return self.comment + print_card_16(card)<|fim▁end|>
at end B relative to end A. For beam p-elements ONLY! None : offt is active pa / pb : int; default=0
<|file_name|>edit-attributes.js<|end_file_name|><|fim▁begin|>/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM 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. * * EspoCRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. *<|fim▁hole|> * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ Espo.define('views/admin/layouts/modals/edit-attributes', ['views/modal', 'model'], function (Dep, Model) { return Dep.extend({ _template: '<div class="edit-container">{{{edit}}}</div>', setup: function () { this.buttonList = [ { name: 'save', text: this.translate('Apply'), style: 'primary' }, { name: 'cancel', text: 'Cancel' } ]; var model = new Model(); model.name = 'LayoutManager'; model.set(this.options.attributes || {}); this.header = this.translate(this.options.name, 'fields', this.options.scope); var attributeList = Espo.Utils.clone(this.options.attributeList || []); var index = attributeList.indexOf('name'); if (~index) { attributeList.splice(index, 1); } this.createView('edit', 'Admin.Layouts.Record.EditAttributes', { el: this.options.el + ' .edit-container', attributeList: attributeList, attributeDefs: this.options.attributeDefs, model: model }); }, actionSave: function () { var editView = this.getView('edit'); var attrs = editView.fetch(); editView.model.set(attrs, {silent: true}); if (editView.validate()) { return; } var attributes = {}; attributes = editView.model.attributes; this.trigger('after:save', attributes); return true; }, }); });<|fim▁end|>
* The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. *
<|file_name|>db.go<|end_file_name|><|fim▁begin|>package bolt import ( "errors" "fmt" "hash/fnv" "log" "os" "runtime" "runtime/debug" "strings" "sync" "time" "unsafe" ) // The largest step that can be taken when remapping the mmap. const maxMmapStep = 1 << 30 // 1GB // The data file format version. const version = 2 // Represents a marker value to indicate that a file is a Bolt DB. const magic uint32 = 0xED0CDAED // IgnoreNoSync specifies whether the NoSync field of a DB is ignored when // syncing changes to a file. This is required as some operating systems, // such as OpenBSD, do not have a unified buffer cache (UBC) and writes // must be synchronized using the msync(2) syscall. const IgnoreNoSync = runtime.GOOS == "openbsd" // Default values if not set in a DB instance. const ( DefaultMaxBatchSize int = 1000 DefaultMaxBatchDelay = 10 * time.Millisecond DefaultAllocSize = 16 * 1024 * 1024 ) // DB represents a collection of buckets persisted to a file on disk. // All data access is performed through transactions which can be obtained through the DB. // All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called. type DB struct { // When enabled, the database will perform a Check() after every commit. // A panic is issued if the database is in an inconsistent state. This // flag has a large performance impact so it should only be used for // debugging purposes. StrictMode bool // Setting the NoSync flag will cause the database to skip fsync() // calls after each commit. This can be useful when bulk loading data // into a database and you can restart the bulk load in the event of // a system failure or database corruption. Do not set this flag for // normal use. //<|fim▁hole|> // ignored. See the comment on that constant for more details. // // THIS IS UNSAFE. PLEASE USE WITH CAUTION. NoSync bool // When true, skips the truncate call when growing the database. // Setting this to true is only safe on non-ext3/ext4 systems. // Skipping truncation avoids preallocation of hard drive space and // bypasses a truncate() and fsync() syscall on remapping. // // https://github.com/boltdb/bolt/issues/284 NoGrowSync bool // If you want to read the entire database fast, you can set MmapFlag to // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead. MmapFlags int // MaxBatchSize is the maximum size of a batch. Default value is // copied from DefaultMaxBatchSize in Open. // // If <=0, disables batching. // // Do not change concurrently with calls to Batch. MaxBatchSize int // MaxBatchDelay is the maximum delay before a batch starts. // Default value is copied from DefaultMaxBatchDelay in Open. // // If <=0, effectively disables batching. // // Do not change concurrently with calls to Batch. MaxBatchDelay time.Duration // AllocSize is the amount of space allocated when the database // needs to create new pages. This is done to amortize the cost // of truncate() and fsync() when growing the data file. AllocSize int path string file *os.File dataref []byte // mmap'ed readonly, write throws SEGV data *[maxMapSize]byte datasz int filesz int // current on disk file size meta0 *meta meta1 *meta pageSize int opened bool rwtx *Tx txs []*Tx freelist *freelist stats Stats batchMu sync.Mutex batch *batch rwlock sync.Mutex // Allows only one writer at a time. metalock sync.Mutex // Protects meta page access. mmaplock sync.RWMutex // Protects mmap access during remapping. statlock sync.RWMutex // Protects stats access. ops struct { writeAt func(b []byte, off int64) (n int, err error) } // Read only mode. // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately. readOnly bool } // Path returns the path to currently open database file. func (db *DB) Path() string { return db.path } // GoString returns the Go string representation of the database. func (db *DB) GoString() string { return fmt.Sprintf("bolt.DB{path:%q}", db.path) } // String returns the string representation of the database. func (db *DB) String() string { return fmt.Sprintf("DB<%q>", db.path) } // Open creates and opens a database at the given path. // If the file does not exist then it will be created automatically. // Passing in nil options will cause Bolt to open the database with the default options. func Open(path string, mode os.FileMode, options *Options) (*DB, error) { var db = &DB{opened: true} // Set default options if no options are provided. if options == nil { options = DefaultOptions } db.NoGrowSync = options.NoGrowSync db.MmapFlags = options.MmapFlags // Set default values for later DB operations. db.MaxBatchSize = DefaultMaxBatchSize db.MaxBatchDelay = DefaultMaxBatchDelay db.AllocSize = DefaultAllocSize flag := os.O_RDWR if options.ReadOnly { flag = os.O_RDONLY db.readOnly = true } // Open data file and separate sync handler for metadata writes. db.path = path var err error if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { _ = db.close() return nil, err } // Lock file so that other processes using Bolt in read-write mode cannot // use the database at the same time. This would cause corruption since // the two processes would write meta pages and free pages separately. // The database file is locked exclusively (only one process can grab the lock) // if !options.ReadOnly. // The database file is locked using the shared lock (more than one process may // hold a lock at the same time) otherwise (options.ReadOnly is set). if err := flock(db.file, !db.readOnly, options.Timeout); err != nil { _ = db.close() return nil, err } // Default values for test hooks db.ops.writeAt = db.file.WriteAt // Initialize the database if it doesn't exist. if info, err := db.file.Stat(); err != nil { return nil, err } else if info.Size() == 0 { // Initialize new files with meta pages. if err := db.init(); err != nil { return nil, err } } else { // Read the first meta page to determine the page size. var buf [0x1000]byte if _, err := db.file.ReadAt(buf[:], 0); err == nil { m := db.pageInBuffer(buf[:], 0).meta() if err := m.validate(); err != nil { return nil, err } db.pageSize = int(m.pageSize) } } // Memory map the data file. if err := db.mmap(options.InitialMmapSize); err != nil { _ = db.close() return nil, err } // Read in the freelist. db.freelist = newFreelist() db.freelist.read(db.page(db.meta().freelist)) // Mark the database as opened and return. return db, nil } // mmap opens the underlying memory-mapped file and initializes the meta references. // minsz is the minimum size that the new mmap can be. func (db *DB) mmap(minsz int) error { db.mmaplock.Lock() defer db.mmaplock.Unlock() info, err := db.file.Stat() if err != nil { return fmt.Errorf("mmap stat error: %s", err) } else if int(info.Size()) < db.pageSize*2 { return fmt.Errorf("file size too small") } // Ensure the size is at least the minimum size. var size = int(info.Size()) if size < minsz { size = minsz } size, err = db.mmapSize(size) if err != nil { return err } // Dereference all mmap references before unmapping. if db.rwtx != nil { db.rwtx.root.dereference() } // Unmap existing data before continuing. if err := db.munmap(); err != nil { return err } // Memory-map the data file as a byte slice. if err := mmap(db, size); err != nil { return err } // Save references to the meta pages. db.meta0 = db.page(0).meta() db.meta1 = db.page(1).meta() // Validate the meta pages. if err := db.meta0.validate(); err != nil { return err } if err := db.meta1.validate(); err != nil { return err } return nil } // munmap unmaps the data file from memory. func (db *DB) munmap() error { if err := munmap(db); err != nil { return fmt.Errorf("unmap error: " + err.Error()) } return nil } // mmapSize determines the appropriate size for the mmap given the current size // of the database. The minimum size is 32KB and doubles until it reaches 1GB. // Returns an error if the new mmap size is greater than the max allowed. func (db *DB) mmapSize(size int) (int, error) { // Double the size from 32KB until 1GB. for i := uint(15); i <= 30; i++ { if size <= 1<<i { return 1 << i, nil } } // Verify the requested size is not above the maximum allowed. if size > maxMapSize { return 0, fmt.Errorf("mmap too large") } // If larger than 1GB then grow by 1GB at a time. sz := int64(size) if remainder := sz % int64(maxMmapStep); remainder > 0 { sz += int64(maxMmapStep) - remainder } // Ensure that the mmap size is a multiple of the page size. // This should always be true since we're incrementing in MBs. pageSize := int64(db.pageSize) if (sz % pageSize) != 0 { sz = ((sz / pageSize) + 1) * pageSize } // If we've exceeded the max size then only grow up to the max size. if sz > maxMapSize { sz = maxMapSize } return int(sz), nil } // init creates a new database file and initializes its meta pages. func (db *DB) init() error { // Set the page size to the OS page size. db.pageSize = os.Getpagesize() // Create two meta pages on a buffer. buf := make([]byte, db.pageSize*4) for i := 0; i < 2; i++ { p := db.pageInBuffer(buf[:], pgid(i)) p.id = pgid(i) p.flags = metaPageFlag // Initialize the meta page. m := p.meta() m.magic = magic m.version = version m.pageSize = uint32(db.pageSize) m.freelist = 2 m.root = bucket{root: 3} m.pgid = 4 m.txid = txid(i) } // Write an empty freelist at page 3. p := db.pageInBuffer(buf[:], pgid(2)) p.id = pgid(2) p.flags = freelistPageFlag p.count = 0 // Write an empty leaf page at page 4. p = db.pageInBuffer(buf[:], pgid(3)) p.id = pgid(3) p.flags = leafPageFlag p.count = 0 // Write the buffer to our data file. if _, err := db.ops.writeAt(buf, 0); err != nil { return err } if err := fdatasync(db); err != nil { return err } return nil } // Close releases all database resources. // All transactions must be closed before closing the database. func (db *DB) Close() error { db.rwlock.Lock() defer db.rwlock.Unlock() db.metalock.Lock() defer db.metalock.Unlock() db.mmaplock.RLock() defer db.mmaplock.RUnlock() return db.close() } func (db *DB) close() error { db.opened = false db.freelist = nil db.path = "" // Clear ops. db.ops.writeAt = nil // Close the mmap. if err := db.munmap(); err != nil { return err } // Close file handles. if db.file != nil { // No need to unlock read-only file. if !db.readOnly { // Unlock the file. if err := funlock(db.file); err != nil { log.Printf("bolt.Close(): funlock error: %s", err) } } // Close the file descriptor. if err := db.file.Close(); err != nil { return fmt.Errorf("db file close: %s", err) } db.file = nil } return nil } // Begin starts a new transaction. // Multiple read-only transactions can be used concurrently but only one // write transaction can be used at a time. Starting multiple write transactions // will cause the calls to block and be serialized until the current write // transaction finishes. // // Transactions should not be dependent on one another. Opening a read // transaction and a write transaction in the same goroutine can cause the // writer to deadlock because the database periodically needs to re-mmap itself // as it grows and it cannot do that while a read transaction is open. // // If a long running read transaction (for example, a snapshot transaction) is // needed, you might want to set DB.InitialMmapSize to a large enough value // to avoid potential blocking of write transaction. // // IMPORTANT: You must close read-only transactions after you are finished or // else the database will not reclaim old pages. func (db *DB) Begin(writable bool) (*Tx, error) { if writable { return db.beginRWTx() } return db.beginTx() } func (db *DB) beginTx() (*Tx, error) { // Lock the meta pages while we initialize the transaction. We obtain // the meta lock before the mmap lock because that's the order that the // write transaction will obtain them. db.metalock.Lock() // Obtain a read-only lock on the mmap. When the mmap is remapped it will // obtain a write lock so all transactions must finish before it can be // remapped. db.mmaplock.RLock() // Exit if the database is not open yet. if !db.opened { db.mmaplock.RUnlock() db.metalock.Unlock() return nil, ErrDatabaseNotOpen } // Create a transaction associated with the database. t := &Tx{} t.init(db) // Keep track of transaction until it closes. db.txs = append(db.txs, t) n := len(db.txs) // Unlock the meta pages. db.metalock.Unlock() // Update the transaction stats. db.statlock.Lock() db.stats.TxN++ db.stats.OpenTxN = n db.statlock.Unlock() return t, nil } func (db *DB) beginRWTx() (*Tx, error) { // If the database was opened with Options.ReadOnly, return an error. if db.readOnly { return nil, ErrDatabaseReadOnly } // Obtain writer lock. This is released by the transaction when it closes. // This enforces only one writer transaction at a time. db.rwlock.Lock() // Once we have the writer lock then we can lock the meta pages so that // we can set up the transaction. db.metalock.Lock() defer db.metalock.Unlock() // Exit if the database is not open yet. if !db.opened { db.rwlock.Unlock() return nil, ErrDatabaseNotOpen } // Create a transaction associated with the database. t := &Tx{writable: true} t.init(db) db.rwtx = t // Free any pages associated with closed read-only transactions. var minid txid = 0xFFFFFFFFFFFFFFFF for _, t := range db.txs { if t.meta.txid < minid { minid = t.meta.txid } } if minid > 0 { db.freelist.release(minid - 1) } return t, nil } // removeTx removes a transaction from the database. func (db *DB) removeTx(tx *Tx) { // Release the read lock on the mmap. db.mmaplock.RUnlock() // Use the meta lock to restrict access to the DB object. db.metalock.Lock() // Remove the transaction. for i, t := range db.txs { if t == tx { db.txs = append(db.txs[:i], db.txs[i+1:]...) break } } n := len(db.txs) // Unlock the meta pages. db.metalock.Unlock() // Merge statistics. db.statlock.Lock() db.stats.OpenTxN = n db.stats.TxStats.add(&tx.stats) db.statlock.Unlock() } // Update executes a function within the context of a read-write managed transaction. // If no error is returned from the function then the transaction is committed. // If an error is returned then the entire transaction is rolled back. // Any error that is returned from the function or returned from the commit is // returned from the Update() method. // // Attempting to manually commit or rollback within the function will cause a panic. func (db *DB) Update(fn func(*Tx) error) error { t, err := db.Begin(true) if err != nil { return err } // Make sure the transaction rolls back in the event of a panic. defer func() { if t.db != nil { t.rollback() } }() // Mark as a managed tx so that the inner function cannot manually commit. t.managed = true // If an error is returned from the function then rollback and return error. err = fn(t) t.managed = false if err != nil { _ = t.Rollback() return err } return t.Commit() } // View executes a function within the context of a managed read-only transaction. // Any error that is returned from the function is returned from the View() method. // // Attempting to manually rollback within the function will cause a panic. func (db *DB) View(fn func(*Tx) error) error { t, err := db.Begin(false) if err != nil { return err } // Make sure the transaction rolls back in the event of a panic. defer func() { if t.db != nil { t.rollback() } }() // Mark as a managed tx so that the inner function cannot manually rollback. t.managed = true // If an error is returned from the function then pass it through. err = fn(t) t.managed = false if err != nil { _ = t.Rollback() return err } if err := t.Rollback(); err != nil { return err } return nil } // Batch calls fn as part of a batch. It behaves similar to Update, // except: // // 1. concurrent Batch calls can be combined into a single Bolt // transaction. // // 2. the function passed to Batch may be called multiple times, // regardless of whether it returns error or not. // // This means that Batch function side effects must be idempotent and // take permanent effect only after a successful return is seen in // caller. // // The maximum batch size and delay can be adjusted with DB.MaxBatchSize // and DB.MaxBatchDelay, respectively. // // Batch is only useful when there are multiple goroutines calling it. func (db *DB) Batch(fn func(*Tx) error) error { errCh := make(chan error, 1) db.batchMu.Lock() if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) { // There is no existing batch, or the existing batch is full; start a new one. db.batch = &batch{ db: db, } db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger) } db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh}) if len(db.batch.calls) >= db.MaxBatchSize { // wake up batch, it's ready to run go db.batch.trigger() } db.batchMu.Unlock() err := <-errCh if err == trySolo { err = db.Update(fn) } return err } type call struct { fn func(*Tx) error err chan<- error } type batch struct { db *DB timer *time.Timer start sync.Once calls []call } // trigger runs the batch if it hasn't already been run. func (b *batch) trigger() { b.start.Do(b.run) } // run performs the transactions in the batch and communicates results // back to DB.Batch. func (b *batch) run() { b.db.batchMu.Lock() b.timer.Stop() // Make sure no new work is added to this batch, but don't break // other batches. if b.db.batch == b { b.db.batch = nil } b.db.batchMu.Unlock() retry: for len(b.calls) > 0 { var failIdx = -1 err := b.db.Update(func(tx *Tx) error { for i, c := range b.calls { if err := safelyCall(c.fn, tx); err != nil { failIdx = i return err } } return nil }) if failIdx >= 0 { // take the failing transaction out of the batch. it's // safe to shorten b.calls here because db.batch no longer // points to us, and we hold the mutex anyway. c := b.calls[failIdx] b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] // tell the submitter re-run it solo, continue with the rest of the batch c.err <- trySolo continue retry } // pass success, or bolt internal errors, to all callers for _, c := range b.calls { if c.err != nil { c.err <- err } } break retry } } // trySolo is a special sentinel error value used for signaling that a // transaction function should be re-run. It should never be seen by // callers. var trySolo = errors.New("batch function returned an error and should be re-run solo") type panicked struct { reason interface{} } func (p panicked) Error() string { if err, ok := p.reason.(error); ok { return err.Error() } return fmt.Sprintf("panic: %v", p.reason) } func safelyCall(fn func(*Tx) error, tx *Tx) (err error) { defer func() { if p := recover(); p != nil { err = panicked{p} } }() return fn(tx) } // Sync executes fdatasync() against the database file handle. // // This is not necessary under normal operation, however, if you use NoSync // then it allows you to force the database file to sync against the disk. func (db *DB) Sync() error { return fdatasync(db) } // Stats retrieves ongoing performance stats for the database. // This is only updated when a transaction closes. func (db *DB) Stats() Stats { db.statlock.RLock() defer db.statlock.RUnlock() return db.stats } // This is for internal access to the raw data bytes from the C cursor, use // carefully, or not at all. func (db *DB) Info() *Info { return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} } // page retrieves a page reference from the mmap based on the current page size. func (db *DB) page(id pgid) *page { pos := id * pgid(db.pageSize) return (*page)(unsafe.Pointer(&db.data[pos])) } // pageInBuffer retrieves a page reference from a given byte array based on the current page size. func (db *DB) pageInBuffer(b []byte, id pgid) *page { return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) } // meta retrieves the current meta page reference. func (db *DB) meta() *meta { if db.meta0.txid > db.meta1.txid { return db.meta0 } return db.meta1 } // allocate returns a contiguous block of memory starting at a given page. func (db *DB) allocate(count int) (*page, error) { // Allocate a temporary buffer for the page. buf := make([]byte, count*db.pageSize) p := (*page)(unsafe.Pointer(&buf[0])) p.overflow = uint32(count - 1) // Use pages from the freelist if they are available. if p.id = db.freelist.allocate(count); p.id != 0 { return p, nil } // Resize mmap() if we're at the end. p.id = db.rwtx.meta.pgid var minsz = int((p.id+pgid(count))+1) * db.pageSize if minsz >= db.datasz { if err := db.mmap(minsz); err != nil { return nil, fmt.Errorf("mmap allocate error: %s", err) } } // Move the page id high water mark. db.rwtx.meta.pgid += pgid(count) return p, nil } // grow grows the size of the database to the given sz. func (db *DB) grow(sz int) error { // Ignore if the new size is less than available file size. if sz <= db.filesz { return nil } // If the data is smaller than the alloc size then only allocate what's needed. // Once it goes over the allocation size then allocate in chunks. if db.datasz < db.AllocSize { sz = db.datasz } else { sz += db.AllocSize } // Truncate and fsync to ensure file size metadata is flushed. // https://github.com/boltdb/bolt/issues/284 if !db.NoGrowSync && !db.readOnly { if err := db.file.Truncate(int64(sz)); err != nil { return fmt.Errorf("file resize error: %s", err) } if err := db.file.Sync(); err != nil { return fmt.Errorf("file sync error: %s", err) } } db.filesz = sz return nil } func (db *DB) IsReadOnly() bool { return db.readOnly } // Options represents the options that can be set when opening a database. type Options struct { // Timeout is the amount of time to wait to obtain a file lock. // When set to zero it will wait indefinitely. This option is only // available on Darwin and Linux. Timeout time.Duration // Sets the DB.NoGrowSync flag before memory mapping the file. NoGrowSync bool // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to // grab a shared lock (UNIX). ReadOnly bool // Sets the DB.MmapFlags flag before memory mapping the file. MmapFlags int // InitialMmapSize is the initial mmap size of the database // in bytes. Read transactions won't block write transaction // if the InitialMmapSize is large enough to hold database mmap // size. (See DB.Begin for more information) // // If <=0, the initial map size is 0. // If initialMmapSize is smaller than the previous database size, // it takes no effect. InitialMmapSize int } // DefaultOptions represent the options used if nil options are passed into Open(). // No timeout is used which will cause Bolt to wait indefinitely for a lock. var DefaultOptions = &Options{ Timeout: 0, NoGrowSync: false, } // Stats represents statistics about the database. type Stats struct { // Freelist stats FreePageN int // total number of free pages on the freelist PendingPageN int // total number of pending pages on the freelist FreeAlloc int // total bytes allocated in free pages FreelistInuse int // total bytes used by the freelist // Transaction stats TxN int // total number of started read transactions OpenTxN int // number of currently open read transactions TxStats TxStats // global, ongoing stats. } // Sub calculates and returns the difference between two sets of database stats. // This is useful when obtaining stats at two different points and time and // you need the performance counters that occurred within that time span. func (s *Stats) Sub(other *Stats) Stats { if other == nil { return *s } var diff Stats diff.FreePageN = s.FreePageN diff.PendingPageN = s.PendingPageN diff.FreeAlloc = s.FreeAlloc diff.FreelistInuse = s.FreelistInuse diff.TxN = other.TxN - s.TxN diff.TxStats = s.TxStats.Sub(&other.TxStats) return diff } func (s *Stats) add(other *Stats) { s.TxStats.add(&other.TxStats) } type Info struct { Data uintptr PageSize int } type meta struct { magic uint32 version uint32 pageSize uint32 flags uint32 root bucket freelist pgid pgid pgid txid txid checksum uint64 } // validate checks the marker bytes and version of the meta page to ensure it matches this binary. func (m *meta) validate() error { if m.checksum != 0 && m.checksum != m.sum64() { return ErrChecksum } else if m.magic != magic { return ErrInvalid } else if m.version != version { return ErrVersionMismatch } return nil } // copy copies one meta object to another. func (m *meta) copy(dest *meta) { *dest = *m } // write writes the meta onto a page. func (m *meta) write(p *page) { if m.root.root >= m.pgid { panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) } else if m.freelist >= m.pgid { panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) } // Page id is either going to be 0 or 1 which we can determine by the transaction ID. p.id = pgid(m.txid % 2) p.flags |= metaPageFlag // Calculate the checksum. m.checksum = m.sum64() m.copy(p.meta()) } // generates the checksum for the meta. func (m *meta) sum64() uint64 { var h = fnv.New64a() _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) return h.Sum64() } // _assert will panic with a given formatted message if the given condition is false. func _assert(condition bool, msg string, v ...interface{}) { if !condition { panic(fmt.Sprintf("assertion failed: "+msg, v...)) } } func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) } func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) } func printstack() { stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n") fmt.Fprintln(os.Stderr, stack) }<|fim▁end|>
// If the package global IgnoreNoSync constant is true, this value is
<|file_name|>bigip_snmp_trap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) <|fim▁hole|>from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: bigip_snmp_trap short_description: Manipulate SNMP trap information on a BIG-IP description: - Manipulate SNMP trap information on a BIG-IP. version_added: 2.4 options: name: description: - Name of the SNMP configuration endpoint. required: True snmp_version: description: - Specifies to which Simple Network Management Protocol (SNMP) version the trap destination applies. choices: - 1 - 2c community: description: - Specifies the community name for the trap destination. destination: description: - Specifies the address for the trap destination. This can be either an IP address or a hostname. port: description: - Specifies the port for the trap destination. network: description: - Specifies the name of the trap network. This option is not supported in versions of BIG-IP < 12.1.0. If used on versions < 12.1.0, it will simply be ignored. choices: - other - management - default state: description: - When C(present), ensures that the cloud connector exists. When C(absent), ensures that the cloud connector does not exist. default: present choices: - present - absent notes: - Requires the f5-sdk Python package on the host. This is as easy as pip install f5-sdk. - This module only supports version v1 and v2c of SNMP. - The C(network) option is not supported on versions of BIG-IP < 12.1.0 because the platform did not support that option until 12.1.0. If used on versions < 12.1.0, it will simply be ignored. extends_documentation_fragment: f5 requirements: - f5-sdk >= 2.2.0 author: - Tim Rupp (@caphrim007) ''' EXAMPLES = ''' - name: Create snmp v1 trap bigip_snmp_trap: community: "general" destination: "1.2.3.4" name: "my-trap1" network: "management" port: "9000" snmp_version: "1" server: "lb.mydomain.com" user: "admin" password: "secret" delegate_to: localhost - name: Create snmp v2 trap bigip_snmp_trap: community: "general" destination: "5.6.7.8" name: "my-trap2" network: "default" port: "7000" snmp_version: "2c" server: "lb.mydomain.com" user: "admin" password: "secret" delegate_to: localhost ''' RETURN = ''' snmp_version: description: The new C(snmp_version) configured on the remote device. returned: changed and success type: string sample: "2c" community: description: The new C(community) name for the trap destination. returned: changed and success type: list sample: "secret" destination: description: The new address for the trap destination in either IP or hostname form. returned: changed and success type: string sample: "1.2.3.4" port: description: The new C(port) of the trap destination. returned: changed and success type: string sample: "900" network: description: The new name of the network the SNMP trap is on. returned: changed and success type: string sample: "management" ''' from distutils.version import LooseVersion from ansible.module_utils.f5_utils import ( AnsibleF5Client, AnsibleF5Parameters, HAS_F5SDK, F5ModuleError, iControlUnexpectedHTTPError ) class Parameters(AnsibleF5Parameters): api_map = { 'version': 'snmp_version', 'community': 'community', 'host': 'destination' } @property def snmp_version(self): if self._values['snmp_version'] is None: return None return str(self._values['snmp_version']) @property def port(self): if self._values['port'] is None: return None return int(self._values['port']) def to_return(self): result = {} for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) return result def api_params(self): result = {} for api_attribute in self.api_attributes: if self.api_map is not None and api_attribute in self.api_map: result[api_attribute] = getattr(self, self.api_map[api_attribute]) else: result[api_attribute] = getattr(self, api_attribute) result = self._filter_params(result) return result class NetworkedParameters(Parameters): updatables = [ 'snmp_version', 'community', 'destination', 'port', 'network' ] returnables = [ 'snmp_version', 'community', 'destination', 'port', 'network' ] api_attributes = [ 'version', 'community', 'host', 'port', 'network' ] @property def network(self): if self._values['network'] is None: return None network = str(self._values['network']) if network == 'management': return 'mgmt' elif network == 'default': return '' else: return network class NonNetworkedParameters(Parameters): updatables = [ 'snmp_version', 'community', 'destination', 'port' ] returnables = [ 'snmp_version', 'community', 'destination', 'port' ] api_attributes = [ 'version', 'community', 'host', 'port' ] @property def network(self): return None class ModuleManager(object): def __init__(self, client): self.client = client def exec_module(self): if self.is_version_non_networked(): manager = NonNetworkedManager(self.client) else: manager = NetworkedManager(self.client) return manager.exec_module() def is_version_non_networked(self): """Checks to see if the TMOS version is less than 13 Anything less than BIG-IP 13.x does not support users on different partitions. :return: Bool """ version = self.client.api.tmos_version if LooseVersion(version) < LooseVersion('12.1.0'): return True else: return False class BaseManager(object): def __init__(self, client): self.client = client self.have = None def exec_module(self): changed = False result = dict() state = self.want.state try: if state == "present": changed = self.present() elif state == "absent": changed = self.absent() except iControlUnexpectedHTTPError as e: raise F5ModuleError(str(e)) changes = self.changes.to_return() result.update(**changes) result.update(dict(changed=changed)) return result def exists(self): result = self.client.api.tm.sys.snmp.traps_s.trap.exists( name=self.want.name, partition=self.want.partition ) return result def present(self): if self.exists(): return self.update() else: return self.create() def create(self): self._set_changed_options() if self.client.check_mode: return True if all(getattr(self.want, v) is None for v in self.required_resources): raise F5ModuleError( "You must specify at least one of " ', '.join(self.required_resources) ) self.create_on_device() return True def should_update(self): result = self._update_changed_options() if result: return True return False def update(self): self.have = self.read_current_from_device() if not self.should_update(): return False if self.client.check_mode: return True self.update_on_device() return True def update_on_device(self): params = self.want.api_params() result = self.client.api.tm.sys.snmp.traps_s.trap.load( name=self.want.name, partition=self.want.partition ) result.modify(**params) def create_on_device(self): params = self.want.api_params() self.client.api.tm.sys.snmp.traps_s.trap.create( name=self.want.name, partition=self.want.partition, **params ) def absent(self): if self.exists(): return self.remove() return False def remove(self): if self.client.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError("Failed to delete the snmp trap") return True def remove_from_device(self): result = self.client.api.tm.sys.snmp.traps_s.trap.load( name=self.want.name, partition=self.want.partition ) if result: result.delete() class NetworkedManager(BaseManager): def __init__(self, client): super(NetworkedManager, self).__init__(client) self.required_resources = [ 'version', 'community', 'destination', 'port', 'network' ] self.want = NetworkedParameters(self.client.module.params) self.changes = NetworkedParameters() def _set_changed_options(self): changed = {} for key in NetworkedParameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = NetworkedParameters(changed) def _update_changed_options(self): changed = {} for key in NetworkedParameters.updatables: if getattr(self.want, key) is not None: attr1 = getattr(self.want, key) attr2 = getattr(self.have, key) if attr1 != attr2: changed[key] = attr1 if changed: self.changes = NetworkedParameters(changed) return True return False def read_current_from_device(self): resource = self.client.api.tm.sys.snmp.traps_s.trap.load( name=self.want.name, partition=self.want.partition ) result = resource.attrs self._ensure_network(result) return NetworkedParameters(result) def _ensure_network(self, result): # BIG-IP's value for "default" is that the key does not # exist. This conflicts with our purpose of having a key # not exist (which we equate to "i dont want to change that" # therefore, if we load the information from BIG-IP and # find that there is no 'network' key, that is BIG-IP's # way of saying that the network value is "default" if 'network' not in result: result['network'] = 'default' class NonNetworkedManager(BaseManager): def __init__(self, client): super(NonNetworkedManager, self).__init__(client) self.required_resources = [ 'version', 'community', 'destination', 'port' ] self.want = NonNetworkedParameters(self.client.module.params) self.changes = NonNetworkedParameters() def _set_changed_options(self): changed = {} for key in NonNetworkedParameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = NonNetworkedParameters(changed) def _update_changed_options(self): changed = {} for key in NonNetworkedParameters.updatables: if getattr(self.want, key) is not None: attr1 = getattr(self.want, key) attr2 = getattr(self.have, key) if attr1 != attr2: changed[key] = attr1 if changed: self.changes = NonNetworkedParameters(changed) return True return False def read_current_from_device(self): resource = self.client.api.tm.sys.snmp.traps_s.trap.load( name=self.want.name, partition=self.want.partition ) result = resource.attrs return NonNetworkedParameters(result) class ArgumentSpec(object): def __init__(self): self.supports_check_mode = True self.argument_spec = dict( name=dict( required=True ), snmp_version=dict( choices=['1', '2c'] ), community=dict(), destination=dict(), port=dict(), network=dict( choices=['other', 'management', 'default'] ), state=dict( default='present', choices=['absent', 'present'] ) ) self.f5_product_name = 'bigip' def main(): if not HAS_F5SDK: raise F5ModuleError("The python f5-sdk module is required") spec = ArgumentSpec() client = AnsibleF5Client( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode, f5_product_name=spec.f5_product_name ) mm = ModuleManager(client) results = mm.exec_module() client.module.exit_json(**results) if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>test_wapi_metrics.py<|end_file_name|><|fim▁begin|>import uuid from unithelper import DBTestCase from unithelper import mocker from unithelper import requestor from unithelper import hashable_dict from bc import database from bc import metrics from bc_wapi import wapi_metrics class Test(DBTestCase): def test_metric_get(self): """Check getting metric with metricGet""" data={ 'id': str(uuid.uuid4()), 'type': str(uuid.uuid4())[:10], 'formula': metrics.constants.FORMULA_SPEED, 'aggregate': 0L, } with database.DBConnect() as db: db.insert('metrics', data) self.assertEquals(wapi_metrics.metricGet({'id': data['id']}), requestor({'metric': data}, 'ok')) self.assertEquals(wapi_metrics.metricGet({'id':''}), requestor({'message': 'Metric not found' }, 'error')) with mocker([('bc.metrics.get', mocker.exception), ('bc_wapi.wapi_metrics.LOG.error', mocker.passs)]): self.assertEquals(wapi_metrics.metricGet({'id':''}), requestor({'message': 'Unable to obtain metric' }, 'servererror')) def test_metric_get_list(self): """Check getting metrics with metricList""" data = [] for i in range(2, 10): d={ 'id': str(uuid.uuid4()), 'type': str(uuid.uuid4())[:10], 'formula': metrics.constants.FORMULA_SPEED, 'aggregate': 0L, } with database.DBConnect() as db: db.insert('metrics', d) data.append(d) ans = wapi_metrics.metricList('') self.assertEquals(ans[0], (01 << 2)) self.assertEquals(ans[1]['status'], 'ok') self.assertEquals(set(map(lambda x: hashable_dict(x), ans[1]['metrics'])), set(map(lambda x: hashable_dict(x), data))) with mocker([('bc.metrics.get_all', mocker.exception), ('bc_wapi.wapi_metrics.LOG.error', mocker.passs)]): self.assertEquals(wapi_metrics.metricList({'id':''}), requestor({'message': 'Unable to obtain metric list' }, 'servererror')) <|fim▁hole|> """Check the creating metric with metricAdd""" data={ 'id': str(uuid.uuid4()), 'type': str(uuid.uuid4())[:10], 'formula': metrics.constants.FORMULA_SPEED, 'aggregate': 0L, } ans = wapi_metrics.metricAdd(data.copy()) self.assertEquals(ans, requestor({'id':data['id']}, 'ok')) with database.DBConnect() as db: t1 = db.find('metrics').one() self.assertEquals(data['id'], t1['id']) self.assertEquals(data['type'], t1['type']) with mocker([('bc.metrics.add', mocker.exception), ('bc_wapi.wapi_metrics.LOG.error', mocker.passs)]): self.assertEquals(wapi_metrics.metricAdd({'id':''}), requestor({'message': 'Unable to add new metric' }, 'servererror'))<|fim▁end|>
def test_metric_add(self):
<|file_name|>sendData.js<|end_file_name|><|fim▁begin|>var request = require('request'), log = require('bole')('npme-send-data'), config = require('../../../config') module.exports = function (formGuid, data, callback) { var hubspot = config.license.hubspot.forms .replace(":portal_id", config.license.hubspot.portal_id) .replace(":form_guid", formGuid); request.post(hubspot, function (er, resp) { // we can ignore 302 responses if (resp.statusCode === 204 || resp.statusCode === 302) { return callback(null); } log.error('unexpected status code from hubspot; status=' + resp.statusCode + '; data=', data); callback(new Error('unexpected status code: ' + resp.statusCode)); }).form(data);<|fim▁hole|><|fim▁end|>
}
<|file_name|>time_encoder.go<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | io/time_encoder.go | | | | LastModified: Feb 18, 2021 | | Author: Ma Bingyao <[email protected]> | | | \*________________________________________________________*/ package io import ( "time" "github.com/modern-go/reflect2" ) // timeEncoder is the implementation of ValueEncoder for time.Time/*time.Time. type timeEncoder struct{} func (valenc timeEncoder) Encode(enc *Encoder, v interface{}) { enc.EncodeReference(valenc, v) } func (timeEncoder) Write(enc *Encoder, v interface{}) { enc.SetReference(v) enc.writeTime(*(*time.Time)(reflect2.PtrOf(v))) } func (enc *Encoder) writeDatePart(year int, month int, day int) { enc.buf = append(enc.buf, TagDate) q := year / 100 p := q << 1 enc.buf = append(enc.buf, digit2[p:p+2]...) p = (year - q*100) << 1 enc.buf = append(enc.buf, digit2[p:p+2]...) p = month << 1 enc.buf = append(enc.buf, digit2[p:p+2]...) p = day << 1 enc.buf = append(enc.buf, digit2[p:p+2]...) } func (enc *Encoder) writeTimePart(hour int, min int, sec int, nsec int) { enc.buf = append(enc.buf, TagTime) p := hour << 1 enc.buf = append(enc.buf, digit2[p:p+2]...) p = min << 1 enc.buf = append(enc.buf, digit2[p:p+2]...) p = sec << 1 enc.buf = append(enc.buf, digit2[p:p+2]...) if nsec == 0 { return } enc.buf = append(enc.buf, TagPoint) q := nsec / 1000000 p = q * 3 nsec -= q * 1000000 enc.buf = append(enc.buf, digit3[p:p+3]...) if nsec == 0 { return } q = nsec / 1000 p = q * 3 nsec -= q * 1000 enc.buf = append(enc.buf, digit3[p:p+3]...) if nsec == 0 { return } p = nsec * 3 enc.buf = append(enc.buf, digit3[p:p+3]...) } func (enc *Encoder) writeTime(t time.Time) { year, month, day := t.Date() hour, min, sec := t.Clock() nsec := t.Nanosecond() if (hour == 0) && (min == 0) && (sec == 0) && (nsec == 0) { enc.writeDatePart(year, int(month), day) } else if (year == 1970) && (month == 1) && (day == 1) { enc.writeTimePart(hour, min, sec, nsec) } else { enc.writeDatePart(year, int(month), day) enc.writeTimePart(hour, min, sec, nsec) } loc := TagSemicolon<|fim▁hole|> enc.buf = append(enc.buf, loc) } func init() { RegisterValueEncoder((*time.Time)(nil), timeEncoder{}) }<|fim▁end|>
if t.Location() == time.UTC { loc = TagUTC }
<|file_name|>ContainerPlayer.java<|end_file_name|><|fim▁begin|>package net.minecraft.inventory; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.util.IIcon; // CraftBukkit start import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S2FPacketSetSlot; import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; import org.bukkit.craftbukkit.inventory.CraftInventoryView; // CraftBukkit end public class ContainerPlayer extends Container { public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2); public IInventory craftResult = new InventoryCraftResult(); public boolean isLocalWorld; private final EntityPlayer thePlayer; // CraftBukkit start private CraftInventoryView bukkitEntity = null; private InventoryPlayer player; // CraftBukkit end private static final String __OBFID = "CL_00001754"; public ContainerPlayer(final InventoryPlayer p_i1819_1_, boolean p_i1819_2_, EntityPlayer p_i1819_3_) { this.isLocalWorld = p_i1819_2_; this.thePlayer = p_i1819_3_; this.craftResult = new InventoryCraftResult(); // CraftBukkit - moved to before InventoryCrafting construction this.craftMatrix = new InventoryCrafting(this, 2, 2, p_i1819_1_.player); // CraftBukkit - pass player this.craftMatrix.resultInventory = this.craftResult; // CraftBukkit - let InventoryCrafting know about its result slot this.player = p_i1819_1_; // CraftBukkit - save player this.addSlotToContainer(new SlotCrafting(p_i1819_1_.player, this.craftMatrix, this.craftResult, 0, 144, 36)); int i; int j; for (i = 0; i < 2; ++i) { for (j = 0; j < 2; ++j) {<|fim▁hole|> } } for (i = 0; i < 4; ++i) { final int k = i; this.addSlotToContainer(new Slot(p_i1819_1_, p_i1819_1_.getSizeInventory() - 1 - i, 8, 8 + i * 18) { private static final String __OBFID = "CL_00001755"; public int getSlotStackLimit() { return 1; } public boolean isItemValid(ItemStack p_75214_1_) { if (p_75214_1_ == null) return false; return p_75214_1_.getItem().isValidArmor(p_75214_1_, k, thePlayer); } @SideOnly(Side.CLIENT) public IIcon getBackgroundIconIndex() { return ItemArmor.func_94602_b(k); } }); } for (i = 0; i < 3; ++i) { for (j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(p_i1819_1_, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18)); } } for (i = 0; i < 9; ++i) { this.addSlotToContainer(new Slot(p_i1819_1_, i, 8 + i * 18, 142)); } // this.onCraftMatrixChanged(this.craftMatrix); // CraftBukkit - unneeded since it just sets result slot to empty } public void onCraftMatrixChanged(IInventory p_75130_1_) { // CraftBukkit start (Note: the following line would cause an error if called during construction) CraftingManager.getInstance().lastCraftView = getBukkitView(); ItemStack craftResult = CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj); this.craftResult.setInventorySlotContents(0, craftResult); if (super.crafters.size() < 1) { return; } EntityPlayerMP player = (EntityPlayerMP) super.crafters.get(0); // TODO: Is this _always_ correct? Seems like it. player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, 0, craftResult)); // CraftBukkit end } public void onContainerClosed(EntityPlayer p_75134_1_) { super.onContainerClosed(p_75134_1_); for (int i = 0; i < 4; ++i) { ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i); if (itemstack != null) { p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false); } } this.craftResult.setInventorySlotContents(0, (ItemStack)null); } public boolean canInteractWith(EntityPlayer p_75145_1_) { return true; } public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_) { ItemStack itemstack = null; Slot slot = (Slot)this.inventorySlots.get(p_82846_2_); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (p_82846_2_ == 0) { if (!this.mergeItemStack(itemstack1, 9, 45, true)) { return null; } slot.onSlotChange(itemstack1, itemstack); } else if (p_82846_2_ >= 1 && p_82846_2_ < 5) { if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } } else if (p_82846_2_ >= 5 && p_82846_2_ < 9) { if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } } else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack()) { int j = 5 + ((ItemArmor)itemstack.getItem()).armorType; if (!this.mergeItemStack(itemstack1, j, j + 1, false)) { return null; } } else if (p_82846_2_ >= 9 && p_82846_2_ < 36) { if (!this.mergeItemStack(itemstack1, 36, 45, false)) { return null; } } else if (p_82846_2_ >= 36 && p_82846_2_ < 45) { if (!this.mergeItemStack(itemstack1, 9, 36, false)) { return null; } } else if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize == itemstack.stackSize) { return null; } slot.onPickupFromSlot(p_82846_1_, itemstack1); } return itemstack; } public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_) { return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_); } // CraftBukkit start public CraftInventoryView getBukkitView() { if (bukkitEntity != null) { return bukkitEntity; } CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftMatrix, this.craftResult); bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); return bukkitEntity; } // CraftBukkit end }<|fim▁end|>
this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18));
<|file_name|>noop.go<|end_file_name|><|fim▁begin|>// Copyright 2017 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package storage import ( "github.com/prometheus/prometheus/model/labels" ) type noopQuerier struct{} // NoopQuerier is a Querier that does nothing. func NoopQuerier() Querier { return noopQuerier{} } func (noopQuerier) Select(bool, *SelectHints, ...*labels.Matcher) SeriesSet { return NoopSeriesSet() } func (noopQuerier) LabelValues(string, ...*labels.Matcher) ([]string, Warnings, error) { return nil, nil, nil } func (noopQuerier) LabelNames(...*labels.Matcher) ([]string, Warnings, error) { return nil, nil, nil } func (noopQuerier) Close() error { return nil } type noopChunkQuerier struct{} // NoopChunkedQuerier is a ChunkQuerier that does nothing. func NoopChunkedQuerier() ChunkQuerier {<|fim▁hole|> func (noopChunkQuerier) Select(bool, *SelectHints, ...*labels.Matcher) ChunkSeriesSet { return NoopChunkedSeriesSet() } func (noopChunkQuerier) LabelValues(string, ...*labels.Matcher) ([]string, Warnings, error) { return nil, nil, nil } func (noopChunkQuerier) LabelNames(...*labels.Matcher) ([]string, Warnings, error) { return nil, nil, nil } func (noopChunkQuerier) Close() error { return nil } type noopSeriesSet struct{} // NoopSeriesSet is a SeriesSet that does nothing. func NoopSeriesSet() SeriesSet { return noopSeriesSet{} } func (noopSeriesSet) Next() bool { return false } func (noopSeriesSet) At() Series { return nil } func (noopSeriesSet) Err() error { return nil } func (noopSeriesSet) Warnings() Warnings { return nil } type noopChunkedSeriesSet struct{} // NoopChunkedSeriesSet is a ChunkSeriesSet that does nothing. func NoopChunkedSeriesSet() ChunkSeriesSet { return noopChunkedSeriesSet{} } func (noopChunkedSeriesSet) Next() bool { return false } func (noopChunkedSeriesSet) At() ChunkSeries { return nil } func (noopChunkedSeriesSet) Err() error { return nil } func (noopChunkedSeriesSet) Warnings() Warnings { return nil }<|fim▁end|>
return noopChunkQuerier{} }
<|file_name|>Agent.py<|end_file_name|><|fim▁begin|>''' Created on Sep 15, 2012 Agent classes. Contains references to instances of classes containing observer handlers and code Agent Instances are created automatically. Create a named Handler instance under the Agent, as an instance of the desired handler class, by create (POST) of a JSON object containing a dictionary of settings for example Agent.create({'resourceCName': 'addHandler_1','resourceClass': 'addHandler'}) @author: mjkoster ''' from RESTfulResource import RESTfulResource from LinkFormatProxy import LinkFormatProxy import subprocess class Handler(RESTfulResource): # single base class for handlers to extend directly, contains convenience methods for linking resources def __init__(self, parentObject=None, resourceDescriptor = {}): RESTfulResource.__init__(self, parentObject, resourceDescriptor) self._settings = self._resourceDescriptor # use the constructor descriptor for the initial settings # link cache keeps endpoints hashed by pathFromBase string, only need to walk the path one time self._linkBaseDict = self.Resources.get('baseObject').resources self._linkCache = {} self._init() def _init(self): pass def get(self, Key=None): if Key != None : return self._settings[Key] else : return self._settings def set(self, newSettings): # create an instance of a handler from settings dictionary self._settings.update(newSettings) def handleNotify(self, updateRef=None): # external method to call from Observer-Notifier self._handleNotify(updateRef) def _handleNotify(self, updateRef=None ): # override this for handling state changes from an observer pass def linkToRef(self, linkPath): ''' takes a path string and walks the object tree from a base dictionary returns a ref to the resource at the path endpoint store translations in a hash cache for fast lookup after the first walk ''' self._linkPath = linkPath if self._linkPath in self._linkCache.keys() : return self._linkCache[self._linkPath] # cache miss, walk path and update cache at end self._currentDict = self._linkBaseDict self._pathElements = linkPath.split('/') for pathElement in self._pathElements[:-1] : # all but the last, which should be the endpoint self._currentDict = self._currentDict[pathElement].resources self._resource = self._currentDict[self._pathElements[-1] ] self._linkCache.update({ self._linkPath : self._resource }) return self._resource def getByLink(self, linkPath): return self.linkToRef(linkPath).get() def setByLink(self, linkPath, newValue): self.linkToRef(linkPath).set(newValue) class addHandler(Handler): # an example appHandler that adds two values together and stores the result # define a method for handling state changes in observed resources def _handleNotify(self, updateRef = None ): # get the 2 addends, add them, and set the sum location self._addend1 = self.getByLink(self._settings['addendLink1']) self._addend2 = self.getByLink(self._settings['addendLink2']) self.setByLink( self._settings['sumOutLink'], self._addend1 + self._addend2 ) # simple print handler that echoes the value each time an observed resource is updated class logPrintHandler(Handler): def _handleNotify(self, resource) : print resource.Properties.get('resourceName'), ' = ', resource.get() class BLE_ColorLED_handler(Handler): def _handleNotify(self, resource = None ):<|fim▁hole|> subprocess.call([("/usr/local/bin/gatttool"),\ ("--device="+self._settings['MACaddress']),\ ("--addr-type="+self._settings['MACtype']),\ ("--char-write"),\ ("--handle="+self._settings['charHandle']),\ ("--value=0x"+resource.get())]) class Agent(RESTfulResource): # Agent is a container for Handlers and daemons, instantiated as a resource of a SmartObject def __init__(self, parentObject=None, resourceDescriptor = {}): RESTfulResource.__init__(self, parentObject, resourceDescriptor) self._handlers = {} def get(self, handlerName=None): if handlerName == None: return self._handlers # to get the list of names else: if self._handlers.has_key(handlerName) : return self._handlers[handlerName] # to get reference to handler resources by handler name return None # new create takes dictionary built from JSON object POSTed to parent resource def create(self, resourceDescriptor): resourceName = resourceDescriptor['resourceName'] resourceClass = resourceDescriptor['resourceClass'] # import the module if it's specified in the descriptor if resourceDescriptor.has_key('resourceClassPath') : resourceClassPath = resourceDescriptor['resourceClassPath'] self.importByPath(resourceClassPath) if resourceName not in self.resources: # create new instance of the named class and add to resources directory, return the ref self.resources.update({resourceName : globals()[resourceClass](self, resourceDescriptor)}) #pass the constructor the entire descriptor for creating the properties object #self.resources.update({resourceName : globals()[resourceClass](self, resourceDescriptor)}) self._handlers.update({resourceName: resourceClass}) return self.resources[resourceName] # returns a reference to the created instance # need to destroy instance of code module # FIXME Doesn't seem to work. Need to look at this and recursive import issue, devise dynamic import system def importByPath(self,classPath): # separate the module path from the class,import the module, and return the class name self._components = classPath.split('.') self._module = __import__( '.'.join(self._components[:-1]) ) return self._module<|fim▁end|>
<|file_name|>store.ts<|end_file_name|><|fim▁begin|>/// <reference path="../../typings/redux/redux.d.ts" /> declare var module: any; declare var require: (modulePath: string) => any; import { Store, Reducer, createStore } from 'redux'; import rootReducer from '../reducers/index' export default function configureStore(initialState?: any): Store { const store = createStore(rootReducer, initialState); if (module.hot) { module.hot.accept('../reducers', () => { const nextReducer = require('../reducers') as Reducer; store.replaceReducer(nextReducer);<|fim▁hole|> } return store; }<|fim▁end|>
});
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> #![allow(non_camel_case_types)] extern crate libc; use libc::{c_void, c_int, c_uint, c_float, c_double, c_char, c_uchar, c_long, c_ulong, size_t}; pub type GQuark = u32; pub type gsize = size_t; pub type GType = gsize; pub type gboolean = c_int; pub const GFALSE: c_int = 0; pub const GTRUE: c_int = 1; pub type gconstpointer = *const c_void; pub type gpointer = *mut c_void; pub type GSourceFunc = extern "C" fn(user_data: gpointer) -> gboolean; pub type GCallback = extern "C" fn(); pub type GClosureNotify = extern "C" fn(data: gpointer, closure: gpointer); pub type GDestroyNotify = extern "C" fn(data: gpointer); pub type GHashFunc = unsafe extern "C" fn(v: gconstpointer) -> c_uint; pub type GEqualFunc = unsafe extern "C" fn(v1: gconstpointer, v2: gconstpointer) -> gboolean; #[repr(C)] pub struct GAppInfo; #[repr(C)] pub struct GValue { type_: GType, data: [size_t; 2], } #[repr(C)] pub struct GList { pub data: *mut c_void, pub next: *mut GList, pub prev: *mut GList } #[repr(C)] pub struct GSList { pub data: *mut c_void, pub next: *mut GSList } #[repr(C)] pub struct GError { pub domain : GQuark, pub code : i32, pub message: *mut c_char } #[repr(C)] pub struct GPermission; #[repr(C)] pub struct GObject; #[repr(C)] pub struct GMainLoop; #[repr(C)] pub struct GMainContext; #[repr(C)] pub struct GSource; #[repr(C)] pub struct GPid; #[repr(C)] pub struct GPollFD; /// Represents a day between January 1, Year 1 and a few thousand years in the future. None of its members should be accessed directly. /// /// If the GDate is obtained from g_date_new(), it will be safe to mutate but invalid and thus not safe for calendrical computations. /// /// If it's declared on the stack, it will contain garbage so must be initialized with g_date_clear(). g_date_clear() makes the date /// invalid but sane. An invalid date doesn't represent a day, it's "empty." A date becomes valid after you set it to a Julian day or /// you set a day, month, and year. #[repr(C)] pub struct GDate; /*pub struct GDate { /// the Julian representation of the date pub julian_days : u32, /// this bit is set if julian_days is valid pub julian: bool, /// this is set if day , month and year are valid pub dmy: bool, /// the day of the day-month-year representation of the date, as a number between 1 and 31 pub day: u8, /// the day of the day-month-year representation of the date, as a number between 1 and 12 pub month: u8, /// the day of the day-month-year representation of the date pub year: u8 }*/ #[repr(C)] pub struct GHashTable; //========================================================================= // GType constants //========================================================================= pub const G_TYPE_FUNDAMENTAL_SHIFT: u8 = 2; pub const G_TYPE_INVALID: GType = 0 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_NONE: GType = 1 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_INTERFACE: GType = 2 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_CHAR: GType = 3 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_UCHAR: GType = 4 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_BOOLEAN: GType = 5 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_INT: GType = 6 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_UINT: GType = 7 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_LONG: GType = 8 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_ULONG: GType = 9 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_INT64: GType = 10 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_UINT64: GType = 11 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_ENUM: GType = 12 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_FLAGS: GType = 13 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_FLOAT: GType = 14 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_DOUBLE: GType = 15 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_STRING: GType = 16 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_POINTER: GType = 17 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_BOXED: GType = 18 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_PARAM: GType = 19 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_OBJECT: GType = 20 << G_TYPE_FUNDAMENTAL_SHIFT; pub const G_TYPE_VARIANT: GType = 21 << G_TYPE_FUNDAMENTAL_SHIFT; extern "C" { pub fn g_free (ptr: gpointer); //========================================================================= // GSList //========================================================================= pub fn g_slist_free (list: *mut GSList); pub fn g_slist_append (list: *mut GSList, data: *mut c_void) -> *mut GSList; pub fn g_slist_prepend (list: *mut GSList, data: *mut c_void) -> *mut GSList; pub fn g_slist_insert (list: *mut GSList, data: *mut c_void, position: c_int) -> *mut GSList; pub fn g_slist_concat (list: *mut GSList, list2: *mut GSList) -> *mut GSList; pub fn g_slist_nth_data (list: *mut GSList, n: c_uint) -> *mut c_void; pub fn g_slist_length (list: *mut GSList) -> c_uint; pub fn g_slist_last (list: *mut GSList) -> *mut GSList; pub fn g_slist_copy (list: *mut GSList) -> *mut GSList; pub fn g_slist_reverse (list: *mut GSList) -> *mut GSList; // pub fn g_slist_free_full (list: *GSList, GDestroyNotify free_func); // pub fn g_slist_free_1 (list: *GSList); // pub fn g_slist_insert_sorted (list: *GSList, data: *c_void, GCompareFunc func) -> *GSList; // pub fn g_slist_insert_sorted_with_data (list: *GSList, data: *c_void, GCompareDataFunc func, gpointer user_data) -> *GSList; // pub fn g_slist_insert_before (list: *GSList, GSList *sibling, gpointer data) -> *GSList; pub fn g_slist_remove (list: *mut GSList, data: *mut c_void) -> *mut GSList; pub fn g_slist_remove_all (list: *mut GSList, data: *mut c_void) -> *mut GSList; pub fn g_slist_remove_link (list: *mut GSList, link_: GSList) -> *mut GSList; pub fn g_slist_delete_link (list: *mut GSList, link_: GSList) -> *mut GSList; pub fn g_slist_find (list: *mut GSList, data: *mut c_void) -> *mut GSList; // pub fn g_slist_find_custom (list: *GSList, data: *c_void, GCompareFunc func) -> *GSList; pub fn g_slist_position (list: *mut GSList, link_: GSList) -> c_int; // pub fn g_slist_index (list: *GSList, data: *c_void) -> c_int; //========================================================================= // GList<|fim▁hole|> pub fn g_list_append (list: *mut GList, data: *mut c_void) -> *mut GList; pub fn g_list_prepend (list: *mut GList, data: *mut c_void) -> *mut GList; pub fn g_list_insert (list: *mut GList, data: *mut c_void, position: c_int) -> *mut GList; pub fn g_list_concat (list: *mut GList, list2: *mut GList) -> *mut GList; pub fn g_list_nth_data (list: *mut GList, n: c_uint) -> *mut c_void; pub fn g_list_length (list: *mut GList) -> c_uint; pub fn g_list_last (list: *mut GList) -> *mut GList; pub fn g_list_first (list: *mut GList) -> *mut GList; pub fn g_list_copy (list: *mut GList) -> *mut GList; pub fn g_list_reverse (list: *mut GList) -> *mut GList; // pub fn g_slist_free_full (list: *GSList, GDestroyNotify free_func); // pub fn g_slist_free_1 (list: *GSList); // pub fn g_slist_insert_sorted (list: *GSList, data: *c_void, GCompareFunc func) -> *GSList; // pub fn g_slist_insert_sorted_with_data (list: *GSList, data: *c_void, GCompareDataFunc func, gpointer user_data) -> *GSList; // pub fn g_slist_insert_before (list: *GSList, GSList *sibling, gpointer data) -> *GSList; pub fn g_list_remove (list: *mut GList, data: *mut c_void) -> *mut GList; pub fn g_list_remove_all (list: *mut GList, data: *mut c_void) -> *mut GList; pub fn g_list_remove_link (list: *mut GList, link_: GList) -> *mut GList; pub fn g_list_delete_link (list: *mut GList, link_: GList) -> *mut GList; pub fn g_list_find (list: *mut GList, data: *mut c_void) -> *mut GList; // pub fn g_slist_find_custom (list: *GSList, data: *c_void, GCompareFunc func) -> *GSList; pub fn g_list_position (list: *mut GList, link_: GList) -> c_int; // pub fn g_slist_index (list: *GSList, data: *c_void) -> c_int; //========================================================================= // GAppInfo //========================================================================= pub fn g_app_info_get_type () -> GType; //========================================================================= // GError //========================================================================= //pub fn g_error_new (domain: GQuark, code: c_int, format: *c_char, ...) -> *GError; pub fn g_error_new_literal (domain: GQuark, code: c_int, message: *const c_char) -> *mut GError; //pub fn g_error_new_valist (domain: GQuark, code: c_int, fomat: *c_char, args: va_list) -> *GError; pub fn g_error_free (error: *mut GError) -> (); pub fn g_error_copy (error: *mut GError) -> *mut GError; pub fn g_error_matches (error: *mut GError, domain: GQuark, code: c_int) -> gboolean; //pub fn g_set_error (error: **GError, domain: GQuark, code: c_int, format: *c_char, ...) -> (); pub fn g_set_error_literal (error: *mut *mut GError, domain: GQuark, code: c_int, message: *const c_char) -> (); pub fn g_propagate_error (dest: *mut *mut GError, src: *mut GError) -> (); pub fn g_clear_error (err: *mut *mut GError) -> (); //pub fn g_prefix_error (err: **GError, format: *c_char, ...) -> (); //pub fn g_propagate_prefixed_error (dest: **GError, src: *GError, format: *c_char, ...) -> (); //========================================================================= // GPermission NOT OK //========================================================================= pub fn g_permission_get_allowed (permission: *mut GPermission) -> gboolean; pub fn g_permission_get_can_acquire (permission: *mut GPermission) -> gboolean; pub fn g_permission_get_can_release (permission: *mut GPermission) -> gboolean; //pub fn g_permission_acquire (permission: *mut GPermission, cancellable: *mut GCancellable, // error: *mut *mut GError) -> gboolean; //pub fn g_permission_acquire_async (permission: *mut GPermission, cancellable: *mut GCancellable, // callback: GAsyncReadyCallback, user_data: gpointer); //pub fn g_permission_acquire_finish (permission: *mut GPermission, result: *mut GAsyncResult, // error: *mut *mut GError) -> gboolean; //pub fn g_permission_release (permission: *mut GPermission, cancellable: *mut GCancellable, // error: *mut *mut GError) -> gboolean; //pub fn g_permission_release_async (permission: *mut GPermission, cancellable: *mut GCancellable, // callback: GAsyncReadyCallback, user_data: gpointer); //pub fn g_permission_release_finish (permission: *mut GPermission, cancellable: *mut GCancellable, // error: *mut *mut GError) -> gboolean; pub fn g_permission_impl_update (permission: *mut GPermission, allowed: gboolean, can_acquire: gboolean, can_release: gboolean); //pub type GAsyncReadyCallback = Option<extern "C" fn(source_object: *mut GObject, res: *mut GAsyncResult, user_data: gpointer)>; //========================================================================= // GObject //========================================================================= pub fn g_object_ref(object: *mut c_void) -> *mut c_void; pub fn g_object_ref_sink(object: *mut c_void) -> *mut c_void; pub fn g_object_unref(object: *mut c_void); pub fn glue_signal_connect(g_object: *mut GObject, signal: *const c_char, func: Option<extern "C" fn()>, user_data: *const c_void); pub fn g_type_check_instance_is_a(type_instance: gconstpointer, iface_type: GType) -> gboolean; //========================================================================= // GValue //========================================================================= pub fn create_gvalue () -> *mut GValue; pub fn get_gtype (_type: GType) -> GType; pub fn g_value_init (value: *mut GValue, _type: GType); pub fn g_value_reset (value: *mut GValue); pub fn g_value_unset (value: *mut GValue); pub fn g_strdup_value_contents (value: *mut GValue) -> *mut c_char; pub fn g_value_set_boolean (value: *mut GValue, b: gboolean); pub fn g_value_get_boolean (value: *const GValue) -> gboolean; pub fn g_value_set_schar (value: *mut GValue, b: c_char); pub fn g_value_get_schar (value: *const GValue) -> c_char; pub fn g_value_set_uchar (value: *mut GValue, b: c_uchar); pub fn g_value_get_uchar (value: *const GValue) -> c_uchar; pub fn g_value_set_int (value: *mut GValue, b: c_int); pub fn g_value_get_int (value: *const GValue) -> c_int; pub fn g_value_set_uint (value: *mut GValue, b: c_uint); pub fn g_value_get_uint (value: *const GValue) -> c_uint; pub fn g_value_set_long (value: *mut GValue, b: c_long); pub fn g_value_get_long (value: *const GValue) -> c_long; pub fn g_value_set_ulong (value: *mut GValue, b: c_ulong); pub fn g_value_get_ulong (value: *const GValue) -> c_ulong; pub fn g_value_set_int64 (value: *mut GValue, b: i64); pub fn g_value_get_int64 (value: *const GValue) -> i64; pub fn g_value_set_uint64 (value: *mut GValue, b: u64); pub fn g_value_get_uint64 (value: *const GValue) -> u64; pub fn g_value_set_float (value: *mut GValue, b: c_float); pub fn g_value_get_float (value: *const GValue) -> c_float; pub fn g_value_set_double (value: *mut GValue, b: c_double); pub fn g_value_get_double (value: *const GValue) -> c_double; pub fn g_value_set_enum (value: *mut GValue, b: GType); pub fn g_value_get_enum (value: *const GValue) -> GType; pub fn g_value_set_flags (value: *mut GValue, b: GType); pub fn g_value_get_flags (value: *const GValue) -> GType; pub fn g_value_set_string (value: *mut GValue, b: *const c_char); pub fn g_value_set_static_string (value: *mut GValue, b: *const c_char); pub fn g_value_get_string (value: *const GValue) -> *const c_char; pub fn g_value_dup_string (value: *mut GValue) -> *mut c_char; pub fn g_value_set_boxed (value: *mut GValue, b: *const c_void); pub fn g_value_set_static_boxed (value: *mut GValue, b: *const c_void); pub fn g_value_get_boxed (value: *const GValue) -> *const c_void; pub fn g_value_set_pointer (value: *mut GValue, b: *const c_void); pub fn g_value_get_pointer (value: *const GValue) -> *const c_void; pub fn g_value_set_object (value: *mut GValue, b: *const c_void); pub fn g_value_take_object (value: *mut GValue, b: *const c_void); pub fn g_value_get_object (value: *const GValue) -> *const c_void; pub fn g_value_set_gtype (value: *mut GValue, b: GType); pub fn g_value_get_gtype (value: *const GValue) -> GType; pub fn g_value_type_compatible (src_type: GType, dest_type: GType) -> gboolean; pub fn g_value_type_transformable (src_type: GType, dest_type: GType) -> gboolean; //========================================================================= // GMainLoop //========================================================================= pub fn g_main_loop_new (context: *mut GMainContext, is_running: gboolean) -> *mut GMainLoop; pub fn g_main_loop_ref (loop_: *mut GMainLoop) -> *mut GMainLoop; pub fn g_main_loop_unref (loop_: *mut GMainLoop); pub fn g_main_loop_run (loop_: *mut GMainLoop); pub fn g_main_loop_quit (loop_: *mut GMainLoop); pub fn g_main_loop_is_running (loop_: *mut GMainLoop) -> gboolean; pub fn g_main_loop_get_context (loop_: *mut GMainLoop) -> *mut GMainContext; //========================================================================= // GMainContext //========================================================================= pub fn g_main_context_new () -> *mut GMainContext; pub fn g_main_context_ref (context: *mut GMainContext) -> *mut GMainContext; pub fn g_main_context_unref (context: *mut GMainContext); pub fn g_main_context_default () -> *mut GMainContext; pub fn g_main_context_iteration (context: *mut GMainContext, may_block: gboolean) -> gboolean; pub fn g_main_context_pending (context: *mut GMainContext) -> gboolean; pub fn g_main_context_find_source_by_id (context: *mut GMainContext, source_id: c_uint) -> *mut GSource; pub fn g_main_context_find_source_by_user_data(context: *mut GMainContext, user_data: gpointer) -> *mut GSource; //pub fn g_main_context_find_source_by_funcs_user_data(context: *mut GMainContext, funcs: GSourceFuncs, user_data: gpointer) -> *mut GSource; pub fn g_main_context_wakeup (context: *mut GMainContext); pub fn g_main_context_acquire (context: *mut GMainContext) -> gboolean; pub fn g_main_context_release (context: *mut GMainContext); pub fn g_main_context_is_owner (context: *mut GMainContext) -> gboolean; //pub fn g_main_context_wait (context: *mut GMainContext, cond: *mut GCond, mutex: *mut GMutex) -> gboolean; pub fn g_main_context_prepare (context: *mut GMainContext, priority: *mut c_int) -> gboolean; //pub fn g_main_context_query (context: *mut GMainContext, max_priority: c_int, timeout_: *mut c_int, fds: *mut GPollFD, // n_fds: c_int) -> c_int; //pub fn g_main_context_check (context: *mut GMainContext, max_priority: c_int, fds: *mut GPollFD, // n_fds: c_int) -> c_int; pub fn g_main_context_dispatch (context: *mut GMainContext); //pub fn g_main_context_set_poll_func (); //pub fn g_main_context_get_poll_func (); pub fn g_main_context_add_poll (context: *mut GMainContext, fd: *mut GPollFD, priority: c_int); pub fn g_main_context_remove_poll (context: *mut GMainContext, fd: *mut GPollFD); pub fn g_main_depth () -> c_int; pub fn g_main_current_source () -> *mut GSource; //pub fn g_main_context_invoke (); //pub fn g_main_context_invoke_full (); pub fn g_main_context_get_thread_default () -> *mut GMainContext; pub fn g_main_context_ref_thread_default () -> *mut GMainContext; pub fn g_main_context_push_thread_default (context: *mut GMainContext); pub fn g_main_context_pop_thread_default (context: *mut GMainContext); //========================================================================= // GSource //========================================================================= pub fn g_timeout_source_new () -> *mut GSource; pub fn g_timeout_source_new_seconds (interval: c_uint) -> *mut GSource; //pub fn g_timeout_add (interval: c_uint, function: GSourceFunc, data: gpointer) -> c_uint; pub fn g_timeout_add_full (priority: c_int, interval: c_uint, function: GSourceFunc, data: gpointer, notify: GDestroyNotify) -> c_uint; //pub fn g_timeout_add_seconds (interval: c_uint, function: GSourceFunc, data: gpointer) -> c_uint; pub fn g_timeout_add_seconds_full (priority: c_int, interval: c_uint, function: GSourceFunc, data: gpointer, notify: GDestroyNotify) -> c_uint; pub fn g_idle_source_new () -> *mut GSource; // pub fn g_idle_add (function: GSourceFunc, data: gpointer) -> c_uint; pub fn g_idle_add_full (priority: c_int, function: GSourceFunc, data: gpointer, notify: GDestroyNotify) -> c_uint; pub fn g_idle_remove_by_data (data: gpointer) -> gboolean; pub fn g_child_watch_source_new (pid: GPid) -> *mut GSource; //pub fn g_child_watch_add (); //pub fn g_child_watch_add_full (); pub fn g_poll (fds: *mut GPollFD, nfds: c_uint, timeout: c_int) -> c_int; //pub fn g_source_new (); pub fn g_source_ref (source: *mut GSource) -> *mut GSource; pub fn g_source_unref (source: *mut GSource); //pub fn g_source_set_funcs (); pub fn g_source_attach (source: *mut GSource, context: *mut GMainContext); pub fn g_source_destroy (source: *mut GSource); pub fn g_source_is_destroyed (source: *mut GSource) -> gboolean; pub fn g_source_set_priority (source: *mut GSource, priority: c_int); pub fn g_source_get_priority (source: *mut GSource) -> c_int; pub fn g_source_set_can_recurse (source: *mut GSource, can_recurse: gboolean); pub fn g_source_get_can_recurse (source: *mut GSource) -> gboolean; pub fn g_source_get_id (source: *mut GSource) -> c_uint; pub fn g_source_get_name (source: *mut GSource) -> *const c_char; pub fn g_source_set_name (source: *mut GSource, name: *const c_char); pub fn g_source_set_name_by_id (tag: c_uint, name: *const c_char); pub fn g_source_get_context (source: *mut GSource) -> *mut GMainContext; //pub fn g_source_set_callback (); //pub fn g_source_set_callback_indirect (); pub fn g_source_set_ready_time (source: *mut GSource, ready_time: i64); pub fn g_source_get_ready_time (source: *mut GSource) -> i64; //pub fn g_source_add_unix_fd (); //pub fn g_source_remove_unix_fd (); //pub fn g_source_modify_unix_fd (); //pub fn g_source_query_unix_fd (); pub fn g_source_add_poll (source: *mut GSource, fd: *mut GPollFD); pub fn g_source_remove_poll (source: *mut GSource, fd: *mut GPollFD); pub fn g_source_add_child_source (source: *mut GSource, child_source: *mut GSource); pub fn g_source_remove_child_source (source: *mut GSource, child_source: *mut GSource); pub fn g_source_get_time (source: *mut GSource) -> i64; pub fn g_source_remove (tag: c_uint) -> gboolean; //pub fn g_source_remove_by_funcs_user_data (); pub fn g_source_remove_by_user_data (user_data: gpointer) -> gboolean; //========================================================================= // GSignal //========================================================================= pub fn g_signal_connect_data(instance: gpointer, detailed_signal: *const c_char, c_handler: GCallback, data: gpointer, destroy_data: GClosureNotify, connect_flags: c_int) -> c_ulong; //========================================================================= // GDate functions //========================================================================= pub fn g_get_current_time (result: *mut c_void); pub fn g_usleep (microseconds: c_ulong); pub fn g_get_monotonic_time () -> i64; pub fn g_get_real_time () -> i64; pub fn g_date_get_days_in_month (month: c_int, year: u16) -> u8; pub fn g_date_is_leap_year (year: u16) -> gboolean; pub fn g_date_get_monday_weeks_in_year(year: u16) -> u8; pub fn g_date_get_sunday_weeks_in_year(year: u16) -> u8; pub fn g_date_valid_day (day: c_int) -> gboolean; pub fn g_date_valid_month (month: c_int) -> gboolean; pub fn g_date_valid_year (year: u16) -> gboolean; pub fn g_date_valid_dmy (day: c_int, month: c_int, year: u16) -> gboolean; pub fn g_date_valid_julian (julian: u32) -> gboolean; pub fn g_date_valid_weekday (year: c_int) -> gboolean; //========================================================================= // GDate //========================================================================= pub fn g_date_new () -> *mut GDate; pub fn g_date_new_dmy (day: c_int, month: c_int, year: u16) -> *mut GDate; pub fn g_date_new_julian (julian_day: u32) -> *mut GDate; pub fn g_date_clear (date: *mut GDate, n_dates: c_uint); pub fn g_date_free (date: *mut GDate); pub fn g_date_set_day (date: *mut GDate, day: c_int); pub fn g_date_set_month (date: *mut GDate, month: c_int); pub fn g_date_set_year (date: *mut GDate, year: u16); pub fn g_date_set_dmy (date: *mut GDate, day: c_int, month: c_int, year: u16); pub fn g_date_set_julian (date: *mut GDate, julian: u32); pub fn g_date_set_time_t (date: *mut GDate, timet: i64); pub fn g_date_set_time_val (date: *mut GDate, timeval: *mut c_void); pub fn g_date_set_parse (date: *mut GDate, str_: *const c_char); pub fn g_date_add_days (date: *mut GDate, days: c_uint); pub fn g_date_subtract_days (date: *mut GDate, days: c_uint); pub fn g_date_add_months (date: *mut GDate, months: c_uint); pub fn g_date_subtract_months (date: *mut GDate, months: c_uint); pub fn g_date_add_years (date: *mut GDate, years: c_uint); pub fn g_date_subtract_years (date: *mut GDate, years: c_uint); pub fn g_date_days_between (date1: *const GDate, date2: *const GDate) -> c_int; pub fn g_date_compare (lhs: *const GDate, rhs: *const GDate) -> c_int; pub fn g_date_clamp (date: *mut GDate, min_date: *const GDate, max_date: *const GDate); pub fn g_date_order (date1: *mut GDate, date2: *mut GDate); pub fn g_date_get_day (date: *const GDate) -> u8; pub fn g_date_get_month (date: *const GDate) -> c_int; pub fn g_date_get_year (date: *const GDate) -> u16; pub fn g_date_get_julian (date: *const GDate) -> u32; pub fn g_date_get_weekday (date: *const GDate) -> c_int; pub fn g_date_get_day_of_year (date: *const GDate) -> c_uint; pub fn g_date_is_first_of_month(date: *const GDate) -> gboolean; pub fn g_date_is_last_of_month(date: *const GDate) -> gboolean; pub fn g_date_get_monday_week_of_year(date: *const GDate) -> c_uint; pub fn g_date_get_sunday_week_of_year(date: *const GDate) -> c_uint; pub fn g_date_get_iso8601_week_of_year(date: *const GDate) -> c_uint; pub fn g_date_strftime (s: *mut c_char, slen: u32, format: *const c_char, date: *const GDate) -> u32; //pub fn g_date_to_struct_tm (date: *const GDate, tm: *mut struct tm); pub fn g_date_valid (date: *const GDate) -> gboolean; //========================================================================= // GTimeVal //========================================================================= pub fn g_time_val_add (time_: *mut c_void, microseconds: c_ulong); pub fn g_time_val_from_iso8601(iso_date: *const c_char, time_: *mut c_void); pub fn g_time_val_to_iso8601 (time_: *mut c_void) -> *mut c_char; //========================================================================= // GHashTable //========================================================================= pub fn g_hash_table_new (hash_func: GHashFunc, key_equal_func: GEqualFunc) -> *mut GHashTable; // pub fn g_hash_table_new_full (hash_func: GHashFunc, key_equal_func: GEqualFunc, .. ) -> *mut GHashTable; pub fn g_hash_table_insert (hash_table: *mut GHashTable, key: gpointer, value: gpointer) -> gboolean; pub fn g_hash_table_replace (hash_table: *mut GHashTable, key: gpointer, value: gpointer) -> gboolean; pub fn g_hash_table_add (hash_table: *mut GHashTable, key: gpointer) -> gboolean; pub fn g_hash_table_contains (hash_table: *mut GHashTable, key: gconstpointer) -> gboolean; pub fn g_hash_table_size (hash_table: *mut GHashTable) -> c_uint; pub fn g_hash_table_lookup (hash_table: *mut GHashTable, key: gconstpointer) -> gpointer; pub fn g_hash_table_lookup_extended (hash_table: *mut GHashTable, lookup_key: gconstpointer, orig_key: gpointer, value: gpointer) -> gboolean; // pub fn g_hash_table_foreach (); // pub fn g_hash_table_find (); pub fn g_hash_table_remove (hash_table: *mut GHashTable, key: gconstpointer) -> gboolean; pub fn g_hash_table_steal (hash_table: *mut GHashTable, key: gconstpointer) -> gboolean; // pub fn g_hash_table_foreach_remove() -> c_uint; // pub fn g_hash_table_foreach_steal() -> c_uint; pub fn g_hash_table_remove_all (hash_table: *mut GHashTable); pub fn g_hash_table_steal_all (hash_table: *mut GHashTable); pub fn g_hash_table_get_keys (hash_table: *mut GHashTable) -> *mut GList; pub fn g_hash_table_get_values (hash_table: *mut GHashTable) -> *mut GList; pub fn g_hash_table_get_keys_as_array(hash_table: *mut GHashTable, length: *mut c_uint) -> gpointer; pub fn g_hash_table_destroy (hash_table: *mut GHashTable); pub fn g_hash_table_ref (hash_table: *mut GHashTable) -> *mut GHashTable; pub fn g_hash_table_unref (hash_table: *mut GHashTable); // skipped g_hash_table_iter functions (TODO?) pub fn g_direct_equal (v1: gconstpointer, v2: gconstpointer) -> gboolean; pub fn g_direct_hash (v: gconstpointer) -> c_uint; pub fn g_int_equal (v1: gconstpointer, v2: gconstpointer) -> gboolean; pub fn g_int_hash (v: gconstpointer) -> c_uint; pub fn g_int64_equal (v1: gconstpointer, v2: gconstpointer) -> gboolean; pub fn g_int64_hash (v: gconstpointer) -> c_uint; pub fn g_double_equal (v1: gconstpointer, v2: gconstpointer) -> gboolean; pub fn g_double_hash (v: gconstpointer) -> c_uint; pub fn g_str_equal (v1: gconstpointer, v2: gconstpointer) -> gboolean; pub fn g_str_hash (v: gconstpointer) -> c_uint; }<|fim▁end|>
//========================================================================= pub fn g_list_free (list: *mut GList);
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ getname ~~~~~~~<|fim▁hole|> :copyright: (c) 2015 by lord63. :license: MIT, see LICENSE for more details. """ from getname.main import random_name __title__ = "getname" __version__ = '0.1.1' __author__ = "lord63" __license__ = "MIT" __copyright__ = "Copyright 2015 lord63"<|fim▁end|>
Get popular cat/dog/superhero/supervillain names.
<|file_name|>easy_install.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Easy Install ------------ A tool for doing automatic download/extract/build of distutils-based Python packages. For detailed documentation, see the accompanying EasyInstall.txt file, or visit the `EasyInstall home page`__. __ https://pythonhosted.org/setuptools/easy_install.html """ import sys import os import zipimport import shutil import tempfile import zipfile import re import stat import random import platform import textwrap import warnings import site import struct from glob import glob from distutils import log, dir_util from distutils.command.build_scripts import first_line_re import pkg_resources from setuptools import Command, _dont_write_bytecode from setuptools.sandbox import run_setup from setuptools.py31compat import get_path, get_config_vars from distutils.util import get_platform from distutils.util import convert_path, subst_vars from distutils.errors import DistutilsArgError, DistutilsOptionError, \ DistutilsError, DistutilsPlatformError from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS from setuptools.command import setopt from setuptools.archive_util import unpack_archive from setuptools.package_index import PackageIndex from setuptools.package_index import URL_SCHEME from setuptools.command import bdist_egg, egg_info from setuptools.compat import (iteritems, maxsize, basestring, unicode, reraise) from pkg_resources import ( yield_lines, normalize_path, resource_string, ensure_directory, get_distribution, find_distributions, Environment, Requirement, Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound, VersionConflict, DEVELOP_DIST, ) sys_executable = os.environ.get('__PYVENV_LAUNCHER__', os.path.normpath(sys.executable)) __all__ = [ 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg', 'main', 'get_exe_prefixes', ] def is_64bit(): return struct.calcsize("P") == 8 def samefile(p1, p2): both_exist = os.path.exists(p1) and os.path.exists(p2) use_samefile = hasattr(os.path, 'samefile') and both_exist if use_samefile: return os.path.samefile(p1, p2) norm_p1 = os.path.normpath(os.path.normcase(p1)) norm_p2 = os.path.normpath(os.path.normcase(p2)) return norm_p1 == norm_p2 if sys.version_info <= (3,): def _to_ascii(s): return s def isascii(s): try: unicode(s, 'ascii') return True except UnicodeError: return False else: def _to_ascii(s): return s.encode('ascii') def isascii(s): try: s.encode('ascii') return True except UnicodeError: return False class easy_install(Command): """Manage a download/build/install process""" description = "Find/get/install Python packages" command_consumes_arguments = True user_options = [ ('prefix=', None, "installation prefix"), ("zip-ok", "z", "install package as a zipfile"), ("multi-version", "m", "make apps have to require() a version"), ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"), ("install-dir=", "d", "install package to DIR"), ("script-dir=", "s", "install scripts to DIR"), ("exclude-scripts", "x", "Don't install scripts"), ("always-copy", "a", "Copy all needed packages to install dir"), ("index-url=", "i", "base URL of Python Package Index"), ("find-links=", "f", "additional URL(s) to search for packages"), ("build-directory=", "b", "download/extract/build in DIR; keep the results"), ('optimize=', 'O', "also compile with optimization: -O1 for \"python -O\", " "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"), ('record=', None, "filename in which to record list of installed files"), ('always-unzip', 'Z', "don't install as a zipfile, no matter what"), ('site-dirs=','S',"list of directories where .pth files work"), ('editable', 'e', "Install specified packages in editable form"), ('no-deps', 'N', "don't install dependencies"), ('allow-hosts=', 'H', "pattern(s) that hostnames must match"), ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"), ('version', None, "print version information and exit"), ('no-find-links', None, "Don't load find-links defined in packages being installed") ] boolean_options = [ 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version' ] if site.ENABLE_USER_SITE: help_msg = "install in user site-package '%s'" % site.USER_SITE user_options.append(('user', None, help_msg)) boolean_options.append('user') negative_opt = {'always-unzip': 'zip-ok'} create_index = PackageIndex def initialize_options(self): if site.ENABLE_USER_SITE: whereami = os.path.abspath(__file__) self.user = whereami.startswith(site.USER_SITE) else: self.user = 0 self.zip_ok = self.local_snapshots_ok = None self.install_dir = self.script_dir = self.exclude_scripts = None self.index_url = None self.find_links = None self.build_directory = None self.args = None self.optimize = self.record = None self.upgrade = self.always_copy = self.multi_version = None self.editable = self.no_deps = self.allow_hosts = None self.root = self.prefix = self.no_report = None self.version = None self.install_purelib = None # for pure module distributions self.install_platlib = None # non-pure (dists w/ extensions) self.install_headers = None # for C/C++ headers self.install_lib = None # set to either purelib or platlib self.install_scripts = None self.install_data = None self.install_base = None self.install_platbase = None if site.ENABLE_USER_SITE: self.install_userbase = site.USER_BASE self.install_usersite = site.USER_SITE else: self.install_userbase = None self.install_usersite = None self.no_find_links = None # Options not specifiable via command line self.package_index = None self.pth_file = self.always_copy_from = None self.site_dirs = None self.installed_projects = {} self.sitepy_installed = False # Always read easy_install options, even if we are subclassed, or have # an independent instance created. This ensures that defaults will # always come from the standard configuration file(s)' "easy_install" # section, even if this is a "develop" or "install" command, or some # other embedding. self._dry_run = None self.verbose = self.distribution.verbose self.distribution._set_command_options( self, self.distribution.get_option_dict('easy_install') ) def delete_blockers(self, blockers): for filename in blockers: if os.path.exists(filename) or os.path.islink(filename): log.info("Deleting %s", filename) if not self.dry_run: if os.path.isdir(filename) and not os.path.islink(filename): rmtree(filename) else: os.unlink(filename) def finalize_options(self): if self.version: print('setuptools %s' % get_distribution('setuptools').version) sys.exit() py_version = sys.version.split()[0] prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix') self.config_vars = { 'dist_name': self.distribution.get_name(), 'dist_version': self.distribution.get_version(), 'dist_fullname': self.distribution.get_fullname(), 'py_version': py_version, 'py_version_short': py_version[0:3], 'py_version_nodot': py_version[0] + py_version[2], 'sys_prefix': prefix, 'prefix': prefix, 'sys_exec_prefix': exec_prefix, 'exec_prefix': exec_prefix, # Only python 3.2+ has abiflags 'abiflags': getattr(sys, 'abiflags', ''), } if site.ENABLE_USER_SITE: self.config_vars['userbase'] = self.install_userbase self.config_vars['usersite'] = self.install_usersite # fix the install_dir if "--user" was used #XXX: duplicate of the code in the setup command if self.user and site.ENABLE_USER_SITE: self.create_home_path() if self.install_userbase is None: raise DistutilsPlatformError( "User base directory is not specified") self.install_base = self.install_platbase = self.install_userbase if os.name == 'posix': self.select_scheme("unix_user") else: self.select_scheme(os.name + "_user") self.expand_basedirs() self.expand_dirs() self._expand('install_dir','script_dir','build_directory','site_dirs') # If a non-default installation directory was specified, default the # script directory to match it. if self.script_dir is None: self.script_dir = self.install_dir if self.no_find_links is None: self.no_find_links = False # Let install_dir get set by install_lib command, which in turn # gets its info from the install command, and takes into account # --prefix and --home and all that other crud. self.set_undefined_options('install_lib', ('install_dir','install_dir') ) # Likewise, set default script_dir from 'install_scripts.install_dir' self.set_undefined_options('install_scripts', ('install_dir', 'script_dir') ) if self.user and self.install_purelib: self.install_dir = self.install_purelib self.script_dir = self.install_scripts # default --record from the install command self.set_undefined_options('install', ('record', 'record')) # Should this be moved to the if statement below? It's not used # elsewhere normpath = map(normalize_path, sys.path) self.all_site_dirs = get_site_dirs() if self.site_dirs is not None: site_dirs = [ os.path.expanduser(s.strip()) for s in self.site_dirs.split(',') ] for d in site_dirs: if not os.path.isdir(d): log.warn("%s (in --site-dirs) does not exist", d) elif normalize_path(d) not in normpath: raise DistutilsOptionError( d+" (in --site-dirs) is not on sys.path" ) else: self.all_site_dirs.append(normalize_path(d)) if not self.editable: self.check_site_dir() self.index_url = self.index_url or "https://pypi.python.org/simple" self.shadow_path = self.all_site_dirs[:] for path_item in self.install_dir, normalize_path(self.script_dir): if path_item not in self.shadow_path: self.shadow_path.insert(0, path_item) if self.allow_hosts is not None: hosts = [s.strip() for s in self.allow_hosts.split(',')] else: hosts = ['*'] if self.package_index is None: self.package_index = self.create_index( self.index_url, search_path = self.shadow_path, hosts=hosts, ) self.local_index = Environment(self.shadow_path+sys.path) if self.find_links is not None: if isinstance(self.find_links, basestring): self.find_links = self.find_links.split() else: self.find_links = [] if self.local_snapshots_ok: self.package_index.scan_egg_links(self.shadow_path+sys.path) if not self.no_find_links: self.package_index.add_find_links(self.find_links) self.set_undefined_options('install_lib', ('optimize','optimize')) if not isinstance(self.optimize,int): try: self.optimize = int(self.optimize) if not (0 <= self.optimize <= 2): raise ValueError except ValueError: raise DistutilsOptionError("--optimize must be 0, 1, or 2") if self.editable and not self.build_directory: raise DistutilsArgError( "Must specify a build directory (-b) when using --editable" ) if not self.args: raise DistutilsArgError( "No urls, filenames, or requirements specified (see --help)") self.outputs = [] def _expand_attrs(self, attrs): for attr in attrs: val = getattr(self, attr) if val is not None: if os.name == 'posix' or os.name == 'nt': val = os.path.expanduser(val) val = subst_vars(val, self.config_vars) setattr(self, attr, val) def expand_basedirs(self): """Calls `os.path.expanduser` on install_base, install_platbase and root.""" self._expand_attrs(['install_base', 'install_platbase', 'root']) def expand_dirs(self): """Calls `os.path.expanduser` on install dirs.""" self._expand_attrs(['install_purelib', 'install_platlib', 'install_lib', 'install_headers', 'install_scripts', 'install_data',]) def run(self): if self.verbose != self.distribution.verbose: log.set_verbosity(self.verbose) try: for spec in self.args: self.easy_install(spec, not self.no_deps) if self.record: outputs = self.outputs if self.root: # strip any package prefix root_len = len(self.root) for counter in range(len(outputs)): outputs[counter] = outputs[counter][root_len:] from distutils import file_util self.execute( file_util.write_file, (self.record, outputs), "writing list of installed files to '%s'" % self.record ) self.warn_deprecated_options() finally: log.set_verbosity(self.distribution.verbose) def pseudo_tempname(self): """Return a pseudo-tempname base in the install directory. This code is intentionally naive; if a malicious party can write to the target directory you're already in deep doodoo. """ try: pid = os.getpid() except: pid = random.randint(0, maxsize) return os.path.join(self.install_dir, "test-easy-install-%s" % pid) def warn_deprecated_options(self): pass def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir,'easy-install.pth') # Is it a configured, PYTHONPATH, implicit, or explicit site dir? is_site_dir = instdir in self.all_site_dirs if not is_site_dir and not self.multi_version: # No? Then directly test whether it does .pth file processing is_site_dir = self.check_pth_processing() else: # make sure we can write to target dir testfile = self.pseudo_tempname()+'.write-test' test_exists = os.path.exists(testfile) try: if test_exists: os.unlink(testfile) open(testfile,'w').close() os.unlink(testfile) except (OSError,IOError): self.cant_write_to_target() if not is_site_dir and not self.multi_version: # Can't install non-multi to non-site dir raise DistutilsError(self.no_default_version_msg()) if is_site_dir: if self.pth_file is None: self.pth_file = PthDistributions(pth_file, self.all_site_dirs) else: self.pth_file = None PYTHONPATH = os.environ.get('PYTHONPATH','').split(os.pathsep) if instdir not in map(normalize_path, [_f for _f in PYTHONPATH if _f]): # only PYTHONPATH dirs need a site.py, so pretend it's there self.sitepy_installed = True elif self.multi_version and not os.path.exists(pth_file): self.sitepy_installed = True # don't need site.py in this case self.pth_file = None # and don't create a .pth file self.install_dir = instdir def cant_write_to_target(self): template = """can't create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: %s The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: %s """ msg = template % (sys.exc_info()[1], self.install_dir,) if not os.path.exists(self.install_dir): msg += """ This directory does not currently exist. Please create it and try again, or choose a different installation directory (using the -d or --install-dir option). """ else: msg += """ Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. For information on other options, you may wish to consult the documentation at: https://pythonhosted.org/setuptools/easy_install.html Please make the appropriate changes for your system and try again. """ raise DistutilsError(msg) def check_pth_processing(self): """Empirically verify whether .pth files are supported in inst. dir""" instdir = self.install_dir log.info("Checking .pth file support in %s", instdir) pth_file = self.pseudo_tempname()+".pth" ok_file = pth_file+'.ok' ok_exists = os.path.exists(ok_file) try: if ok_exists: os.unlink(ok_file) dirname = os.path.dirname(ok_file) if not os.path.exists(dirname): os.makedirs(dirname) f = open(pth_file,'w') except (OSError,IOError): self.cant_write_to_target() else: try: f.write("import os; f = open(%r, 'w'); f.write('OK'); f.close()\n" % (ok_file,)) f.close() f=None executable = sys.executable if os.name=='nt': dirname,basename = os.path.split(executable) alt = os.path.join(dirname,'pythonw.exe') if basename.lower()=='python.exe' and os.path.exists(alt): # use pythonw.exe to avoid opening a console window executable = alt from distutils.spawn import spawn spawn([executable,'-E','-c','pass'],0) if os.path.exists(ok_file): log.info( "TEST PASSED: %s appears to support .pth files", instdir ) return True finally: if f: f.close() if os.path.exists(ok_file): os.unlink(ok_file) if os.path.exists(pth_file): os.unlink(pth_file) if not self.multi_version: log.warn("TEST FAILED: %s does NOT support .pth files", instdir) return False def install_egg_scripts(self, dist): """Write all the scripts for `dist`, unless scripts are excluded""" if not self.exclude_scripts and dist.metadata_isdir('scripts'): for script_name in dist.metadata_listdir('scripts'): if dist.metadata_isdir('scripts/' + script_name): # The "script" is a directory, likely a Python 3 # __pycache__ directory, so skip it. continue self.install_script( dist, script_name, dist.get_metadata('scripts/'+script_name) ) self.install_wrapper_scripts(dist) def add_output(self, path): if os.path.isdir(path): for base, dirs, files in os.walk(path): for filename in files: self.outputs.append(os.path.join(base,filename)) else: self.outputs.append(path) def not_editable(self, spec): if self.editable: raise DistutilsArgError( "Invalid argument %r: you can't use filenames or URLs " "with --editable (except via the --find-links option)." % (spec,) ) def check_editable(self,spec): if not self.editable: return if os.path.exists(os.path.join(self.build_directory, spec.key)): raise DistutilsArgError( "%r already exists in %s; can't do a checkout there" % (spec.key, self.build_directory) ) def easy_install(self, spec, deps=False): tmpdir = tempfile.mkdtemp(prefix="easy_install-") download = None if not self.editable: self.install_site_py() try: if not isinstance(spec,Requirement): if URL_SCHEME(spec): # It's a url, download it to tmpdir and process self.not_editable(spec) download = self.package_index.download(spec, tmpdir) return self.install_item(None, download, tmpdir, deps, True) elif os.path.exists(spec): # Existing file or directory, just process it directly self.not_editable(spec) return self.install_item(None, spec, tmpdir, deps, True) else: spec = parse_requirement_arg(spec) self.check_editable(spec) dist = self.package_index.fetch_distribution( spec, tmpdir, self.upgrade, self.editable, not self.always_copy, self.local_index ) if dist is None: msg = "Could not find suitable distribution for %r" % spec if self.always_copy: msg+=" (--always-copy skips system and development eggs)" raise DistutilsError(msg) elif dist.precedence==DEVELOP_DIST: # .egg-info dists don't need installing, just process deps self.process_distribution(spec, dist, deps, "Using") return dist else: return self.install_item(spec, dist.location, tmpdir, deps) finally: if os.path.exists(tmpdir): rmtree(tmpdir) def install_item(self, spec, download, tmpdir, deps, install_needed=False): # Installation is also needed if file in tmpdir or is not an egg install_needed = install_needed or self.always_copy install_needed = install_needed or os.path.dirname(download) == tmpdir install_needed = install_needed or not download.endswith('.egg') install_needed = install_needed or ( self.always_copy_from is not None and os.path.dirname(normalize_path(download)) == normalize_path(self.always_copy_from) ) if spec and not install_needed: # at this point, we know it's a local .egg, we just don't know if # it's already installed. for dist in self.local_index[spec.project_name]: if dist.location==download: break else: install_needed = True # it's not in the local index log.info("Processing %s", os.path.basename(download)) if install_needed: dists = self.install_eggs(spec, download, tmpdir) for dist in dists: self.process_distribution(spec, dist, deps) else: dists = [self.egg_distribution(download)] self.process_distribution(spec, dists[0], deps, "Using") if spec is not None: for dist in dists: if dist in spec: return dist def select_scheme(self, name): """Sets the install directories by applying the install schemes.""" # it's the caller's problem if they supply a bad name! scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = 'install_' + key if getattr(self, attrname) is None: setattr(self, attrname, scheme[key]) def process_distribution(self, requirement, dist, deps=True, *info): self.update_pth(dist) self.package_index.add(dist) # First remove the dist from self.local_index, to avoid problems using # old cached data in case its underlying file has been replaced. # # This is a quick-fix for a zipimporter caching issue in case the dist # has been implemented as and already loaded from a zip file that got # replaced later on. For more detailed information see setuptools issue # #168 at 'http://bitbucket.org/pypa/setuptools/issue/168'. if dist in self.local_index[dist.key]: self.local_index.remove(dist) self.local_index.add(dist) self.install_egg_scripts(dist) self.installed_projects[dist.key] = dist log.info(self.installation_report(requirement, dist, *info)) if (dist.has_metadata('dependency_links.txt') and not self.no_find_links): self.package_index.add_find_links( dist.get_metadata_lines('dependency_links.txt') ) if not deps and not self.always_copy:<|fim▁hole|> elif requirement is not None and dist.key != requirement.key: log.warn("Skipping dependencies for %s", dist) return # XXX this is not the distribution we were looking for elif requirement is None or dist not in requirement: # if we wound up with a different version, resolve what we've got distreq = dist.as_requirement() requirement = requirement or distreq requirement = Requirement( distreq.project_name, distreq.specs, requirement.extras ) log.info("Processing dependencies for %s", requirement) try: distros = WorkingSet([]).resolve( [requirement], self.local_index, self.easy_install ) except DistributionNotFound: e = sys.exc_info()[1] raise DistutilsError( "Could not find required distribution %s" % e.args ) except VersionConflict: e = sys.exc_info()[1] raise DistutilsError( "Installed distribution %s conflicts with requirement %s" % e.args ) if self.always_copy or self.always_copy_from: # Force all the relevant distros to be copied or activated for dist in distros: if dist.key not in self.installed_projects: self.easy_install(dist.as_requirement()) log.info("Finished processing dependencies for %s", requirement) def should_unzip(self, dist): if self.zip_ok is not None: return not self.zip_ok if dist.has_metadata('not-zip-safe'): return True if not dist.has_metadata('zip-safe'): return True return False def maybe_move(self, spec, dist_filename, setup_base): dst = os.path.join(self.build_directory, spec.key) if os.path.exists(dst): msg = "%r already exists in %s; build directory %s will not be kept" log.warn(msg, spec.key, self.build_directory, setup_base) return setup_base if os.path.isdir(dist_filename): setup_base = dist_filename else: if os.path.dirname(dist_filename)==setup_base: os.unlink(dist_filename) # get it out of the tmp dir contents = os.listdir(setup_base) if len(contents)==1: dist_filename = os.path.join(setup_base,contents[0]) if os.path.isdir(dist_filename): # if the only thing there is a directory, move it instead setup_base = dist_filename ensure_directory(dst) shutil.move(setup_base, dst) return dst def install_wrapper_scripts(self, dist): if not self.exclude_scripts: for args in get_script_args(dist): self.write_script(*args) def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) def get_template(filename): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. These templates use triple-quotes to escape variable substitutions so the scripts get the 2to3 treatment when build on Python 3. The templates cannot use triple-quotes naturally. """ raw_bytes = resource_string('setuptools', template_name) template_str = raw_bytes.decode('utf-8') clean_template = template_str.replace('"""', '') return clean_template if is_script: # See https://bitbucket.org/pypa/setuptools/issue/134 for info # on script file naming and downstream issues with SVR4 template_name = 'script template.py' if dev_path: template_name = template_name.replace('.py', ' (dev).py') script_text = (get_script_header(script_text) + get_template(template_name) % locals()) self.write_script(script_name, _to_ascii(script_text), 'b') def write_script(self, script_name, contents, mode="t", blockers=()): """Write an executable file to the scripts directory""" self.delete_blockers( # clean up old .py/.pyw w/o a script [os.path.join(self.script_dir,x) for x in blockers]) log.info("Installing %s script to %s", script_name, self.script_dir) target = os.path.join(self.script_dir, script_name) self.add_output(target) mask = current_umask() if not self.dry_run: ensure_directory(target) if os.path.exists(target): os.unlink(target) f = open(target,"w"+mode) f.write(contents) f.close() chmod(target, 0o777-mask) def install_eggs(self, spec, dist_filename, tmpdir): # .egg dirs or files are already built, so just return them if dist_filename.lower().endswith('.egg'): return [self.install_egg(dist_filename, tmpdir)] elif dist_filename.lower().endswith('.exe'): return [self.install_exe(dist_filename, tmpdir)] # Anything else, try to extract and build setup_base = tmpdir if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'): unpack_archive(dist_filename, tmpdir, self.unpack_progress) elif os.path.isdir(dist_filename): setup_base = os.path.abspath(dist_filename) if (setup_base.startswith(tmpdir) # something we downloaded and self.build_directory and spec is not None): setup_base = self.maybe_move(spec, dist_filename, setup_base) # Find the setup.py file setup_script = os.path.join(setup_base, 'setup.py') if not os.path.exists(setup_script): setups = glob(os.path.join(setup_base, '*', 'setup.py')) if not setups: raise DistutilsError( "Couldn't find a setup script in %s" % os.path.abspath(dist_filename) ) if len(setups)>1: raise DistutilsError( "Multiple setup scripts in %s" % os.path.abspath(dist_filename) ) setup_script = setups[0] # Now run it, and return the result if self.editable: log.info(self.report_editable(spec, setup_script)) return [] else: return self.build_and_install(setup_script, setup_base) def egg_distribution(self, egg_path): if os.path.isdir(egg_path): metadata = PathMetadata(egg_path,os.path.join(egg_path,'EGG-INFO')) else: metadata = EggMetadata(zipimport.zipimporter(egg_path)) return Distribution.from_filename(egg_path,metadata=metadata) def install_egg(self, egg_path, tmpdir): destination = os.path.join(self.install_dir,os.path.basename(egg_path)) destination = os.path.abspath(destination) if not self.dry_run: ensure_directory(destination) dist = self.egg_distribution(egg_path) if not samefile(egg_path, destination): if os.path.isdir(destination) and not os.path.islink(destination): dir_util.remove_tree(destination, dry_run=self.dry_run) elif os.path.exists(destination): self.execute(os.unlink,(destination,),"Removing "+destination) uncache_zipdir(destination) if os.path.isdir(egg_path): if egg_path.startswith(tmpdir): f,m = shutil.move, "Moving" else: f,m = shutil.copytree, "Copying" elif self.should_unzip(dist): self.mkpath(destination) f,m = self.unpack_and_compile, "Extracting" elif egg_path.startswith(tmpdir): f,m = shutil.move, "Moving" else: f,m = shutil.copy2, "Copying" self.execute(f, (egg_path, destination), (m+" %s to %s") % (os.path.basename(egg_path),os.path.dirname(destination))) self.add_output(destination) return self.egg_distribution(destination) def install_exe(self, dist_filename, tmpdir): # See if it's valid, get data cfg = extract_wininst_cfg(dist_filename) if cfg is None: raise DistutilsError( "%s is not a valid distutils Windows .exe" % dist_filename ) # Create a dummy distribution object until we build the real distro dist = Distribution( None, project_name=cfg.get('metadata','name'), version=cfg.get('metadata','version'), platform=get_platform(), ) # Convert the .exe to an unpacked egg egg_path = dist.location = os.path.join(tmpdir, dist.egg_name()+'.egg') egg_tmp = egg_path + '.tmp' _egg_info = os.path.join(egg_tmp, 'EGG-INFO') pkg_inf = os.path.join(_egg_info, 'PKG-INFO') ensure_directory(pkg_inf) # make sure EGG-INFO dir exists dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX self.exe_to_egg(dist_filename, egg_tmp) # Write EGG-INFO/PKG-INFO if not os.path.exists(pkg_inf): f = open(pkg_inf,'w') f.write('Metadata-Version: 1.0\n') for k,v in cfg.items('metadata'): if k != 'target_version': f.write('%s: %s\n' % (k.replace('_','-').title(), v)) f.close() script_dir = os.path.join(_egg_info,'scripts') self.delete_blockers( # delete entry-point scripts to avoid duping [os.path.join(script_dir,args[0]) for args in get_script_args(dist)] ) # Build .egg file from tmpdir bdist_egg.make_zipfile( egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run ) # install the .egg return self.install_egg(egg_path, tmpdir) def exe_to_egg(self, dist_filename, egg_tmp): """Extract a bdist_wininst to the directories an egg would use""" # Check for .pth file and set up prefix translations prefixes = get_exe_prefixes(dist_filename) to_compile = [] native_libs = [] top_level = {} def process(src,dst): s = src.lower() for old,new in prefixes: if s.startswith(old): src = new+src[len(old):] parts = src.split('/') dst = os.path.join(egg_tmp, *parts) dl = dst.lower() if dl.endswith('.pyd') or dl.endswith('.dll'): parts[-1] = bdist_egg.strip_module(parts[-1]) top_level[os.path.splitext(parts[0])[0]] = 1 native_libs.append(src) elif dl.endswith('.py') and old!='SCRIPTS/': top_level[os.path.splitext(parts[0])[0]] = 1 to_compile.append(dst) return dst if not src.endswith('.pth'): log.warn("WARNING: can't process %s", src) return None # extract, tracking .pyd/.dll->native_libs and .py -> to_compile unpack_archive(dist_filename, egg_tmp, process) stubs = [] for res in native_libs: if res.lower().endswith('.pyd'): # create stubs for .pyd's parts = res.split('/') resource = parts[-1] parts[-1] = bdist_egg.strip_module(parts[-1])+'.py' pyfile = os.path.join(egg_tmp, *parts) to_compile.append(pyfile) stubs.append(pyfile) bdist_egg.write_stub(resource, pyfile) self.byte_compile(to_compile) # compile .py's bdist_egg.write_safety_flag(os.path.join(egg_tmp,'EGG-INFO'), bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag for name in 'top_level','native_libs': if locals()[name]: txt = os.path.join(egg_tmp, 'EGG-INFO', name+'.txt') if not os.path.exists(txt): f = open(txt,'w') f.write('\n'.join(locals()[name])+'\n') f.close() def installation_report(self, req, dist, what="Installed"): """Helpful installation message for display to package users""" msg = "\n%(what)s %(eggloc)s%(extras)s" if self.multi_version and not self.no_report: msg += """ Because this distribution was installed --multi-version, before you can import modules from this package in an application, you will need to 'import pkg_resources' and then use a 'require()' call similar to one of these examples, in order to select the desired version: pkg_resources.require("%(name)s") # latest installed version pkg_resources.require("%(name)s==%(version)s") # this exact version pkg_resources.require("%(name)s>=%(version)s") # this version or higher """ if self.install_dir not in map(normalize_path,sys.path): msg += """ Note also that the installation directory must be on sys.path at runtime for this to work. (e.g. by being the application's script directory, by being on PYTHONPATH, or by being added to sys.path by your code.) """ eggloc = dist.location name = dist.project_name version = dist.version extras = '' # TODO: self.report_extras(req, dist) return msg % locals() def report_editable(self, spec, setup_script): dirname = os.path.dirname(setup_script) python = sys.executable return """\nExtracted editable version of %(spec)s to %(dirname)s If it uses setuptools in its setup script, you can activate it in "development" mode by going to that directory and running:: %(python)s setup.py develop See the setuptools documentation for the "develop" command for more info. """ % locals() def run_setup(self, setup_script, setup_base, args): sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg) sys.modules.setdefault('distutils.command.egg_info', egg_info) args = list(args) if self.verbose>2: v = 'v' * (self.verbose - 1) args.insert(0,'-'+v) elif self.verbose<2: args.insert(0,'-q') if self.dry_run: args.insert(0,'-n') log.info( "Running %s %s", setup_script[len(setup_base)+1:], ' '.join(args) ) try: run_setup(setup_script, args) except SystemExit: v = sys.exc_info()[1] raise DistutilsError("Setup script exited with %s" % (v.args[0],)) def build_and_install(self, setup_script, setup_base): args = ['bdist_egg', '--dist-dir'] dist_dir = tempfile.mkdtemp( prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script) ) try: self._set_fetcher_options(os.path.dirname(setup_script)) args.append(dist_dir) self.run_setup(setup_script, setup_base, args) all_eggs = Environment([dist_dir]) eggs = [] for key in all_eggs: for dist in all_eggs[key]: eggs.append(self.install_egg(dist.location, setup_base)) if not eggs and not self.dry_run: log.warn("No eggs found in %s (setup script problem?)", dist_dir) return eggs finally: rmtree(dist_dir) log.set_verbosity(self.verbose) # restore our log verbosity def _set_fetcher_options(self, base): """ When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well. """ # find the fetch options from easy_install and write them out # to the setup.cfg file. ei_opts = self.distribution.get_option_dict('easy_install').copy() fetch_directives = ( 'find_links', 'site_dirs', 'index_url', 'optimize', 'site_dirs', 'allow_hosts', ) fetch_options = {} for key, val in ei_opts.items(): if key not in fetch_directives: continue fetch_options[key.replace('_', '-')] = val[1] # create a settings dictionary suitable for `edit_config` settings = dict(easy_install=fetch_options) cfg_filename = os.path.join(base, 'setup.cfg') setopt.edit_config(cfg_filename, settings) def update_pth(self, dist): if self.pth_file is None: return for d in self.pth_file[dist.key]: # drop old entries if self.multi_version or d.location != dist.location: log.info("Removing %s from easy-install.pth file", d) self.pth_file.remove(d) if d.location in self.shadow_path: self.shadow_path.remove(d.location) if not self.multi_version: if dist.location in self.pth_file.paths: log.info( "%s is already the active version in easy-install.pth", dist ) else: log.info("Adding %s to easy-install.pth file", dist) self.pth_file.add(dist) # add new entry if dist.location not in self.shadow_path: self.shadow_path.append(dist.location) if not self.dry_run: self.pth_file.save() if dist.key=='setuptools': # Ensure that setuptools itself never becomes unavailable! # XXX should this check for latest version? filename = os.path.join(self.install_dir,'setuptools.pth') if os.path.islink(filename): os.unlink(filename) f = open(filename, 'wt') f.write(self.pth_file.make_relative(dist.location)+'\n') f.close() def unpack_progress(self, src, dst): # Progress filter for unpacking log.debug("Unpacking %s to %s", src, dst) return dst # only unpack-and-compile skips files for dry run def unpack_and_compile(self, egg_path, destination): to_compile = [] to_chmod = [] def pf(src, dst): if dst.endswith('.py') and not src.startswith('EGG-INFO/'): to_compile.append(dst) elif dst.endswith('.dll') or dst.endswith('.so'): to_chmod.append(dst) self.unpack_progress(src,dst) return not self.dry_run and dst or None unpack_archive(egg_path, destination, pf) self.byte_compile(to_compile) if not self.dry_run: for f in to_chmod: mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755 chmod(f, mode) def byte_compile(self, to_compile): if _dont_write_bytecode: self.warn('byte-compiling is disabled, skipping.') return from distutils.util import byte_compile try: # try to make the byte compile messages quieter log.set_verbosity(self.verbose - 1) byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run) if self.optimize: byte_compile( to_compile, optimize=self.optimize, force=1, dry_run=self.dry_run ) finally: log.set_verbosity(self.verbose) # restore original verbosity def no_default_version_msg(self): template = """bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: %s and your PYTHONPATH environment variable currently contains: %r Here are some of your options for correcting the problem: * You can choose a different installation directory, i.e., one that is on PYTHONPATH or supports .pth files * You can add the installation directory to the PYTHONPATH environment variable. (It must then also be on PYTHONPATH whenever you run Python and want to use the package(s) you are installing.) * You can set up the installation directory to support ".pth" files by using one of the approaches described here: https://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations Please make the appropriate changes for your system and try again.""" return template % (self.install_dir, os.environ.get('PYTHONPATH','')) def install_site_py(self): """Make sure there's a site.py in the target dir, if needed""" if self.sitepy_installed: return # already did it, or don't need to sitepy = os.path.join(self.install_dir, "site.py") source = resource_string("setuptools", "site-patch.py") current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) f = open(sitepy,'rb') current = f.read() # we want str, not bytes if sys.version_info >= (3,): current = current.decode() f.close() if not current.startswith('def __boot():'): raise DistutilsError( "%s is not a setuptools-generated site.py; please" " remove it." % sitepy ) if current != source: log.info("Creating %s", sitepy) if not self.dry_run: ensure_directory(sitepy) f = open(sitepy,'wb') f.write(source) f.close() self.byte_compile([sitepy]) self.sitepy_installed = True def create_home_path(self): """Create directories under ~.""" if not self.user: return home = convert_path(os.path.expanduser("~")) for name, path in iteritems(self.config_vars): if path.startswith(home) and not os.path.isdir(path): self.debug_print("os.makedirs('%s', 0o700)" % path) os.makedirs(path, 0o700) INSTALL_SCHEMES = dict( posix = dict( install_dir = '$base/lib/python$py_version_short/site-packages', script_dir = '$base/bin', ), ) DEFAULT_SCHEME = dict( install_dir = '$base/Lib/site-packages', script_dir = '$base/Scripts', ) def _expand(self, *attrs): config_vars = self.get_finalized_command('install').config_vars if self.prefix: # Set default install_dir/scripts from --prefix config_vars = config_vars.copy() config_vars['base'] = self.prefix scheme = self.INSTALL_SCHEMES.get(os.name,self.DEFAULT_SCHEME) for attr,val in scheme.items(): if getattr(self,attr,None) is None: setattr(self,attr,val) from distutils.util import subst_vars for attr in attrs: val = getattr(self, attr) if val is not None: val = subst_vars(val, config_vars) if os.name == 'posix': val = os.path.expanduser(val) setattr(self, attr, val) def get_site_dirs(): # return a list of 'site' dirs sitedirs = [_f for _f in os.environ.get('PYTHONPATH', '').split(os.pathsep) if _f] prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: if sys.platform in ('os2emx', 'riscos'): sitedirs.append(os.path.join(prefix, "Lib", "site-packages")) elif os.sep == '/': sitedirs.extend([os.path.join(prefix, "lib", "python" + sys.version[:3], "site-packages"), os.path.join(prefix, "lib", "site-python")]) else: sitedirs.extend( [prefix, os.path.join(prefix, "lib", "site-packages")] ) if sys.platform == 'darwin': # for framework builds *only* we add the standard Apple # locations. Currently only per-user, but /Library and # /Network/Library could be added too if 'Python.framework' in prefix: home = os.environ.get('HOME') if home: sitedirs.append( os.path.join(home, 'Library', 'Python', sys.version[:3], 'site-packages')) lib_paths = get_path('purelib'), get_path('platlib') for site_lib in lib_paths: if site_lib not in sitedirs: sitedirs.append(site_lib) if site.ENABLE_USER_SITE: sitedirs.append(site.USER_SITE) sitedirs = list(map(normalize_path, sitedirs)) return sitedirs def expand_paths(inputs): """Yield sys.path directories that might contain "old-style" packages""" seen = {} for dirname in inputs: dirname = normalize_path(dirname) if dirname in seen: continue seen[dirname] = 1 if not os.path.isdir(dirname): continue files = os.listdir(dirname) yield dirname, files for name in files: if not name.endswith('.pth'): # We only care about the .pth files continue if name in ('easy-install.pth','setuptools.pth'): # Ignore .pth files that we control continue # Read the .pth file f = open(os.path.join(dirname,name)) lines = list(yield_lines(f)) f.close() # Yield existing non-dupe, non-import directory lines from it for line in lines: if not line.startswith("import"): line = normalize_path(line.rstrip()) if line not in seen: seen[line] = 1 if not os.path.isdir(line): continue yield line, os.listdir(line) def extract_wininst_cfg(dist_filename): """Extract configuration data from a bdist_wininst .exe Returns a ConfigParser.RawConfigParser, or None """ f = open(dist_filename,'rb') try: endrec = zipfile._EndRecData(f) if endrec is None: return None prepended = (endrec[9] - endrec[5]) - endrec[6] if prepended < 12: # no wininst data here return None f.seek(prepended-12) from setuptools.compat import StringIO, ConfigParser import struct tag, cfglen, bmlen = struct.unpack("<iii",f.read(12)) if tag not in (0x1234567A, 0x1234567B): return None # not a valid tag f.seek(prepended-(12+cfglen)) cfg = ConfigParser.RawConfigParser({'version':'','target_version':''}) try: part = f.read(cfglen) # part is in bytes, but we need to read up to the first null # byte. if sys.version_info >= (2,6): null_byte = bytes([0]) else: null_byte = chr(0) config = part.split(null_byte, 1)[0] # Now the config is in bytes, but for RawConfigParser, it should # be text, so decode it. config = config.decode(sys.getfilesystemencoding()) cfg.readfp(StringIO(config)) except ConfigParser.Error: return None if not cfg.has_section('metadata') or not cfg.has_section('Setup'): return None return cfg finally: f.close() def get_exe_prefixes(exe_filename): """Get exe->egg path translations for a given .exe file""" prefixes = [ ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''), ('PLATLIB/', ''), ('SCRIPTS/', 'EGG-INFO/scripts/'), ('DATA/lib/site-packages', ''), ] z = zipfile.ZipFile(exe_filename) try: for info in z.infolist(): name = info.filename parts = name.split('/') if len(parts)==3 and parts[2]=='PKG-INFO': if parts[1].endswith('.egg-info'): prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/')) break if len(parts) != 2 or not name.endswith('.pth'): continue if name.endswith('-nspkg.pth'): continue if parts[0].upper() in ('PURELIB','PLATLIB'): contents = z.read(name) if sys.version_info >= (3,): contents = contents.decode() for pth in yield_lines(contents): pth = pth.strip().replace('\\','/') if not pth.startswith('import'): prefixes.append((('%s/%s/' % (parts[0],pth)), '')) finally: z.close() prefixes = [(x.lower(),y) for x, y in prefixes] prefixes.sort() prefixes.reverse() return prefixes def parse_requirement_arg(spec): try: return Requirement.parse(spec) except ValueError: raise DistutilsError( "Not a URL, existing file, or requirement spec: %r" % (spec,) ) class PthDistributions(Environment): """A .pth file with Distribution paths in it""" dirty = False def __init__(self, filename, sitedirs=()): self.filename = filename self.sitedirs = list(map(normalize_path, sitedirs)) self.basedir = normalize_path(os.path.dirname(self.filename)) self._load() Environment.__init__(self, [], None, None) for path in yield_lines(self.paths): list(map(self.add, find_distributions(path, True))) def _load(self): self.paths = [] saw_import = False seen = dict.fromkeys(self.sitedirs) if os.path.isfile(self.filename): f = open(self.filename,'rt') for line in f: if line.startswith('import'): saw_import = True continue path = line.rstrip() self.paths.append(path) if not path.strip() or path.strip().startswith('#'): continue # skip non-existent paths, in case somebody deleted a package # manually, and duplicate paths as well path = self.paths[-1] = normalize_path( os.path.join(self.basedir,path) ) if not os.path.exists(path) or path in seen: self.paths.pop() # skip it self.dirty = True # we cleaned up, so we're dirty now :) continue seen[path] = 1 f.close() if self.paths and not saw_import: self.dirty = True # ensure anything we touch has import wrappers while self.paths and not self.paths[-1].strip(): self.paths.pop() def save(self): """Write changed .pth file back to disk""" if not self.dirty: return data = '\n'.join(map(self.make_relative,self.paths)) if data: log.debug("Saving %s", self.filename) data = ( "import sys; sys.__plen = len(sys.path)\n" "%s\n" "import sys; new=sys.path[sys.__plen:];" " del sys.path[sys.__plen:];" " p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;" " sys.__egginsert = p+len(new)\n" ) % data if os.path.islink(self.filename): os.unlink(self.filename) f = open(self.filename,'wt') f.write(data) f.close() elif os.path.exists(self.filename): log.debug("Deleting empty %s", self.filename) os.unlink(self.filename) self.dirty = False def add(self, dist): """Add `dist` to the distribution map""" if (dist.location not in self.paths and ( dist.location not in self.sitedirs or dist.location == os.getcwd() # account for '.' being in PYTHONPATH )): self.paths.append(dist.location) self.dirty = True Environment.add(self, dist) def remove(self, dist): """Remove `dist` from the distribution map""" while dist.location in self.paths: self.paths.remove(dist.location) self.dirty = True Environment.remove(self, dist) def make_relative(self,path): npath, last = os.path.split(normalize_path(path)) baselen = len(self.basedir) parts = [last] sep = os.altsep=='/' and '/' or os.sep while len(npath)>=baselen: if npath==self.basedir: parts.append(os.curdir) parts.reverse() return sep.join(parts) npath, last = os.path.split(npath) parts.append(last) else: return path def _first_line_re(): """ Return a regular expression based on first_line_re suitable for matching strings. """ if isinstance(first_line_re.pattern, str): return first_line_re # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. return re.compile(first_line_re.pattern.decode()) def get_script_header(script_text, executable=sys_executable, wininst=False): """Create a #! line, getting options (if any) from script_text""" first = (script_text+'\n').splitlines()[0] match = _first_line_re().match(first) options = '' if match: options = match.group(1) or '' if options: options = ' '+options if wininst: executable = "python.exe" else: executable = nt_quote_arg(executable) hdr = "#!%(executable)s%(options)s\n" % locals() if not isascii(hdr): # Non-ascii path to sys.executable, use -x to prevent warnings if options: if options.strip().startswith('-'): options = ' -x'+options.strip()[1:] # else: punt, we can't do it, let the warning happen anyway else: options = ' -x' executable = fix_jython_executable(executable, options) hdr = "#!%(executable)s%(options)s\n" % locals() return hdr def auto_chmod(func, arg, exc): if func is os.remove and os.name=='nt': chmod(arg, stat.S_IWRITE) return func(arg) et, ev, _ = sys.exc_info() reraise(et, (ev[0], ev[1] + (" %s %s" % (func,arg)))) def uncache_zipdir(path): """ Remove any globally cached zip file related data for `path` Stale zipimport.zipimporter objects need to be removed when a zip file is replaced as they contain cached zip file directory information. If they are asked to get data from their zip file, they will use that cached information to calculate the data location in the zip file. This calculated location may be incorrect for the replaced zip file, which may in turn cause the read operation to either fail or return incorrect data. Note we have no way to clear any local caches from here. That is left up to whomever is in charge of maintaining that cache. """ normalized_path = normalize_path(path) _uncache(normalized_path, zipimport._zip_directory_cache) _uncache(normalized_path, sys.path_importer_cache) def _uncache(normalized_path, cache): to_remove = [] prefix_len = len(normalized_path) for p in cache: np = normalize_path(p) if (np.startswith(normalized_path) and np[prefix_len:prefix_len + 1] in (os.sep, '')): to_remove.append(p) for p in to_remove: del cache[p] def is_python(text, filename='<string>'): "Is this string a valid Python script?" try: compile(text, filename, 'exec') except (SyntaxError, TypeError): return False else: return True def is_sh(executable): """Determine if the specified executable is a .sh (contains a #! line)""" try: fp = open(executable) magic = fp.read(2) fp.close() except (OSError,IOError): return executable return magic == '#!' def nt_quote_arg(arg): """Quote a command line argument according to Windows parsing rules""" result = [] needquote = False nb = 0 needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': nb += 1 elif c == '"': # double preceding backslashes, then add a \" result.append('\\' * (nb*2) + '\\"') nb = 0 else: if nb: result.append('\\' * nb) nb = 0 result.append(c) if nb: result.append('\\' * nb) if needquote: result.append('\\' * nb) # double the trailing backslashes result.append('"') return ''.join(result) def is_python_script(script_text, filename): """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. """ if filename.endswith('.py') or filename.endswith('.pyw'): return True # extension says it's Python if is_python(script_text, filename): return True # it's syntactically valid Python if script_text.startswith('#!'): # It begins with a '#!' line, so check if 'python' is in it somewhere return 'python' in script_text.splitlines()[0].lower() return False # Not any Python I can recognize try: from os import chmod as _chmod except ImportError: # Jython compatibility def _chmod(*args): pass def chmod(path, mode): log.debug("changing mode of %s to %o", path, mode) try: _chmod(path, mode) except os.error: e = sys.exc_info()[1] log.debug("chmod failed: %s", e) def fix_jython_executable(executable, options): if sys.platform.startswith('java') and is_sh(executable): # Workaround for Jython is not needed on Linux systems. import java if java.lang.System.getProperty("os.name") == "Linux": return executable # Workaround Jython's sys.executable being a .sh (an invalid # shebang line interpreter) if options: # Can't apply the workaround, leave it broken log.warn( "WARNING: Unable to adapt shebang line for Jython," " the following script is NOT executable\n" " see http://bugs.jython.org/issue1112 for" " more information.") else: return '/usr/bin/env %s' % executable return executable class ScriptWriter(object): """ Encapsulates behavior around writing entry point scripts for console and gui apps. """ template = textwrap.dedent(""" # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r __requires__ = %(spec)r import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point(%(spec)r, %(group)r, %(name)r)() ) """).lstrip() @classmethod def get_script_args(cls, dist, executable=sys_executable, wininst=False): """ Yield write_script() argument tuples for a distribution's entrypoints """ gen_class = cls.get_writer(wininst) spec = str(dist.as_requirement()) header = get_script_header("", executable, wininst) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): script_text = gen_class.template % locals() for res in gen_class._get_script_args(type_, name, header, script_text): yield res @classmethod def get_writer(cls, force_windows): if force_windows or sys.platform=='win32': return WindowsScriptWriter.get_writer() return cls @classmethod def _get_script_args(cls, type_, name, header, script_text): # Simply write the stub with no extension. yield (name, header+script_text) class WindowsScriptWriter(ScriptWriter): @classmethod def get_writer(cls): """ Get a script writer suitable for Windows """ writer_lookup = dict( executable=WindowsExecutableLauncherWriter, natural=cls, ) # for compatibility, use the executable launcher by default launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable') return writer_lookup[launcher] @classmethod def _get_script_args(cls, type_, name, header, script_text): "For Windows, add a .py extension" ext = dict(console='.pya', gui='.pyw')[type_] if ext not in os.environ['PATHEXT'].lower().split(';'): warnings.warn("%s not listed in PATHEXT; scripts will not be " "recognized as executables." % ext, UserWarning) old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe'] old.remove(ext) header = cls._adjust_header(type_, header) blockers = [name+x for x in old] yield name+ext, header+script_text, 't', blockers @staticmethod def _adjust_header(type_, orig_header): """ Make sure 'pythonw' is used for gui and and 'python' is used for console (regardless of what sys.executable is). """ pattern = 'pythonw.exe' repl = 'python.exe' if type_ == 'gui': pattern, repl = repl, pattern pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE) new_header = pattern_ob.sub(string=orig_header, repl=repl) clean_header = new_header[2:-1].strip('"') if sys.platform == 'win32' and not os.path.exists(clean_header): # the adjusted version doesn't exist, so return the original return orig_header return new_header class WindowsExecutableLauncherWriter(WindowsScriptWriter): @classmethod def _get_script_args(cls, type_, name, header, script_text): """ For Windows, add a .py extension and an .exe launcher """ if type_=='gui': launcher_type = 'gui' ext = '-script.pyw' old = ['.pyw'] else: launcher_type = 'cli' ext = '-script.py' old = ['.py','.pyc','.pyo'] hdr = cls._adjust_header(type_, header) blockers = [name+x for x in old] yield (name+ext, hdr+script_text, 't', blockers) yield ( name+'.exe', get_win_launcher(launcher_type), 'b' # write in binary mode ) if not is_64bit(): # install a manifest for the launcher to prevent Windows # from detecting it as an installer (which it will for # launchers like easy_install.exe). Consider only # adding a manifest for launchers detected as installers. # See Distribute #143 for details. m_name = name + '.exe.manifest' yield (m_name, load_launcher_manifest(name), 't') # for backward-compatibility get_script_args = ScriptWriter.get_script_args def get_win_launcher(type): """ Load the Windows launcher (executable) suitable for launching a script. `type` should be either 'cli' or 'gui' Returns the executable as a byte string. """ launcher_fn = '%s.exe' % type if platform.machine().lower()=='arm': launcher_fn = launcher_fn.replace(".", "-arm.") if is_64bit(): launcher_fn = launcher_fn.replace(".", "-64.") else: launcher_fn = launcher_fn.replace(".", "-32.") return resource_string('setuptools', launcher_fn) def load_launcher_manifest(name): manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') if sys.version_info[0] < 3: return manifest % vars() else: return manifest.decode('utf-8') % vars() def rmtree(path, ignore_errors=False, onerror=auto_chmod): """Recursively delete a directory tree. This code is taken from the Python 2.4 version of 'shutil', because the 2.3 version doesn't really work right. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise names = [] try: names = os.listdir(path) except os.error: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): rmtree(fullname, ignore_errors, onerror) else: try: os.remove(fullname) except os.error: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) except os.error: onerror(os.rmdir, path, sys.exc_info()) def current_umask(): tmp = os.umask(0o022) os.umask(tmp) return tmp def bootstrap(): # This function is called when setuptools*.egg is run using /bin/sh import setuptools argv0 = os.path.dirname(setuptools.__path__[0]) sys.argv[0] = argv0 sys.argv.append(argv0) main() def main(argv=None, **kw): from setuptools import setup from setuptools.dist import Distribution import distutils.core USAGE = """\ usage: %(script)s [options] requirement_or_url ... or: %(script)s --help """ def gen_usage(script_name): return USAGE % dict( script=os.path.basename(script_name), ) def with_ei_usage(f): old_gen_usage = distutils.core.gen_usage try: distutils.core.gen_usage = gen_usage return f() finally: distutils.core.gen_usage = old_gen_usage class DistributionWithoutHelpCommands(Distribution): common_usage = "" def _show_help(self,*args,**kw): with_ei_usage(lambda: Distribution._show_help(self,*args,**kw)) if argv is None: argv = sys.argv[1:] with_ei_usage(lambda: setup( script_args = ['-q','easy_install', '-v']+argv, script_name = sys.argv[0] or 'easy_install', distclass=DistributionWithoutHelpCommands, **kw ) )<|fim▁end|>
return
<|file_name|>MainMemoryReplaceDatabase.java<|end_file_name|><|fim▁begin|>package it.unibas.lunatic.model.chase.chasede.operators.mainmemory;<|fim▁hole|>import it.unibas.lunatic.Scenario; import it.unibas.lunatic.model.chase.chasede.operators.IReplaceDatabase; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import speedy.model.algebra.operators.ITupleIterator; import speedy.model.algebra.operators.mainmemory.MainMemoryInsertTuple; import speedy.model.database.Cell; import speedy.model.database.IDatabase; import speedy.model.database.Tuple; import speedy.model.database.mainmemory.MainMemoryDB; import speedy.model.database.mainmemory.MainMemoryTable; import speedy.model.database.mainmemory.MainMemoryVirtualDB; import speedy.model.database.mainmemory.MainMemoryVirtualTable; public class MainMemoryReplaceDatabase implements IReplaceDatabase { private final static Logger logger = LoggerFactory.getLogger(MainMemoryReplaceDatabase.class); private final static MainMemoryInsertTuple insert = new MainMemoryInsertTuple(); public void replaceTargetDB(IDatabase newDatabase, Scenario scenario) { if (newDatabase instanceof MainMemoryDB) { scenario.setTarget(newDatabase); return; } MainMemoryVirtualDB virtualDB = (MainMemoryVirtualDB) newDatabase; if (logger.isDebugEnabled()) logger.debug("Copying virtual db\n" + newDatabase); MainMemoryDB mainMemoryDB = new MainMemoryDB(virtualDB.getDataSource()); for (String tableName : mainMemoryDB.getTableNames()) { MainMemoryTable table = (MainMemoryTable) mainMemoryDB.getTable(tableName); emptyTable(table); insertAllTuples(table, (MainMemoryVirtualTable) virtualDB.getTable(tableName)); } if (logger.isDebugEnabled()) logger.debug("New db\n" + mainMemoryDB); scenario.setTarget(mainMemoryDB); } private void emptyTable(MainMemoryTable table) { table.getDataSource().getInstances().get(0).getChildren().clear(); } private void insertAllTuples(MainMemoryTable table, MainMemoryVirtualTable mainMemoryVirtualTable) { ITupleIterator it = mainMemoryVirtualTable.getTupleIterator(); while (it.hasNext()) { Tuple tuple = it.next(); removeOID(tuple); insert.execute(table, tuple, null, null); } } private void removeOID(Tuple tuple) { for (Iterator<Cell> it = tuple.getCells().iterator(); it.hasNext();) { Cell cell = it.next(); if (cell.isOID()) { it.remove(); } } } }<|fim▁end|>
<|file_name|>custom_reporter.cpp<|end_file_name|><|fim▁begin|><|fim▁hole|> namespace { class MyReporter : public sltbench::reporter::IReporter { public: MyReporter() = default; ~MyReporter() override = default; public: void ReportBenchmarkStarted() override { // for example, ignore this event } void ReportBenchmarkFinished() override { // for example, ignore this event } void Report( const std::string& name, const std::string& params, sltbench::Verdict verdict, std::chrono::nanoseconds timing_result) override { std::cout << std::left << std::setw(60) << name << std::left << std::setw(25) << params << std::left << std::setw(9) << ToString(verdict) << std::right << std::setw(20) << timing_result.count() << std::endl; } void ReportWarning(sltbench::RunWarning warning) override { // for example, do not report warnings. } }; } // namespace SLTBENCH_CONFIG().SetReporter(std::unique_ptr<MyReporter>(new MyReporter()));<|fim▁end|>
#include <sltbench/Bench.h> #include <iomanip> #include <iostream>
<|file_name|>DefaultOAuthCodeFactory.java<|end_file_name|><|fim▁begin|>package org.apereo.cas.ticket.code; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.ticket.ExpirationPolicy; import org.apereo.cas.ticket.Ticket; import org.apereo.cas.ticket.TicketFactory; import org.apereo.cas.ticket.UniqueTicketIdGenerator; import org.apereo.cas.util.DefaultUniqueTicketIdGenerator; /** * Default OAuth code factory. * * @author Jerome Leleu * @since 5.0.0 */ public class DefaultOAuthCodeFactory implements OAuthCodeFactory { /** Default instance for the ticket id generator. */ protected final UniqueTicketIdGenerator oAuthCodeIdGenerator; /** ExpirationPolicy for refresh tokens. */ protected final ExpirationPolicy expirationPolicy; <|fim▁hole|> } public DefaultOAuthCodeFactory(final UniqueTicketIdGenerator refreshTokenIdGenerator, final ExpirationPolicy expirationPolicy) { this.oAuthCodeIdGenerator = refreshTokenIdGenerator; this.expirationPolicy = expirationPolicy; } @Override public OAuthCode create(final Service service, final Authentication authentication) { final String codeId = this.oAuthCodeIdGenerator.getNewTicketId(OAuthCode.PREFIX); return new OAuthCodeImpl(codeId, service, authentication, this.expirationPolicy); } @Override public <T extends TicketFactory> T get(final Class<? extends Ticket> clazz) { return (T) this; } }<|fim▁end|>
public DefaultOAuthCodeFactory(final ExpirationPolicy expirationPolicy) { this(new DefaultUniqueTicketIdGenerator(), expirationPolicy);
<|file_name|>htmloptionelement.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataCast, ElementCast, HTMLElementCast, NodeCast, TextDerived}; use dom::bindings::codegen::InheritTypes::{HTMLOptionElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived}; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::js::Root; use dom::document::Document; use dom::element::{AttributeHandlers, ElementHelpers}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use util::str::{DOMString, split_html_space_chars}; #[dom_struct] pub struct HTMLOptionElement { htmlelement: HTMLElement<|fim▁hole|> impl HTMLOptionElementDerived for EventTarget { fn is_htmloptionelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement))) } } impl HTMLOptionElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLOptionElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLOptionElement> { let element = HTMLOptionElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap) } } fn collect_text(node: &&Node, value: &mut DOMString) { let elem = ElementCast::to_ref(*node).unwrap(); let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name() == &atom!("script"); let html_script = node.is_htmlscriptelement(); if svg_script || html_script { return; } else { for child in node.children() { if child.r().is_text() { let characterdata = CharacterDataCast::to_ref(child.r()).unwrap(); value.push_str(&characterdata.Data()); } else { collect_text(&child.r(), value); } } } } impl<'a> HTMLOptionElementMethods for &'a HTMLOptionElement { // https://www.whatwg.org/html/#dom-option-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-option-disabled fn SetDisabled(self, disabled: bool) { let elem = ElementCast::from_ref(self); elem.set_bool_attribute(&atom!("disabled"), disabled) } // https://www.whatwg.org/html/#dom-option-text fn Text(self) -> DOMString { let node = NodeCast::from_ref(self); let mut content = String::new(); collect_text(&node, &mut content); let v: Vec<&str> = split_html_space_chars(&content).collect(); v.join(" ") } // https://www.whatwg.org/html/#dom-option-text fn SetText(self, value: DOMString) { let node = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } // https://html.spec.whatwg.org/multipage/#attr-option-value fn Value(self) -> DOMString { let element = ElementCast::from_ref(self); let attr = &atom!("value"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/#attr-option-value make_setter!(SetValue, "value"); // https://html.spec.whatwg.org/multipage/#attr-option-label fn Label(self) -> DOMString { let element = ElementCast::from_ref(self); let attr = &atom!("label"); if element.has_attribute(attr) { element.get_string_attribute(attr) } else { self.Text() } } // https://html.spec.whatwg.org/multipage/#attr-option-label make_setter!(SetLabel, "label"); } impl<'a> VirtualMethods for &'a HTMLOptionElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: &Attr) { if let Some(ref s) = self.super_type() { s.after_set_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, attr: &Attr) { if let Some(ref s) = self.super_type() { s.before_remove_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_parent_disabled_state_for_option(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } let node = NodeCast::from_ref(*self); node.check_parent_disabled_state_for_option(); } fn unbind_from_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(tree_in_doc); } let node = NodeCast::from_ref(*self); if node.GetParentNode().is_some() { node.check_parent_disabled_state_for_option(); } else { node.check_disabled_attribute(); } } }<|fim▁end|>
}
<|file_name|>taskbar_window_thumbnailer_win.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/panels/taskbar_window_thumbnailer_win.h" #include <dwmapi.h> #include "base/logging.h" #include "base/win/scoped_hdc.h" #include "skia/ext/image_operations.h" #include "ui/gfx/canvas.h" #include "ui/gfx/gdi_util.h" namespace { HBITMAP GetNativeBitmapFromSkBitmap(const SkBitmap& bitmap) { int width = bitmap.width(); int height = bitmap.height(); BITMAPV4HEADER native_bitmap_header; gfx::CreateBitmapV4Header(width, height, &native_bitmap_header); HDC dc = ::GetDC(NULL); void* bits; HBITMAP native_bitmap = ::CreateDIBSection(dc, reinterpret_cast<BITMAPINFO*>(&native_bitmap_header), DIB_RGB_COLORS, &bits, NULL, 0); DCHECK(native_bitmap); ::ReleaseDC(NULL, dc); bitmap.copyPixelsTo(bits, width * height * 4, width * 4); return native_bitmap; } void EnableCustomThumbnail(HWND hwnd, bool enable) { BOOL enable_value = enable; ::DwmSetWindowAttribute(hwnd, DWMWA_FORCE_ICONIC_REPRESENTATION, &enable_value, sizeof(enable_value)); ::DwmSetWindowAttribute(hwnd, DWMWA_HAS_ICONIC_BITMAP, &enable_value, sizeof(enable_value)); } } // namespace TaskbarWindowThumbnailerWin::TaskbarWindowThumbnailerWin(HWND hwnd) : hwnd_(hwnd) { } TaskbarWindowThumbnailerWin::~TaskbarWindowThumbnailerWin() { } void TaskbarWindowThumbnailerWin::Start( const std::vector<HWND>& snapshot_hwnds) { snapshot_hwnds_ = snapshot_hwnds; if (snapshot_hwnds_.empty()) snapshot_hwnds_.push_back(hwnd_); capture_bitmap_.reset(CaptureWindowImage()); if (capture_bitmap_) EnableCustomThumbnail(hwnd_, true); } void TaskbarWindowThumbnailerWin::Stop() { capture_bitmap_.reset(); EnableCustomThumbnail(hwnd_, false); } bool TaskbarWindowThumbnailerWin::FilterMessage(HWND hwnd, UINT message, WPARAM w_param, LPARAM l_param, LRESULT* l_result) { DCHECK_EQ(hwnd_, hwnd); switch (message) { case WM_DWMSENDICONICTHUMBNAIL: return OnDwmSendIconicThumbnail(HIWORD(l_param), LOWORD(l_param), l_result); case WM_DWMSENDICONICLIVEPREVIEWBITMAP: return OnDwmSendIconicLivePreviewBitmap(l_result); } return false; } bool TaskbarWindowThumbnailerWin::OnDwmSendIconicThumbnail( int width, int height, LRESULT* l_result) { DCHECK(capture_bitmap_.get()); SkBitmap* thumbnail_bitmap = capture_bitmap_.get(); // Scale the image if needed. SkBitmap scaled_bitmap; if (capture_bitmap_->width() != width || capture_bitmap_->height() != height) { double x_scale = static_cast<double>(width) / capture_bitmap_->width(); double y_scale = static_cast<double>(height) / capture_bitmap_->height(); double scale = std::min(x_scale, y_scale); width = capture_bitmap_->width() * scale; height = capture_bitmap_->height() * scale; scaled_bitmap = skia::ImageOperations::Resize( *capture_bitmap_, skia::ImageOperations::RESIZE_GOOD, width, height); thumbnail_bitmap = &scaled_bitmap; } HBITMAP native_bitmap = GetNativeBitmapFromSkBitmap(*thumbnail_bitmap); ::DwmSetIconicThumbnail(hwnd_, native_bitmap, 0); ::DeleteObject(native_bitmap); *l_result = 0; return true; } bool TaskbarWindowThumbnailerWin::OnDwmSendIconicLivePreviewBitmap( LRESULT* l_result) { scoped_ptr<SkBitmap> live_bitmap(CaptureWindowImage()); HBITMAP native_bitmap = GetNativeBitmapFromSkBitmap(*live_bitmap); ::DwmSetIconicLivePreviewBitmap(hwnd_, native_bitmap, NULL, 0); ::DeleteObject(native_bitmap); *l_result = 0; return true; } SkBitmap* TaskbarWindowThumbnailerWin::CaptureWindowImage() const { int enclosing_x = 0; int enclosing_y = 0; int enclosing_right = 0; int enclosing_bottom = 0; for (std::vector<HWND>::const_iterator iter = snapshot_hwnds_.begin(); iter != snapshot_hwnds_.end(); ++iter) { RECT bounds; if (!::GetWindowRect(*iter, &bounds))<|fim▁hole|> enclosing_y = bounds.top; enclosing_right = bounds.right; enclosing_bottom = bounds.bottom; } else { if (bounds.left < enclosing_x) enclosing_x = bounds.left; if (bounds.top < enclosing_y) enclosing_y = bounds.top; if (bounds.right > enclosing_right) enclosing_right = bounds.right; if (bounds.bottom > enclosing_bottom) enclosing_bottom = bounds.bottom; } } int width = enclosing_right - enclosing_x; int height = enclosing_bottom - enclosing_y; if (!width || !height) return NULL; gfx::Canvas canvas(gfx::Size(width, height), ui::SCALE_FACTOR_100P, false); { skia::ScopedPlatformPaint scoped_platform_paint(canvas.sk_canvas()); HDC target_dc = scoped_platform_paint.GetPlatformSurface(); for (std::vector<HWND>::const_iterator iter = snapshot_hwnds_.begin(); iter != snapshot_hwnds_.end(); ++iter) { HWND current_hwnd = *iter; RECT current_bounds; if (!::GetWindowRect(current_hwnd, &current_bounds)) continue; base::win::ScopedGetDC source_dc(current_hwnd); ::BitBlt(target_dc, current_bounds.left - enclosing_x, current_bounds.top - enclosing_y, current_bounds.right - current_bounds.left, current_bounds.bottom - current_bounds.top, source_dc, 0, 0, SRCCOPY); ::ReleaseDC(current_hwnd, source_dc); } } return new SkBitmap(canvas.ExtractImageRep().sk_bitmap()); }<|fim▁end|>
continue; if (iter == snapshot_hwnds_.begin()) { enclosing_x = bounds.left;
<|file_name|>ListService.js<|end_file_name|><|fim▁begin|>(function(){ 'use strict'; function ListService($http){ this.getList = function(list_id){ return $http.get('/lists/' + list_id + ".json") } } ListService.$inject = ['$http'] angular<|fim▁hole|><|fim▁end|>
.module('app') .service('ListService', ListService) }())
<|file_name|>FMM.py<|end_file_name|><|fim▁begin|>import numpy as np import pygame<|fim▁hole|>def emFit(results, numComponents): if len(results) == 0: return None m =np.matrix(results) gmm = GMM(numComponents,covariance_type='full', n_iter= 100, n_init = 4) gmm.fit(results) components = [] for componentID in xrange(numComponents): mu = gmm.means_[componentID] cov = gmm.covars_[componentID] proba = gmm.weights_[componentID] components.append((mu,cov,proba)) components = sorted(components,key=lambda x: x[0][0]) return components def drawComponents(surface, windowSize, scaleFactor, components): if components is None: return colors = [(255, 150, 150),(150, 150, 255),(150, 255, 150)] for color,(mu,cov, proba) in zip(colors[:len(components)],components): eigenvalues, eigenvectors = np.linalg.eig(cov) major = 2.0 * sqrt(5.991 * eigenvalues.max()) minor = 2.0 * sqrt(5.991 * eigenvalues.min()) angle1 = atan(eigenvectors[1][0]/eigenvectors[0][0]) angle2 = atan(eigenvectors[1][1]/eigenvectors[0][1]) if eigenvalues[0] > eigenvalues[1]: angle = angle1 else: angle = angle2 mu_x,mu_y = mu if major < 1.0 or minor < 1.0: continue s = pygame.Surface((major*scaleFactor[0], minor*scaleFactor[1]),pygame.SRCALPHA, 32) ellipse = pygame.draw.ellipse(s, color, (0, 0, major*scaleFactor[0], minor*scaleFactor[0])) s2 = pygame.transform.rotate(s, angle*360.0/(2.0*pi)) height, width = s2.get_rect().height,s2.get_rect().width surface.blit(s2,(mu_x*scaleFactor[0]-width/2.0,mu_y*scaleFactor[1]-height/2.0))#(mu_x*scaleFactor[0]-height/2.0,mu_y*scaleFactor[1]-width/2.0)) #s = pygame.Surface((major*scaleFactor[0], minor*scaleFactor[1])) #s.fill((255,255,255)) #s.set_alpha(128) #ellipse = pygame.draw.ellipse(s, blue, (0, 0, major*scaleFactor[0], minor*scaleFactor[0])) #s3 = pygame.transform.rotate(s, angle1*360.0/(2.0*pi)) #height, width = s3.get_rect().height,s3.get_rect().width #surface.blit(s3,(mu_x*scaleFactor[0]-width/2.0,mu_y*scaleFactor[1]-height/2.0))#(mu_x*scaleFactor[0]-height/2.0,mu_y*scaleFactor[1]-width/2.0)) #surface.blit(s,(0,0)) #print angle*360.0/(2.0*pi)<|fim▁end|>
from sklearn.mixture import GMM from math import sqrt, atan, pi
<|file_name|>test_temperature.py<|end_file_name|><|fim▁begin|>from unittest import TestCase from rfxcom.protocol.temperature import Temperature from rfxcom.exceptions import (InvalidPacketLength, UnknownPacketSubtype, UnknownPacketType) class TemperatureTestCase(TestCase): def setUp(self): self.data = bytearray(b'\x08\x50\x02\x11\x70\x02\x00\xA7\x89') self.parser = Temperature() def test_parse_bytes(self): self.assertTrue(self.parser.validate_packet(self.data)) self.assertTrue(self.parser.can_handle(self.data)) result = self.parser.load(self.data) self.assertEquals(result, { 'packet_length': 8, 'packet_type': 80, 'packet_type_name': 'Temperature sensors', 'sequence_number': 17, 'packet_subtype': 2, 'packet_subtype_name': 'THC238/268,THN132,THWR288,THRN122,THN122,AW129/131', 'temperature': 16.7, 'id': '0x7002', # 'channel': 2, TBC 'signal_level': 8, 'battery_level': 9 }) self.assertEquals(str(self.parser), "<Temperature ID:0x7002>") def test_parse_bytes2(self): self.data = bytearray(b'\x08\x50\x03\x02\xAE\x01\x00\x63\x59') self.assertTrue(self.parser.validate_packet(self.data)) self.assertTrue(self.parser.can_handle(self.data)) result = self.parser.load(self.data) self.assertEquals(result, { 'packet_length': 8,<|fim▁hole|> 'sequence_number': 2, 'packet_subtype': 3, 'packet_subtype_name': 'THWR800', 'temperature': 9.9, 'id': '0xAE01', # 'channel': 1, TBC 'signal_level': 5, 'battery_level': 9 }) self.assertEquals(str(self.parser), "<Temperature ID:0xAE01>") def test_parse_bytes_negative_temp(self): self.data = bytearray(b'\x08\x50\x06\x02\xAE\x01\x80\x55\x59') self.assertTrue(self.parser.validate_packet(self.data)) self.assertTrue(self.parser.can_handle(self.data)) result = self.parser.load(self.data) self.assertEquals(result, { 'packet_length': 8, 'packet_type': 80, 'packet_type_name': 'Temperature sensors', 'sequence_number': 2, 'packet_subtype': 6, 'packet_subtype_name': 'TS15C', 'temperature': -8.5, 'id': '0xAE01', # 'channel': 1, TBC 'signal_level': 5, 'battery_level': 9 }) self.assertEquals(str(self.parser), "<Temperature ID:0xAE01>") def test_validate_bytes_short(self): data = self.data[:1] with self.assertRaises(InvalidPacketLength): self.parser.validate_packet(data) def test_validate_unkown_packet_type(self): self.data[1] = 0xFF self.assertFalse(self.parser.can_handle(self.data)) with self.assertRaises(UnknownPacketType): self.parser.validate_packet(self.data) def test_validate_unknown_sub_type(self): self.data[2] = 0xEE self.assertFalse(self.parser.can_handle(self.data)) with self.assertRaises(UnknownPacketSubtype): self.parser.validate_packet(self.data) def test_log_name(self): self.assertEquals(self.parser.log.name, 'rfxcom.protocol.Temperature')<|fim▁end|>
'packet_type': 80, 'packet_type_name': 'Temperature sensors',
<|file_name|>dark-green.js<|end_file_name|><|fim▁begin|>version https://git-lfs.github.com/spec/v1 oid sha256:5f2b413f8d0cfe55ce8c84acbcfabcff78bd6d2a8f389d8201cb728b429b9bd5<|fim▁hole|><|fim▁end|>
size 4323
<|file_name|>demo_contact-vi-snes.py<|end_file_name|><|fim▁begin|>"""This demo program uses the interface to SNES solver for variational inequalities to solve a contact mechanics problems in FEniCS. The example considers a heavy hyperelastic circle in a box of the same size""" # Copyright (C) 2012 Corrado Maurini # # This file is part of DOLFIN. # # DOLFIN is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # DOLFIN is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>. # # Modified by Corrado Maurini 2013 # # First added: 2012-09-03 # Last changed: 2014-02-21 # from dolfin import * # Check that DOLFIN is configured with PETSc and CGAL if not has_petsc_snes(): print "DOLFIN must be compiled with PETSc version > 3.2 to run this demo." exit(0) # Create mesh mesh = Mesh("../circle_yplane.xml.gz") V = VectorFunctionSpace(mesh, "Lagrange", 1) # Define functions du = TrialFunction(V) # Incremental displacement v = TestFunction(V) # Test function u = Function(V) # Displacement from previous iteration B = Constant((0.0, -0.05)) # Body force per unit volume # Kinematics I = Identity(u.geometric_dimension()) # Identity tensor F = I + grad(u) # Deformation gradient C = F.T*F # Right Cauchy-Green tensor<|fim▁hole|> # Invariants of deformation tensors Ic = tr(C) J = det(F) # Elasticity parameters E, nu = 10.0, 0.3 mu, lmbda = Constant(E/(2*(1 + nu))), Constant(E*nu/((1 + nu)*(1 - 2*nu))) # Stored strain energy density (compressible neo-Hookean model) psi = (mu/2)*(Ic - 2) - mu*ln(J) + (lmbda/2)*(ln(J))**2 # Total potential energy Pi = psi*dx - dot(B, u)*dx # Compute first variation of Pi (directional derivative about u in the # direction of v) F = derivative(Pi, u, v) # Compute Jacobian of F J = derivative(F, u, du) # Symmetry condition (to block rigid body rotations) tol = mesh.hmin() def symmetry_line(x): return abs(x[0]) < DOLFIN_EPS bc = DirichletBC(V.sub(0), 0., symmetry_line, method="pointwise") # The displacement u must be such that the current configuration x+u # remains in the box [xmin,xmax] x [umin,ymax] constraint_u = Expression(("xmax - x[0]","ymax - x[1]"), \ xmax=1.0+DOLFIN_EPS, ymax=1.0) constraint_l = Expression(("xmin - x[0]","ymin - x[1]"), \ xmin=-1.0-DOLFIN_EPS, ymin=-1.0) umin = interpolate(constraint_l, V) umax = interpolate(constraint_u, V) # Define the solver parameters snes_solver_parameters = {"nonlinear_solver": "snes", "snes_solver" : { "linear_solver" : "lu", "maximum_iterations": 20, "report": True, "error_on_nonconvergence": False, }} # Set up the non-linear problem problem = NonlinearVariationalProblem(F, u, bc, J=J) # Set up the non-linear solver solver = NonlinearVariationalSolver(problem) solver.parameters.update(snes_solver_parameters) info(solver.parameters, True) # Solve the problem (iter, converged) = solver.solve(umin, umax) # Check for convergence if not converged: warning("This demo is a complex nonlinear problem. Convergence is not guaranteed when modifying some parameters or using PETSC 3.2.") # Save solution in VTK format file = File("displacement.pvd") file << u # plot the current configuration plot(u, mode="displacement", wireframe=True, title="Displacement field") interactive()<|fim▁end|>
<|file_name|>test_classes.py<|end_file_name|><|fim▁begin|>"""Test inter-conversion of different polynomial classes. This tests the convert and cast methods of all the polynomial classes. """ import operator as op from numbers import Number import pytest import numpy as np from numpy.polynomial import ( Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE) from numpy.testing import ( assert_almost_equal, assert_raises, assert_equal, assert_, ) from numpy.polynomial.polyutils import RankWarning # # fixtures # classes = ( Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE ) classids = tuple(cls.__name__ for cls in classes) @pytest.fixture(params=classes, ids=classids) def Poly(request): return request.param # # helper functions # random = np.random.random def assert_poly_almost_equal(p1, p2, msg=""): try: assert_(np.all(p1.domain == p2.domain)) assert_(np.all(p1.window == p2.window)) assert_almost_equal(p1.coef, p2.coef) except AssertionError: msg = f"Result: {p1}\nTarget: {p2}" raise AssertionError(msg) # # Test conversion methods that depend on combinations of two classes. # Poly1 = Poly Poly2 = Poly def test_conversion(Poly1, Poly2): x = np.linspace(0, 1, 10) coef = random((3,)) d1 = Poly1.domain + random((2,))*.25 w1 = Poly1.window + random((2,))*.25 p1 = Poly1(coef, domain=d1, window=w1) d2 = Poly2.domain + random((2,))*.25 w2 = Poly2.window + random((2,))*.25 p2 = p1.convert(kind=Poly2, domain=d2, window=w2) assert_almost_equal(p2.domain, d2) assert_almost_equal(p2.window, w2) assert_almost_equal(p2(x), p1(x)) def test_cast(Poly1, Poly2): x = np.linspace(0, 1, 10) coef = random((3,)) d1 = Poly1.domain + random((2,))*.25 w1 = Poly1.window + random((2,))*.25 p1 = Poly1(coef, domain=d1, window=w1) d2 = Poly2.domain + random((2,))*.25 w2 = Poly2.window + random((2,))*.25 p2 = Poly2.cast(p1, domain=d2, window=w2) assert_almost_equal(p2.domain, d2) assert_almost_equal(p2.window, w2) assert_almost_equal(p2(x), p1(x)) # # test methods that depend on one class # def test_identity(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 x = np.linspace(d[0], d[1], 11) p = Poly.identity(domain=d, window=w) assert_equal(p.domain, d) assert_equal(p.window, w) assert_almost_equal(p(x), x) def test_basis(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly.basis(5, domain=d, window=w) assert_equal(p.domain, d) assert_equal(p.window, w) assert_equal(p.coef, [0]*5 + [1]) def test_fromroots(Poly): # check that requested roots are zeros of a polynomial # of correct degree, domain, and window. d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 r = random((5,)) p1 = Poly.fromroots(r, domain=d, window=w) assert_equal(p1.degree(), len(r)) assert_equal(p1.domain, d) assert_equal(p1.window, w) assert_almost_equal(p1(r), 0) # check that polynomial is monic pdom = Polynomial.domain pwin = Polynomial.window p2 = Polynomial.cast(p1, domain=pdom, window=pwin) assert_almost_equal(p2.coef[-1], 1) def test_bad_conditioned_fit(Poly): x = [0., 0., 1.] y = [1., 2., 3.] # check RankWarning is raised with pytest.warns(RankWarning) as record: Poly.fit(x, y, 2) assert record[0].message.args[0] == "The fit may be poorly conditioned" def test_fit(Poly): def f(x): return x*(x - 1)*(x - 2) x = np.linspace(0, 3) y = f(x) # check default value of domain and window p = Poly.fit(x, y, 3) assert_almost_equal(p.domain, [0, 3]) assert_almost_equal(p(x), y) assert_equal(p.degree(), 3) # check with given domains and window d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly.fit(x, y, 3, domain=d, window=w) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, d) assert_almost_equal(p.window, w) p = Poly.fit(x, y, [0, 1, 2, 3], domain=d, window=w) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, d) assert_almost_equal(p.window, w) # check with class domain default p = Poly.fit(x, y, 3, []) assert_equal(p.domain, Poly.domain) assert_equal(p.window, Poly.window) p = Poly.fit(x, y, [0, 1, 2, 3], []) assert_equal(p.domain, Poly.domain) assert_equal(p.window, Poly.window) # check that fit accepts weights. w = np.zeros_like(x) z = y + random(y.shape)*.25 w[::2] = 1 p1 = Poly.fit(x[::2], z[::2], 3) p2 = Poly.fit(x, z, 3, w=w) p3 = Poly.fit(x, z, [0, 1, 2, 3], w=w) assert_almost_equal(p1(x), p2(x)) assert_almost_equal(p2(x), p3(x)) def test_equal(Poly): p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3]) p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3]) p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3]) p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2]) assert_(p1 == p1) assert_(not p1 == p2) assert_(not p1 == p3) assert_(not p1 == p4) def test_not_equal(Poly): p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3]) p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3]) p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3]) p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2]) assert_(not p1 != p1) assert_(p1 != p2) assert_(p1 != p3) assert_(p1 != p4) def test_add(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 + p2 assert_poly_almost_equal(p2 + p1, p3) assert_poly_almost_equal(p1 + c2, p3) assert_poly_almost_equal(c2 + p1, p3) assert_poly_almost_equal(p1 + tuple(c2), p3) assert_poly_almost_equal(tuple(c2) + p1, p3) assert_poly_almost_equal(p1 + np.array(c2), p3) assert_poly_almost_equal(np.array(c2) + p1, p3) assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.add, p1, Chebyshev([0])) else: assert_raises(TypeError, op.add, p1, Polynomial([0])) def test_sub(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 - p2 assert_poly_almost_equal(p2 - p1, -p3) assert_poly_almost_equal(p1 - c2, p3) assert_poly_almost_equal(c2 - p1, -p3) assert_poly_almost_equal(p1 - tuple(c2), p3) assert_poly_almost_equal(tuple(c2) - p1, -p3) assert_poly_almost_equal(p1 - np.array(c2), p3) assert_poly_almost_equal(np.array(c2) - p1, -p3) assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.sub, p1, Chebyshev([0])) else: assert_raises(TypeError, op.sub, p1, Polynomial([0])) def test_mul(Poly): c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 * p2 assert_poly_almost_equal(p2 * p1, p3) assert_poly_almost_equal(p1 * c2, p3) assert_poly_almost_equal(c2 * p1, p3) assert_poly_almost_equal(p1 * tuple(c2), p3) assert_poly_almost_equal(tuple(c2) * p1, p3) assert_poly_almost_equal(p1 * np.array(c2), p3) assert_poly_almost_equal(np.array(c2) * p1, p3) assert_poly_almost_equal(p1 * 2, p1 * Poly([2])) assert_poly_almost_equal(2 * p1, p1 * Poly([2])) assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.mul, p1, Chebyshev([0])) else: assert_raises(TypeError, op.mul, p1, Polynomial([0])) def test_floordiv(Poly): c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) assert_poly_almost_equal(p4 // p2, p1) assert_poly_almost_equal(p4 // c2, p1) assert_poly_almost_equal(c4 // p2, p1) assert_poly_almost_equal(p4 // tuple(c2), p1) assert_poly_almost_equal(tuple(c4) // p2, p1) assert_poly_almost_equal(p4 // np.array(c2), p1) assert_poly_almost_equal(np.array(c4) // p2, p1) assert_poly_almost_equal(2 // p2, Poly([0])) assert_poly_almost_equal(p2 // 2, 0.5*p2) assert_raises( TypeError, op.floordiv, p1, Poly([0], domain=Poly.domain + 1)) assert_raises( TypeError, op.floordiv, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.floordiv, p1, Chebyshev([0])) else: assert_raises(TypeError, op.floordiv, p1, Polynomial([0])) def test_truediv(Poly): # true division is valid only if the denominator is a Number and # not a python bool. p1 = Poly([1,2,3]) p2 = p1 * 5 for stype in np.ScalarType: if not issubclass(stype, Number) or issubclass(stype, bool): continue s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for stype in (int, float): s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1)<|fim▁hole|> assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for s in [tuple(), list(), dict(), bool(), np.array([1])]: assert_raises(TypeError, op.truediv, p2, s) assert_raises(TypeError, op.truediv, s, p2) for ptype in classes: assert_raises(TypeError, op.truediv, p2, ptype(1)) def test_mod(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) assert_poly_almost_equal(p4 % p2, p3) assert_poly_almost_equal(p4 % c2, p3) assert_poly_almost_equal(c4 % p2, p3) assert_poly_almost_equal(p4 % tuple(c2), p3) assert_poly_almost_equal(tuple(c4) % p2, p3) assert_poly_almost_equal(p4 % np.array(c2), p3) assert_poly_almost_equal(np.array(c4) % p2, p3) assert_poly_almost_equal(2 % p2, Poly([2])) assert_poly_almost_equal(p2 % 2, Poly([0])) assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.mod, p1, Chebyshev([0])) else: assert_raises(TypeError, op.mod, p1, Polynomial([0])) def test_divmod(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) quo, rem = divmod(p4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, c2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(c4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, tuple(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(tuple(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, np.array(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(np.array(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p2, 2) assert_poly_almost_equal(quo, 0.5*p2) assert_poly_almost_equal(rem, Poly([0])) quo, rem = divmod(2, p2) assert_poly_almost_equal(quo, Poly([0])) assert_poly_almost_equal(rem, Poly([2])) assert_raises(TypeError, divmod, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, divmod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, divmod, p1, Chebyshev([0])) else: assert_raises(TypeError, divmod, p1, Polynomial([0])) def test_roots(Poly): d = Poly.domain * 1.25 + .25 w = Poly.window tgt = np.linspace(d[0], d[1], 5) res = np.sort(Poly.fromroots(tgt, domain=d, window=w).roots()) assert_almost_equal(res, tgt) # default domain and window res = np.sort(Poly.fromroots(tgt).roots()) assert_almost_equal(res, tgt) def test_degree(Poly): p = Poly.basis(5) assert_equal(p.degree(), 5) def test_copy(Poly): p1 = Poly.basis(5) p2 = p1.copy() assert_(p1 == p2) assert_(p1 is not p2) assert_(p1.coef is not p2.coef) assert_(p1.domain is not p2.domain) assert_(p1.window is not p2.window) def test_integ(Poly): P = Polynomial # Check defaults p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ()) p2 = P.cast(p0.integ(2)) assert_poly_almost_equal(p1, P([0, 2, 3, 4])) assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1])) # Check with k p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ(k=1)) p2 = P.cast(p0.integ(2, k=[1, 1])) assert_poly_almost_equal(p1, P([1, 2, 3, 4])) assert_poly_almost_equal(p2, P([1, 1, 1, 1, 1])) # Check with lbnd p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ(lbnd=1)) p2 = P.cast(p0.integ(2, lbnd=1)) assert_poly_almost_equal(p1, P([-9, 2, 3, 4])) assert_poly_almost_equal(p2, P([6, -9, 1, 1, 1])) # Check scaling d = 2*Poly.domain p0 = Poly.cast(P([1*2, 2*3, 3*4]), domain=d) p1 = P.cast(p0.integ()) p2 = P.cast(p0.integ(2)) assert_poly_almost_equal(p1, P([0, 2, 3, 4])) assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1])) def test_deriv(Poly): # Check that the derivative is the inverse of integration. It is # assumes that the integration has been checked elsewhere. d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p1 = Poly([1, 2, 3], domain=d, window=w) p2 = p1.integ(2, k=[1, 2]) p3 = p1.integ(1, k=[1]) assert_almost_equal(p2.deriv(1).coef, p3.coef) assert_almost_equal(p2.deriv(2).coef, p1.coef) # default domain and window p1 = Poly([1, 2, 3]) p2 = p1.integ(2, k=[1, 2]) p3 = p1.integ(1, k=[1]) assert_almost_equal(p2.deriv(1).coef, p3.coef) assert_almost_equal(p2.deriv(2).coef, p1.coef) def test_linspace(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly([1, 2, 3], domain=d, window=w) # check default domain xtgt = np.linspace(d[0], d[1], 20) ytgt = p(xtgt) xres, yres = p.linspace(20) assert_almost_equal(xres, xtgt) assert_almost_equal(yres, ytgt) # check specified domain xtgt = np.linspace(0, 2, 20) ytgt = p(xtgt) xres, yres = p.linspace(20, domain=[0, 2]) assert_almost_equal(xres, xtgt) assert_almost_equal(yres, ytgt) def test_pow(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 tgt = Poly([1], domain=d, window=w) tst = Poly([1, 2, 3], domain=d, window=w) for i in range(5): assert_poly_almost_equal(tst**i, tgt) tgt = tgt * tst # default domain and window tgt = Poly([1]) tst = Poly([1, 2, 3]) for i in range(5): assert_poly_almost_equal(tst**i, tgt) tgt = tgt * tst # check error for invalid powers assert_raises(ValueError, op.pow, tgt, 1.5) assert_raises(ValueError, op.pow, tgt, -1) def test_call(Poly): P = Polynomial d = Poly.domain x = np.linspace(d[0], d[1], 11) # Check defaults p = Poly.cast(P([1, 2, 3])) tgt = 1 + x*(2 + 3*x) res = p(x) assert_almost_equal(res, tgt) def test_cutdeg(Poly): p = Poly([1, 2, 3]) assert_raises(ValueError, p.cutdeg, .5) assert_raises(ValueError, p.cutdeg, -1) assert_equal(len(p.cutdeg(3)), 3) assert_equal(len(p.cutdeg(2)), 3) assert_equal(len(p.cutdeg(1)), 2) assert_equal(len(p.cutdeg(0)), 1) def test_truncate(Poly): p = Poly([1, 2, 3]) assert_raises(ValueError, p.truncate, .5) assert_raises(ValueError, p.truncate, 0) assert_equal(len(p.truncate(4)), 3) assert_equal(len(p.truncate(3)), 3) assert_equal(len(p.truncate(2)), 2) assert_equal(len(p.truncate(1)), 1) def test_trim(Poly): c = [1, 1e-6, 1e-12, 0] p = Poly(c) assert_equal(p.trim().coef, c[:3]) assert_equal(p.trim(1e-10).coef, c[:2]) assert_equal(p.trim(1e-5).coef, c[:1]) def test_mapparms(Poly): # check with defaults. Should be identity. d = Poly.domain w = Poly.window p = Poly([1], domain=d, window=w) assert_almost_equal([0, 1], p.mapparms()) # w = 2*d + 1 p = Poly([1], domain=d, window=w) assert_almost_equal([1, 2], p.mapparms()) def test_ufunc_override(Poly): p = Poly([1, 2, 3]) x = np.ones(3) assert_raises(TypeError, np.add, p, x) assert_raises(TypeError, np.add, x, p) # # Test class method that only exists for some classes # class TestInterpolate: def f(self, x): return x * (x - 1) * (x - 2) def test_raises(self): assert_raises(ValueError, Chebyshev.interpolate, self.f, -1) assert_raises(TypeError, Chebyshev.interpolate, self.f, 10.) def test_dimensions(self): for deg in range(1, 5): assert_(Chebyshev.interpolate(self.f, deg).degree() == deg) def test_approximation(self): def powx(x, p): return x**p x = np.linspace(0, 2, 10) for deg in range(0, 10): for t in range(0, deg + 1): p = Chebyshev.interpolate(powx, deg, domain=[0, 2], args=(t,)) assert_almost_equal(p(x), powx(x, t), decimal=11)<|fim▁end|>
assert_raises(TypeError, op.truediv, s, p2) for stype in [complex]: s = stype(5, 0)
<|file_name|>acl.go<|end_file_name|><|fim▁begin|>package app import ( "errors" "net/http" "strings" "github.com/h2object/h2object/httpext" ) func acl_filter(ctx *context, c *ext.Controller, filters []filter) { if done := do_authentic(ctx, c); done { ctx.Info("request (%s) (%s) done by acl", c.Request.MethodToLower(), c.Request.URI()) return } filters[0](ctx, c, filters[1:]) } func do_authentic(ctx *context, ctrl *ext.Controller) bool { r := ctrl.Request required := false switch r.MethodToLower() { case "get": switch r.Suffix() { case "page": fallthrough case "click": fallthrough <|fim▁hole|> required = true } if r.URI() == "/stats" { required = true } case "put": required = true if ctx.storage_full() { ctrl.JsonError(http.StatusForbidden, errors.New("application storage reach max limit.")) return true } case "delete": required = true } token := r.Param("token") if token == "" { authorization := r.Header.Get("Authorization") if strings.HasPrefix(authorization, "H2OBJECT ") { token = authorization[len("H2OBJECT "):] } } if required { if token != ctx.signature { ctrl.JsonError(http.StatusUnauthorized, errors.New("require administrator right")) return true } } return false }<|fim▁end|>
case "system":
<|file_name|>derive.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 Syn Developers // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use super::*; use punctuated::Punctuated; ast_struct! { /// Data structure sent to a `proc_macro_derive` macro. /// /// *This type is available if Syn is built with the `"derive"` feature.* pub struct DeriveInput { /// Attributes tagged on the whole struct or enum. pub attrs: Vec<Attribute>, /// Visibility of the struct or enum. pub vis: Visibility, /// Name of the struct or enum. pub ident: Ident, /// Generics required to complete the definition. pub generics: Generics, /// Data within the struct or enum. pub data: Data, } } ast_enum_of_structs! { /// The storage of a struct, enum or union data structure. /// /// *This type is available if Syn is built with the `"derive"` feature.* /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums pub enum Data { /// A struct input to a `proc_macro_derive` macro. /// /// *This type is available if Syn is built with the `"derive"` /// feature.* pub Struct(DataStruct { pub struct_token: Token![struct], pub fields: Fields, pub semi_token: Option<Token![;]>, }), /// An enum input to a `proc_macro_derive` macro. /// /// *This type is available if Syn is built with the `"derive"` /// feature.* pub Enum(DataEnum { pub enum_token: Token![enum], pub brace_token: token::Brace, pub variants: Punctuated<Variant, Token![,]>, }), /// A tagged union input to a `proc_macro_derive` macro. /// /// *This type is available if Syn is built with the `"derive"` /// feature.* pub Union(DataUnion { pub union_token: Token![union], pub fields: FieldsNamed, }), } do_not_generate_to_tokens } #[cfg(feature = "parsing")] pub mod parsing { use super::*; use synom::Synom; impl Synom for DeriveInput { named!(parse -> Self, do_parse!( attrs: many0!(Attribute::parse_outer) >> vis: syn!(Visibility) >> which: alt!( keyword!(struct) => { Ok } | keyword!(enum) => { Err } ) >> id: syn!(Ident) >> generics: syn!(Generics) >> item: switch!(value!(which), Ok(s) => map!(data_struct, move |(wh, fields, semi)| DeriveInput { ident: id, vis: vis, attrs: attrs, generics: Generics { where_clause: wh, .. generics }, data: Data::Struct(DataStruct { struct_token: s, fields: fields, semi_token: semi, }), }) | Err(e) => map!(data_enum, move |(wh, brace, variants)| DeriveInput { ident: id, vis: vis, attrs: attrs, generics: Generics { where_clause: wh, .. generics }, data: Data::Enum(DataEnum { variants: variants, brace_token: brace, enum_token: e, }), }) ) >> (item) )); fn description() -> Option<&'static str> {<|fim▁hole|> } } named!(data_struct -> (Option<WhereClause>, Fields, Option<Token![;]>), alt!( do_parse!( wh: option!(syn!(WhereClause)) >> fields: syn!(FieldsNamed) >> (wh, Fields::Named(fields), None) ) | do_parse!( fields: syn!(FieldsUnnamed) >> wh: option!(syn!(WhereClause)) >> semi: punct!(;) >> (wh, Fields::Unnamed(fields), Some(semi)) ) | do_parse!( wh: option!(syn!(WhereClause)) >> semi: punct!(;) >> (wh, Fields::Unit, Some(semi)) ) )); named!(data_enum -> (Option<WhereClause>, token::Brace, Punctuated<Variant, Token![,]>), do_parse!( wh: option!(syn!(WhereClause)) >> data: braces!(Punctuated::parse_terminated) >> (wh, data.0, data.1) )); } #[cfg(feature = "printing")] mod printing { use super::*; use attr::FilterAttrs; use proc_macro2::TokenStream; use quote::ToTokens; impl ToTokens for DeriveInput { fn to_tokens(&self, tokens: &mut TokenStream) { for attr in self.attrs.outer() { attr.to_tokens(tokens); } self.vis.to_tokens(tokens); match self.data { Data::Struct(ref d) => d.struct_token.to_tokens(tokens), Data::Enum(ref d) => d.enum_token.to_tokens(tokens), Data::Union(ref d) => d.union_token.to_tokens(tokens), } self.ident.to_tokens(tokens); self.generics.to_tokens(tokens); match self.data { Data::Struct(ref data) => match data.fields { Fields::Named(ref fields) => { self.generics.where_clause.to_tokens(tokens); fields.to_tokens(tokens); } Fields::Unnamed(ref fields) => { fields.to_tokens(tokens); self.generics.where_clause.to_tokens(tokens); TokensOrDefault(&data.semi_token).to_tokens(tokens); } Fields::Unit => { self.generics.where_clause.to_tokens(tokens); TokensOrDefault(&data.semi_token).to_tokens(tokens); } }, Data::Enum(ref data) => { self.generics.where_clause.to_tokens(tokens); data.brace_token.surround(tokens, |tokens| { data.variants.to_tokens(tokens); }); } Data::Union(ref data) => { self.generics.where_clause.to_tokens(tokens); data.fields.to_tokens(tokens); } } } } }<|fim▁end|>
Some("derive input")
<|file_name|>parseUrl.js<|end_file_name|><|fim▁begin|>export default (original) => { <|fim▁hole|> let [path, params] = url.split('?'); if (path.length >= 2) { path = path.replace(/\/$/, ''); } if (params) { params = parseSearchParams(params); } else { params = {} } const actual = path + joinSearchParams(params); return { path, params, original, actual }; } const getHashUrl = (original) => { let url = original.split('#'); if (url.length >= 2) { url = url[1]; } else { url = '/'; } if (url === '') { url = '/'; } if (url[0] !== '/') { url = '/' + url; } return url; } const parseSearchParams = (searchString) => { let pairSplit; return (searchString || '').replace(/^\?/, '').split('&').reduce((p, pair) => { pairSplit = pair.split('='); if (pairSplit.length >= 1 && pairSplit[0].length >= 1) { p[decodeURIComponent(pairSplit[0])] = decodeURIComponent(pairSplit[1]) || ''; } return p; }, {}); } const joinSearchParams = (searchParams) => { const searchString = Object .keys(searchParams) .reduce((p, paramKey) => p += `&${paramKey}=${searchParams[paramKey]}`, '?'); if (searchString.length <= 1) { return ''; } return searchString.replace('?&', '?'); }<|fim▁end|>
const url = getHashUrl(original);
<|file_name|>coherence-tuple-conflict.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::Debug; use std::default::Default; // Test that a blank impl for all T conflicts with an impl for some // specific T. trait MyTrait { fn get(&self) -> usize; } impl<T> MyTrait for (T,T) { //~ ERROR E0119 fn get(&self) -> usize { 0 } } impl<A,B> MyTrait for (A,B) { fn get(&self) -> usize { self.dummy } }<|fim▁hole|> fn main() { }<|fim▁end|>
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import os class generic(object): def __init__(self,myspec): self.settings=myspec self.settings.setdefault('CHROOT', 'chroot') def setarch(self, arch): """Set the chroot wrapper to run through `setarch |arch|`<|fim▁hole|> self.settings['CHROOT'] = 'setarch %s %s' % (arch, self.settings['CHROOT']) def mount_safety_check(self): """ Make sure that no bind mounts exist in chrootdir (to use before cleaning the directory, to make sure we don't wipe the contents of a bind mount """ pass def mount_all(self): """do all bind mounts""" pass def umount_all(self): """unmount all bind mounts""" pass<|fim▁end|>
Useful for building x86-on-amd64 and such. """ if os.uname()[0] == 'Linux':
<|file_name|>managers.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.contrib.auth.models import BaseUserManager from django.db.models import Q from django.utils import timezone<|fim▁hole|>from pootle_app.models.permissions import check_user_permission from pootle_translationproject.models import TranslationProject from . import utils __all__ = ('UserManager', ) class UserManager(BaseUserManager): """Pootle User manager. This manager hides the 'nobody' and 'default' users for normal queries, since they are special users. Code that needs access to these users should use the methods get_default_user and get_nobody_user. """ PERMISSION_USERS = ('default', 'nobody') META_USERS = ('default', 'nobody', 'system') def _create_user(self, username, email, password, is_superuser, **extra_fields): """Creates and saves a User with the given username, email, password and superuser status. Adapted from the core ``auth.User`` model's ``UserManager``: we have no use for the ``is_staff`` field. """ now = timezone.now() if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) utils.validate_email_unique(email) user = self.model(username=username, email=email, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): return self._create_user(username, email, password, False, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): return self._create_user(username, email, password, True, **extra_fields) @lru_cache() def get_default_user(self): return self.get_queryset().get(username='default') @lru_cache() def get_nobody_user(self): return self.get_queryset().get(username='nobody') @lru_cache() def get_system_user(self): return self.get_queryset().get(username='system') def hide_permission_users(self): return self.get_queryset().exclude(username__in=self.PERMISSION_USERS) def hide_meta(self): return self.get_queryset().exclude(username__in=self.META_USERS) def meta_users(self): return self.get_queryset().filter(username__in=self.META_USERS) def get_users_with_permission(self, permission_code, project, language): default = self.get_default_user() directory = TranslationProject.objects.get( project=project, language=language ).directory if check_user_permission(default, permission_code, directory): return self.hide_meta().filter(is_active=True) user_filter = Q( permissionset__positive_permissions__codename=permission_code ) language_path = language.directory.pootle_path project_path = project.directory.pootle_path user_filter &= ( Q(permissionset__directory__pootle_path=directory.pootle_path) | Q(permissionset__directory__pootle_path=language_path) | Q(permissionset__directory__pootle_path=project_path) ) user_filter |= Q(is_superuser=True) return self.get_queryset().filter(user_filter).distinct()<|fim▁end|>
from django.utils.lru_cache import lru_cache
<|file_name|>NetInfo.java<|end_file_name|><|fim▁begin|>package edu.ut.mobile.network; public class NetInfo{ //public static byte[] IPAddress = {Integer.valueOf("54").byteValue(),Integer.valueOf("73").byteValue(),Integer.valueOf("28").byteValue(),Integer.valueOf("236").byteValue()}; static byte[] IPAddress = {Integer.valueOf("192").byteValue(),Integer.valueOf("168").byteValue(),Integer.valueOf("1").byteValue(),Integer.valueOf("67").byteValue()}; static int port = 6000;<|fim▁hole|> }<|fim▁end|>
static int waitTime = 100000;
<|file_name|>test_bug_1896463.py<|end_file_name|><|fim▁begin|># 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import fixtures import time from oslo_config import cfg from nova import context from nova import objects from nova import test from nova.tests import fixtures as nova_fixtures from nova.tests.functional import fixtures as func_fixtures from nova.tests.functional import integrated_helpers from nova import utils from nova.virt import fake CONF = cfg.CONF class TestEvacuateResourceTrackerRace( test.TestCase, integrated_helpers.InstanceHelperMixin, ): """Demonstrate bug #1896463. Trigger a race condition between an almost finished evacuation that is dropping the migration context, and the _update_available_resource() periodic task that already loaded the instance list but haven't loaded the migration list yet. The result is that the PCI allocation made by the evacuation is deleted by the overlapping periodic task run and the instance will not have PCI allocation after the evacuation. """ def setUp(self): super().setUp() self.neutron = self.useFixture(nova_fixtures.NeutronFixture(self)) self.glance = self.useFixture(nova_fixtures.GlanceFixture(self)) self.placement = self.useFixture(func_fixtures.PlacementFixture()).api self.api_fixture = self.useFixture(nova_fixtures.OSAPIFixture(<|fim▁hole|> api_version='v2.1')) self.useFixture(fixtures.MockPatch( 'nova.pci.utils.get_mac_by_pci_address', return_value='52:54:00:1e:59:c6')) self.useFixture(fixtures.MockPatch( 'nova.pci.utils.get_vf_num_by_pci_address', return_value=1)) self.admin_api = self.api_fixture.admin_api self.admin_api.microversion = 'latest' self.api = self.admin_api self.start_service('conductor') self.start_service('scheduler') self.flags(compute_driver='fake.FakeDriverWithPciResources') self.useFixture( fake.FakeDriverWithPciResources. FakeDriverWithPciResourcesConfigFixture()) self.compute1 = self._start_compute('host1') self.compute1_id = self._get_compute_node_id_by_host('host1') self.compute1_service_id = self.admin_api.get_services( host='host1', binary='nova-compute')[0]['id'] self.compute2 = self._start_compute('host2') self.compute2_id = self._get_compute_node_id_by_host('host2') self.compute2_service_id = self.admin_api.get_services( host='host2', binary='nova-compute')[0]['id'] # add extra ports and the related network to the neutron fixture # specifically for these tests. It cannot be added globally in the # fixture init as it adds a second network that makes auto allocation # based test to fail due to ambiguous networks. self.neutron._ports[self.neutron.sriov_port['id']] = \ copy.deepcopy(self.neutron.sriov_port) self.neutron._networks[ self.neutron.network_2['id']] = self.neutron.network_2 self.neutron._subnets[ self.neutron.subnet_2['id']] = self.neutron.subnet_2 self.ctxt = context.get_admin_context() def _get_compute_node_id_by_host(self, host): # we specifically need the integer id of the node not the UUID so we # need to use the old microversion with utils.temporary_mutation(self.admin_api, microversion='2.52'): hypers = self.admin_api.api_get( 'os-hypervisors').body['hypervisors'] for hyper in hypers: if hyper['hypervisor_hostname'] == host: return hyper['id'] self.fail('Hypervisor with hostname=%s not found' % host) def _assert_pci_device_allocated( self, instance_uuid, compute_node_id, num=1): """Assert that a given number of PCI devices are allocated to the instance on the given host. """ devices = objects.PciDeviceList.get_by_instance_uuid( self.ctxt, instance_uuid) devices_on_host = [dev for dev in devices if dev.compute_node_id == compute_node_id] self.assertEqual(num, len(devices_on_host)) def test_evacuate_races_with_update_available_resource(self): # Create a server with a direct port to have PCI allocation server = self._create_server( name='test-server-for-bug-1896463', networks=[{'port': self.neutron.sriov_port['id']}], host='host1' ) self._assert_pci_device_allocated(server['id'], self.compute1_id) self._assert_pci_device_allocated( server['id'], self.compute2_id, num=0) # stop and force down the compute the instance is on to allow # evacuation self.compute1.stop() self.admin_api.put_service( self.compute1_service_id, {'forced_down': 'true'}) # Inject some sleeps both in the Instance.drop_migration_context and # the MigrationList.get_in_progress_and_error code to make them # overlap. # We want to create the following execution scenario: # 1) The evacuation makes a move claim on the dest including the PCI # claim. This means there is a migration context. But the evacuation # is not complete yet so the instance.host does not point to the # dest host. # 2) The dest resource tracker starts an _update_available_resource() # periodic task and this task loads the list of instances on its # host from the DB. Our instance is not in this list due to #1. # 3) The evacuation finishes, the instance.host is set to the dest host # and the migration context is deleted. # 4) The periodic task now loads the list of in-progress migration from # the DB to check for incoming our outgoing migrations. However due # to #3 our instance is not in this list either. # 5) The periodic task cleans up every lingering PCI claim that is not # connected to any instance collected above from the instance list # and from the migration list. As our instance is not in either of # the lists, the resource tracker cleans up the PCI allocation for # the already finished evacuation of our instance. # # Unfortunately we cannot reproduce the above situation without sleeps. # We need that the evac starts first then the periodic starts, but not # finishes, then evac finishes, then periodic finishes. If I trigger # and run the whole periodic in a wrapper of drop_migration_context # then I could not reproduce the situation described at #4). In general # it is not # # evac # | # | # | periodic # | | # | | # | x # | # | # x # # but # # evac # | # | # | periodic # | | # | | # | | # x | # | # x # # what is needed need. # # Starting the periodic from the test in a separate thread at # drop_migration_context() might work but that is an extra complexity # in the test code. Also it might need a sleep still to make the # reproduction stable but only one sleep instead of two. orig_drop = objects.Instance.drop_migration_context def slow_drop(*args, **kwargs): time.sleep(1) return orig_drop(*args, **kwargs) self.useFixture( fixtures.MockPatch( 'nova.objects.instance.Instance.drop_migration_context', new=slow_drop)) orig_get_mig = objects.MigrationList.get_in_progress_and_error def slow_get_mig(*args, **kwargs): time.sleep(2) return orig_get_mig(*args, **kwargs) self.useFixture( fixtures.MockPatch( 'nova.objects.migration.MigrationList.' 'get_in_progress_and_error', new=slow_get_mig)) self.admin_api.post_server_action(server['id'], {'evacuate': {}}) # we trigger the _update_available_resource periodic to overlap with # the already started evacuation self._run_periodics() self._wait_for_server_parameter( server, {'OS-EXT-SRV-ATTR:host': 'host2', 'status': 'ACTIVE'}) self._assert_pci_device_allocated(server['id'], self.compute1_id) self._assert_pci_device_allocated(server['id'], self.compute2_id)<|fim▁end|>
<|file_name|>unit-students-editor.component.ts<|end_file_name|><|fim▁begin|>import { Unit, csvUploadModalService, csvResultModalService, unitStudentEnrolmentModal, } from './../../../../../ajs-upgraded-providers'; import { ViewChild, Component, Input, Inject } from '@angular/core'; import { MatTable, MatTableDataSource } from '@angular/material/table'; import { MatSort, Sort } from '@angular/material/sort'; import { alertService } from 'src/app/ajs-upgraded-providers'; import { MatPaginator } from '@angular/material/paginator'; import { HttpClient } from '@angular/common/http'; import { FileDownloaderService } from 'src/app/common/file-downloader/file-downloader'; @Component({ selector: 'unit-students-editor', templateUrl: 'unit-students-editor.component.html', styleUrls: ['unit-students-editor.component.scss'], }) export class UnitStudentsEditorComponent { @ViewChild(MatTable, { static: false }) table: MatTable<any>; @ViewChild(MatSort, { static: false }) sort: MatSort; @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator; @Input() unit: any; columns: string[] = [ 'student_id', 'first_name', 'last_name', 'student_email', 'campus', 'tutorial', 'enrolled', 'goto', ]; dataSource: MatTableDataSource<any>; // Calls the parent's constructor, passing in an object // that maps all of the form controls that this form consists of. constructor( private httpClient: HttpClient, @Inject(unitStudentEnrolmentModal) private enrolModal: any, @Inject(alertService) private alerts: any, @Inject(Unit) private unitService: any, @Inject(csvUploadModalService) private csvUploadModal: any, @Inject(csvResultModalService) private csvResultModal: any, @Inject(FileDownloaderService) private fileDownloader: FileDownloaderService ) {} ngOnInit() {} // The paginator is inside the table ngAfterViewInit() { this.dataSource = new MatTableDataSource(this.unit.students); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; this.dataSource.filterPredicate = (data: any, filter: string) => data.matches(filter); } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } private sortCompare(aValue: number | string, bValue: number | string, isAsc: boolean) { return (aValue < bValue ? -1 : 1) * (isAsc ? 1 : -1); } // Sorting function to sort data when sort // event is triggered sortTableData(sort: Sort) { if (!sort.active || sort.direction === '') { return; } this.dataSource.data = this.dataSource.data.sort((a, b) => { const isAsc = sort.direction === 'asc'; switch (sort.active) { case 'student_id': case 'first_name': case 'last_name': case 'student_email': case 'enrolled': return this.sortCompare(a[sort.active], b[sort.active], isAsc); case 'campus': return this.sortCompare(a.campus().abbreviation, b.campus().abbreviation, isAsc); default: return 0; } }); } public gotoStudent(student: any) { student.viewProject(true); } <|fim▁hole|> enrolStudent() { this.enrolModal.show(this.unit); } uploadEnrolments() { this.csvUploadModal.show( 'Upload Students to Enrol', 'Test message', { file: { name: 'Enrol CSV Data', type: 'csv' } }, this.unitService.enrolStudentsCSVUrl(this.unit), (response: any) => { // at least one student? this.csvResultModal.show('Enrol Student CSV Results', response); if (response.success.length > 0) { this.unit.refreshStudents(); } } ); } uploadWithdrawals() { this.csvUploadModal.show( 'Upload Students to Withdraw', 'Test message', { file: { name: 'Withdraw CSV Data', type: 'csv' } }, this.unitService.withdrawStudentsCSVUrl(this.unit), (response: any) => { // at least one student? this.csvResultModal.show('Withdraw Student CSV Results', response); if (response.success.length > 0) { this.unit.refreshStudents(); } } ); } downloadEnrolments() { const url: string = this.unitService.enrolStudentsCSVUrl(this.unit); this.fileDownloader.downloadFile(url, `${this.unit.code}-students.csv`); } }<|fim▁end|>
<|file_name|>libARDrone.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ python library for the AR.Drone 1.0 (1.11.5) and 2.0 (2.2.9). parts of code from Bastian Venthur, Jean-Baptiste Passot, Florian Lacrampe. tested with Python 2.7.3 and AR.Drone vanilla firmware 1.11.5. """ # < imports >-------------------------------------------------------------------------------------- import logging import multiprocessing import sys import threading import time import arATCmds import arNetwork import arIPCThread # < variáveis globais >---------------------------------------------------------------------------- # logging level w_logLvl = logging.ERROR # < class ARDrone >-------------------------------------------------------------------------------- class ARDrone ( object ): """ ARDrone class. instanciate this class to control AR.Drone and receive decoded video and navdata. """ # --------------------------------------------------------------------------------------------- # ARDrone::__init__ # --------------------------------------------------------------------------------------------- def __init__ ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::__init__" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.seq_nr = 1 self.timer_t = 0.2 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.lock = threading.Lock () self.speed = 0.2 self.at ( arATCmds.at_config, "general:navdata_demo", "TRUE" ) self.vid_pipe, vid_pipe_other = multiprocessing.Pipe () self.nav_pipe, nav_pipe_other = multiprocessing.Pipe () self.com_pipe, com_pipe_other = multiprocessing.Pipe () self.network_process = arNetwork.ARDroneNetworkProcess ( nav_pipe_other, vid_pipe_other, com_pipe_other ) self.network_process.start () self.ipc_thread = arIPCThread.IPCThread ( self ) self.ipc_thread.start () self.image = None self.navdata = {} self.time = 0 # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::apply_command # --------------------------------------------------------------------------------------------- def apply_command ( self, f_command ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::apply_command" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) las_available_commands = [ "emergency", "hover", "land", "move_backward", "move_down", "move_forward", "move_left", "move_right", "move_up", "takeoff", "turn_left", "turn_right", ] # validade command if ( f_command not in las_available_commands ): # sherlock logger # l_log.error ( "Command %s not recognized !" % f_command ) # sherlock logger # l_log.debug ( "<< (E01)" ) return if ( "hover" != f_command ): self.last_command_is_hovering = False if ( "emergency" == f_command ): self.reset () elif (( "hover" == f_command ) and ( not self.last_command_is_hovering )): self.hover () self.last_command_is_hovering = True elif ( "land" == f_command ): self.land () self.last_command_is_hovering = True elif ( "move_backward" == f_command ): self.move_backward () elif ( "move_forward" == f_command ): self.move_forward () elif ( "move_down" == f_command ): self.move_down () elif ( "move_up" == f_command ): self.move_up () elif ( "move_left" == f_command ): self.move_left () elif ( "move_right" == f_command ): self.move_right () elif ( "takeoff" == f_command ): self.takeoff () self.last_command_is_hovering = True elif ( "turn_left" == f_command ): self.turn_left () elif ( "turn_right" == f_command ): self.turn_right () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::at # --------------------------------------------------------------------------------------------- def at ( self, f_cmd, *args, **kwargs ): """ wrapper for the low level at commands. this method takes care that the sequence number is increased after each at command and the watchdog timer is started to make sure the drone receives a command at least every second. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::at" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.lock.acquire () self.com_watchdog_timer.cancel () f_cmd ( self.seq_nr, *args, **kwargs ) self.seq_nr += 1 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.com_watchdog_timer.start () self.lock.release () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::commwdg # --------------------------------------------------------------------------------------------- def commwdg ( self ): """ communication watchdog signal. this needs to be send regulary to keep the communication with the drone alive. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::commwdg" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_comwdg ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_boom # --------------------------------------------------------------------------------------------- def event_boom ( self ): """ boom event """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_boom" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_THETA_30_DEG # total duration in seconds of the animation lf_secs = 1000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_thetamixed # --------------------------------------------------------------------------------------------- def event_thetamixed ( self ): """ make the drone execute thetamixed ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_thetamixed" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_THETA_MIXED # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_turnarround # --------------------------------------------------------------------------------------------- def event_turnarround ( self ): """ make the drone turnarround. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_turnarround" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_TURNAROUND # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_yawdance # --------------------------------------------------------------------------------------------- def event_yawdance ( self ): """ make the drone execute yawdance YEAH ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_yawdance" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_YAW_DANCE # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_yawshake # --------------------------------------------------------------------------------------------- def event_yawshake ( self ): """ Make the drone execute yawshake YEAH ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_yawshake" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_YAW_SHAKE # total duration in seconds of the animation lf_secs = 2000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::get_image # --------------------------------------------------------------------------------------------- def get_image ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::get_image" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) _im = np.copy ( self.image ) # sherlock logger # l_log.debug ( "<<" ) return _im # --------------------------------------------------------------------------------------------- # ARDrone::get_navdata # --------------------------------------------------------------------------------------------- def get_navdata ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::get_navdata" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( "><" ) return self.navdata # --------------------------------------------------------------------------------------------- # ARDrone::halt # --------------------------------------------------------------------------------------------- def halt ( self ): """ shutdown the drone. does not land or halt the actual drone, but the communication with the drone. Should call it at the end of application to close all sockets, pipes, processes and threads related with this object. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::halt" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.lock.acquire () self.com_watchdog_timer.cancel () self.com_pipe.send ( "die!" ) self.network_process.terminate () # 2.0 ? self.network_process.join () self.ipc_thread.stop () # 2.0 ? self.ipc_thread.join () # 2.0 ? self.lock.release () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::hover # --------------------------------------------------------------------------------------------- def hover ( self ): """ make the drone hover. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::hover" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, False, 0, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::land # --------------------------------------------------------------------------------------------- def land ( self ): """ make the drone land. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::land" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ref, False ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move # --------------------------------------------------------------------------------------------- def move ( self, ff_lr, ff_fb, ff_vv, ff_va ): """ makes the drone move (translate/rotate). @param lr : left-right tilt: float [-1..1] negative: left / positive: right @param rb : front-back tilt: float [-1..1] negative: forwards / positive: backwards @param vv : vertical speed: float [-1..1] negative: go down / positive: rise @param va : angular speed: float [-1..1] negative: spin left / positive: spin right """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # validate inputs # assert ( 1. >= ff_lr >= -1. ) # assert ( 1. >= ff_fb >= -1. ) # assert ( 1. >= ff_vv >= -1. ) # assert ( 1. >= ff_va >= -1. ) # move drone self.at ( arATCmds.at_pcmd, True, float ( ff_lr ), float ( ff_fb ), float ( ff_vv ), float ( ff_va )) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_backward # --------------------------------------------------------------------------------------------- def move_backward ( self ): """ make the drone move backwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_backward" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, self.speed, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_down # --------------------------------------------------------------------------------------------- def move_down ( self ): """ make the drone decent downwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_down" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, -self.speed, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_forward # --------------------------------------------------------------------------------------------- def move_forward ( self ): """ make the drone move forward. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_forward" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, -self.speed, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_left # --------------------------------------------------------------------------------------------- def move_left ( self ): """ make the drone move left. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_left" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, -self.speed, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_right # --------------------------------------------------------------------------------------------- def move_right ( self ): """ make the drone move right. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_right" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, self.speed, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_up # --------------------------------------------------------------------------------------------- def move_up ( self ): """ make the drone rise upwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_up" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, self.speed, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::reset # --------------------------------------------------------------------------------------------- def reset ( self ): """ toggle the drone's emergency state. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::reset" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ftrim ) time.sleep ( 0.1 ) self.at ( arATCmds.at_ref, False, True ) time.sleep ( 0.1 ) self.at ( arATCmds.at_ref, False, False ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_image # --------------------------------------------------------------------------------------------- def set_image ( self, fo_image ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_image" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) if ( f_image.shape == self.image_shape ): self.image = fo_image self.image = fo_image # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_navdata # --------------------------------------------------------------------------------------------- def set_navdata ( self, fo_navdata ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_navdata" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.navdata = fo_navdata # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_speed # --------------------------------------------------------------------------------------------- def set_speed ( self, ff_speed ): """ set the drone's speed. valid values are floats from [0..1] """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_speed" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # validate input # assert ( 1. >= ff_speed >= 0. ) # set speed self.speed = float ( ff_speed ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::takeoff # --------------------------------------------------------------------------------------------- def takeoff ( self ): """ make the drone takeoff. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::takeoff" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # calibrate drone self.at ( arATCmds.at_ftrim ) # set maximum altitude self.at ( arATCmds.at_config, "control:altitude_max", "20000" ) # take-off self.at ( arATCmds.at_ref, True ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::trim # --------------------------------------------------------------------------------------------- def trim ( self ): """ flat trim the drone. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::trim" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ftrim ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::turn_left # --------------------------------------------------------------------------------------------- def turn_left ( self ): """ make the drone rotate left. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::turn_left" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, 0, -self.speed ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::turn_right # --------------------------------------------------------------------------------------------- def turn_right ( self ): """ make the drone rotate right. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::turn_right" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, 0, self.speed ) # sherlock logger # l_log.debug ( "<<" ) # < class ARDrone2 >------------------------------------------------------------------------------- class ARDrone2 ( ARDrone ): """ ARDrone2 class instanciate this class to control your drone and receive decoded video and navdata. """ # --------------------------------------------------------------------------------------------- # ARDrone2::__init__ # --------------------------------------------------------------------------------------------- def __init__ ( self, is_ar_drone_2 = True, hd = False ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::__init__" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # init super class ARDrone.__init__ ( self ) self.seq_nr = 1 self.timer_t = 0.2 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.lock = threading.Lock () self.speed = 0.2 self.image_shape = ( 720, 1080, 1 ) time.sleep ( 0.2 ) self.config_ids_string = [ arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID ] self.configure_multisession ( arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID, self.config_ids_string ) self.set_session_id ( self.config_ids_string, arDefs.SESSION_ID ) time.sleep ( 0.2 ) self.set_profile_id ( self.config_ids_string, arDefs.USER_ID ) time.sleep ( 0.2 ) self.set_app_id ( self.config_ids_string, arDefs.APP_ID ) time.sleep ( 0.2 ) self.set_video_bitrate_control_mode ( self.config_ids_string, "1" ) time.sleep ( 0.2 ) self.set_video_bitrate ( self.config_ids_string, "500" ) time.sleep ( 0.2 ) self.set_max_bitrate ( self.config_ids_string, "500" ) time.sleep ( 0.2 ) self.set_fps ( self.config_ids_string, "30" ) time.sleep ( 0.2 ) self.set_video_codec ( self.config_ids_string, 0x80 ) self.last_command_is_hovering = True self.com_pipe, com_pipe_other = multiprocessing.Pipe () self.navdata = {} self.navdata [ 0 ] = { "ctrl_state":0, "battery":0, "theta":0, "phi":0, "psi":0, "altitude":0, "vx":0, "vy":0, "vz":0, "num_frames":0 } self.network_process = arNetwork.ARDrone2NetworkProcess ( com_pipe_other, is_ar_drone_2, self ) self.network_process.start () self.image = np.zeros ( self.image_shape, np.uint8 ) self.time = 0 self.last_command_is_hovering = True time.sleep ( 1.0 ) self.at ( arATCmds.at_config_ids, self.config_ids_string ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::configure_multisession # --------------------------------------------------------------------------------------------- def configure_multisession ( self, f_session_id, f_user_id, f_app_id, f_config_ids_string ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::configure_multisession" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config, "custom:session_id", f_session_id ) self.at ( arATCmds.at_config, "custom:profile_id", f_user_id ) self.at ( arATCmds.at_config, "custom:application_id", f_app_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_app_id # --------------------------------------------------------------------------------------------- def set_app_id ( self, f_config_ids_string, f_app_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_app_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:application_id", f_app_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_fps # --------------------------------------------------------------------------------------------- def set_fps ( self, f_config_ids_string, f_fps ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_fps" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:codec_fps", f_fps ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_max_bitrate # --------------------------------------------------------------------------------------------- def set_max_bitrate ( self, f_config_ids_string, f_max_bitrate ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_max_bitrate" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:max_bitrate", f_max_bitrate ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_profile_id # --------------------------------------------------------------------------------------------- def set_profile_id ( self, f_config_ids_string, f_profile_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_profile_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:profile_id", f_profile_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_session_id # --------------------------------------------------------------------------------------------- def set_session_id ( self, f_config_ids_string, f_session_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_session_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:session_id", f_session_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_bitrate # --------------------------------------------------------------------------------------------- def set_video_bitrate ( self, f_config_ids_string, f_bitrate ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_bitrate" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:bitrate", f_bitrate ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_bitrate_control_mode # --------------------------------------------------------------------------------------------- def set_video_bitrate_control_mode ( self, f_config_ids_string, f_mode ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_bitrate_control_mode" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:bitrate_control_mode", f_mode ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_codec # --------------------------------------------------------------------------------------------- def set_video_codec ( self, f_config_ids_string, f_codec ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_codec" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:video_codec", f_codec ) # sherlock logger # l_log.debug ( "<<" ) # ------------------------------------------------------------------------------------------------- # the bootstrap process # ------------------------------------------------------------------------------------------------- if ( "__main__" == __name__ ): import termios import fcntl import os l_fd = sys.stdin.fileno () l_old_term = termios.tcgetattr ( l_fd ) l_new_attr = termios.tcgetattr ( l_fd ) l_new_attr [ 3 ] = l_new_attr [ 3 ] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr ( l_fd, termios.TCSANOW, l_new_attr ) l_old_flags = fcntl.fcntl ( l_fd, fcntl.F_GETFL ) fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags | os.O_NONBLOCK ) lo_drone = ARDrone () # assert ( lo_drone ) try: while ( True ): try: lc_c = sys.stdin.read ( 1 ) lc_c = lc_c.lower () print "Got character", lc_c # left ? if ( 'a' == lc_c ): lo_drone.move_left () # right ?<|fim▁hole|> # forward ? elif ( 'w' == lc_c ): lo_drone.move_forward () # backward ? elif ( 's' == lc_c ): lo_drone.move_backward () # land ? elif ( ' ' == lc_c ): lo_drone.land () # takeoff ? elif ( '\n' == lc_c ): lo_drone.takeoff () # turn left ? elif ( 'q' == lc_c ): lo_drone.turn_left () # turn right ? elif ( 'e' == lc_c ): lo_drone.turn_right () # move up ? elif ( '1' == lc_c ): lo_drone.move_up () # hover ? elif ( '2' == lc_c ): lo_drone.hover () # move down ? elif ( '3' == lc_c ): lo_drone.move_down () # reset ? elif ( 't' == lc_c ): lo_drone.reset () # hover ? elif ( 'x' == lc_c ): lo_drone.hover () # trim ? elif ( 'y' == lc_c ): lo_drone.trim () except IOError: pass finally: termios.tcsetattr ( l_fd, termios.TCSAFLUSH, l_old_term ) fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags ) lo_drone.halt () # < the end >-------------------------------------------------------------------------------------- #<|fim▁end|>
elif ( 'd' == lc_c ): lo_drone.move_right ()
<|file_name|>TPlus.java<|end_file_name|><|fim▁begin|>/* This file was generated by SableCC (http://www.sablecc.org/). */ package com.bju.cps450.node; import com.bju.cps450.analysis.*; @SuppressWarnings("nls") public final class TPlus extends Token { public TPlus() { super.setText("+"); }<|fim▁hole|> public TPlus(int line, int pos) { super.setText("+"); setLine(line); setPos(pos); } @Override public Object clone() { return new TPlus(getLine(), getPos()); } @Override public void apply(Switch sw) { ((Analysis) sw).caseTPlus(this); } @Override public void setText(@SuppressWarnings("unused") String text) { throw new RuntimeException("Cannot change TPlus text."); } }<|fim▁end|>
<|file_name|>0047_add_system_stats.py<|end_file_name|><|fim▁begin|># encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'SystemStats' db.create_table('core_systemstats', ( ('date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)), ('revision', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)), ('stats', self.gf('pykeg.core.jsonfield.JSONField')(default='{}')), ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('site', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['core.KegbotSite'])), )) db.send_create_signal('core', ['SystemStats']) def backwards(self, orm): # Deleting model 'SystemStats' db.delete_table('core_systemstats') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'beerdb.beerimage': { 'Meta': {'object_name': 'BeerImage'}, 'added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'edited': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '36', 'primary_key': 'True'}), 'num_views': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'original_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'revision': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'beerdb.beerstyle': { 'Meta': {'object_name': 'BeerStyle'}, 'added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'edited': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '36', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'revision': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'beerdb.beertype': { 'Meta': {'object_name': 'BeerType'}, 'abv': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'brewer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['beerdb.Brewer']"}), 'calories_oz': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'carbs_oz': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'edited': ('django.db.models.fields.DateTimeField', [], {}), 'edition': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '36', 'primary_key': 'True'}), 'image': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'beers'", 'null': 'True', 'to': "orm['beerdb.BeerImage']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'original_gravity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'revision': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'specific_gravity': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'style': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['beerdb.BeerStyle']"}) }, 'beerdb.brewer': { 'Meta': {'object_name': 'Brewer'}, 'added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'country': ('pykeg.core.fields.CountryField', [], {'default': "'USA'", 'max_length': '3'}), 'description': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True', 'blank': 'True'}), 'edited': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '36', 'primary_key': 'True'}), 'image': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'brewers'", 'null': 'True', 'to': "orm['beerdb.BeerImage']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'origin_city': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128', 'null': 'True', 'blank': 'True'}), 'origin_state': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128', 'null': 'True', 'blank': 'True'}), 'production': ('django.db.models.fields.CharField', [], {'default': "'commercial'", 'max_length': '128'}), 'revision': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'core.authenticationtoken': { 'Meta': {'unique_together': "(('site', 'seqn', 'auth_device', 'token_value'),)", 'object_name': 'AuthenticationToken'}, 'auth_device': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'pin': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tokens'", 'to': "orm['core.KegbotSite']"}), 'token_value': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'core.bac': { 'Meta': {'object_name': 'BAC'}, 'bac': ('django.db.models.fields.FloatField', [], {}), 'drink': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Drink']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'rectime': ('django.db.models.fields.DateTimeField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'core.config': { 'Meta': {'object_name': 'Config'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'configs'", 'to': "orm['core.KegbotSite']"}), 'value': ('django.db.models.fields.TextField', [], {}) }, 'core.drink': { 'Meta': {'unique_together': "(('site', 'seqn'),)", 'object_name': 'Drink'}, 'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'duration': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'endtime': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keg': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'drinks'", 'null': 'True', 'to': "orm['core.Keg']"}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'drinks'", 'null': 'True', 'to': "orm['core.DrinkingSession']"}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'drinks'", 'to': "orm['core.KegbotSite']"}), 'starttime': ('django.db.models.fields.DateTimeField', [], {}), 'status': ('django.db.models.fields.CharField', [], {'default': "'valid'", 'max_length': '128'}), 'ticks': ('django.db.models.fields.PositiveIntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'drinks'", 'null': 'True', 'to': "orm['auth.User']"}), 'volume_ml': ('django.db.models.fields.FloatField', [], {}) }, 'core.drinkingsession': { 'Meta': {'unique_together': "(('site', 'seqn'),)", 'object_name': 'DrinkingSession'}, 'endtime': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sessions'", 'to': "orm['core.KegbotSite']"}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'blank': 'True', 'null': 'True', 'populate_from': 'None', 'db_index': 'True'}), 'starttime': ('django.db.models.fields.DateTimeField', [], {}), 'volume_ml': ('django.db.models.fields.FloatField', [], {'default': '0'}) }, 'core.keg': { 'Meta': {'unique_together': "(('site', 'seqn'),)", 'object_name': 'Keg'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'enddate': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'origcost': ('django.db.models.fields.FloatField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'kegs'", 'to': "orm['core.KegbotSite']"}), 'size': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.KegSize']"}), 'startdate': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['beerdb.BeerType']"}) }, 'core.kegbotsite': { 'Meta': {'object_name': 'KegbotSite'}, 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}) }, 'core.kegsessionchunk': { 'Meta': {'unique_together': "(('session', 'keg'),)", 'object_name': 'KegSessionChunk'}, 'endtime': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keg': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'keg_session_chunks'", 'null': 'True', 'to': "orm['core.Keg']"}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'keg_chunks'", 'to': "orm['core.DrinkingSession']"}), 'starttime': ('django.db.models.fields.DateTimeField', [], {}), 'volume_ml': ('django.db.models.fields.FloatField', [], {'default': '0'}) }, 'core.kegsize': { 'Meta': {'object_name': 'KegSize'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'volume_ml': ('django.db.models.fields.FloatField', [], {}) }, 'core.kegstats': { 'Meta': {'object_name': 'KegStats'},<|fim▁hole|> 'keg': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stats'", 'unique': 'True', 'to': "orm['core.Keg']"}), 'revision': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.KegbotSite']"}), 'stats': ('pykeg.core.jsonfield.JSONField', [], {'default': "'{}'"}) }, 'core.kegtap': { 'Meta': {'object_name': 'KegTap'}, 'current_keg': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Keg']", 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'max_tick_delta': ('django.db.models.fields.PositiveIntegerField', [], {'default': '100'}), 'meter_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'ml_per_tick': ('django.db.models.fields.FloatField', [], {'default': '0.45454545454545453'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.KegbotSite']"}), 'temperature_sensor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.ThermoSensor']", 'null': 'True', 'blank': 'True'}) }, 'core.relaylog': { 'Meta': {'unique_together': "(('site', 'seqn'),)", 'object_name': 'RelayLog'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'relaylogs'", 'to': "orm['core.KegbotSite']"}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'time': ('django.db.models.fields.DateTimeField', [], {}) }, 'core.sessionchunk': { 'Meta': {'unique_together': "(('session', 'user', 'keg'),)", 'object_name': 'SessionChunk'}, 'endtime': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keg': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'session_chunks'", 'null': 'True', 'to': "orm['core.Keg']"}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'chunks'", 'to': "orm['core.DrinkingSession']"}), 'starttime': ('django.db.models.fields.DateTimeField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'session_chunks'", 'null': 'True', 'to': "orm['auth.User']"}), 'volume_ml': ('django.db.models.fields.FloatField', [], {'default': '0'}) }, 'core.sessionstats': { 'Meta': {'object_name': 'SessionStats'}, 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'revision': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stats'", 'unique': 'True', 'to': "orm['core.DrinkingSession']"}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.KegbotSite']"}), 'stats': ('pykeg.core.jsonfield.JSONField', [], {'default': "'{}'"}) }, 'core.systemevent': { 'Meta': {'object_name': 'SystemEvent'}, 'drink': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'to': "orm['core.Drink']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keg': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'to': "orm['core.Keg']"}), 'kind': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'to': "orm['core.DrinkingSession']"}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.KegbotSite']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'to': "orm['auth.User']"}), 'when': ('django.db.models.fields.DateTimeField', [], {}) }, 'core.systemstats': { 'Meta': {'object_name': 'SystemStats'}, 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'revision': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.KegbotSite']"}), 'stats': ('pykeg.core.jsonfield.JSONField', [], {'default': "'{}'"}) }, 'core.thermolog': { 'Meta': {'unique_together': "(('site', 'seqn'),)", 'object_name': 'Thermolog'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'sensor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.ThermoSensor']"}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'thermologs'", 'to': "orm['core.KegbotSite']"}), 'temp': ('django.db.models.fields.FloatField', [], {}), 'time': ('django.db.models.fields.DateTimeField', [], {}) }, 'core.thermosensor': { 'Meta': {'unique_together': "(('site', 'seqn'),)", 'object_name': 'ThermoSensor'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nice_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'raw_name': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'thermosensors'", 'to': "orm['core.KegbotSite']"}) }, 'core.thermosummarylog': { 'Meta': {'unique_together': "(('site', 'seqn'),)", 'object_name': 'ThermoSummaryLog'}, 'date': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'max_temp': ('django.db.models.fields.FloatField', [], {}), 'mean_temp': ('django.db.models.fields.FloatField', [], {}), 'min_temp': ('django.db.models.fields.FloatField', [], {}), 'num_readings': ('django.db.models.fields.PositiveIntegerField', [], {}), 'period': ('django.db.models.fields.CharField', [], {'default': "'daily'", 'max_length': '64'}), 'sensor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.ThermoSensor']"}), 'seqn': ('django.db.models.fields.PositiveIntegerField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'thermosummarylogs'", 'to': "orm['core.KegbotSite']"}) }, 'core.userpicture': { 'Meta': {'object_name': 'UserPicture'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'core.userprofile': { 'Meta': {'object_name': 'UserProfile'}, 'gender': ('django.db.models.fields.CharField', [], {'max_length': '8'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mugshot': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.UserPicture']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}), 'weight': ('django.db.models.fields.FloatField', [], {}) }, 'core.usersessionchunk': { 'Meta': {'unique_together': "(('session', 'user'),)", 'object_name': 'UserSessionChunk'}, 'endtime': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_chunks'", 'to': "orm['core.DrinkingSession']"}), 'starttime': ('django.db.models.fields.DateTimeField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_session_chunks'", 'null': 'True', 'to': "orm['auth.User']"}), 'volume_ml': ('django.db.models.fields.FloatField', [], {'default': '0'}) }, 'core.userstats': { 'Meta': {'object_name': 'UserStats'}, 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'revision': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.KegbotSite']"}), 'stats': ('pykeg.core.jsonfield.JSONField', [], {'default': "'{}'"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stats'", 'unique': 'True', 'to': "orm['auth.User']"}) } } complete_apps = ['core']<|fim▁end|>
'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
<|file_name|>plot2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 from glob import glob import re import matplotlib.pyplot as plt import numpy as np from sys import argv def get_a1(pattern): a1 = {} for fit_file in glob(pattern): with open(fit_file) as f: line = f.readline() coeffs = line.split(' ')<|fim▁hole|> if fit_params[0] not in a1: a1[fit_params[0]] = [] a1[fit_params[0]].append((float(fit_params[1]), float(coeffs[1]))) # Sort and remove the soring hints for key in a1.keys(): a1[key] = sorted(a1[key], key=lambda x: x[0]) a1[key] = dict(y=map(lambda x: float(x[1]), a1[key]), x=map(lambda x: float(x[0]), a1[key])) return a1 def plot_a1(): a1 = get_a1(argv[1]) fig, ax = plt.subplots() for domain in sorted(a1.keys(), key=lambda x: float(x)): ax.plot(a1[domain]['x'], a1[domain]['y'], label='%s pi' % (domain)) ax.legend(loc=0) fig.savefig('a1.png', dpi=300) plt.show() if __name__ == '__main__': plot_a1()<|fim▁end|>
fit_params = fit_file.split('-')
<|file_name|>environment.js<|end_file_name|><|fim▁begin|>const { environment } = require('@rails/webpacker') const webpack = require('webpack') // excluding node_modules from being transpiled by babel-loader.<|fim▁hole|> new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: "jquery", Popper: ['popper.js', 'default'] })) // const aliasConfig = { // 'jquery': 'jquery-ui-dist/external/jquery/jquery.js', // 'jquery-ui': 'jquery-ui-dist/jquery-ui.js' // }; // environment.config.set('resolve.alias', aliasConfig); // resolve-url-loader must be used before sass-loader // https://github.com/rails/webpacker/blob/master/docs/css.md#resolve-url-loader environment.loaders.get("sass").use.splice(-1, 0, { loader: "resolve-url-loader" }); module.exports = environment<|fim▁end|>
environment.loaders.delete("nodeModules"); environment.plugins.prepend('Provide',
<|file_name|>pyunit_binop2_plus.py<|end_file_name|><|fim▁begin|>import sys sys.path.insert(1, "../../../") import h2o def binop_plus(ip,port): # Connect to h2o h2o.init(ip,port) iris = h2o.import_frame(path=h2o.locate("smalldata/iris/iris_wheader_65_rows.csv")) rows, cols = iris.dim() iris.show() ################################################################### # LHS: scaler, RHS: H2OFrame res = 2 + iris res_rows, res_cols = res.dim() assert res_rows == rows and res_cols == cols, "dimension mismatch" for x, y in zip([res[c].sum() for c in range(cols-1)], [469.9, 342.6, 266.9, 162.2]): assert abs(x - y) < 1e-1, "expected same values" # LHS: scaler, RHS: scaler res = 2 + iris[0] res2 = 1.1 + res[21,:] assert abs(res2 - 8.2) < 1e-1, "expected same values" ################################################################### # LHS: scaler, RHS: H2OFrame res = 1.2 + iris[2] res2 = res[21,:] + iris res2.show() # LHS: scaler, RHS: H2OVec res = 1.2 + iris[2] res2 = res[21,:] + iris[1] res2.show() # LHS: scaler, RHS: scaler res = 1.1 + iris[2] res2 = res[21,:] + res[10,:] assert abs(res2 - 5.2) < 1e-1, "expected same values" # LHS: scaler, RHS: scaler res = 2 + iris[0] res2 = res[21,:] + 3 assert abs(res2 - 10.1) < 1e-1, "expected same values" ################################################################### # LHS: H2OVec, RHS: H2OFrame #try: # res = iris[2] + iris # res.show() # assert False, "expected error. objects with different dimensions not supported." #except EnvironmentError: # pass # LHS: H2OVec, RHS: scaler<|fim▁hole|> ################################################################### # LHS: H2OFrame, RHS: H2OFrame res = iris + iris res_rows, res_cols = res.dim() assert res_rows == rows and res_cols == cols, "dimension mismatch" res = iris[0:2] + iris[1:3] res_rows, res_cols = res.dim() assert res_rows == rows and res_cols == 2, "dimension mismatch" #try: # res = iris + iris[0:3] # res.show() # assert False, "expected error. frames are different dimensions." #except EnvironmentError: # pass # LHS: H2OFrame, RHS: H2OVec #try: # res = iris + iris[0] # res.show() # assert False, "expected error. objects of different dimensions not supported." #except EnvironmentError: # pass # LHS: H2OFrame, RHS: scaler res = 1.2 + iris[2] res2 = iris + res[21,:] res2.show() # LHS: H2OFrame, RHS: scaler res = iris + 2 res_rows, res_cols = res.dim() assert res_rows == rows and res_cols == cols, "dimension mismatch" for x, y in zip([res[c].sum() for c in range(cols-1)], [469.9, 342.6, 266.9, 162.2]): assert abs(x - y) < 1e-1, "expected same values" ################################################################### if __name__ == "__main__": h2o.run_test(sys.argv, binop_plus)<|fim▁end|>
res = 1.2 + iris[2] res2 = iris[1] + res[21,:] res2.show()
<|file_name|>crateC.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. <|fim▁hole|>// causing a type mismatch. // The test is nearly the same as the one in // compile-fail/type-mismatch-same-crate-name.rs // but deals with the case where one of the crates // is only introduced as an indirect dependency. // and the type is accessed via a re-export. // This is similar to how the error can be introduced // when using cargo's automatic dependency resolution. extern crate crateA; fn main() { let foo2 = crateA::Foo; let bar2 = crateA::bar(); { extern crate crateB; crateB::try_foo(foo2); crateB::try_bar(bar2); } }<|fim▁end|>
// This tests the extra note reported when a type error deals with // seemingly identical types. // The main use case of this error is when there are two crates // (generally different versions of the same crate) with the same name
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin<|fim▁hole|> admin.site.register(Comment)<|fim▁end|>
from comments.models import Comment # Register your models here.
<|file_name|>calculator.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import sys import logging from warnings import warn import six from scss.ast import Literal from scss.cssdefs import _expr_glob_re, _interpolate_re from scss.errors import SassError, SassEvaluationError, SassParseError from scss.grammar.expression import SassExpression, SassExpressionScanner from scss.rule import Namespace from scss.types import String from scss.types import Value from scss.util import dequote log = logging.getLogger(__name__) class Calculator(object): """Expression evaluator.""" ast_cache = {} def __init__( self, namespace=None, ignore_parse_errors=False, undefined_variables_fatal=True, ): if namespace is None: self.namespace = Namespace() else: self.namespace = namespace self.ignore_parse_errors = ignore_parse_errors self.undefined_variables_fatal = undefined_variables_fatal def _pound_substitute(self, result): expr = result.group(1) value = self.evaluate_expression(expr) if value is None: return self.apply_vars(expr) elif value.is_null: return "" else: return dequote(value.render()) def do_glob_math(self, cont): """Performs #{}-interpolation. The result is always treated as a fixed syntactic unit and will not be re-evaluated. """ # TODO that's a lie! this should be in the parser for most cases. if not isinstance(cont, six.string_types): warn(FutureWarning( "do_glob_math was passed a non-string {0!r} " "-- this will no longer be supported in pyScss 2.0" .format(cont) )) cont = six.text_type(cont) if '#{' not in cont: return cont cont = _expr_glob_re.sub(self._pound_substitute, cont) return cont def apply_vars(self, cont): # TODO this is very complicated. it should go away once everything # valid is actually parseable. if isinstance(cont, six.string_types) and '$' in cont: try: # Optimization: the full cont is a variable in the context, cont = self.namespace.variable(cont) except KeyError: # Interpolate variables: def _av(m): v = None n = m.group(2) try: v = self.namespace.variable(n) except KeyError: if self.undefined_variables_fatal: raise SyntaxError("Undefined variable: '%s'." % n) else: log.error("Undefined variable '%s'", n, extra={'stack': True}) return n else:<|fim▁hole|> "with a non-Sass value: {1!r}" .format(n, v) ) v = v.render() # TODO this used to test for _dequote if m.group(1): v = dequote(v) else: v = m.group(0) return v cont = _interpolate_re.sub(_av, cont) else: # Variable succeeded, so we need to render it cont = cont.render() # TODO this is surprising and shouldn't be here cont = self.do_glob_math(cont) return cont def calculate(self, expression, divide=False): result = self.evaluate_expression(expression, divide=divide) if result is None: return String.unquoted(self.apply_vars(expression)) return result # TODO only used by magic-import...? def interpolate(self, var): value = self.namespace.variable(var) if var != value and isinstance(value, six.string_types): _vi = self.evaluate_expression(value) if _vi is not None: value = _vi return value def evaluate_expression(self, expr, divide=False): try: ast = self.parse_expression(expr) except SassError as e: if self.ignore_parse_errors: return None raise try: return ast.evaluate(self, divide=divide) except Exception as e: six.reraise(SassEvaluationError, SassEvaluationError(e, expression=expr), sys.exc_info()[2]) def parse_expression(self, expr, target='goal'): if isinstance(expr, six.text_type): # OK pass elif isinstance(expr, six.binary_type): # Dubious warn(FutureWarning( "parse_expression was passed binary data {0!r} " "-- this will no longer be supported in pyScss 2.0" .format(expr) )) # Don't guess an encoding; you reap what you sow expr = six.text_type(expr) else: raise TypeError("Expected string, got %r" % (expr,)) key = (target, expr) if key in self.ast_cache: return self.ast_cache[key] try: parser = SassExpression(SassExpressionScanner(expr)) ast = getattr(parser, target)() except SyntaxError as e: raise SassParseError(e, expression=expr, expression_pos=parser._char_pos) self.ast_cache[key] = ast return ast def parse_interpolations(self, string): """Parse a string for interpolations, but don't treat anything else as Sass syntax. Returns an AST node. """ # Shortcut: if there are no #s in the string in the first place, it # must not have any interpolations, right? if '#' not in string: return Literal(String.unquoted(string)) return self.parse_expression(string, 'goal_interpolated_literal') def parse_vars_and_interpolations(self, string): """Parse a string for variables and interpolations, but don't treat anything else as Sass syntax. Returns an AST node. """ # Shortcut: if there are no #s or $s in the string in the first place, # it must not have anything of interest. if '#' not in string and '$' not in string: return Literal(String.unquoted(string)) return self.parse_expression( string, 'goal_interpolated_literal_with_vars') __all__ = ('Calculator',)<|fim▁end|>
if v: if not isinstance(v, Value): raise TypeError( "Somehow got a variable {0!r} "
<|file_name|>sns.py<|end_file_name|><|fim▁begin|># Copyright 2016 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from c7n.filters import CrossAccountAccessFilter from c7n.manager import resources from c7n.query import QueryResourceManager from c7n.utils import local_session @resources.register('sns') class SNS(QueryResourceManager): resource_type = 'aws.sns.topic' def augment(self, resources): def _augment(r): client = local_session(self.session_factory).client('sns') attrs = client.get_topic_attributes( TopicArn=r['TopicArn'])['Attributes'] r.update(attrs) return r self.log.debug("retrieving details for %d topics" % len(resources)) with self.executor_factory(max_workers=4) as w: return list(w.map(_augment, resources)) <|fim▁hole|><|fim▁end|>
SNS.filter_registry.register('cross-account', CrossAccountAccessFilter)
<|file_name|>objimport.py<|end_file_name|><|fim▁begin|># # Copyright 2011-2019 Universidad Complutense de Madrid # # This file is part of Numina #<|fim▁hole|># """Import objects by name""" import importlib import inspect import warnings def import_object(path): """Import an object given its fully qualified name.""" spl = path.split('.') if len(spl) == 1: return importlib.import_module(path) # avoid last part for the moment cls = spl[-1] mods = '.'.join(spl[:-1]) mm = importlib.import_module(mods) # try to get the last part as an attribute try: obj = getattr(mm, cls) return obj except AttributeError: pass # Try to import the last part rr = importlib.import_module(path) return rr def fully_qualified_name(obj, sep='.'): warnings.warn( "use numina.util.fqn.fully_qualified_name instead", DeprecationWarning, stacklevel=2 ) import numina.util.fqn as fqn return fqn.fully_qualified_name(obj, sep)<|fim▁end|>
# SPDX-License-Identifier: GPL-3.0+ # License-Filename: LICENSE.txt
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod util; pub mod tools; pub mod uidmap;<|fim▁hole|><|fim▁end|>
pub mod mount; pub mod root; pub mod nsutil; pub mod vagga;
<|file_name|>corrplot.py<|end_file_name|><|fim▁begin|>import seaborn as sns import matplotlib.pyplot as plt <|fim▁hole|> size=None, figsize=(12, 9), *args, **kwargs): """ Plot correlation matrix of the dataset see doc at https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html#seaborn.heatmap """ sns.set(context="paper", font="monospace") f, ax = plt.subplots(figsize=figsize) sns.heatmap(df.corr(), vmax=1, square=square, linewidths=linewidths, annot=annot, annot_kws={"size": size}, *args, **kwargs)<|fim▁end|>
def plot_corrmatrix(df, square=True, linewidths=0.1, annot=True,
<|file_name|>scanner_test.go<|end_file_name|><|fim▁begin|>// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package biglog import ( "bytes" "fmt" "os" "sync" "testing" ) func TestScanner(t *testing.T) { var readers = 200 bl := tempBigLog() data := randDataSet(2398, 1024) for k := range data { n, err := bl.Write(data[k]) if err != nil { t.Error(err) } if n != len(data[k]) { t.Errorf("Wrote %d bytes. Expected %d", n, len(data[k])) } } var wg sync.WaitGroup for i := 0; i < readers; i++ { wg.Add(1) go func(data [][]byte, i int) { var offset = int64(i) // each reader starts one offset later sc, err := NewScanner(bl, offset) if err != nil { t.Error(err) } var prevActual []byte var prevOffset int64 var prevDelta int for k := i; k < len(data); k++ { <|fim▁hole|> if sc.Offset() != offset { t.Errorf("Bad offset Actual: %d\n Expected: %d\n Prev: %d \n", sc.Offset(), offset, prevOffset, ) os.Exit(1) } if !bytes.Equal(sc.Bytes(), data[k]) { fmt.Printf("%d => %s \n \n", k, data[k]) defer wg.Done() t.Errorf("fatal payload read i=%d k=%d offset=%d delta=%d error:\n"+ " Actual: % x\n Expected: % x\n Prev: % x \n prevOffset=%d prevDelta=%d \n", i, k, sc.Offset(), sc.ODelta(), sc.Bytes(), data[k], prevActual, prevOffset, prevDelta, ) os.Exit(1) } prevActual = sc.Bytes() prevOffset = sc.Offset() prevDelta = sc.ODelta() offset++ } wg.Done() }(data, i) } wg.Wait() err := bl.Delete(false) if err != ErrBusy { t.Error(err) } err = bl.Delete(true) if err != nil { t.Error(err) } }<|fim▁end|>
if !sc.Scan() { t.Errorf("Scanner finished before end of loop: i=%d k=%d\n", i, k) continue }
<|file_name|>cube.test.js<|end_file_name|><|fim▁begin|>// test cube var assert = require('assert'), math = require('../../../index'), error = require('../../../lib/error/index'), unit = math.unit, bignumber = math.bignumber, matrix = math.matrix, range = math.range, cube = math.cube; describe('cube', function() { it('should return the cube of a boolean', function () { assert.equal(cube(true), 1); assert.equal(cube(false), 0); }); it('should return the cube of null', function () { assert.equal(math.ceil(null), 0); }); it('should return the cube of a number', function() { assert.equal(cube(4), 64); assert.equal(cube(-2), -8); assert.equal(cube(0), 0); }); it('should return the cube of a big number', function() { assert.deepEqual(cube(bignumber(4)), bignumber(64)); assert.deepEqual(cube(bignumber(-2)), bignumber(-8)); assert.deepEqual(cube(bignumber(0)), bignumber(0)); }); it('should return the cube of a complex number', function() { assert.deepEqual(cube(math.complex('2i')), math.complex('-8i')); assert.deepEqual(cube(math.complex('2+3i')), math.complex('-46+9i')); assert.deepEqual(cube(math.complex('2')), math.complex('8')); }); it('should throw an error with strings', function() { assert.throws(function () {cube('text')});<|fim▁hole|> }); it('should throw an error if there\'s wrong number of args', function() { assert.throws(function () {cube()}, error.ArgumentsError); assert.throws(function () {cube(1, 2)}, error.ArgumentsError); }); it('should cube each element in a matrix, array or range', function() { // array, matrix, range // arrays are evaluated element wise assert.deepEqual(cube([2,3,4,5]), [8,27,64,125]); assert.deepEqual(cube(matrix([2,3,4,5])), matrix([8,27,64,125])); assert.deepEqual(cube(matrix([[1,2],[3,4]])), matrix([[1,8],[27,64]])); }); });<|fim▁end|>
}); it('should throw an error with units', function() { assert.throws(function () {cube(unit('5cm'))});
<|file_name|>main.js<|end_file_name|><|fim▁begin|>import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory } from 'react-router' import { mySyncHistoryWithStore, default as createStore } from './store/createStore' import AppContainer from './containers/AppContainer' import injectTapEventPlugin from 'react-tap-event-plugin'; // ======================================================== // Browser History Setup // ======================================================== const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }) // ======================================================== // Store and History Instantiation // ======================================================== // Create redux store and sync with react-router-redux. We have installed the<|fim▁hole|>const initialState = window.___INITIAL_STATE__ const store = createStore(initialState, browserHistory) const history = mySyncHistoryWithStore(browserHistory, store) // ======================================================== // Developer Tools Setup // ======================================================== if (__DEBUG__) { if (window.devToolsExtension) { window.devToolsExtension.open() } } // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = (routerKey = null) => { const routes = require('./routes/index').default(store) // TODO, uncomment this before production // injectTapEventPlugin() ReactDOM.render( <AppContainer store={store} history={history} routes={routes} routerKey={routerKey} />, MOUNT_NODE ) } // Enable HMR and catch runtime errors in RedBox // This code is excluded from production bundle if (__DEV__ && module.hot) { const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react') ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } render = () => { try { renderApp(Math.random()) } catch (error) { renderError(error) } } module.hot.accept(['./routes/index'], () => render()) } // ======================================================== // Go! // ======================================================== render()<|fim▁end|>
// react-router-redux reducer under the routerKey "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location.
<|file_name|>FactoredParser.java<|end_file_name|><|fim▁begin|>// StanfordLexicalizedParser -- a probabilistic lexicalized NL CFG parser // Copyright (c) 2002, 2003, 2004, 2005 The Board of Trustees of // The Leland Stanford Junior University. All Rights Reserved. // // This program 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 the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information, bug reports, fixes, contact: // Christopher Manning // Dept of Computer Science, Gates 1A // Stanford CA 94305-9010 // USA // [email protected] // http://nlp.stanford.edu/downloads/lex-parser.shtml package edu.stanford.nlp.parser.lexparser; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import edu.stanford.nlp.io.NumberRangeFileFilter; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.TaggedWord; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.parser.metrics.AbstractEval; import edu.stanford.nlp.parser.metrics.UnlabeledAttachmentEval; import edu.stanford.nlp.parser.metrics.Evalb; import edu.stanford.nlp.parser.metrics.TaggingEval; import edu.stanford.nlp.trees.LeftHeadFinder; import edu.stanford.nlp.trees.MemoryTreebank; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TreeLengthComparator; import edu.stanford.nlp.trees.TreeTransformer; import edu.stanford.nlp.trees.Treebank; import edu.stanford.nlp.trees.TreebankLanguagePack; import java.util.function.Function; import edu.stanford.nlp.util.Generics; import edu.stanford.nlp.util.HashIndex; import edu.stanford.nlp.util.Index; import edu.stanford.nlp.util.Pair; import edu.stanford.nlp.util.Timing; import edu.stanford.nlp.util.StringUtils; /** * @author Dan Klein (original version) * @author Christopher Manning (better features, ParserParams, serialization) * @author Roger Levy (internationalization) * @author Teg Grenager (grammar compaction, etc., tokenization, etc.) * @author Galen Andrew (lattice parsing) * @author Philip Resnik and Dan Zeman (n good parses) */ public class FactoredParser { /* some documentation for Roger's convenience * {pcfg,dep,combo}{PE,DE,TE} are precision/dep/tagging evals for the models * parser is the PCFG parser * dparser is the dependency parser * bparser is the combining parser * during testing: * tree is the test tree (gold tree) * binaryTree is the gold tree binarized * tree2b is the best PCFG paser, binarized * tree2 is the best PCFG parse (debinarized) * tree3 is the dependency parse, binarized * tree3db is the dependency parser, debinarized * tree4 is the best combo parse, binarized and then debinarized * tree4b is the best combo parse, binarized */ public static void main(String[] args) { Options op = new Options(new EnglishTreebankParserParams()); // op.tlpParams may be changed to something else later, so don't use it till // after options are parsed. System.out.println(StringUtils.toInvocationString("FactoredParser", args)); String path = "/u/nlp/stuff/corpora/Treebank3/parsed/mrg/wsj"; int trainLow = 200, trainHigh = 2199, testLow = 2200, testHigh = 2219; String serializeFile = null; int i = 0; while (i < args.length && args[i].startsWith("-")) { if (args[i].equalsIgnoreCase("-path") && (i + 1 < args.length)) { path = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-train") && (i + 2 < args.length)) { trainLow = Integer.parseInt(args[i + 1]); trainHigh = Integer.parseInt(args[i + 2]); i += 3; } else if (args[i].equalsIgnoreCase("-test") && (i + 2 < args.length)) { testLow = Integer.parseInt(args[i + 1]); testHigh = Integer.parseInt(args[i + 2]); i += 3; } else if (args[i].equalsIgnoreCase("-serialize") && (i + 1 < args.length)) { serializeFile = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-tLPP") && (i + 1 < args.length)) { try { op.tlpParams = (TreebankLangParserParams) Class.forName(args[i + 1]).newInstance(); } catch (ClassNotFoundException e) { System.err.println("Class not found: " + args[i + 1]); throw new RuntimeException(e); } catch (InstantiationException e) { System.err.println("Couldn't instantiate: " + args[i + 1] + ": " + e.toString()); throw new RuntimeException(e); } catch (IllegalAccessException e) { System.err.println("illegal access" + e); throw new RuntimeException(e); } i += 2; } else if (args[i].equals("-encoding")) { // sets encoding for TreebankLangParserParams op.tlpParams.setInputEncoding(args[i + 1]); op.tlpParams.setOutputEncoding(args[i + 1]);<|fim▁hole|> } // System.out.println(tlpParams.getClass()); TreebankLanguagePack tlp = op.tlpParams.treebankLanguagePack(); op.trainOptions.sisterSplitters = Generics.newHashSet(Arrays.asList(op.tlpParams.sisterSplitters())); // BinarizerFactory.TreeAnnotator.setTreebankLang(tlpParams); PrintWriter pw = op.tlpParams.pw(); op.testOptions.display(); op.trainOptions.display(); op.display(); op.tlpParams.display(); // setup tree transforms Treebank trainTreebank = op.tlpParams.memoryTreebank(); MemoryTreebank testTreebank = op.tlpParams.testMemoryTreebank(); // Treebank blippTreebank = ((EnglishTreebankParserParams) tlpParams).diskTreebank(); // String blippPath = "/afs/ir.stanford.edu/data/linguistic-data/BLLIP-WSJ/"; // blippTreebank.loadPath(blippPath, "", true); Timing.startTime(); System.err.print("Reading trees..."); testTreebank.loadPath(path, new NumberRangeFileFilter(testLow, testHigh, true)); if (op.testOptions.increasingLength) { Collections.sort(testTreebank, new TreeLengthComparator()); } trainTreebank.loadPath(path, new NumberRangeFileFilter(trainLow, trainHigh, true)); Timing.tick("done."); System.err.print("Binarizing trees..."); TreeAnnotatorAndBinarizer binarizer; if (!op.trainOptions.leftToRight) { binarizer = new TreeAnnotatorAndBinarizer(op.tlpParams, op.forceCNF, !op.trainOptions.outsideFactor(), true, op); } else { binarizer = new TreeAnnotatorAndBinarizer(op.tlpParams.headFinder(), new LeftHeadFinder(), op.tlpParams, op.forceCNF, !op.trainOptions.outsideFactor(), true, op); } CollinsPuncTransformer collinsPuncTransformer = null; if (op.trainOptions.collinsPunc) { collinsPuncTransformer = new CollinsPuncTransformer(tlp); } TreeTransformer debinarizer = new Debinarizer(op.forceCNF); List<Tree> binaryTrainTrees = new ArrayList<>(); if (op.trainOptions.selectiveSplit) { op.trainOptions.splitters = ParentAnnotationStats.getSplitCategories(trainTreebank, op.trainOptions.tagSelectiveSplit, 0, op.trainOptions.selectiveSplitCutOff, op.trainOptions.tagSelectiveSplitCutOff, op.tlpParams.treebankLanguagePack()); if (op.trainOptions.deleteSplitters != null) { List<String> deleted = new ArrayList<>(); for (String del : op.trainOptions.deleteSplitters) { String baseDel = tlp.basicCategory(del); boolean checkBasic = del.equals(baseDel); for (Iterator<String> it = op.trainOptions.splitters.iterator(); it.hasNext(); ) { String elem = it.next(); String baseElem = tlp.basicCategory(elem); boolean delStr = checkBasic && baseElem.equals(baseDel) || elem.equals(del); if (delStr) { it.remove(); deleted.add(elem); } } } System.err.println("Removed from vertical splitters: " + deleted); } } if (op.trainOptions.selectivePostSplit) { TreeTransformer myTransformer = new TreeAnnotator(op.tlpParams.headFinder(), op.tlpParams, op); Treebank annotatedTB = trainTreebank.transform(myTransformer); op.trainOptions.postSplitters = ParentAnnotationStats.getSplitCategories(annotatedTB, true, 0, op.trainOptions.selectivePostSplitCutOff, op.trainOptions.tagSelectivePostSplitCutOff, op.tlpParams.treebankLanguagePack()); } if (op.trainOptions.hSelSplit) { binarizer.setDoSelectiveSplit(false); for (Tree tree : trainTreebank) { if (op.trainOptions.collinsPunc) { tree = collinsPuncTransformer.transformTree(tree); } //tree.pennPrint(tlpParams.pw()); tree = binarizer.transformTree(tree); //binaryTrainTrees.add(tree); } binarizer.setDoSelectiveSplit(true); } for (Tree tree : trainTreebank) { if (op.trainOptions.collinsPunc) { tree = collinsPuncTransformer.transformTree(tree); } tree = binarizer.transformTree(tree); binaryTrainTrees.add(tree); } if (op.testOptions.verbose) { binarizer.dumpStats(); } List<Tree> binaryTestTrees = new ArrayList<>(); for (Tree tree : testTreebank) { if (op.trainOptions.collinsPunc) { tree = collinsPuncTransformer.transformTree(tree); } tree = binarizer.transformTree(tree); binaryTestTrees.add(tree); } Timing.tick("done."); // binarization BinaryGrammar bg = null; UnaryGrammar ug = null; DependencyGrammar dg = null; // DependencyGrammar dgBLIPP = null; Lexicon lex = null; Index<String> stateIndex = new HashIndex<>(); // extract grammars Extractor<Pair<UnaryGrammar,BinaryGrammar>> bgExtractor = new BinaryGrammarExtractor(op, stateIndex); //Extractor bgExtractor = new SmoothedBinaryGrammarExtractor();//new BinaryGrammarExtractor(); // Extractor lexExtractor = new LexiconExtractor(); //Extractor dgExtractor = new DependencyMemGrammarExtractor(); if (op.doPCFG) { System.err.print("Extracting PCFG..."); Pair<UnaryGrammar, BinaryGrammar> bgug = null; if (op.trainOptions.cheatPCFG) { List<Tree> allTrees = new ArrayList<>(binaryTrainTrees); allTrees.addAll(binaryTestTrees); bgug = bgExtractor.extract(allTrees); } else { bgug = bgExtractor.extract(binaryTrainTrees); } bg = bgug.second; bg.splitRules(); ug = bgug.first; ug.purgeRules(); Timing.tick("done."); } System.err.print("Extracting Lexicon..."); Index<String> wordIndex = new HashIndex<>(); Index<String> tagIndex = new HashIndex<>(); lex = op.tlpParams.lex(op, wordIndex, tagIndex); lex.initializeTraining(binaryTrainTrees.size()); lex.train(binaryTrainTrees); lex.finishTraining(); Timing.tick("done."); if (op.doDep) { System.err.print("Extracting Dependencies..."); binaryTrainTrees.clear(); Extractor<DependencyGrammar> dgExtractor = new MLEDependencyGrammarExtractor(op, wordIndex, tagIndex); // dgBLIPP = (DependencyGrammar) dgExtractor.extract(new ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new TransformTreeDependency(tlpParams,true)); // DependencyGrammar dg1 = dgExtractor.extract(trainTreebank.iterator(), new TransformTreeDependency(op.tlpParams, true)); //dgBLIPP=(DependencyGrammar)dgExtractor.extract(blippTreebank.iterator(),new TransformTreeDependency(tlpParams)); //dg = (DependencyGrammar) dgExtractor.extract(new ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new TransformTreeDependency(tlpParams)); // dg=new DependencyGrammarCombination(dg1,dgBLIPP,2); dg = dgExtractor.extract(binaryTrainTrees); //uses information whether the words are known or not, discards unknown words Timing.tick("done."); //System.out.print("Extracting Unknown Word Model..."); //UnknownWordModel uwm = (UnknownWordModel)uwmExtractor.extract(binaryTrainTrees); //Timing.tick("done."); System.out.print("Tuning Dependency Model..."); dg.tune(binaryTestTrees); //System.out.println("TUNE DEPS: "+tuneDeps); Timing.tick("done."); } BinaryGrammar boundBG = bg; UnaryGrammar boundUG = ug; GrammarProjection gp = new NullGrammarProjection(bg, ug); // serialization if (serializeFile != null) { System.err.print("Serializing parser..."); LexicalizedParser parser = new LexicalizedParser(lex, bg, ug, dg, stateIndex, wordIndex, tagIndex, op); parser.saveParserToSerialized(serializeFile); Timing.tick("done."); } // test: pcfg-parse and output ExhaustivePCFGParser parser = null; if (op.doPCFG) { parser = new ExhaustivePCFGParser(boundBG, boundUG, lex, op, stateIndex, wordIndex, tagIndex); } ExhaustiveDependencyParser dparser = ((op.doDep && ! op.testOptions.useFastFactored) ? new ExhaustiveDependencyParser(dg, lex, op, wordIndex, tagIndex) : null); Scorer scorer = (op.doPCFG ? new TwinScorer(new ProjectionScorer(parser, gp, op), dparser) : null); //Scorer scorer = parser; BiLexPCFGParser bparser = null; if (op.doPCFG && op.doDep) { bparser = (op.testOptions.useN5) ? new BiLexPCFGParser.N5BiLexPCFGParser(scorer, parser, dparser, bg, ug, dg, lex, op, gp, stateIndex, wordIndex, tagIndex) : new BiLexPCFGParser(scorer, parser, dparser, bg, ug, dg, lex, op, gp, stateIndex, wordIndex, tagIndex); } Evalb pcfgPE = new Evalb("pcfg PE", true); Evalb comboPE = new Evalb("combo PE", true); AbstractEval pcfgCB = new Evalb.CBEval("pcfg CB", true); AbstractEval pcfgTE = new TaggingEval("pcfg TE"); AbstractEval comboTE = new TaggingEval("combo TE"); AbstractEval pcfgTEnoPunct = new TaggingEval("pcfg nopunct TE"); AbstractEval comboTEnoPunct = new TaggingEval("combo nopunct TE"); AbstractEval depTE = new TaggingEval("depnd TE"); AbstractEval depDE = new UnlabeledAttachmentEval("depnd DE", true, null, tlp.punctuationWordRejectFilter()); AbstractEval comboDE = new UnlabeledAttachmentEval("combo DE", true, null, tlp.punctuationWordRejectFilter()); if (op.testOptions.evalb) { EvalbFormatWriter.initEVALBfiles(op.tlpParams); } // int[] countByLength = new int[op.testOptions.maxLength+1]; // Use a reflection ruse, so one can run this without needing the // tagger. Using a function rather than a MaxentTagger means we // can distribute a version of the parser that doesn't include the // entire tagger. Function<List<? extends HasWord>,ArrayList<TaggedWord>> tagger = null; if (op.testOptions.preTag) { try { Class[] argsClass = { String.class }; Object[] arguments = new Object[]{op.testOptions.taggerSerializedFile}; tagger = (Function<List<? extends HasWord>,ArrayList<TaggedWord>>) Class.forName("edu.stanford.nlp.tagger.maxent.MaxentTagger").getConstructor(argsClass).newInstance(arguments); } catch (Exception e) { System.err.println(e); System.err.println("Warning: No pretagging of sentences will be done."); } } for (int tNum = 0, ttSize = testTreebank.size(); tNum < ttSize; tNum++) { Tree tree = testTreebank.get(tNum); int testTreeLen = tree.yield().size(); if (testTreeLen > op.testOptions.maxLength) { continue; } Tree binaryTree = binaryTestTrees.get(tNum); // countByLength[testTreeLen]++; System.out.println("-------------------------------------"); System.out.println("Number: " + (tNum + 1)); System.out.println("Length: " + testTreeLen); //tree.pennPrint(pw); // System.out.println("XXXX The binary tree is"); // binaryTree.pennPrint(pw); //System.out.println("Here are the tags in the lexicon:"); //System.out.println(lex.showTags()); //System.out.println("Here's the tagnumberer:"); //System.out.println(Numberer.getGlobalNumberer("tags").toString()); long timeMil1 = System.currentTimeMillis(); Timing.tick("Starting parse."); if (op.doPCFG) { //System.err.println(op.testOptions.forceTags); if (op.testOptions.forceTags) { if (tagger != null) { //System.out.println("Using a tagger to set tags"); //System.out.println("Tagged sentence as: " + tagger.processSentence(cutLast(wordify(binaryTree.yield()))).toString(false)); parser.parse(addLast(tagger.apply(cutLast(wordify(binaryTree.yield()))))); } else { //System.out.println("Forcing tags to match input."); parser.parse(cleanTags(binaryTree.taggedYield(), tlp)); } } else { // System.out.println("XXXX Parsing " + binaryTree.yield()); parser.parse(binaryTree.yieldHasWord()); } //Timing.tick("Done with pcfg phase."); } if (op.doDep) { dparser.parse(binaryTree.yieldHasWord()); //Timing.tick("Done with dependency phase."); } boolean bothPassed = false; if (op.doPCFG && op.doDep) { bothPassed = bparser.parse(binaryTree.yieldHasWord()); //Timing.tick("Done with combination phase."); } long timeMil2 = System.currentTimeMillis(); long elapsed = timeMil2 - timeMil1; System.err.println("Time: " + ((int) (elapsed / 100)) / 10.00 + " sec."); //System.out.println("PCFG Best Parse:"); Tree tree2b = null; Tree tree2 = null; //System.out.println("Got full best parse..."); if (op.doPCFG) { tree2b = parser.getBestParse(); tree2 = debinarizer.transformTree(tree2b); } //System.out.println("Debinarized parse..."); //tree2.pennPrint(); //System.out.println("DepG Best Parse:"); Tree tree3 = null; Tree tree3db = null; if (op.doDep) { tree3 = dparser.getBestParse(); // was: but wrong Tree tree3db = debinarizer.transformTree(tree2); tree3db = debinarizer.transformTree(tree3); tree3.pennPrint(pw); } //tree.pennPrint(); //((Tree)binaryTrainTrees.get(tNum)).pennPrint(); //System.out.println("Combo Best Parse:"); Tree tree4 = null; if (op.doPCFG && op.doDep) { try { tree4 = bparser.getBestParse(); if (tree4 == null) { tree4 = tree2b; } } catch (NullPointerException e) { System.err.println("Blocked, using PCFG parse!"); tree4 = tree2b; } } if (op.doPCFG && !bothPassed) { tree4 = tree2b; } //tree4.pennPrint(); if (op.doDep) { depDE.evaluate(tree3, binaryTree, pw); depTE.evaluate(tree3db, tree, pw); } TreeTransformer tc = op.tlpParams.collinizer(); TreeTransformer tcEvalb = op.tlpParams.collinizerEvalb(); if (op.doPCFG) { // System.out.println("XXXX Best PCFG was: "); // tree2.pennPrint(); // System.out.println("XXXX Transformed best PCFG is: "); // tc.transformTree(tree2).pennPrint(); //System.out.println("True Best Parse:"); //tree.pennPrint(); //tc.transformTree(tree).pennPrint(); pcfgPE.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw); pcfgCB.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw); Tree tree4b = null; if (op.doDep) { comboDE.evaluate((bothPassed ? tree4 : tree3), binaryTree, pw); tree4b = tree4; tree4 = debinarizer.transformTree(tree4); if (op.nodePrune) { NodePruner np = new NodePruner(parser, debinarizer); tree4 = np.prune(tree4); } //tree4.pennPrint(); comboPE.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw); } //pcfgTE.evaluate(tree2, tree); pcfgTE.evaluate(tcEvalb.transformTree(tree2), tcEvalb.transformTree(tree), pw); pcfgTEnoPunct.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw); if (op.doDep) { comboTE.evaluate(tcEvalb.transformTree(tree4), tcEvalb.transformTree(tree), pw); comboTEnoPunct.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw); } System.out.println("PCFG only: " + parser.scoreBinarizedTree(tree2b, 0)); //tc.transformTree(tree2).pennPrint(); tree2.pennPrint(pw); if (op.doDep) { System.out.println("Combo: " + parser.scoreBinarizedTree(tree4b, 0)); // tc.transformTree(tree4).pennPrint(pw); tree4.pennPrint(pw); } System.out.println("Correct:" + parser.scoreBinarizedTree(binaryTree, 0)); /* if (parser.scoreBinarizedTree(tree2b,true) < parser.scoreBinarizedTree(binaryTree,true)) { System.out.println("SCORE INVERSION"); parser.validateBinarizedTree(binaryTree,0); } */ tree.pennPrint(pw); } // end if doPCFG if (op.testOptions.evalb) { if (op.doPCFG && op.doDep) { EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree4)); } else if (op.doPCFG) { EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree2)); } else if (op.doDep) { EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree3db)); } } } // end for each tree in test treebank if (op.testOptions.evalb) { EvalbFormatWriter.closeEVALBfiles(); } // op.testOptions.display(); if (op.doPCFG) { pcfgPE.display(false, pw); System.out.println("Grammar size: " + stateIndex.size()); pcfgCB.display(false, pw); if (op.doDep) { comboPE.display(false, pw); } pcfgTE.display(false, pw); pcfgTEnoPunct.display(false, pw); if (op.doDep) { comboTE.display(false, pw); comboTEnoPunct.display(false, pw); } } if (op.doDep) { depTE.display(false, pw); depDE.display(false, pw); } if (op.doPCFG && op.doDep) { comboDE.display(false, pw); } // pcfgPE.printGoodBad(); } private static List<TaggedWord> cleanTags(List<TaggedWord> twList, TreebankLanguagePack tlp) { int sz = twList.size(); List<TaggedWord> l = new ArrayList<>(sz); for (TaggedWord tw : twList) { TaggedWord tw2 = new TaggedWord(tw.word(), tlp.basicCategory(tw.tag())); l.add(tw2); } return l; } private static ArrayList<Word> wordify(List wList) { ArrayList<Word> s = new ArrayList<>(); for (Object obj : wList) { s.add(new Word(obj.toString())); } return s; } private static ArrayList<Word> cutLast(ArrayList<Word> s) { return new ArrayList<>(s.subList(0, s.size() - 1)); } private static ArrayList<Word> addLast(ArrayList<? extends Word> s) { ArrayList<Word> s2 = new ArrayList<>(s); //s2.add(new StringLabel(Lexicon.BOUNDARY)); s2.add(new Word(Lexicon.BOUNDARY)); return s2; } /** * Not an instantiable class */ private FactoredParser() { } }<|fim▁end|>
i += 2; } else { i = op.setOptionOrWarn(args, i); }
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>#import webdemo<|fim▁end|>
<|file_name|>plSDL.cpp<|end_file_name|><|fim▁begin|>/* This file is part of HSPlasma. * * HSPlasma 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. * * HSPlasma is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of<|fim▁hole|> * along with HSPlasma. If not, see <http://www.gnu.org/licenses/>. */ #include "plSDL.h" unsigned int plSDL::VariableLengthRead(hsStream* S, size_t size) { if (size < 0x100) return S->readByte(); else if (size < 0x10000) return S->readShort(); else return S->readInt(); } void plSDL::VariableLengthWrite(hsStream* S, size_t size, unsigned int value) { if (size < 0x100) S->writeByte(value); else if (size < 0x10000) S->writeShort(value); else S->writeInt(value); }<|fim▁end|>
* 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
<|file_name|>geo.py<|end_file_name|><|fim▁begin|>import re from blaze import resource, DataFrame import pandas as pd from snakemakelib.odo.pandas import annotate_by_uri <|fim▁hole|> with open(uri): data = pd.read_csv(uri, sep=",", index_col=["fileName"]) return DataFrame(data)<|fim▁end|>
@resource.register('.+fastq.summary') @annotate_by_uri def resource_fastqc_summary(uri, **kwargs):
<|file_name|>riordan_avoiding_patterns.py<|end_file_name|><|fim▁begin|>from sage.misc.functional import symbolic_sum from sage.calculus import var def from_pattern_family_10j_1(j, variable=var('t')): """ This function allow to build a pair of functions (d, h) to build a Riordan array for the pattern family (10)**j1, for a given j. """ def make_sum(from_index): return symbolic_sum(variable**i, i, from_index, j) i = var('i') d = make_sum(from_index=0)/sqrt( 1-2*make_sum(from_index=1)-3*make_sum(from_index=1)**2) h = (make_sum(from_index=0) - sqrt( 1-2*make_sum(from_index=1)-3*make_sum(from_index=1)**2))/(2*make_sum(from_index=0)) return d,h def from_pattern_family_01j_0(j, variable=var('t')): """ This function allow to build a pair of functions (d, h) to build a Riordan array for the pattern family (10)**j1, for a given j. """ def make_sum(from_index, to=j): return symbolic_sum(variable**i, i, from_index, to) i = var('i') d = make_sum(from_index=0)/sqrt( 1-2*make_sum(from_index=1)-3*make_sum(from_index=1)**2) h = (make_sum(from_index=0) - sqrt( 1-2*make_sum(from_index=1)-3*make_sum(from_index=1)**2))/(2*make_sum( from_index=0, to=j-1)) return d,h def from_pattern_family_j_j(j, variable=var('t')): """ This function allow to build a pair of functions (d, h) to build a Riordan array for the pattern family (10)**j1, for a given j. """ d = 1/sqrt(1-4*variable + 2*variable**j + variable**(2*j)) h = (1 + variable**j - sqrt(1-4*variable + 2*variable**j + variable**(2*j)))/2 return d,h def from_pattern_family_1_succj_0_j(j, variable=var('t')): """ This function allow to build a pair of functions (d, h) to build a Riordan array for the pattern family (10)**j1, for a given j. """ d = 1/sqrt(1-4*variable + 4*variable**(j+1)) h = (1 - sqrt(1-4*variable + 4*variable**(j+1)))/2 return d,h def from_pattern_family_0_succj_1_j(j, variable=var('t')): """ This function allow to build a pair of functions (d, h) to build a Riordan array for the pattern family (10)**j1, for a given j. """ d = 1/sqrt(1-4*variable + 4*variable**(j+1)) h = (1 - sqrt(1-4*variable + 4*variable**(j+1)))/(2*(1-variable**j)) <|fim▁hole|><|fim▁end|>
return d,h
<|file_name|>expander.rs<|end_file_name|><|fim▁begin|>// Our use cases use super::stream; pub const WAVE_FORMAT_PCM: usize = 1; #[derive(Default)] pub struct WaveFormatEx { pub format_tag: u16, pub channels: u16, pub samples_per_second: i32, pub average_bytes_per_second: i32, pub block_align: u16, pub bits_per_sample: u16, pub cb_size: u16, } pub struct SoundExpander { pub memb_20: i32, pub memb_24: i32, pub memb_28: i32, pub memb_30: i32, pub memb_34: i32, pub memb_40: i32, pub memb_48: i32, pub memb_4C: i32, pub memb_54: i32, pub memb_58: i32, pub memb_5C: i32, pub memb_64: i32, pub memb_68: i32, pub memb_70: i32, pub memb_74: i32, pub memb_80: i32, pub memb_8C: i32, pub memb_90: i32, pub file_reader: stream::FileReader, pub wave_format_ex: WaveFormatEx, pub flags0: i32, pub flags1: i32, pub flags2: i32, pub loop_point: i32, pub file_length: i32, pub read_limit: i32, pub some_var_6680EC: i32, pub some_var_6680E8: i32, pub previous: Box<SoundExpander>, pub next: Box<SoundExpander>, } impl SoundExpander { pub fn new() -> SoundExpander { let wave_format: WaveFormatEx = Default::default(); <|fim▁hole|> memb_30: 0, memb_34: 0, memb_40: 0, memb_48: 0, memb_4C: 0, memb_54: 0, memb_58: 0, memb_5C: 0, memb_64: 0, memb_68: 0, memb_70: 0, memb_74: 0, memb_80: 0, memb_8C: 0, memb_90: 0, file_reader: stream::FileReader::new(), wave_format_ex: wave_format, flags0: 0, flags1: 0, flags2: 0, loop_point: 0, file_length: 0, read_limit: 0, some_var_6680EC: 0, some_var_6680E8: 0, previous: Box::new(SoundExpander::new()), next: Box::new(SoundExpander::new()), } } }<|fim▁end|>
SoundExpander { memb_20: 0, memb_24: 0, memb_28: 0,
<|file_name|>thrift-tests.ts<|end_file_name|><|fim▁begin|>// Currently, the thrift bindings are minimal just to support the thrift generated // evernote bindings. Add more tests if you flesh out and plan to use the thrift // bindings more deeply. <|fim▁hole|>1 + 1;<|fim▁end|>
import evernote = require("evernote");
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2019 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # #################################################################### """ Loaders plugin manager """ from __future__ import print_function<|fim▁hole|>from fife import fife from fife.extensions.serializers.xmlmap import XMLMapLoader mapFileMapping = { 'xml' : XMLMapLoader} fileExtensions = set(['xml']) def loadMapFile(path, engine, callback=None, debug=True, extensions={}): """ load map file and get (an optional) callback if major stuff is done: - map creation - parsed imports - parsed layers - parsed cameras the callback will send both a string and a float (which shows the overall process), callback(string, float) @type engine: object @param engine: FIFE engine instance @type callback: function @param callback: callback for maploading progress @type debug: bool @param debug: flag to activate / deactivate print statements @rtype object @return FIFE map object """ (filename, extension) = os.path.splitext(path) map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions) map = map_loader.loadResource(path) if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.") return map def addMapLoader(fileExtension, loaderClass): """Add a new loader for fileextension @type fileExtension: string @param fileExtension: The file extension the loader is registered for @type loaderClass: object @param loaderClass: A fife.ResourceLoader implementation that loads maps from files with the given fileExtension """ mapFileMapping[fileExtension] = loaderClass _updateMapFileExtensions() def _updateMapFileExtensions(): global fileExtensions fileExtensions = set(mapFileMapping.keys())<|fim▁end|>
import os.path
<|file_name|>constants.js<|end_file_name|><|fim▁begin|>(function() { 'use strict'; <|fim▁hole|><|fim▁end|>
angular .module('app.core') .constant('STATIC_URL', '/static/js/'); })();
<|file_name|>menubutton.rs<|end_file_name|><|fim▁begin|>// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! A widget that shows a menu when clicked on use gtk::{mod, ffi}; use gtk::cast::GTK_MENUBUTTON; use gtk::ArrowType; /// MenuButton — A widget that shows a menu when clicked on struct_Widget!(MenuButton) impl MenuButton { pub fn new() -> Option<MenuButton> { let tmp_pointer = unsafe { ffi::gtk_menu_button_new() }; check_pointer!(tmp_pointer, MenuButton) } pub fn set_popup<T: gtk::WidgetTrait>(&mut self, popup: &T) -> () { unsafe { ffi::gtk_menu_button_set_popup(GTK_MENUBUTTON(self.pointer), popup.get_widget()); } } pub fn set_direction(&mut self, direction: ArrowType) -> () { unsafe { ffi::gtk_menu_button_set_direction(GTK_MENUBUTTON(self.pointer), direction); } } pub fn get_direction(&self) -> ArrowType { unsafe { ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer)) } } pub fn set_align_widget<T: gtk::WidgetTrait>(&mut self, align_widget: &T) -> () { unsafe { ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget.get_widget()) } } } impl_drop!(MenuButton) impl_TraitWidget!(MenuButton)<|fim▁hole|>impl gtk::ToggleButtonTrait for MenuButton {} impl_widget_events!(MenuButton)<|fim▁end|>
impl gtk::ContainerTrait for MenuButton {} impl gtk::ButtonTrait for MenuButton {}
<|file_name|>run_tests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """Execute the tests for the razers2 program. The golden test outputs are generated by the script generate_outputs.sh. You have to give the root paths to the source and the binaries as arguments to the program. These are the paths to the directory that contains the 'projects' directory. Usage: run_tests.py SOURCE_ROOT_PATH BINARY_ROOT_PATH """ import logging import os.path import sys # Automagically add util/py_lib to PYTHONPATH environment variable. path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', 'util', 'py_lib')) sys.path.insert(0, path) import seqan.app_tests as app_tests def main(source_base, binary_base): """Main entry point of the script.""" print 'Executing test for razers2' print '===========================' print ph = app_tests.TestPathHelper( source_base, binary_base, 'core/apps/razers2/tests') # tests dir # ============================================================ # Auto-detect the binary path. # ============================================================ path_to_program = app_tests.autolocateBinary( binary_base, 'core/apps/razers2', 'razers2') # ============================================================ # Built TestConf list. # ============================================================ # Build list with TestConf objects, analoguely to how the output # was generated in generate_outputs.sh. conf_list = [] # ============================================================ # Run Adeno Single-End Tests # ============================================================ # We run the following for all read lengths we have reads for. for rl in [36, 100]: # Run with default options. conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('se-adeno-reads%d_1.stdout' % rl), args=['--low-memory', ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), '-o', ph.outFile('se-adeno-reads%d_1.razers' % rl)], to_diff=[(ph.inFile('se-adeno-reads%d_1.razers' % rl), ph.outFile('se-adeno-reads%d_1.razers' % rl)), (ph.inFile('se-adeno-reads%d_1.stdout' % rl), ph.outFile('se-adeno-reads%d_1.stdout' % rl))]) conf_list.append(conf) # Allow indels. conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('se-adeno-reads%d_1-id.stdout' % rl), args=['--low-memory', '-id', ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), '-o', ph.outFile('se-adeno-reads%d_1-id.razers' % rl)], to_diff=[(ph.inFile('se-adeno-reads%d_1-id.razers' % rl), ph.outFile('se-adeno-reads%d_1-id.razers' % rl)), (ph.inFile('se-adeno-reads%d_1-id.stdout' % rl), ph.outFile('se-adeno-reads%d_1-id.stdout' % rl))]) conf_list.append(conf) # Compute forward/reverse matches only. for o in ['-r', '-f']: conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('se-adeno-reads%d_1-id%s.stdout' % (rl, o)), args=['--low-memory', '-id', o, ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), '-o', ph.outFile('se-adeno-reads%d_1-id%s.razers' % (rl, o))], to_diff=[(ph.inFile('se-adeno-reads%d_1-id%s.razers' % (rl, o)), ph.outFile('se-adeno-reads%d_1-id%s.razers' % (rl, o))), (ph.inFile('se-adeno-reads%d_1-id%s.stdout' % (rl, o)), ph.outFile('se-adeno-reads%d_1-id%s.stdout' % (rl, o)))]) conf_list.append(conf) # Compute with different identity rates. for i in range(90, 101): conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('se-adeno-reads%d_1-id-i%d.stdout' % (rl, i)), args=['--low-memory', '-id', '-i', str(i), ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), '-o', ph.outFile('se-adeno-reads%d_1-id-i%d.razers' % (rl, i))], to_diff=[(ph.inFile('se-adeno-reads%d_1-id-i%d.razers' % (rl, i)), ph.outFile('se-adeno-reads%d_1-id-i%d.razers' % (rl, i))), (ph.inFile('se-adeno-reads%d_1-id-i%d.stdout' % (rl, i)), ph.outFile('se-adeno-reads%d_1-id-i%d.stdout' % (rl, i)))]) conf_list.append(conf) # Compute with different output formats. for suffix in ['razers', 'fa', 'eland', 'gff', 'sam', 'afg']: conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('se-adeno-reads%d_1-id.%s.stdout' % (rl, suffix)), args=['--low-memory', '-id', ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), '-o', ph.outFile('se-adeno-reads%d_1-id.%s' % (rl, suffix))], to_diff=[(ph.inFile('se-adeno-reads%d_1-id.%s' % (rl, suffix)), ph.outFile('se-adeno-reads%d_1-id.%s' % (rl, suffix))), (ph.inFile('se-adeno-reads%d_1-id.%s.stdout' % (rl, suffix)), ph.outFile('se-adeno-reads%d_1-id.%s.stdout' % (rl, suffix)))]) conf_list.append(conf) # Compute with different sort orders. for so in [0, 1]: conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('se-adeno-reads%d_1-id-so%d.stdout' % (rl, so)), args=['--low-memory', '-id', '-so', str(so), ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), '-o', ph.outFile('se-adeno-reads%d_1-id-so%d.razers' % (rl, so))], to_diff=[(ph.inFile('se-adeno-reads%d_1-id-so%d.razers' % (rl, so)), ph.outFile('se-adeno-reads%d_1-id-so%d.razers' % (rl, so))), (ph.inFile('se-adeno-reads%d_1-id-so%d.stdout' % (rl, so)), ph.outFile('se-adeno-reads%d_1-id-so%d.stdout' % (rl, so)))]) conf_list.append(conf) # ============================================================ # Run Adeno Paired-End Tests # ============================================================ # We run the following for all read lengths we have reads for. for rl in [36, 100]: # Run with default options. conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('pe-adeno-reads%d_2.stdout' % rl), args=['--low-memory', ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), ph.inFile('adeno-reads%d_2.fa' % rl), '-o', ph.outFile('pe-adeno-reads%d_2.razers' % rl)], to_diff=[(ph.inFile('pe-adeno-reads%d_2.razers' % rl), ph.outFile('pe-adeno-reads%d_2.razers' % rl)), (ph.inFile('pe-adeno-reads%d_2.stdout' % rl), ph.outFile('pe-adeno-reads%d_2.stdout' % rl))]) conf_list.append(conf) # Allow indels. conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('pe-adeno-reads%d_2-id.stdout' % rl), args=['--low-memory', '-id', ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), ph.inFile('adeno-reads%d_2.fa' % rl), '-o', ph.outFile('pe-adeno-reads%d_2-id.razers' % rl)], to_diff=[(ph.inFile('pe-adeno-reads%d_2-id.razers' % rl), ph.outFile('pe-adeno-reads%d_2-id.razers' % rl)), (ph.inFile('pe-adeno-reads%d_2-id.stdout' % rl), ph.outFile('pe-adeno-reads%d_2-id.stdout' % rl))]) conf_list.append(conf) # Compute forward/reverse matches only. for o in ['-r', '-f']: conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('pe-adeno-reads%d_2-id%s.stdout' % (rl, o)), args=['--low-memory', '-id', o, ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), ph.inFile('adeno-reads%d_2.fa' % rl), '-o', ph.outFile('pe-adeno-reads%d_2-id%s.razers' % (rl, o))], to_diff=[(ph.inFile('pe-adeno-reads%d_2-id%s.razers' % (rl, o)), ph.outFile('pe-adeno-reads%d_2-id%s.razers' % (rl, o))), (ph.inFile('pe-adeno-reads%d_2-id%s.stdout' % (rl, o)), ph.outFile('pe-adeno-reads%d_2-id%s.stdout' % (rl, o)))]) conf_list.append(conf) # Compute with different identity rates. for i in range(90, 101): conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('pe-adeno-reads%d_2-id-i%d.stdout' % (rl, i)), args=['--low-memory', '-id', '-i', str(i), ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), ph.inFile('adeno-reads%d_2.fa' % rl), '-o', ph.outFile('pe-adeno-reads%d_2-id-i%d.razers' % (rl, i))], to_diff=[(ph.inFile('pe-adeno-reads%d_2-id-i%d.razers' % (rl, i)), ph.outFile('pe-adeno-reads%d_2-id-i%d.razers' % (rl, i))), (ph.inFile('pe-adeno-reads%d_2-id-i%d.stdout' % (rl, i)), ph.outFile('pe-adeno-reads%d_2-id-i%d.stdout' % (rl, i)))]) conf_list.append(conf) # Compute with different output formats. for suffix in ['razers', 'fa', 'eland', 'gff', 'sam', 'afg']: conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('pe-adeno-reads%d_2-id.%s.stdout' % (rl, suffix)), args=['--low-memory', '-id', ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), ph.inFile('adeno-reads%d_2.fa' % rl), '-o', ph.outFile('pe-adeno-reads%d_2-id.%s' % (rl, suffix))], to_diff=[(ph.inFile('pe-adeno-reads%d_2-id.%s' % (rl, suffix)), ph.outFile('pe-adeno-reads%d_2-id.%s' % (rl, suffix))), (ph.inFile('pe-adeno-reads%d_2-id.%s.stdout' % (rl, suffix)), ph.outFile('pe-adeno-reads%d_2-id.%s.stdout' % (rl, suffix)))]) conf_list.append(conf) # Compute with different sort orders. for so in [0, 1]: conf = app_tests.TestConf( program=path_to_program, redir_stdout=ph.outFile('pe-adeno-reads%d_2-id-so%d.stdout' % (rl, so)), args=['--low-memory', '-id', '-so', str(so), ph.inFile('adeno-genome.fa'),<|fim▁hole|> to_diff=[(ph.inFile('pe-adeno-reads%d_2-id-so%d.razers' % (rl, so)), ph.outFile('pe-adeno-reads%d_2-id-so%d.razers' % (rl, so))), (ph.inFile('pe-adeno-reads%d_2-id-so%d.stdout' % (rl, so)), ph.outFile('pe-adeno-reads%d_2-id-so%d.stdout' % (rl, so)))]) conf_list.append(conf) # Execute the tests. failures = 0 for conf in conf_list: res = app_tests.runTest(conf) # Output to the user. print ' '.join(['razers2'] + conf.args), if res: print 'OK' else: failures += 1 print 'FAILED' # Cleanup. ph.deleteTempDir() print '==============================' print ' total tests: %d' % len(conf_list) print ' failed tests: %d' % failures print 'successful tests: %d' % (len(conf_list) - failures) print '==============================' # Compute and return return code. return failures != 0 if __name__ == '__main__': sys.exit(app_tests.main(main))<|fim▁end|>
ph.inFile('adeno-reads%d_1.fa' % rl), ph.inFile('adeno-reads%d_2.fa' % rl), '-o', ph.outFile('pe-adeno-reads%d_2-id-so%d.razers' % (rl, so))],
<|file_name|>ValidationMappingGrid.java<|end_file_name|><|fim▁begin|>package org.activityinfo.ui.client.component.importDialog.validation; /* * #%L * ActivityInfo Server * %% * Copyright (C) 2009 - 2013 UNICEF * %% * This program 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.<|fim▁hole|> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import com.google.gwt.user.cellview.client.DataGrid; import com.google.gwt.user.cellview.client.TextHeader; import com.google.gwt.user.client.ui.ResizeComposite; import org.activityinfo.core.shared.importing.validation.ValidationResult; import org.activityinfo.i18n.shared.I18N; import org.activityinfo.ui.client.style.table.DataGridResources; import java.util.List; /** * @author yuriyz on 4/30/14. */ public class ValidationMappingGrid extends ResizeComposite { private DataGrid<ValidationResult> dataGrid; public ValidationMappingGrid() { this.dataGrid = new DataGrid<>(100, DataGridResources.INSTANCE); dataGrid.addColumn(new ValidationClassGridColumn(), new TextHeader(I18N.CONSTANTS.message())); initWidget(dataGrid); } public void refresh(List<ValidationResult> resultList) { dataGrid.setRowData(resultList); } }<|fim▁end|>
*
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from distutils.core import setup from dangagearman import __version__ as version setup( name = 'danga-gearman', version = version, description = 'Client for the Danga (Perl) Gearman implementation', author = 'Samuel Stauffer', author_email = '[email protected]', url = 'http://github.com/saymedia/python-danga-gearman/tree/master', packages = ['dangagearman'],<|fim▁hole|> 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )<|fim▁end|>
classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License',
<|file_name|>wall.js<|end_file_name|><|fim▁begin|>var Phaser = require('phaser-unofficial'); <|fim▁hole|>/** * Wall class. * @param {object} game * @param {number} x * @param {number} y */ Wall = function (game, x, y) { Phaser.Sprite.call(this, game, x, y, 'paddle'); this.game.physics.arcade.enable(this); this.width = 200; this.height = this.game.world.bounds.height; this.blendMode = Phaser.blendModes.ADD; this.body.bounce.setTo(1, 1); this.body.immovable = true; this.alpha = 0; }; Wall.prototype = Object.create(Phaser.Sprite.prototype); Wall.prototype.constructor = Wall; module.exports = Wall;<|fim▁end|>
<|file_name|>main_window.cpp<|end_file_name|><|fim▁begin|>#include <QApplication> #include <QMenuBar> #include <QMessageBox> #include <QFileDialog> #include <QVBoxLayout> #include <QDockWidget> #include <QProgressDialog> #include <QDesktopWidget> #include "vfs_dialog.h" #include "save_manager_dialog.h" #include "kernel_explorer.h" #include "game_list_frame.h" #include "debugger_frame.h" #include "log_frame.h" #include "settings_dialog.h" #include "auto_pause_settings_dialog.h" #include "cg_disasm_window.h" #include "memory_string_searcher.h" #include "memory_viewer_panel.h" #include "rsx_debugger.h" #include "main_window.h" #include "emu_settings.h" #include "about_dialog.h" #include "gamepads_settings_dialog.h" #include <thread> #include "stdafx.h" #include "Emu/System.h" #include "Emu/Memory/Memory.h" #include "Crypto/unpkg.h" #include "Crypto/unself.h" #include "Loader/PUP.h" #include "Loader/TAR.h" #include "Utilities/Thread.h" #include "Utilities/StrUtil.h" #include "rpcs3_version.h" #include "Utilities/sysinfo.h" #include "ui_main_window.h" inline std::string sstr(const QString& _in) { return _in.toUtf8().toStdString(); } main_window::main_window(std::shared_ptr<gui_settings> guiSettings, QWidget *parent) : QMainWindow(parent), guiSettings(guiSettings), m_sys_menu_opened(false), ui(new Ui::main_window) { } main_window::~main_window() { delete ui; } auto Pause = []() { if (Emu.IsReady()) Emu.Run(); else if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsRunning()) Emu.Pause(); else if (!Emu.GetPath().empty()) Emu.Load(); }; /* An init method is used so that RPCS3App can create the necessary connects before calling init (specifically the stylesheet connect). * Simplifies logic a bit. */ void main_window::Init() { ui->setupUi(this); m_appIcon = QIcon(":/rpcs3.ico"); // hide utilities from the average user ui->menuUtilities->menuAction()->setVisible(guiSettings->GetValue(GUI::m_showDebugTab).toBool()); // add toolbar widgets (crappy Qt designer is not able to) ui->toolBar->setObjectName("mw_toolbar"); ui->sizeSlider->setRange(0, GUI::gl_max_slider_pos); ui->sizeSlider->setSliderPosition(guiSettings->GetValue(GUI::gl_iconSize).toInt()); ui->toolBar->addWidget(ui->sizeSliderContainer); ui->toolBar->addSeparator(); ui->toolBar->addWidget(ui->mw_searchbar); // for highdpi resize toolbar icons and height dynamically // choose factors to mimic Gui-Design in main_window.ui // TODO: in case Qt::AA_EnableHighDpiScaling is enabled in main.cpp we only need the else branch #ifdef _WIN32 const int toolBarHeight = menuBar()->sizeHint().height() * 1.5; ui->toolBar->setIconSize(QSize(toolBarHeight, toolBarHeight)); #else const int toolBarHeight = ui->toolBar->iconSize().height(); #endif ui->sizeSliderContainer->setFixedWidth(toolBarHeight * 5); ui->sizeSlider->setFixedHeight(toolBarHeight * 0.65f); CreateActions(); CreateDockWindows(); setMinimumSize(350, minimumSizeHint().height()); // seems fine on win 10 CreateConnects(); setWindowTitle(QString::fromStdString("RPCS3 v" + rpcs3::version.to_string())); !m_appIcon.isNull() ? setWindowIcon(m_appIcon) : LOG_WARNING(GENERAL, "AppImage could not be loaded!"); Q_EMIT RequestGlobalStylesheetChange(guiSettings->GetCurrentStylesheetPath()); ConfigureGuiFromSettings(true); RepaintToolBarIcons(); m_gameListFrame->RepaintToolBarIcons(); if (!utils::has_ssse3()) { QMessageBox::critical(this, "SSSE3 Error (with three S, not two)", "Your system does not meet the minimum requirements needed to run RPCS3.\n" "Your CPU does not support SSSE3 (with three S, not two).\n"); std::exit(EXIT_FAILURE); } #ifdef BRANCH if ("RPCS3/rpcs3/master"s != STRINGIZE(BRANCH)) #elif _MSC_VER fs::stat_t st; if (!fs::stat(fs::get_config_dir() + "rpcs3.pdb", st) || st.is_directory || st.size < 1024 * 1024 * 100) #else if (false) #endif { LOG_WARNING(GENERAL, "Experimental Build Warning! Build origin: " STRINGIZE(BRANCH)); QMessageBox msg; msg.setWindowTitle("Experimental Build Warning"); msg.setWindowIcon(m_appIcon); msg.setIcon(QMessageBox::Critical); msg.setTextFormat(Qt::RichText); msg.setText("Please understand that this build is not an official RPCS3 release.<br>This build contains changes that may break games, or even <b>damage</b> your data.<br>It's recommended to download and use the official build from <a href='https://rpcs3.net/download'>RPCS3 website</a>.<br><br>Build origin: " STRINGIZE(BRANCH) "<br>Do you wish to use this build anyway?"); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg.setDefaultButton(QMessageBox::No); if (msg.exec() == QMessageBox::No) { std::exit(EXIT_SUCCESS); } } } void main_window::CreateThumbnailToolbar() { #ifdef _WIN32 m_icon_thumb_play = QIcon(":/Icons/play_blue.png"); m_icon_thumb_pause = QIcon(":/Icons/pause_blue.png"); m_icon_thumb_stop = QIcon(":/Icons/stop_blue.png"); m_icon_thumb_restart = QIcon(":/Icons/restart_blue.png"); m_thumb_bar = new QWinThumbnailToolBar(this); m_thumb_bar->setWindow(windowHandle()); m_thumb_playPause = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_playPause->setToolTip(tr("Pause")); m_thumb_playPause->setIcon(m_icon_thumb_pause); m_thumb_playPause->setEnabled(false); m_thumb_stop = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_stop->setToolTip(tr("Stop")); m_thumb_stop->setIcon(m_icon_thumb_stop); m_thumb_stop->setEnabled(false); m_thumb_restart = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_restart->setToolTip(tr("Restart")); m_thumb_restart->setIcon(m_icon_thumb_restart); m_thumb_restart->setEnabled(false); m_thumb_bar->addButton(m_thumb_playPause); m_thumb_bar->addButton(m_thumb_stop); m_thumb_bar->addButton(m_thumb_restart); connect(m_thumb_stop, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); }); connect(m_thumb_restart, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); Emu.Load(); }); connect(m_thumb_playPause, &QWinThumbnailToolButton::clicked, Pause); #endif } // returns appIcon QIcon main_window::GetAppIcon() { return m_appIcon; } // loads the appIcon from path and embeds it centered into an empty square icon void main_window::SetAppIconFromPath(const std::string path) { // get Icon for the gs_frame from path. this handles presumably all possible use cases QString qpath = qstr(path); std::string icon_list[] = { "/ICON0.PNG", "/PS3_GAME/ICON0.PNG" }; std::string path_list[] = { path, sstr(qpath.section("/", 0, -2)), sstr(qpath.section("/", 0, -3)) }; for (std::string pth : path_list) { if (!fs::is_dir(pth)) continue; for (std::string ico : icon_list) { ico = pth + ico; if (fs::is_file(ico)) { // load the image from path. It will most likely be a rectangle QImage source = QImage(qstr(ico)); int edgeMax = std::max(source.width(), source.height()); // create a new transparent image with square size and same format as source (maybe handle other formats than RGB32 as well?) QImage::Format format = source.format() == QImage::Format_RGB32 ? QImage::Format_ARGB32 : source.format(); QImage dest = QImage(edgeMax, edgeMax, format); dest.fill(QColor("transparent")); // get the location to draw the source image centered within the dest image. QPoint destPos = source.width() > source.height() ? QPoint(0, (source.width() - source.height()) / 2) : QPoint((source.height() - source.width()) / 2, 0); // Paint the source into/over the dest QPainter painter(&dest); painter.drawImage(destPos, source); painter.end(); // set Icon m_appIcon = QIcon(QPixmap::fromImage(dest)); return; } } } // if nothing was found reset the icon to default m_appIcon = QIcon(":/rpcs3.ico"); } void main_window::BootElf() { bool stopped = false; if (Emu.IsRunning()) { Emu.Pause(); stopped = true; } QString path_last_ELF = guiSettings->GetValue(GUI::fd_boot_elf).toString(); QString filePath = QFileDialog::getOpenFileName(this, tr("Select (S)ELF To Boot"), path_last_ELF, tr( "(S)ELF files (*BOOT.BIN *.elf *.self);;" "ELF files (BOOT.BIN *.elf);;" "SELF files (EBOOT.BIN *.self);;" "BOOT files (*BOOT.BIN);;" "BIN files (*.bin);;" "All files (*.*)"), Q_NULLPTR, QFileDialog::DontResolveSymlinks); if (filePath == NULL) { if (stopped) Emu.Resume(); return; } LOG_NOTICE(LOADER, "(S)ELF: booting..."); // If we resolved the filepath earlier we would end up setting the last opened dir to the unwanted // game folder in case of having e.g. a Game Folder with collected links to elf files. // Don't set last path earlier in case of cancelled dialog guiSettings->SetValue(GUI::fd_boot_elf, filePath); const std::string path = sstr(QFileInfo(filePath).canonicalFilePath()); SetAppIconFromPath(path); Emu.Stop(); if (!Emu.BootGame(path, true)) { LOG_ERROR(GENERAL, "PS3 executable not found at path (%s)", path); } else { LOG_SUCCESS(LOADER, "(S)ELF: boot done."); const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] "; AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle()))); m_gameListFrame->Refresh(true); } } void main_window::BootGame() { bool stopped = false; if (Emu.IsRunning()) { Emu.Pause(); stopped = true; } QString path_last_Game = guiSettings->GetValue(GUI::fd_boot_game).toString(); QString dirPath = QFileDialog::getExistingDirectory(this, tr("Select Game Folder"), path_last_Game, QFileDialog::ShowDirsOnly); if (dirPath == NULL) { if (stopped) Emu.Resume(); return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_boot_game, QFileInfo(dirPath).path()); const std::string path = sstr(dirPath); SetAppIconFromPath(path); if (!Emu.BootGame(path)) { LOG_ERROR(GENERAL, "PS3 executable not found in selected folder (%s)", path); } else { LOG_SUCCESS(LOADER, "Boot Game: boot done."); const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] "; AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle()))); m_gameListFrame->Refresh(true); } } void main_window::InstallPkg(const QString& dropPath) { QString filePath = dropPath; if (filePath.isEmpty()) { QString path_last_PKG = guiSettings->GetValue(GUI::fd_install_pkg).toString(); filePath = QFileDialog::getOpenFileName(this, tr("Select PKG To Install"), path_last_PKG, tr("PKG files (*.pkg);;All files (*.*)")); } else { if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Install package: %1?").arg(filePath), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_NOTICE(LOADER, "PKG: Cancelled installation from drop. File: %s", sstr(filePath)); return; } } if (filePath == NULL) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_install_pkg, QFileInfo(filePath).path()); const std::string fileName = sstr(QFileInfo(filePath).fileName()); const std::string path = sstr(filePath); // Open PKG file fs::file pkg_f(path); if (!pkg_f || pkg_f.size() < 64) { LOG_ERROR(LOADER, "PKG: Failed to open %s", path); return; } //Check header u32 pkg_signature; pkg_f.seek(0); pkg_f.read(pkg_signature); if (pkg_signature != "\x7FPKG"_u32) { LOG_ERROR(LOADER, "PKG: %s is not a pkg file", fileName); return; } // Get title ID std::vector<char> title_id(9); pkg_f.seek(55); pkg_f.read(title_id); pkg_f.seek(0); // Get full path const auto& local_path = Emu.GetHddDir() + "game/" + std::string(std::begin(title_id), std::end(title_id)); if (!fs::create_dir(local_path)) { if (fs::is_dir(local_path)) { if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Another installation found. Do you want to overwrite it?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_ERROR(LOADER, "PKG: Cancelled installation to existing directory %s", local_path); return; } } else { LOG_ERROR(LOADER, "PKG: Could not create the installation directory %s", local_path); return; } } QProgressDialog pdlg(tr("Installing package ... please wait ..."), tr("Cancel"), 0, 1000, this); pdlg.setWindowTitle(tr("RPCS3 Package Installer")); pdlg.setWindowModality(Qt::WindowModal); pdlg.setFixedSize(500, pdlg.height()); pdlg.show(); #ifdef _WIN32 QWinTaskbarButton *taskbar_button = new QWinTaskbarButton(); taskbar_button->setWindow(windowHandle()); QWinTaskbarProgress *taskbar_progress = taskbar_button->progress(); taskbar_progress->setRange(0, 1000); taskbar_progress->setVisible(true); #endif // Synchronization variable atomic_t<double> progress(0.); { // Run PKG unpacking asynchronously<|fim▁hole|> { progress = 1.; return; } // TODO: Ask user to delete files on cancellation/failure? progress = -1.; }); // Wait for the completion while (std::this_thread::sleep_for(5ms), std::abs(progress) < 1.) { if (pdlg.wasCanceled()) { progress -= 1.; #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Remove incomplete folder?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { fs::remove_all(local_path); m_gameListFrame->Refresh(true); LOG_SUCCESS(LOADER, "PKG: removed incomplete installation in %s", local_path); return; } break; } // Update progress window pdlg.setValue(static_cast<int>(progress * pdlg.maximum())); #ifdef _WIN32 taskbar_progress->setValue(static_cast<int>(progress * taskbar_progress->maximum())); #endif QCoreApplication::processEvents(); } if (progress > 0.) { pdlg.setValue(pdlg.maximum()); #ifdef _WIN32 taskbar_progress->setValue(taskbar_progress->maximum()); #endif std::this_thread::sleep_for(100ms); } } if (progress >= 1.) { m_gameListFrame->Refresh(true); LOG_SUCCESS(GENERAL, "Successfully installed %s.", fileName); guiSettings->ShowInfoBox(GUI::ib_pkg_success, tr("Success!"), tr("Successfully installed software from package!"), this); #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif } } void main_window::InstallPup(const QString& dropPath) { QString filePath = dropPath; if (filePath.isEmpty()) { QString path_last_PUP = guiSettings->GetValue(GUI::fd_install_pup).toString(); filePath = QFileDialog::getOpenFileName(this, tr("Select PS3UPDAT.PUP To Install"), path_last_PUP, tr("PS3 update file (PS3UPDAT.PUP)")); } else { if (QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Install firmware: %1?").arg(filePath), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_NOTICE(LOADER, "Firmware: Cancelled installation from drop. File: %s", sstr(filePath)); return; } } if (filePath == NULL) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_install_pup, QFileInfo(filePath).path()); const std::string path = sstr(filePath); fs::file pup_f(path); pup_object pup(pup_f); if (!pup) { LOG_ERROR(GENERAL, "Error while installing firmware: PUP file is invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP file is invalid.")); return; } fs::file update_files_f = pup.get_file(0x300); tar_object update_files(update_files_f); auto updatefilenames = update_files.get_filenames(); updatefilenames.erase(std::remove_if( updatefilenames.begin(), updatefilenames.end(), [](std::string s) { return s.find("dev_flash_") == std::string::npos; }), updatefilenames.end()); std::string version_string = pup.get_file(0x100).to_string(); version_string.erase(version_string.find('\n')); const std::string cur_version = "4.81"; if (version_string < cur_version && QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Old firmware detected.\nThe newest firmware version is %1 and you are trying to install version %2\nContinue installation?").arg(QString::fromStdString(cur_version), QString::fromStdString(version_string)), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No) { return; } QProgressDialog pdlg(tr("Installing firmware version %1\nPlease wait...").arg(QString::fromStdString(version_string)), tr("Cancel"), 0, static_cast<int>(updatefilenames.size()), this); pdlg.setWindowTitle(tr("RPCS3 Firmware Installer")); pdlg.setWindowModality(Qt::WindowModal); pdlg.setFixedSize(500, pdlg.height()); pdlg.show(); #ifdef _WIN32 QWinTaskbarButton *taskbar_button = new QWinTaskbarButton(); taskbar_button->setWindow(windowHandle()); QWinTaskbarProgress *taskbar_progress = taskbar_button->progress(); taskbar_progress->setRange(0, static_cast<int>(updatefilenames.size())); taskbar_progress->setVisible(true); #endif // Synchronization variable atomic_t<int> progress(0); { // Run asynchronously scope_thread worker("Firmware Installer", [&] { for (auto updatefilename : updatefilenames) { if (progress == -1) break; fs::file updatefile = update_files.get_file(updatefilename); SCEDecrypter self_dec(updatefile); self_dec.LoadHeaders(); self_dec.LoadMetadata(SCEPKG_ERK, SCEPKG_RIV); self_dec.DecryptData(); auto dev_flash_tar_f = self_dec.MakeFile(); if (dev_flash_tar_f.size() < 3) { LOG_ERROR(GENERAL, "Error while installing firmware: PUP contents are invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP contents are invalid.")); progress = -1; } tar_object dev_flash_tar(dev_flash_tar_f[2]); if (!dev_flash_tar.extract(fs::get_config_dir())) { LOG_ERROR(GENERAL, "Error while installing firmware: TAR contents are invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: TAR contents are invalid.")); progress = -1; } if (progress >= 0) progress += 1; } }); // Wait for the completion while (std::this_thread::sleep_for(5ms), std::abs(progress) < pdlg.maximum()) { if (pdlg.wasCanceled()) { progress = -1; #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif break; } // Update progress window pdlg.setValue(static_cast<int>(progress)); #ifdef _WIN32 taskbar_progress->setValue(static_cast<int>(progress)); #endif QCoreApplication::processEvents(); } update_files_f.close(); pup_f.close(); if (progress > 0) { pdlg.setValue(pdlg.maximum()); #ifdef _WIN32 taskbar_progress->setValue(taskbar_progress->maximum()); #endif std::this_thread::sleep_for(100ms); } } if (progress > 0) { LOG_SUCCESS(GENERAL, "Successfully installed PS3 firmware version %s.", version_string); guiSettings->ShowInfoBox(GUI::ib_pup_success, tr("Success!"), tr("Successfully installed PS3 firmware and LLE Modules!"), this); #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif } } // This is ugly, but PS3 headers shall not be included there. extern void sysutil_send_system_cmd(u64 status, u64 param); void main_window::DecryptSPRXLibraries() { QString path_last_SPRX = guiSettings->GetValue(GUI::fd_decrypt_sprx).toString(); QStringList modules = QFileDialog::getOpenFileNames(this, tr("Select SPRX files"), path_last_SPRX, tr("SPRX files (*.sprx)")); if (modules.isEmpty()) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_decrypt_sprx, QFileInfo(modules.first()).path()); LOG_NOTICE(GENERAL, "Decrypting SPRX libraries..."); for (QString& module : modules) { std::string prx_path = sstr(module); const std::string& prx_dir = fs::get_parent_dir(prx_path); fs::file elf_file(prx_path); if (elf_file && elf_file.size() >= 4 && elf_file.read<u32>() == "SCE\0"_u32) { const std::size_t prx_ext_pos = prx_path.find_last_of('.'); const std::string& prx_name = prx_path.substr(prx_dir.size()); elf_file = decrypt_self(std::move(elf_file)); prx_path.erase(prx_path.size() - 4, 1); // change *.sprx to *.prx if (elf_file) { if (fs::file new_file{ prx_path, fs::rewrite }) { new_file.write(elf_file.to_string()); LOG_SUCCESS(GENERAL, "Decrypted %s", prx_dir + prx_name); } else { LOG_ERROR(GENERAL, "Failed to create %s", prx_path); } } else { LOG_ERROR(GENERAL, "Failed to decrypt %s", prx_dir + prx_name); } } } LOG_NOTICE(GENERAL, "Finished decrypting all SPRX libraries."); } /** Needed so that when a backup occurs of window state in guisettings, the state is current. * Also, so that on close, the window state is preserved. */ void main_window::SaveWindowState() { // Save gui settings guiSettings->SetValue(GUI::mw_geometry, saveGeometry()); guiSettings->SetValue(GUI::mw_windowState, saveState()); guiSettings->SetValue(GUI::mw_mwState, m_mw->saveState()); // Save column settings m_gameListFrame->SaveSettings(); // Save splitter state m_debuggerFrame->SaveSettings(); } void main_window::RepaintToolBarIcons() { QColor newColor; if (guiSettings->GetValue(GUI::m_enableUIColors).toBool()) { newColor = guiSettings->GetValue(GUI::mw_toolIconColor).value<QColor>(); } else { newColor = GUI::get_Label_Color("toolbar_icon_color"); } auto icon = [&newColor](const QString& path) { return gui_settings::colorizedIcon(QIcon(path), GUI::mw_tool_icon_color, newColor); }; m_icon_play = icon(":/Icons/play.png"); m_icon_pause = icon(":/Icons/pause.png"); m_icon_stop = icon(":/Icons/stop.png"); m_icon_restart = icon(":/Icons/restart.png"); m_icon_fullscreen_on = icon(":/Icons/fullscreen.png"); m_icon_fullscreen_off = icon(":/Icons/fullscreen_invert.png"); ui->toolbar_config ->setIcon(icon(":/Icons/configure.png")); ui->toolbar_controls->setIcon(icon(":/Icons/controllers.png")); ui->toolbar_disc ->setIcon(icon(":/Icons/disc.png")); ui->toolbar_grid ->setIcon(icon(":/Icons/grid.png")); ui->toolbar_list ->setIcon(icon(":/Icons/list.png")); ui->toolbar_refresh ->setIcon(icon(":/Icons/refresh.png")); ui->toolbar_snap ->setIcon(icon(":/Icons/screenshot.png")); ui->toolbar_sort ->setIcon(icon(":/Icons/sort.png")); ui->toolbar_stop ->setIcon(icon(":/Icons/stop.png")); if (Emu.IsRunning()) { ui->toolbar_start->setIcon(m_icon_pause); } else if (Emu.IsStopped() && !Emu.GetPath().empty()) { ui->toolbar_start->setIcon(m_icon_restart); } else { ui->toolbar_start->setIcon(m_icon_play); } if (isFullScreen()) { ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } else { ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off); } ui->sizeSlider->setStyleSheet(ui->sizeSlider->styleSheet().append("QSlider::handle:horizontal{ background: rgba(%1, %2, %3, %4); }") .arg(newColor.red()).arg(newColor.green()).arg(newColor.blue()).arg(newColor.alpha())); } void main_window::OnEmuRun() { m_debuggerFrame->EnableButtons(true); #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Pause emulation")); m_thumb_playPause->setIcon(m_icon_thumb_pause); #endif ui->sysPauseAct->setText(tr("&Pause\tCtrl+P")); ui->sysPauseAct->setIcon(m_icon_pause); ui->toolbar_start->setIcon(m_icon_pause); ui->toolbar_start->setToolTip(tr("Pause emulation")); EnableMenus(true); } void main_window::OnEmuResume() { #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Pause emulation")); m_thumb_playPause->setIcon(m_icon_thumb_pause); #endif ui->sysPauseAct->setText(tr("&Pause\tCtrl+P")); ui->sysPauseAct->setIcon(m_icon_pause); ui->toolbar_start->setIcon(m_icon_pause); ui->toolbar_start->setToolTip(tr("Pause emulation")); } void main_window::OnEmuPause() { #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif ui->sysPauseAct->setText(tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(tr("Resume emulation")); } void main_window::OnEmuStop() { m_debuggerFrame->EnableButtons(false); m_debuggerFrame->ClearBreakpoints(); ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); #ifdef _WIN32 m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif EnableMenus(false); if (!Emu.GetPath().empty()) { ui->toolbar_start->setEnabled(true); ui->toolbar_start->setIcon(m_icon_restart); ui->toolbar_start->setToolTip(tr("Restart emulation")); ui->sysRebootAct->setEnabled(true); #ifdef _WIN32 m_thumb_restart->setEnabled(true); #endif } else { ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); } } void main_window::OnEmuReady() { m_debuggerFrame->EnableButtons(true); #ifdef _WIN32 m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); EnableMenus(true); } void main_window::EnableMenus(bool enabled) { // Thumbnail Buttons #ifdef _WIN32 m_thumb_playPause->setEnabled(enabled); m_thumb_stop->setEnabled(enabled); m_thumb_restart->setEnabled(enabled); #endif // Toolbar ui->toolbar_start->setEnabled(enabled); ui->toolbar_stop->setEnabled(enabled); // Emulation ui->sysPauseAct->setEnabled(enabled); ui->sysStopAct->setEnabled(enabled); ui->sysRebootAct->setEnabled(enabled); // PS3 Commands ui->sysSendOpenMenuAct->setEnabled(enabled); ui->sysSendExitAct->setEnabled(enabled); // Tools ui->toolskernel_explorerAct->setEnabled(enabled); ui->toolsmemory_viewerAct->setEnabled(enabled); ui->toolsRsxDebuggerAct->setEnabled(enabled); ui->toolsStringSearchAct->setEnabled(enabled); } void main_window::BootRecentAction(const QAction* act) { if (Emu.IsRunning()) { return; } const QString pth = act->data().toString(); QString nam; bool containsPath = false; int idx = -1; for (int i = 0; i < m_rg_entries.count(); i++) { if (m_rg_entries.at(i).first == pth) { idx = i; containsPath = true; nam = m_rg_entries.at(idx).second; } } // path is invalid: remove action from list return if ((containsPath && nam.isEmpty()) || (!QFileInfo(pth).isDir() && !QFileInfo(pth).isFile())) { if (containsPath) { // clear menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } // remove action from list m_rg_entries.removeAt(idx); m_recentGameActs.removeAt(idx); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); LOG_ERROR(GENERAL, "Recent Game not valid, removed from Boot Recent list: %s", sstr(pth)); // refill menu with actions for (int i = 0; i < m_recentGameActs.count(); i++) { m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i + 1)); m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second); ui->bootRecentMenu->addAction(m_recentGameActs[i]); } LOG_WARNING(GENERAL, "Boot Recent list refreshed"); return; } LOG_ERROR(GENERAL, "Path invalid and not in m_rg_paths: %s", sstr(pth)); return; } SetAppIconFromPath(sstr(pth)); Emu.Stop(); if (!Emu.BootGame(sstr(pth), true)) { LOG_ERROR(LOADER, "Failed to boot %s", sstr(pth)); } else { LOG_SUCCESS(LOADER, "Boot from Recent List: done"); AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), nam)); m_gameListFrame->Refresh(true); } }; QAction* main_window::CreateRecentAction(const q_string_pair& entry, const uint& sc_idx) { // if path is not valid remove from list if (entry.second.isEmpty() || (!QFileInfo(entry.first).isDir() && !QFileInfo(entry.first).isFile())) { if (m_rg_entries.contains(entry)) { LOG_ERROR(GENERAL, "Recent Game not valid, removing from Boot Recent list: %s", sstr(entry.first)); int idx = m_rg_entries.indexOf(entry); m_rg_entries.removeAt(idx); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); } return nullptr; } // if name is a path get filename QString shown_name = entry.second; if (QFileInfo(entry.second).isFile()) { shown_name = entry.second.section('/', -1); } // create new action QAction* act = new QAction(shown_name, this); act->setData(entry.first); act->setToolTip(entry.second); act->setShortcut(tr("Ctrl+%1").arg(sc_idx)); // truncate if too long if (shown_name.length() > 60) { act->setText(shown_name.left(27) + "(....)" + shown_name.right(27)); } // connect boot connect(act, &QAction::triggered, [=]() {BootRecentAction(act); }); return act; }; void main_window::AddRecentAction(const q_string_pair& entry) { // don't change list on freeze if (ui->freezeRecentAct->isChecked()) { return; } // create new action, return if not valid QAction* act = CreateRecentAction(entry, 1); if (!act) { return; } // clear menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } // if path already exists, remove it in order to get it to beginning if (m_rg_entries.contains(entry)) { int idx = m_rg_entries.indexOf(entry); m_rg_entries.removeAt(idx); m_recentGameActs.removeAt(idx); } // remove oldest action at the end if needed if (m_rg_entries.count() == 9) { m_rg_entries.removeLast(); m_recentGameActs.removeLast(); } else if (m_rg_entries.count() > 9) { LOG_ERROR(LOADER, "Recent games entrylist too big"); } if (m_rg_entries.count() < 9) { // add new action at the beginning m_rg_entries.prepend(entry); m_recentGameActs.prepend(act); } // refill menu with actions for (int i = 0; i < m_recentGameActs.count(); i++) { m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i+1)); m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second); ui->bootRecentMenu->addAction(m_recentGameActs[i]); } guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); } void main_window::RepaintGui() { m_gameListFrame->RepaintIcons(true); m_gameListFrame->RepaintToolBarIcons(); RepaintToolbar(); RepaintToolBarIcons(); } void main_window::RepaintToolbar() { if (guiSettings->GetValue(GUI::m_enableUIColors).toBool()) { QColor tbc = guiSettings->GetValue(GUI::mw_toolBarColor).value<QColor>(); ui->toolBar->setStyleSheet(GUI::stylesheet + QString( "QToolBar { background-color: rgba(%1, %2, %3, %4); }" "QToolBar::separator {background-color: rgba(%5, %6, %7, %8); width: 1px; margin-top: 2px; margin-bottom: 2px;}" "QSlider { background-color: rgba(%1, %2, %3, %4); }" "QLineEdit { background-color: rgba(%1, %2, %3, %4); }") .arg(tbc.red()).arg(tbc.green()).arg(tbc.blue()).arg(tbc.alpha()) .arg(tbc.red() - 20).arg(tbc.green() - 20).arg(tbc.blue() - 20).arg(tbc.alpha() - 20) ); } else { ui->toolBar->setStyleSheet(GUI::stylesheet); } } void main_window::CreateActions() { ui->exitAct->setShortcuts(QKeySequence::Quit); ui->toolbar_start->setEnabled(false); ui->toolbar_stop->setEnabled(false); m_categoryVisibleActGroup = new QActionGroup(this); m_categoryVisibleActGroup->addAction(ui->showCatHDDGameAct); m_categoryVisibleActGroup->addAction(ui->showCatDiscGameAct); m_categoryVisibleActGroup->addAction(ui->showCatHomeAct); m_categoryVisibleActGroup->addAction(ui->showCatAudioVideoAct); m_categoryVisibleActGroup->addAction(ui->showCatGameDataAct); m_categoryVisibleActGroup->addAction(ui->showCatUnknownAct); m_categoryVisibleActGroup->addAction(ui->showCatOtherAct); m_categoryVisibleActGroup->setExclusive(false); m_iconSizeActGroup = new QActionGroup(this); m_iconSizeActGroup->addAction(ui->setIconSizeTinyAct); m_iconSizeActGroup->addAction(ui->setIconSizeSmallAct); m_iconSizeActGroup->addAction(ui->setIconSizeMediumAct); m_iconSizeActGroup->addAction(ui->setIconSizeLargeAct); m_listModeActGroup = new QActionGroup(this); m_listModeActGroup->addAction(ui->setlistModeListAct); m_listModeActGroup->addAction(ui->setlistModeGridAct); } void main_window::CreateConnects() { connect(ui->bootElfAct, &QAction::triggered, this, &main_window::BootElf); connect(ui->bootGameAct, &QAction::triggered, this, &main_window::BootGame); connect(ui->bootRecentMenu, &QMenu::aboutToShow, [=] { // Enable/Disable Recent Games List const bool stopped = Emu.IsStopped(); for (auto act : ui->bootRecentMenu->actions()) { if (act != ui->freezeRecentAct && act != ui->clearRecentAct) { act->setEnabled(stopped); } } }); connect(ui->clearRecentAct, &QAction::triggered, [this] { if (ui->freezeRecentAct->isChecked()) { return; } m_rg_entries.clear(); for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } m_recentGameActs.clear(); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(q_pair_list())); }); connect(ui->freezeRecentAct, &QAction::triggered, [=](bool checked) { guiSettings->SetValue(GUI::rg_freeze, checked); }); connect(ui->bootInstallPkgAct, &QAction::triggered, [this] {InstallPkg(); }); connect(ui->bootInstallPupAct, &QAction::triggered, [this] {InstallPup(); }); connect(ui->exitAct, &QAction::triggered, this, &QWidget::close); connect(ui->sysPauseAct, &QAction::triggered, Pause); connect(ui->sysStopAct, &QAction::triggered, [=]() { Emu.Stop(); }); connect(ui->sysRebootAct, &QAction::triggered, [=]() { Emu.Stop(); Emu.Load(); }); connect(ui->sysSendOpenMenuAct, &QAction::triggered, [=] { sysutil_send_system_cmd(m_sys_menu_opened ? 0x0132 /* CELL_SYSUTIL_SYSTEM_MENU_CLOSE */ : 0x0131 /* CELL_SYSUTIL_SYSTEM_MENU_OPEN */, 0); m_sys_menu_opened = !m_sys_menu_opened; ui->sysSendOpenMenuAct->setText(tr("Send &%0 system menu cmd").arg(m_sys_menu_opened ? tr("close") : tr("open"))); }); connect(ui->sysSendExitAct, &QAction::triggered, [=] { sysutil_send_system_cmd(0x0101 /* CELL_SYSUTIL_REQUEST_EXITGAME */, 0); }); auto openSettings = [=](int tabIndex) { settings_dialog dlg(guiSettings, m_Render_Creator, tabIndex, this); connect(&dlg, &settings_dialog::GuiSettingsSaveRequest, this, &main_window::SaveWindowState); connect(&dlg, &settings_dialog::GuiSettingsSyncRequest, [=]() {ConfigureGuiFromSettings(true); }); connect(&dlg, &settings_dialog::GuiStylesheetRequest, this, &main_window::RequestGlobalStylesheetChange); connect(&dlg, &settings_dialog::GuiRepaintRequest, this, &main_window::RepaintGui); dlg.exec(); }; connect(ui->confCPUAct, &QAction::triggered, [=]() { openSettings(0); }); connect(ui->confGPUAct, &QAction::triggered, [=]() { openSettings(1); }); connect(ui->confAudioAct, &QAction::triggered, [=]() { openSettings(2); }); connect(ui->confIOAct, &QAction::triggered, [=]() { openSettings(3); }); connect(ui->confSystemAct, &QAction::triggered, [=]() { openSettings(4); }); connect(ui->confPadsAct, &QAction::triggered, this, [=] { gamepads_settings_dialog dlg(this); dlg.exec(); }); connect(ui->confAutopauseManagerAct, &QAction::triggered, [=] { auto_pause_settings_dialog dlg(this); dlg.exec(); }); connect(ui->confVFSDialogAct, &QAction::triggered, [=] { vfs_dialog dlg(this); dlg.exec(); m_gameListFrame->Refresh(true); // dev-hdd0 may have changed. Refresh just in case. }); connect(ui->confSavedataManagerAct, &QAction::triggered, [=] { save_manager_dialog* sdid = new save_manager_dialog(); sdid->show(); }); connect(ui->toolsCgDisasmAct, &QAction::triggered, [=] { cg_disasm_window* cgdw = new cg_disasm_window(guiSettings); cgdw->show(); }); connect(ui->toolskernel_explorerAct, &QAction::triggered, [=] { kernel_explorer* kernelExplorer = new kernel_explorer(this); kernelExplorer->show(); }); connect(ui->toolsmemory_viewerAct, &QAction::triggered, [=] { memory_viewer_panel* mvp = new memory_viewer_panel(this); mvp->show(); }); connect(ui->toolsRsxDebuggerAct, &QAction::triggered, [=] { rsx_debugger* rsx = new rsx_debugger(this); rsx->show(); }); connect(ui->toolsStringSearchAct, &QAction::triggered, [=] { memory_string_searcher* mss = new memory_string_searcher(this); mss->show(); }); connect(ui->toolsDecryptSprxLibsAct, &QAction::triggered, this, &main_window::DecryptSPRXLibraries); connect(ui->showDebuggerAct, &QAction::triggered, [=](bool checked) { checked ? m_debuggerFrame->show() : m_debuggerFrame->hide(); guiSettings->SetValue(GUI::mw_debugger, checked); }); connect(ui->showLogAct, &QAction::triggered, [=](bool checked) { checked ? m_logFrame->show() : m_logFrame->hide(); guiSettings->SetValue(GUI::mw_logger, checked); }); connect(ui->showGameListAct, &QAction::triggered, [=](bool checked) { checked ? m_gameListFrame->show() : m_gameListFrame->hide(); guiSettings->SetValue(GUI::mw_gamelist, checked); }); connect(ui->showToolBarAct, &QAction::triggered, [=](bool checked) { ui->toolBar->setVisible(checked); guiSettings->SetValue(GUI::mw_toolBarVisible, checked); }); connect(ui->showGameToolBarAct, &QAction::triggered, [=](bool checked) { m_gameListFrame->SetToolBarVisible(checked); }); connect(ui->refreshGameListAct, &QAction::triggered, [=] { m_gameListFrame->Refresh(true); }); connect(m_categoryVisibleActGroup, &QActionGroup::triggered, [=](QAction* act) { QStringList categories; int id; const bool& checked = act->isChecked(); if (act == ui->showCatHDDGameAct) categories += category::non_disc_games, id = Category::Non_Disc_Game; else if (act == ui->showCatDiscGameAct) categories += category::disc_Game, id = Category::Disc_Game; else if (act == ui->showCatHomeAct) categories += category::home, id = Category::Home; else if (act == ui->showCatAudioVideoAct) categories += category::media, id = Category::Media; else if (act == ui->showCatGameDataAct) categories += category::data, id = Category::Data; else if (act == ui->showCatUnknownAct) categories += category::unknown, id = Category::Unknown_Cat; else if (act == ui->showCatOtherAct) categories += category::others, id = Category::Others; else LOG_WARNING(GENERAL, "categoryVisibleActGroup: category action not found"); m_gameListFrame->SetCategoryActIcon(m_categoryVisibleActGroup->actions().indexOf(act), checked); m_gameListFrame->ToggleCategoryFilter(categories, checked); guiSettings->SetCategoryVisibility(id, checked); }); connect(ui->aboutAct, &QAction::triggered, [this] { about_dialog dlg(this); dlg.exec(); }); connect(ui->aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); auto resizeIcons = [=](const int& index) { int val = ui->sizeSlider->value(); if (val != index) { ui->sizeSlider->setSliderPosition(index); } if (val != m_gameListFrame->GetSliderValue()) { if (m_save_slider_pos) { m_save_slider_pos = false; guiSettings->SetValue(GUI::gl_iconSize, index); } m_gameListFrame->ResizeIcons(index); } }; connect(m_iconSizeActGroup, &QActionGroup::triggered, [=](QAction* act) { int index; if (act == ui->setIconSizeTinyAct) index = 0; else if (act == ui->setIconSizeSmallAct) index = GUI::get_Index(GUI::gl_icon_size_small); else if (act == ui->setIconSizeMediumAct) index = GUI::get_Index(GUI::gl_icon_size_medium); else index = GUI::gl_max_slider_pos; resizeIcons(index); }); connect (m_gameListFrame, &game_list_frame::RequestIconSizeActSet, [=](const int& idx) { if (idx < GUI::get_Index((GUI::gl_icon_size_small + GUI::gl_icon_size_min) / 2)) ui->setIconSizeTinyAct->setChecked(true); else if (idx < GUI::get_Index((GUI::gl_icon_size_medium + GUI::gl_icon_size_small) / 2)) ui->setIconSizeSmallAct->setChecked(true); else if (idx < GUI::get_Index((GUI::gl_icon_size_max + GUI::gl_icon_size_medium) / 2)) ui->setIconSizeMediumAct->setChecked(true); else ui->setIconSizeLargeAct->setChecked(true); resizeIcons(idx); }); connect(m_gameListFrame, &game_list_frame::RequestSaveSliderPos, [=](const bool& save) { Q_UNUSED(save); m_save_slider_pos = true; }); connect(m_gameListFrame, &game_list_frame::RequestListModeActSet, [=](const bool& isList) { isList ? ui->setlistModeListAct->trigger() : ui->setlistModeGridAct->trigger(); }); connect(m_gameListFrame, &game_list_frame::RequestCategoryActSet, [=](const int& id) { m_categoryVisibleActGroup->actions().at(id)->trigger(); }); connect(m_listModeActGroup, &QActionGroup::triggered, [=](QAction* act) { bool isList = act == ui->setlistModeListAct; m_gameListFrame->SetListMode(isList); m_categoryVisibleActGroup->setEnabled(isList); }); connect(ui->toolbar_disc, &QAction::triggered, this, &main_window::BootGame); connect(ui->toolbar_refresh, &QAction::triggered, [=]() { m_gameListFrame->Refresh(true); }); connect(ui->toolbar_stop, &QAction::triggered, [=]() { Emu.Stop(); }); connect(ui->toolbar_start, &QAction::triggered, Pause); connect(ui->toolbar_fullscreen, &QAction::triggered, [=] { if (isFullScreen()) { showNormal(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } else { showFullScreen(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off); } }); connect(ui->toolbar_controls, &QAction::triggered, [=]() { gamepads_settings_dialog dlg(this); dlg.exec(); }); connect(ui->toolbar_config, &QAction::triggered, [=]() { openSettings(0); }); connect(ui->toolbar_list, &QAction::triggered, [=]() { ui->setlistModeListAct->trigger(); }); connect(ui->toolbar_grid, &QAction::triggered, [=]() { ui->setlistModeGridAct->trigger(); }); connect(ui->sizeSlider, &QSlider::valueChanged, resizeIcons); connect(ui->sizeSlider, &QSlider::sliderReleased, this, [&] { guiSettings->SetValue(GUI::gl_iconSize, ui->sizeSlider->value()); }); connect(ui->sizeSlider, &QSlider::actionTriggered, [&](int action) { if (action != QAbstractSlider::SliderNoAction && action != QAbstractSlider::SliderMove) { // we only want to save on mouseclicks or slider release (the other connect handles this) m_save_slider_pos = true; // actionTriggered happens before the value was changed } }); connect(ui->mw_searchbar, &QLineEdit::textChanged, m_gameListFrame, &game_list_frame::SetSearchText); } void main_window::CreateDockWindows() { // new mainwindow widget because existing seems to be bugged for now m_mw = new QMainWindow(); m_gameListFrame = new game_list_frame(guiSettings, m_Render_Creator, m_mw); m_gameListFrame->setObjectName("gamelist"); m_debuggerFrame = new debugger_frame(guiSettings, m_mw); m_debuggerFrame->setObjectName("debugger"); m_logFrame = new log_frame(guiSettings, m_mw); m_logFrame->setObjectName("logger"); m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_gameListFrame); m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_logFrame); m_mw->addDockWidget(Qt::RightDockWidgetArea, m_debuggerFrame); m_mw->setDockNestingEnabled(true); setCentralWidget(m_mw); connect(m_logFrame, &log_frame::LogFrameClosed, [=]() { if (ui->showLogAct->isChecked()) { ui->showLogAct->setChecked(false); guiSettings->SetValue(GUI::mw_logger, false); } }); connect(m_debuggerFrame, &debugger_frame::DebugFrameClosed, [=]() { if (ui->showDebuggerAct->isChecked()) { ui->showDebuggerAct->setChecked(false); guiSettings->SetValue(GUI::mw_debugger, false); } }); connect(m_gameListFrame, &game_list_frame::GameListFrameClosed, [=]() { if (ui->showGameListAct->isChecked()) { ui->showGameListAct->setChecked(false); guiSettings->SetValue(GUI::mw_gamelist, false); } }); connect(m_gameListFrame, &game_list_frame::RequestIconPathSet, this, &main_window::SetAppIconFromPath); connect(m_gameListFrame, &game_list_frame::RequestAddRecentGame, this, &main_window::AddRecentAction); connect(m_gameListFrame, &game_list_frame::RequestPackageInstall, [this](const QStringList& paths) { for (const auto& path : paths) { InstallPkg(path); } }); connect(m_gameListFrame, &game_list_frame::RequestFirmwareInstall, this, &main_window::InstallPup); } void main_window::ConfigureGuiFromSettings(bool configureAll) { // Restore GUI state if needed. We need to if they exist. QByteArray geometry = guiSettings->GetValue(GUI::mw_geometry).toByteArray(); if (geometry.isEmpty() == false) { restoreGeometry(geometry); } else { // By default, set the window to 70% of the screen and the debugger frame is hidden. m_debuggerFrame->hide(); QSize defaultSize = QDesktopWidget().availableGeometry().size() * 0.7; resize(defaultSize); } restoreState(guiSettings->GetValue(GUI::mw_windowState).toByteArray()); m_mw->restoreState(guiSettings->GetValue(GUI::mw_mwState).toByteArray()); ui->freezeRecentAct->setChecked(guiSettings->GetValue(GUI::rg_freeze).toBool()); m_rg_entries = guiSettings->Var2List(guiSettings->GetValue(GUI::rg_entries)); // clear recent games menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } m_recentGameActs.clear(); // Fill the recent games menu for (int i = 0; i < m_rg_entries.count(); i++) { // adjust old unformatted entries (avoid duplication) m_rg_entries[i] = GUI::Recent_Game(m_rg_entries[i].first, m_rg_entries[i].second); // create new action QAction* act = CreateRecentAction(m_rg_entries[i], i + 1); // add action to menu if (act) { m_recentGameActs.append(act); ui->bootRecentMenu->addAction(act); } else { i--; // list count is now an entry shorter so we have to repeat the same index in order to load all other entries } } ui->showLogAct->setChecked(guiSettings->GetValue(GUI::mw_logger).toBool()); ui->showGameListAct->setChecked(guiSettings->GetValue(GUI::mw_gamelist).toBool()); ui->showDebuggerAct->setChecked(guiSettings->GetValue(GUI::mw_debugger).toBool()); ui->showToolBarAct->setChecked(guiSettings->GetValue(GUI::mw_toolBarVisible).toBool()); ui->showGameToolBarAct->setChecked(guiSettings->GetValue(GUI::gl_toolBarVisible).toBool()); m_debuggerFrame->setVisible(ui->showDebuggerAct->isChecked()); m_logFrame->setVisible(ui->showLogAct->isChecked()); m_gameListFrame->setVisible(ui->showGameListAct->isChecked()); m_gameListFrame->SetToolBarVisible(ui->showGameToolBarAct->isChecked()); ui->toolBar->setVisible(ui->showToolBarAct->isChecked()); RepaintToolbar(); ui->showCatHDDGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Non_Disc_Game)); ui->showCatDiscGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Disc_Game)); ui->showCatHomeAct->setChecked(guiSettings->GetCategoryVisibility(Category::Home)); ui->showCatAudioVideoAct->setChecked(guiSettings->GetCategoryVisibility(Category::Media)); ui->showCatGameDataAct->setChecked(guiSettings->GetCategoryVisibility(Category::Data)); ui->showCatUnknownAct->setChecked(guiSettings->GetCategoryVisibility(Category::Unknown_Cat)); ui->showCatOtherAct->setChecked(guiSettings->GetCategoryVisibility(Category::Others)); int idx = guiSettings->GetValue(GUI::gl_iconSize).toInt(); int index = GUI::gl_max_slider_pos / 4; if (idx < index) ui->setIconSizeTinyAct->setChecked(true); else if (idx < index * 2) ui->setIconSizeSmallAct->setChecked(true); else if (idx < index * 3) ui->setIconSizeMediumAct->setChecked(true); else ui->setIconSizeLargeAct->setChecked(true); bool isListMode = guiSettings->GetValue(GUI::gl_listMode).toBool(); if (isListMode) ui->setlistModeListAct->setChecked(true); else ui->setlistModeGridAct->setChecked(true); m_categoryVisibleActGroup->setEnabled(isListMode); if (configureAll) { // Handle log settings m_logFrame->LoadSettings(); // Gamelist m_gameListFrame->LoadSettings(); } } void main_window::keyPressEvent(QKeyEvent *keyEvent) { if (((keyEvent->modifiers() & Qt::AltModifier) && keyEvent->key() == Qt::Key_Return) || (isFullScreen() && keyEvent->key() == Qt::Key_Escape)) { ui->toolbar_fullscreen->trigger(); } if (keyEvent->modifiers() & Qt::ControlModifier) { switch (keyEvent->key()) { case Qt::Key_E: if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsReady()) Emu.Run(); return; case Qt::Key_P: if (Emu.IsRunning()) Emu.Pause(); return; case Qt::Key_S: if (!Emu.IsStopped()) Emu.Stop(); return; case Qt::Key_R: if (!Emu.GetPath().empty()) { Emu.Stop(); Emu.Run(); } return; } } } void main_window::mouseDoubleClickEvent(QMouseEvent *event) { if (isFullScreen()) { if (event->button() == Qt::LeftButton) { showNormal(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } } } /** Override the Qt close event to have the emulator stop and the application die. May add a warning dialog in future. */ void main_window::closeEvent(QCloseEvent* closeEvent) { Q_UNUSED(closeEvent); // Cleanly stop the emulator. Emu.Stop(); SaveWindowState(); // I need the gui settings to sync, and that means having the destructor called as guiSetting's parent is main_window. setAttribute(Qt::WA_DeleteOnClose); QMainWindow::close(); // It's possible to have other windows open, like games. So, force the application to die. QApplication::quit(); }<|fim▁end|>
scope_thread worker("PKG Installer", [&] { if (pkg_install(pkg_f, local_path + '/', progress, path))
<|file_name|>routermodelbase.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # rsak - Router Swiss Army Knife # Copyright (C) 2011 Pablo Castellano <[email protected]> # # This program is free software: you can redistribute it and/or modify<|fim▁hole|># This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class RouterModelBase: def login(self, user, passw): raise NotImplementedError def logout(self): raise NotImplementedError def guess(self): raise NotImplementedError def getClientsList(self): raise NotImplementedError def forwardPort(self): raise NotImplementedError def protocolsSupported(self): raise NotImplementedError<|fim▁end|>
# 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. #
<|file_name|>09-mock-timer.js<|end_file_name|><|fim▁begin|>export default (callback) => { setTimeout(() => { callback(); setTimeout(() => { callback(); }, 3000); }, 3000);<|fim▁hole|><|fim▁end|>
}
<|file_name|>bitcoin_fi.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="fi" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About MasterDoge</source> <translation>Tietoa MasterDogeista</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;MasterDoge&lt;/b&gt; version</source> <translation>&lt;b&gt;MasterDoge&lt;/b&gt;-asiakasohjelman versio</translation> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The MasterDoge developers</source> <translation>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The MasterDoge developers</translation> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:[email protected]&quot;&gt;[email protected]&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation> Tämä on kokeilukäyttöön suunnattua ohjelmistoa. Levitetään MIT/X11 ohjelmistolisenssin alaisuudessa. Tarkemmat tiedot löytyvät tiedostosta COPYING tai osoitteesta http://www.opensource.org/licenses/mit-license.php. Tämä tuote sisältää OpenSSL-projektin kehittämää ohjelmistoa OpenSSL-työkalupakettia varten (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;), Eric Youngin (&lt;a href=&quot;mailto:[email protected]&quot;&gt;[email protected]&lt;/a&gt;) kehittämän salausohjelmiston sekä Thomas Bernardin UPnP-ohjelmiston.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Osoitekirja</translation> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Kaksoisnapauta muokataksesi osoitetta tai nimikettä</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>Luo uusi osoite</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopioi valittu osoite järjestelmän leikepöydälle</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation>&amp;Uusi osoite</translation> </message> <message> <location line="-43"/> <source>These are your MasterDoge addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Nämä ovat MasterDoge-osoitteesi rahansiirtojen vastaanottoa varten. Jos haluat, voit antaa jokaiselle lähettäjälle oman osoitteen jotta voit pitää kirjaa sinulle rahaa siirtäneistä henkilöistä.</translation> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation>&amp;Kopioi osoite</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation>Näytä &amp;QR-koodi</translation> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a MasterDoge address</source> <translation>Allekirjoita viesti osoittaaksesi MasterDoge-osoitteesi omistajuus</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Allekirjoita &amp;Viesti</translation> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation>Poista valittu osoite listalta</translation> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified MasterDoge address</source> <translation>Vahvista viesti varmistaaksesi että kyseinen MasterDoge-osoitteesi on allekirjoittanut sen</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Varmista viesti</translation> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;Poista</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Kopioi &amp;nimike</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Muokkaa</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation>Vie osoitekirja</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Pilkuilla eroteltu tiedosto (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Virhe vietäessä</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ei voida kirjoittaa tiedostoon %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation>Nimike</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ei nimikettä)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Tunnuslauseikkuna</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Syötä tunnuslause</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Uusi tunnuslause</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Toista uusi tunnuslause uudelleen</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation>Tarjoaa estettäväksi yksinkertaisen rahansiirron kun käyttöjärjestelmän käyttäjätunnuksen turvallisuutta on rikottu. Tämä ei takaa aitoa turvallisuutta.</translation> </message> <message> <location line="+3"/> <source>For staking only</source> <translation>Vain osakkuutta varten</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation>Salaa lompakko</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy syöttää lompakon tunnuslause sen avaamiseksi.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Avaa lompakon lukitus</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause salauksen purkuun.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Pura lompakon salaus</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Vaihda tunnuslause</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Syötä vanha sekä uusi tunnuslause.</translation> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation>Vahvista, että lompakko salataan</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation>Varoitus: Jos salaat lompakkosi ja hukkaat salasanasi, &lt;b&gt;MENETÄT KAIKKI CRAVEISI&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Haluatko varmasti salata lompakkosi?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>TÄRKEÄÄ: Kaikki vanhat lompakon varmuuskopiot tulisi korvata uusilla suojatuilla varmuuskopioilla. Turvallisuussyistä edelliset varmuuskopiot muuttuvat käyttökelvottomiksi, kun aloitat uuden salatun lompakon käytön.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Varoitus: Caps Lock-näppäin on käytössä!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Lompakko salattu</translation> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Syötä uusi salasana lompakolle.&lt;br/&gt;Käytäthän salasanaa, joka sisältää &lt;b&gt;vähintään kymmenen täysin arvottua merkkiä&lt;/b&gt;, tai &lt;b&gt;vähintään kahdeksan sanaa&lt;/b&gt;.</translation> </message> <message> <location line="+82"/> <source>MasterDoge will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation>MasterDoge-ohjelma sulkee itsensä päättääkseen salauksen luonnin. Muista, että lompakon salaaminen ei täysin turvaa kolikoitasi haittaohjelmien aiheuttamien varkauksien uhalta.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Lompakon salauksen luonti epäonnistui</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Lompakon salaaminen epäonnistui sisäisen virheen vuoksi. Lompakkoasi ei salattu.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Syötetyt tunnuslauseet eivät täsmää.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Lompakon avaaminen epäonnistui.</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Syötetty tunnuslause lompakon salauksen purkua varten oli väärä.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Lompakon salauksen purku epäonnistui.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Lompakon tunnuslause vaihdettiin onnistuneesti.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation>Allekirjoita &amp;viesti...</translation> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation>Näytä lompakon yleiskatsaus</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Rahansiirrot</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Selaa rahansiirtohistoriaa</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation>&amp;Osoitekirja</translation> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation>Muokkaa tallennettujen osoitteiden ja nimikkeiden listaa</translation> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation>Näytä osoitelista vastaanottaaksesi maksuja</translation> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation>L&amp;opeta</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sulje asiakasohjelma</translation> </message> <message> <location line="+4"/> <source>Show information about MasterDoge</source> <translation>Näytä tietoja MasterDogeista</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Tietoa &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Näytä lisätietoa Qt:sta</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Asetukset...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Salaa lompakko...</translation> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Varmuuskopioi lompakko...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Vaihda tunnuslause...</translation> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation>&amp;Vie...</translation> </message> <message> <location line="-55"/> <source>Send coins to a MasterDoge address</source> <translation>Lähetä varoja MasterDoge-osoitteeseen</translation> </message> <message> <location line="+39"/> <source>Modify configuration options for MasterDoge</source> <translation>Mukauta asiakasohjelman asetuksia</translation> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation>Vie tämänhetkisen välilehden sisältö tiedostoon</translation> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation>Salaa lompakko tai pura salaus lompakosta</translation> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation>Varmuuskopioi lompakko toiseen sijaintiin</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Vaihda lompakon salaukseen käytettävä tunnuslause</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>&amp;Testausikkuna</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Avaa vianetsintä- ja diagnostiikkakonsoli</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Vahvista viesti...</translation> </message> <message> <location line="-214"/> <location line="+551"/> <source>MasterDoge</source> <translation>MasterDoge</translation> </message> <message> <location line="-551"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+193"/> <source>&amp;About MasterDoge</source> <translation>&amp;Tietoa MasterDogeista</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Näytä / Piilota</translation> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation>Avaa lompakon lukitus</translation> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation>&amp;Lukitse Lompakko</translation> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation>Lukitse lompakko</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Tiedosto</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Asetukset</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Apua</translation> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation>Välilehtipalkki</translation> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+58"/> <source>MasterDoge client</source> <translation>MasterDoge-asiakasohjelma</translation> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to MasterDoge network</source> <translation><numerusform>%n aktiivinen yhteys MasterDoge-verkkoon</numerusform><numerusform>%n aktiivista yhteyttä MasterDoge-verkkoon</numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation>Osakkaana.&lt;br&gt;Osuutesi on %1&lt;br&gt;Verkon osuus on %2&lt;br&gt;Odotettu aika palkkion ansaitsemiselle on %3</translation> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation>Ei osakkaana koska lompakko on lukittu</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation>Ei osakkaana koska lompakolla ei ole verkkoyhteyttä</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation>Ei osakkaana koska lompakko synkronoituu</translation> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation>Ei osakkaana koska sinulla ei ole kypsyneitä varoja</translation> </message> <message> <location line="-808"/> <source>&amp;Dashboard</source> <translation>&amp;Hallintapaneeli</translation> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation>&amp;Vastaanota</translation> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation>&amp;Lähetä</translation> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation>&amp;Aukaise lompakko</translation> </message> <message> <location line="+273"/> <source>Up to date</source> <translation>Rahansiirtohistoria on ajan tasalla</translation> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation>Saavutetaan verkkoa...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Hyväksy rahansiirtopalkkio</translation> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Rahansiirto toteutettu</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Saapuva rahansiirto</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Päivä: %1 Määrä: %2 Tyyppi: %3 Osoite: %4</translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation>URI-merkkijonojen käsittely</translation> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid MasterDoge address or malformed URI parameters.</source> <translation>URI-merkkijonoa ei voida jäsentää! Tämä voi johtua väärästä MasterDoge-osoitteesta tai väärässä muodossa olevista URI-parametreistä.</translation> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation>Lompakko &lt;b&gt;ei ole salattu&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;avoinna&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;lukittuna&lt;/b&gt;</translation> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation>Varmuuskopioi lompakkosi</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Lompakkotiedosto (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Varmuuskopion luonti epäonnistui</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Virhe yritettäessä tallentaa lompakkotiedostoa uuteen sijaintiinsa.</translation> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation><numerusform>%n sekunti</numerusform><numerusform>%n sekuntia</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation><numerusform>%n minuutti</numerusform><numerusform>%n minuuttia</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation><numerusform>%n tunti</numerusform><numerusform>%n tuntia</numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation>Käsitelty %1 lohkoa rahansiirtohistoriasta.</translation> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation><numerusform>%n päivä</numerusform><numerusform>%n päivää</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation><numerusform>%n viikko</numerusform><numerusform>%n viikko(a)</numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation>%1 ja %2</translation> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation><numerusform>%n vuosi</numerusform><numerusform>%n vuotta</numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation>%1 takana</translation> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation>Viimeinen vastaanotettu lohko luotiin %1 sitten.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Tämän jälkeen tapahtuneet rahansiirrot eivät ole vielä näkyvissä.</translation> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation>Ei osakkaana</translation> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. MasterDoge can no longer continue safely and will quit.</source> <translation>Virhe kohdattu. MasterDoge-asiakasohjelma ei voi enää jatkaa turvallisesti ja se suljetaan.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation>Ei verkkoyhteyttä</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation>Varojenhallinta</translation> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Määrä:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Tavua:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Prioriteetti:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Kulu:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Heikko ulosanti:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+552"/> <source>no</source> <translation>ei</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Rahansiirtopalkkion jälkeen:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Vaihtoraha:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(tai ei)Valitse kaikki</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Puunäkymä</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Listanäkymä</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation>Nimike</translation> </message> <message> <location line="+5"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Vahvistukset</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Vahvistettu</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Tärkeysjärjestys</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Kopioi osoite</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopioi nimi</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Kopioi siirtotunnus</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Kopioi kulu</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopioi kulun jälkeen</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopioi tavuja</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopioi prioriteetti</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Kopioi heikko ulosanti</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopioi vaihtoraha</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>korkein</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>korkea</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>keskikorkea</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>keski</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>keskimatala</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>matala</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>matalin</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation>PÖLYÄ</translation> </message> <message> <location line="+0"/> <source>yes</source> <translation>kyllä</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation>Tämä nimike muuttuu punaiseksi, jos rahansiirron koko on suurempi kuin 10000 tavua. Tämä tarkoittaa, että ainakin %1 rahansiirtopalkkio per kilotavu tarvitaan. Voi vaihdella välillä +/- 1 Tavu per syöte.</translation> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation>Suuremman prioriteetin rahansiirrot pääsevät suuremmalla todennäköisyydellä lohkoketjuun. Tämä nimike muuttuu punaiseksi, jos prioriteetti on pienempi kuin &quot;keskikokoinen&quot;. Tämä tarkoittaa, että ainakin %1 rahansiirtopalkkio per kilotavu tarvitaan.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation>Tämä nimike muuttuu punaiseksi, jos jokin asiakas saa pienemmän määrän kuin %1. Tämä tarkoittaa, että ainakin %2 rahansiirtopalkkio tarvitaan. Määrät alle 0.546 kertaa pienimmän rahansiirtokulun verran näytetään pölynä.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation>Tämä nimike muuttuu punaiseksi, jos vaihdos on pienempi kuin %1. Tämä tarkoittaa, että ainakin %2 rahansiirtopalkkio tarvitaan.</translation> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>vaihtoraha %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(vaihtoraha)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Muokkaa osoitetta</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Nimi</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Nimike joka on yhdistetty tässä osoitekirjassa olevan osoitteen kanssa</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Osoite</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Nimike joka on yhdistetty tässä osoitekirjassa olevan osoitteen kanssa. Tätä voidaan muuttaa vain lähetysosoitteille.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Uusi vastaanottava osoite</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Uusi lähettävä osoite</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Muokkaa vastaanottajan osoitetta</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Muokkaa lähtevää osoitetta</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Osoite &quot;%1&quot; on jo osoitekirjassa.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid MasterDoge address.</source> <translation>Syöttämäsi osoite &quot;%1&quot; ei ole hyväksytty MasterDoge-osoite.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Lompakkoa ei voitu avata.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Uuden avaimen luonti epäonnistui.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>MasterDoge-Qt</source> <translation>MasterDoge-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versio</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Kulutus:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>komentokehotteen asetukset</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Käyttäjärajapinnan asetukset</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Aseta kieli, esimerkiksi &quot;fi_FI&quot; (oletus: järjestelmän oma)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Käynnistä pienennettynä</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Näytä logo käynnistettäessä (oletus: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Asetukset</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Yleiset</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Vapaavalintainen rahansiirtopalkkio kilotavua kohden auttaa varmistamaan että rahansiirtosi käsitellään nopeasti. Suurin osa rahansiirroista on alle yhden kilotavun. Palkkiota 0.01 suositellaan.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Maksa rahansiirtopalkkio</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation>Varattu määrä ei vaadi osakkuutta jonka vuoksi se on mahdollista käyttää milloin tahansa.</translation> </message> <message> <location line="+15"/> <source>Reserve</source> <translation>Varattuna</translation> </message> <message> <location line="+31"/> <source>Automatically start MasterDoge after logging in to the system.</source> <translation>Käynnistä MasterDoge-asiakasohjelma automaattisesti kun olet kirjautunut järjestelmään.</translation> </message> <message> <location line="+3"/> <source>&amp;Start MasterDoge on system login</source> <translation>%Käynnistä MasterDoge-asiakasohjelma kirjautuessasi</translation> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Verkko</translation> </message> <message> <location line="+6"/> <source>Automatically open the MasterDoge client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Avaa MasterDoge-asiakkaalle automaattisesti portti reitittimestä. Tämä toimii vain, kun reitittimesi tukee UPnP:tä ja se on aktivoituna.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portin uudelleenohjaus käyttäen &amp;UPnP:a</translation> </message> <message> <location line="+7"/> <source>Connect to the MasterDoge network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Yhdistä MasterDoge-verkkoon SOCKS-välityspalvelimen lävitse. (esim. yhdistettäessä Tor:n kautta).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Yhdistä SOCKS-välityspalvelimen läpi:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxyn &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Välityspalvelimen IP-osoite (esim. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Portti</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Välityspalvelimen portti (esim. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versio:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Välityspalvelimen SOCKS-versio (esim. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Ikkuna</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Näytä ainoastaan ilmaisinalueella ikkunan pienentämisen jälkeen.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Pienennä ilmaisinalueelle työkalurivin sijasta</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Pienennä ilmaisinalueelle lopettamatta itse ohjelmaa suljettaessa. Kun tämä asetus on valittuna, ohjelman voi sulkea vain valitsemalla Lopeta ohjelman valikosta.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>P&amp;ienennä suljettaessa</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Näytä</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Käyttöliittymän &amp;kieli:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting MasterDoge.</source> <translation>Käyttöliittymän kieli voidaan valita tästä. Tämä asetus tulee voimaan vasta MasterDoge-asiakasohjelman uudelleenkäynnistyksen jälkeen.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Yksikkö, jossa määrät näytetään:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Valitse mitä yksikköä käytetään ensisijaisesti käyttöliittymässä ja varojen siirrossa määrien näyttämiseen.</translation> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation>Näytä tai piilota rahanhallinnan ominaisuudet.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation>Näytä rahan&amp;hallinnan ominaisuudet (Vain kokeneille käyttäjille!)</translation> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation>Valitaanko kolikot sattumanvaraisesti vai pienimmän kolikon iän mukaan.</translation> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation>Minimoi painoarvon menekki (kokeellinen)</translation> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation>Käytä teemana mustaa ulkoasua (vaatii uudelleenkäynnistyksen)</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Peruuta</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>%Käytä</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>oletus</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation>Varoitus</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting MasterDoge.</source> <translation>Tämä asetus tulee voimaan vasta MasterDoge-asiakasohjelman uudelleenkäynnistyksen jälkeen.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Syötetty välityspalvelmen osoite on epäkelpo.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Lomake</translation> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the MasterDoge network after a connection is established, but this process has not completed yet.</source> <translation>Näytettävät tiedot voivat olla vanhentuneet. Lompakkosi synkronoituu automaattisesti MasterDoge-verkon kanssa kun yhteys on muodostettu, mutta tätä prosessia ei ole viety vielä päätökseen.</translation> </message> <message> <location line="-173"/> <source>Stake:</source> <translation>Osuus:</translation> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation>Vahvistamatonta:</translation> </message> <message> <location line="-113"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation>Käytettävissä:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Käytettävissä olevat varat:</translation> </message> <message> <location line="+80"/> <source>Immature:</source> <translation>Epäkypsää:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Louhittu saldo, joka ei ole vielä kypsynyt</translation> </message> <message> <location line="+23"/> <source>Total:</source> <translation>Yhteensä:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Tämänhetkinen kokonaissaldosi</translation> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Viimeisimmät rahansiirrot&lt;/b&gt;</translation> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Kaikki vahvistamattomat rahansiirrot yhteensä, joita ei vielä ole laskettu saldoosi.</translation> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation>Osuutena olleiden varojen kokonaismäärä, jotka eivät vielä ole laskettu tämänhetkiseen saldoon.</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>ei ajan tasalla</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start masterdoge: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-koodi-ikkuna</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Pyydä rahansiirtoa</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Nimike:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Viesti:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>%Tallenna nimellä...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Virhe koodatessa linkkiä QR-koodiin.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Syötetty määrä on epäkelpoinen; tarkista.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Tuloksena liian pitkä URI, yritä lyhentää nimikkeen tai viestin pituutta.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Tallenna QR-koodi</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-kuvat (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Asiakasohjelman nimi</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation>Ei saatavilla</translation> </message> <message> <location line="-194"/> <source>Client version</source> <translation>Asiakasohjelman versio</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Tietoa</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Käyttää OpenSSL-versiota</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Käynnistysaika</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Verkko</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Yhteyksien lukumäärä</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Testiverkossa</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lohkoketju</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Tämänhetkinen lohkojen määrä</translation> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation>&amp;Verkon liikenne</translation> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation>&amp;Tyhjennä</translation> </message> <message> <location line="+13"/> <source>Totals</source> <translation>Yhteensä</translation> </message> <message> <location line="+64"/> <source>In:</source> <translation>Sisään:</translation> </message> <message> <location line="+80"/> <source>Out:</source> <translation>Ulos:</translation> </message> <message> <location line="-383"/> <source>Last block time</source> <translation>Viimeisimmän lohkon aika</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Avaa</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Komentokehotteen ominaisuudet</translation> </message> <message> <location line="+7"/> <source>Show the MasterDoge-Qt help message to get a list with possible MasterDoge command-line options.</source> <translation>Näytä MasterDoge-Qt:n avustusohje saadaksesi listan käytettävistä MasterDogein komentokehotteen määritteistä.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Näytä</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsoli</translation> </message> <message> <location line="-237"/> <source>Build date</source> <translation>Koontipäivämäärä</translation> </message> <message> <location line="-104"/> <source>MasterDoge - Debug window</source> <translation>MasterDoge - Debug-ikkuna</translation> </message> <message> <location line="+25"/> <source>MasterDoge Core</source> <translation>MasterDogein ydin</translation> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation>Debug-lokitiedosto</translation> </message> <message> <location line="+7"/> <source>Open the MasterDoge debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Avaa MasterDoge-asiakasohjelman debug-lokitiedosto nykyisestä hakemistostaan. Tämä voi kestää muutaman sekunnin avattaessa suuria lokitiedostoja.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Tyhjennä konsoli</translation> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the MasterDoge RPC console.</source> <translation>Tervetuloa MasterDogein RPC-konsoliin.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Ylös- ja alas-nuolet selaavat historiaa ja &lt;b&gt;Ctrl-L&lt;/b&gt; tyhjentää ruudun.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Kirjoita &lt;b&gt;help&lt;/b&gt; nähdäksesi yleiskatsauksen käytettävissä olevista komennoista.</translation> </message> <message> <location line="+127"/> <source>%1 B</source> <translation>%1 t</translation> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation>%1 Kt</translation> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation>%1 Mt</translation> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation>%1 Gt</translation> </message> <message> <location line="+7"/> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <location line="+5"/> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation>%1 h %2 m</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+181"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Lähetä MasterDogeeja</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Varojenhallinnan ominaisuudet</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Syötteet...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>automaattisesti valittu</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Ei tarpeeksi varoja!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Määrä:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation>0</translation> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Tavua:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 MDOGE</source> <translation>123.456 MDOGE {0.00 ?}</translation> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Prioriteetti:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation>keskikokoinen</translation> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Kulu:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Heikko ulosanti:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation>ei</translation> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Kulujen jälkeen:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation>Vaihtoraha</translation> </message> <message> <location line="+50"/> <source>custom change address</source> <translation>erikseen määritetty vaihtorahaosoite</translation> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Lähetä monelle vastaanottajalle samanaikaisesti</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Lisää &amp;vastaanottaja</translation> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation>Tyhjennä kaikki rahansiirtokentät</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Tyhjennnä &amp;kaikki</translation> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 MDOGE</source> <translation>123.456 MDOGE</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Hyväksy lähetystoiminto</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>L&amp;ähetä</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a MasterDoge address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Syötä MasterDoge-osoite (esim. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Kopioi rahansiirtokulu</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopioi rahansiirtokulun jälkeen</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopioi tavuja</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopioi prioriteetti</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Kopioi heikko ulosanti</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopioi vaihtoraha</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt;:sta %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Hyväksy varojen lähettäminen</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Oletko varma että haluat lähettää %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>ja</translation> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Vastaanottajan osoite on virheellinen. Tarkista uudelleen.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Maksettavan summan tulee olla suurempi kuin 0 Bitcoinia.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Määrä ylittää käytettävissä olevan saldon.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Kokonaismäärä ylittää saldosi kun %1 maksukulu lisätään summaan.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Sama osoite toistuu useamman kerran. Samaan osoitteeseen voi lähettää vain kerran per maksu.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Virhe: Rahansiirto evätty. Tämä voi tapahtua kun jotkut kolikot lompakossasi ovat jo käytetty, kuten myös tilanteessa jos käytit wallet.dat-tiedoston kopiota ja rahat olivat käytetty kopiossa, mutta eivät ole merkitty käytetyiksi tässä.</translation> </message> <message> <location line="+247"/> <source>WARNING: Invalid MasterDoge address</source> <translation>VAROITUS: Epäkelpo MasterDoge-osoite</translation> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation>VAROITUS: Tuntematon vaihtorahaosoite</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Kaavake</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>M&amp;äärä:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Maksun &amp;saaja:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Anna nimike tälle osoitteelle, jos haluat lisätä sen osoitekirjaasi</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Nimike:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Valitse osoite osoitekirjasta</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Poista tämä vastaanottaja</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a MasterDoge address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Syötä MasterDoge-osoite (esim. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Allekirjoitukset - Allekirjoita / Varmista viesti</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Allekirjoita viesti</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Voit allekirjoittaa viestit omalla osoitteellasi todistaaksesi että omistat ne. Ole huolellinen, ettet allekirjoita mitään epämääräistä, sillä phishing-hyökkääjät voivat yrittää huijata sinua allekirjoittamaan henkilöllisyytesi heidän hyväksi. Allekirjoita vain se, mihin olet sitoutunut.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Osoite, jolle viesti kirjataan (esim. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation>Valitse osoite osoitekirjasta</translation> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Kirjoita viesti jonka haluat allekirjoittaa</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopioi tämänhetkinen allekirjoitus järjestelmän leikepöydälle</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this MasterDoge address</source> <translation>Allekirjoita viesti vahvistaaksesi, että omistat tämän MasterDoge-osoitteen</translation> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Tyhjennä kaikki kentät allekirjoituksesta</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Tyhjennä &amp;kaikki</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Varmista viesti</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Syötä allekirjoittava osoite, viesti ja allekirjoitus alla oleviin kenttiin varmistaaksesi allekirjoituksen aitouden. Varmista että kopioit kaikki kentät täsmälleen oikein, myös rivinvaihdot, välilyönnit, tabulaattorit, jne.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Osoite, jolla viesti on allekirjoitettu (esim. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i) </translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified MasterDoge address</source> <translation>Vahvista viesti varmistaaksesi että se on allekirjoitettu kyseisellä MasterDoge-osoitteella</translation> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Tyhjennä kaikki varmista-viesti-kentät</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a MasterDoge address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Syötä MasterDoge-osoite (esim. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klikkaa &quot;Allekirjoita Viesti luodaksesi allekirjoituksen </translation> </message> <message> <location line="+3"/> <source>Enter MasterDoge signature</source> <translation>Syötä MasterDoge-allekirjoitus</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Syötetty osoite on virheellinen.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Tarkista osoite ja yritä uudelleen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Syötetty osoite ei täsmää avaimeen.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Lompakon avaaminen peruttiin.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Yksityistä avainta syötetylle osoitteelle ei ole saatavilla.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Viestin allekirjoitus epäonnistui.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Viesti allekirjoitettu.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Allekirjoitusta ei pystytty tulkitsemaan.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Tarkista allekirjoitus ja yritä uudelleen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Allekirjoitus ei täsmää viestin yhteenvetoon.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Viestin vahvistaminen epäonnistui.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Viesti vahvistettu.</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation>Kt/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation>törmännyt</translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/vahvistamaton</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 vahvistusta</translation> </message> <message> <location line="+17"/> <source>Status</source> <translation>Tila</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>lähetetty %n noodin läpi</numerusform><numerusform>lähetetty %n solmukohdan läpi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Lähde</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Luotu</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Lähettäjä</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Saaja</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>oma osoite</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>nimike</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>kypsyy %n lohkon kuluttua</numerusform><numerusform>kypsyy %n lohkon kuluttua</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>ei hyväksytty</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debit</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Rahansiirtopalkkio</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Viesti</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Kommentti</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Siirtotunnus</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Luotujen kolikoiden on eräännyttävä 510 lohkon ajan ennenkuin niitä voidaan käyttää. Kun loit tämän lohkon, se oli lähetetty verkkoon lohkoketjuun lisättäväksi. Jos lohkon siirtyminen ketjuun epäonnistuu, tilaksi muuttuu &quot;ei hyväksytty&quot; ja sillon sitä ei voida käyttää. Tämä voi tapahtua joskus jos toinen verkon noodi luo lohkon muutaman sekunnin sisällä luodusta lohkostasi.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Debug-tietoa</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Rahansiirto</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Sisääntulot</translation> </message> <message> <location line="+21"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>tosi</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>epätosi</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ei ole vielä onnistuneesti lähetetty</translation> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation><numerusform>Avoinna vielä %n lohko</numerusform><numerusform>Avoinna vielä %n lohkolle</numerusform></translation> </message> <message> <location line="+71"/> <source>unknown</source> <translation>tuntematon</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Rahansiirron yksityiskohdat</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Tämä ikkuna näyttää yksityiskohtaiset tiedot rahansiirrosta</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation>Auki kunnes %1 </translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Vahvistettu (%1 vahvistusta)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Avoinna %n lohkolle</numerusform><numerusform>Avoinna %n lohkolle</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>Offline-tila</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Vahvistamaton</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Vahvistetaan (%1 %2:sta suositellusta vahvistuksesta)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>Törmännyt</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Ei vahvistettu (%1 vahvistusta, on saatavilla %2:n jälkeen)</translation> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tätä lohkoa ei vastaanotettu mistään muusta solmusta ja sitä ei mahdollisesti hyväksytä!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generoitu mutta ei hyväksytty</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Vastaanotettu</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Maksu itsellesi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(ei saatavilla)</translation> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Rahansiirron tila. Siirrä osoitin kentän päälle nähdäksesi vahvistusten lukumäärä.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Rahansiirron vastaanottamisen päivämäärä ja aika.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Rahansiirron laatu.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Rahansiirron kohteen Bitcoin-osoite</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Saldoon lisätty tai siitä vähennetty määrä.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation>Kaikki</translation> </message> <message> <location line="-16"/> <source>Today</source> <translation>Tänään</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Tällä viikolla</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Tässä kuussa</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Viime kuussa</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Tänä vuonna</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Alue...</translation> </message> <message> <location line="+12"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Itsellesi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Muu</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Anna etsittävä osoite tai tunniste</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimimäärä</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopioi osoite</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopioi nimi</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopioi rahansiirron ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Muokkaa nimeä</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Näytä rahansiirron yksityiskohdat</translation> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation>Vie tiedot rahansiirrosta</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Vahvistettu</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Aika</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Virhe vietäessä</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ei voida kirjoittaa tiedostoon %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Alue:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>kenelle</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+208"/> <source>Sending...</source> <translation>Lähetetään...</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+173"/> <source>MasterDoge version</source> <translation>MasterDogein versio</translation> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or masterdoged</source> <translation>Syötä komento kohteeseen -server tai masterdoged</translation> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista komennoista</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Hanki apua käskylle</translation> </message> <message> <location line="-147"/> <source>Options:</source> <translation>Asetukset:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: masterdoge.conf)</source> <translation>Määritä asetustiedosto (oletus: masterdoge.conf)</translation> </message> <message> <location line="+1"/> <source>Specify pid file (default: masterdoged.pid)</source> <translation>Määritä prosessitiedosto (oletus: masterdoge.pid)</translation> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Määritä lompakkotiedosto (datahakemiston sisällä)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Määritä datahakemisto</translation> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=masterdogerpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;MasterDoge Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation>Aseta tietokannan lokien maksimikoko megatavuissa (oletus: 100)</translation> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation>Kuuntele yhteyksiä portissa &lt;port&gt; (oletus: 15714 tai testiverkko: 25714)</translation> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Pidä enintään &lt;n&gt; yhteyttä verkkoihin (oletus: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Yhdistä solmukohtaan hakeaksesi vertaistesi osoitteet ja sen jälkeen katkaise yhteys</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Määritä julkinen osoitteesi</translation> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation>Liitä annettuun osoitteeseen. Käytä [host]:port merkintää IPv6:lle</translation> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation>Pyydä vertaistesi osoitteita DNS-kyselyn avulla jos osoitteita on vähän (oletus: 1 jos ei -connect)</translation> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation>Pyydä aina vertaistesi osoitteita DNS-kyselyn avulla (oletus: 0)</translation> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Kynnysarvo irtautumiselle epäilyttävistä vertaisista (oletus: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekunteina aika, kuinka kauan estetään epäilyttävien vertaisten uudelleenyhdistysyritykset (oletus: 86400)</translation> </message> <message> <location line="-37"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Virhe avattaessa RPC-porttia %u kuunneltavaksi IPv4-osoitteessa: %s</translation> </message> <message> <location line="+65"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation>Kuuntele JSON-RPC-yhteyksiä portissa &lt;port&gt; (oletus: 15715 tai testiverkko: 25715)</translation> </message> <message> <location line="-17"/> <source>Accept command line and JSON-RPC commands</source> <translation>Hyväksy merkkipohjaiset- ja JSON-RPC-käskyt</translation> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation>Aja taustalla daemonina ja vastaanota komentoja</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Käytä testiverkkoa</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Hyväksy yhteydet ulkomaailmasta (vakioasetus: 1 jos -proxy tai -connect ei ole määritetty)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Virhe kohdattu määritettäessä RPC-porttia %u IPv6-osoitteelle, palataan takaisin IPv4:n käyttöön: %s</translation> </message> <message> <location line="+96"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Aseta suurin mahdollinen koko korkean prioriteetin/pienen siirtokulun rahansiirroille tavuina (oletus: 27000)</translation> </message> <message> <location line="+12"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Varoitus: -paytxfee on asetettu erittäin korkeaksi! Tämä on maksukulu jonka tulet maksamaan kun lähetät siirron.</translation> </message> <message> <location line="-103"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong MasterDoge will not work properly.</source> <translation>Varoitus: Tarkista, että tietokoneesi aika ja päivämäärä ovat oikeassa! Jos kellosi on väärässä, MasterDoge ei toimi oikein.</translation> </message> <message> <location line="+132"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Varoitus: Virhe luettaessa wallet.dat-tiedostoa! Kaikki avaimet luettiin oikein, mutta rahansiirtodata tai osoitekirjan kentät voivat olla puuttuvat tai väärät.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Varoitus: wallet.dat-tiedosto on korruptoitunut, data pelastettu! Alkuperäinen wallet.dat on tallennettu nimellä wallet.{aikaleima}.bak kohteeseen %s; Jos saldosi tai rahansiirrot ovat väärät, sinun tulee palauttaa lompakko varmuuskopiosta.</translation> </message> <message> <location line="-31"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Yritetään palauttaa yksityisiä salausavaimia korruptoituneesta wallet.dat-tiedostosta</translation> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation>Lohkon luonnin asetukset:</translation> </message> <message> <location line="-69"/> <source>Connect only to the specified node(s)</source> <translation>Yhdistä vain määritettyihin solmukohtiin</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Paljasta oma IP-osoite (vakioasetus: 1 kun kuuntelemassa ja ei -externalip)</translation> </message> <message> <location line="+101"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Kuuntelu ei onnistunut missään portissa. Käytä -listen=0 jos haluat tätä.</translation> </message> <message> <location line="-91"/> <source>Sync checkpoints policy (default: strict)</source> <translation>Synkronoi tallennuspisteiden käytännöt (oletus: strict)</translation> </message> <message> <location line="+89"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Epäkelpo -tor-osoite: &apos;%s&apos;</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation>Epäkelpo määrä -reservebalance=&lt;amount&gt;</translation> </message> <message> <location line="-88"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Suurin vastaanottopuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Suurin lähetyspuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 1000)</translation> </message> <message> <location line="-17"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Yhdistä vain solmukohtiin verkossa &lt;net&gt; (IPv4, IPv6 tai Tor)</translation> </message> <message> <location line="+31"/> <source>Prepend debug output with timestamp</source><|fim▁hole|> <message> <location line="+41"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL asetukset (katso Bitcoin Wikistä tarkemmat SSL ohjeet)</translation> </message> <message> <location line="-81"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Valitse SOCKS-välityspalvelimen versio (4-5, oletus 5)</translation> </message> <message> <location line="+42"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Lähetä jäljitys/debug-tieto konsoliin, debug.log-tiedoston sijaan</translation> </message> <message> <location line="+5"/> <source>Send trace/debug info to debugger</source> <translation>Lähetä debug-tuloste kehittäjille</translation> </message> <message> <location line="+30"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Aseta lohkon maksimikoko tavuissa (oletus: 250000)</translation> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Asetan pienin lohkon koko tavuissa (vakioasetus: 0)</translation> </message> <message> <location line="-35"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Pienennä debug.log tiedosto käynnistyksen yhteydessä (vakioasetus: 1 kun ei -debug)</translation> </message> <message> <location line="-43"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Määritä yhteyden aikakataisu millisekunneissa (vakioasetus: 5000)</translation> </message> <message> <location line="+116"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation>Ei voitu kirjata tallennuspistettä, väärä checkpointkey? </translation> </message> <message> <location line="-86"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 1 kun kuuntelemassa)</translation> </message> <message> <location line="-26"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Käytä välityspalvelinta saavuttaaksesi tor:n piilotetut palvelut (oletus: sama kuin -proxy)</translation> </message> <message> <location line="+47"/> <source>Username for JSON-RPC connections</source> <translation>Käyttäjätunnus JSON-RPC-yhteyksille</translation> </message> <message> <location line="+51"/> <source>Verifying database integrity...</source> <translation>Tarkistetaan tietokannan eheyttä...</translation> </message> <message> <location line="+44"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation>VAROITUS: synkronoidun tallennuspisteen rikkomista havaittu, mutta ohitettu!</translation> </message> <message> <location line="-1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Varoitus: Tämä versio on vanhentunut, päivitys tarpeen!</translation> </message> <message> <location line="-54"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat on korruptoitunut, pelastusyritys epäonnistui</translation> </message> <message> <location line="-56"/> <source>Password for JSON-RPC connections</source> <translation>Salasana JSON-RPC-yhteyksille</translation> </message> <message> <location line="-32"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation>Synkronoi kellonaika muiden solmukohtien kanssa. Poista käytöstä, jos järjestelmäsi aika on tarkka esim. päivittää itsensä NTP-palvelimelta. (oletus: 1)</translation> </message> <message> <location line="+13"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation>Rahansiirtoja luodessa jätä huomioimatta syötteet joiden arvo on vähemmän kuin tämä (oletus: 0.01)</translation> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Salli JSON-RPC yhteydet tietystä ip-osoitteesta</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Lähetä käskyjä solmuun osoitteessa &lt;ip&gt; (oletus: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Suorita käsky kun paras lohko muuttuu (%s cmd on vaihdettu block hashin kanssa)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Suorita komento kun lompakon rahansiirrossa muutoksia (%s komennossa on korvattu TxID:llä)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation>Vaadi vaihtorahalle vahvistus (oletus: 0)</translation> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Suorita komento kun olennainen varoitus on saatu (%s komennossa korvattu viestillä)</translation> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Päivitä lompakko uusimpaan formaattiinsa</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Aseta avainpoolin koko arvoon &lt;n&gt; (oletus: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Skannaa uudelleen lohkoketju lompakon puuttuvien rahasiirtojen vuoksi</translation> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation>Kuinka perusteellisesti lohko vahvistetaan (0-6, oletus: 1)</translation> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation>Tuo lohkoja erillisestä blk000?.dat-tiedostosta</translation> </message> <message> <location line="+9"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Käytä OpenSSL-protokollaa (https) JSON-RPC-yhteyksille</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Palvelimen sertifikaattitiedosto (oletus: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Palvelimen yksityisavain (oletus: server.pem)</translation> </message> <message> <location line="+10"/> <source>Initialization sanity check failed. MasterDoge is shutting down.</source> <translation>Käyttöönottotarkistus epäonnistui. MasterDoge-asiakasohjelma suljetaan.</translation> </message> <message> <location line="+50"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation>Virhe: Lompakko avattu vain osakkuutta varten, rahansiirtoja ei voida luoda.</translation> </message> <message> <location line="+17"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Tämä on esijulkaistu testikäännös - käytä omalla vastuulla - älä käytä louhintaan tai kaupankäyntisovellutuksiin</translation> </message> <message> <location line="+3"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation>VAROITUS: Epäkelpo tarkistuspiste löydetty! Ilmoitetut varojensiirrot eivät välttämättä pidä paikkaansa! Sinun täytyy päivittää asiakasohjelma tai ilmoittaa kehittäjille ongelmasta.</translation> </message> <message> <location line="-174"/> <source>This help message</source> <translation>Tämä ohjeviesti</translation> </message> <message> <location line="+104"/> <source>Wallet %s resides outside data directory %s.</source> <translation>Lompakko %s on datahakemiston %s ulkopuolella.</translation> </message> <message> <location line="+37"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kytkeytyminen %s tällä tietokonella ei onnistu (kytkeytyminen tulosti virheen %d, %s)</translation> </message> <message> <location line="-133"/> <source>Connect through socks proxy</source> <translation>Yhdistä SOCKS-välityspalvelimen lävitse</translation> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Salli DNS kyselyt -addnode, -seednode ja -connect yhteydessä</translation> </message> <message> <location line="+126"/> <source>Loading addresses...</source> <translation>Ladataan osoitteita...</translation> </message> <message> <location line="-12"/> <source>Error loading blkindex.dat</source> <translation>Virhe ladattaessa blkindex.dat-tiedostoa</translation> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko vioittunut</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of MasterDoge</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko tarvitsee uudemman version MasterDoge-asiakasohjelmasta</translation> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart MasterDoge to complete</source> <translation>Lompakko on kirjoitettava uudelleen: käynnistä MasterDoge-asiakasohjelma uudelleen päättääksesi toiminnon</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Epäkelpo välityspalvelimen osoite: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Tuntematon verkko -onlynet parametrina: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Tuntematonta -SOCKS-versiota pyydettiin: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>-bind osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>-externalip osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="-23"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-paytxfee=&lt;amount&gt;: &apos;%s&apos; on virheellinen</translation> </message> <message> <location line="+60"/> <source>Sending...</source> <translation>Lähetetään...</translation> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Virheellinen määrä</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Ei tarpeeksi varoja</translation> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation>Ladataan lohkoindeksiä...</translation> </message> <message> <location line="-110"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Linää solmu mihin liittyä pitääksesi yhteyden auki</translation> </message> <message> <location line="+125"/> <source>Unable to bind to %s on this computer. MasterDoge is probably already running.</source> <translation>Ei voitu liittää %s tällä tietokoneella. MasterDoge-asiakasohjelma on jo ehkä päällä.</translation> </message> <message> <location line="-101"/> <source>Fee per KB to add to transactions you send</source> <translation>Rahansiirtopalkkio kilotavua kohden lähetettäviin rahansiirtoihisi</translation> </message> <message> <location line="+34"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation>Minimoi painoarvon menekki (kokeellinen) (oletus: 0)</translation> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Keep at most &lt;n&gt; unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Epäkelpo määrä parametrille -mininput=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. MasterDoge is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Loading wallet...</source> <translation>Ladataan lompakkoa...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Ei voida päivittää lompakkoasi vanhempaan versioon</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Oletusosoitetta ei voi kirjoittaa</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Haetaan uudelleen...</translation> </message> <message> <location line="+2"/> <source>Done loading</source> <translation>Ladattu</translation> </message> <message> <location line="-161"/> <source>To use the %s option</source> <translation>Käyttääksesi %s vaihtoehtoa</translation> </message> <message> <location line="+188"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location line="-18"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Sinun täytyy asettaa rpcpassword=&lt;password&gt; asetustiedostoon: %s Jos tiedostoa ei ole, luo se sisältäen omistajan kirjoitusoikeudet.</translation> </message> </context> </TS><|fim▁end|>
<translation>Lisää debug-tulosteiden alkuun aikaleimat</translation> </message>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/** * App routes. */ var homepage = require('./homepage'); var user = require('./user'); var news = require('./news'); var test = require('./test'); var passport = require('passport'); function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } req.flash('error', '抱歉,您尚未登录。'); return res.redirect('/user/signin?redirect=' + req.path); } function ensureAdmin(req, res, next) { if (req.isAuthenticated() && req.user.isadmin) { return next(); } req.flash('error', '抱歉,您不是管理员。'); return res.redirect('/user/signin?redirect=' + req.path); } function ensurePermission(req, res, next) { if (req.isAuthenticated() && req.user.isadmin) { return next(); } if (req.isAuthenticated() &&<|fim▁hole|> { return next(); } req.flash('error', '抱歉,您没有权限。'); return res.redirect('/user/signin?redirect=' + req.path); } module.exports = function(app) { app.get('/', homepage.index); app.get('/user', ensureAdmin, user.showList); app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList); app.get('/user/register', user.showRegister); app.post('/user/register', user.doRegister); app.get('/user/signin', user.showSignin); app.post('/user/signin', passport.authenticate('local', { successRedirect: '/', successFlash: '登录成功,欢迎回来。', failureRedirect: 'back', failureFlash: '抱歉,手机号或密码错误。', })); app.get('/user/signout', user.doSignout); app.get('/user/:id(\\d{8,13})/edit', ensurePermission, user.showEditUser); app.post('/user/:id(\\d{8,13})/edit', ensurePermission, user.doEditUser); app.get('/user/:id(\\d{8,13})/setadmin', ensureAdmin, user.setAdmin); app.get('/news', news.showList); app.get('/news/page/:page(\\d+)', news.showList); app.get('/news/:id(\\d+)', news.showItem); app.get('/news/:id(\\d+)/edit', ensureAdmin, news.showEditItem); app.post('/news/:id(\\d+)/edit', ensureAdmin, news.doEditItem); app.get('/news/:id(\\d+)/delete', ensureAdmin, news.doDeleteItem); app.get('/news/post', ensureAdmin, news.showNewItem); app.post('/news/post', ensureAdmin, news.doNewItem); app.get('/test', test); app.get('*', function(req, res){ return res.render('homepage', {title: '404'}); }); }<|fim▁end|>
req.user.username == req.params.id)
<|file_name|>ThemeBuilder.tsx<|end_file_name|><|fim▁begin|>import { ReactElement } from "react"; import { Grid } from "@react-md/utils"; import scssVariables from "@react-md/theme/dist/scssVariables"; import { useTheme } from "components/Theme"; import ThemeConfiguration from "./ThemeConfiguration"; import Preview from "./Preview"; import ThemeUsage from "./ThemeUsage"; import styles from "./ThemeBuilder.module.scss"; export default function ThemeBuilder(): ReactElement { const { primary, secondary, accent, theme } = useTheme(); const primaryName = `rmd-${primary}-500` as "rmd-teal-500";<|fim▁hole|> return ( <Grid desktopColumns={2} columns={1} className={styles.container}> <ThemeConfiguration primary={primary} secondary={secondary} accent={accent} theme={theme} primaryColor={primaryColor} secondaryColor={secondaryColor} /> <Preview /> <ThemeUsage primary={primary} secondary={secondary} accent={accent} theme={theme} /> </Grid> ); }<|fim▁end|>
const primaryColor = scssVariables[primaryName]; const secondaryName = `rmd-${secondary}-a-${accent}` as "rmd-pink-a-200"; const secondaryColor = scssVariables[secondaryName];
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>/** * @author gyb(mocheer) * @email [email protected] * @since 2017.3.16 */ /// <reference path="tree.d.ts" /> declare var $: T; declare var ACTION_INIT: 'init';<|fim▁hole|>declare var GET: 'GET'; declare var POST: 'POST'; declare var PI, max, min, floor, ceil, random;<|fim▁end|>
declare var ACTION_LOAD: 'load'; declare var ACTION_SUSPEND: 'suspend'; declare var ACTION_RESUME: 'resume';
<|file_name|>ricoLocale_ua.js<|end_file_name|><|fim▁begin|>/***************************************************************** Page : ricoLocale_ua.js Description : ukrainian localization strings Version 0.1 (revisions by Alexey Uvarov,Illiya Gannitskiy) If you would like to include translations for another language, please send them to [email protected] ******************************************************************/<|fim▁hole|> RicoTranslate.addPhraseId('bookmarkExact',"Перегляд записів $1 - $2 з $3"); RicoTranslate.addPhraseId('bookmarkAbout',"Перегляд записів $1 - $2 з більш ніж $3"); RicoTranslate.addPhraseId('bookmarkNoRec',"Немає записів"); RicoTranslate.addPhraseId('bookmarkNoMatch',"Немає збігів"); RicoTranslate.addPhraseId('bookmarkLoading',"Завантаження..."); RicoTranslate.addPhraseId('sorting',"Сортування..."); RicoTranslate.addPhraseId('exportStatus',"Експортується запис $1"); RicoTranslate.addPhraseId('filterAll',"(всі)"); RicoTranslate.addPhraseId('filterBlank',"(чистий)"); RicoTranslate.addPhraseId('filterEmpty',"(порожній)"); RicoTranslate.addPhraseId('filterNotEmpty',"(не порожній)"); RicoTranslate.addPhraseId('filterLike',"як: $1"); RicoTranslate.addPhraseId('filterNot',"не: $1"); RicoTranslate.addPhraseId('requestError',"Запит даних повернув помилку:\n$1"); RicoTranslate.addPhraseId('keywordPrompt',"Шукати по ключу (Використовуйте * для всіх записів):"); // used in ricoLiveGridMenu.js RicoTranslate.addPhraseId('gridmenuSortBy',"Сортування по: $1"); RicoTranslate.addPhraseId('gridmenuSortAsc',"Зростаюча"); RicoTranslate.addPhraseId('gridmenuSortDesc',"Убутна"); RicoTranslate.addPhraseId('gridmenuFilterBy',"Фільтрація по: $1"); RicoTranslate.addPhraseId('gridmenuRefresh',"Обновити"); RicoTranslate.addPhraseId('gridmenuChgKeyword',"Змінити ключове слово..."); RicoTranslate.addPhraseId('gridmenuExcludeAlso',"Виключити також це значення"); RicoTranslate.addPhraseId('gridmenuInclude',"Включити тільки це значення"); RicoTranslate.addPhraseId('gridmenuGreaterThan',"Більше або дорівнює даному значенню"); RicoTranslate.addPhraseId('gridmenuLessThan',"Менше або дорівнює даному значенню"); RicoTranslate.addPhraseId('gridmenuContains',"Містить значення..."); RicoTranslate.addPhraseId('gridmenuExclude',"Виключити це значення"); RicoTranslate.addPhraseId('gridmenuRemoveFilter',"Вилучити фільтр"); RicoTranslate.addPhraseId('gridmenuRemoveAll',"Вилучити всі фільтри"); RicoTranslate.addPhraseId('gridmenuExport',"Друк/Експорт""); RicoTranslate.addPhraseId('gridmenuExportVis2Web',"Видимі записи на веб-сторінку"); RicoTranslate.addPhraseId('gridmenuExportAll2Web',"Усі записи на веб-сторінку"); RicoTranslate.addPhraseId('gridmenuExportVis2SS',"Видимі записи в аркуш excel"); RicoTranslate.addPhraseId('gridmenuExportAll2SS',"Усі записи в аркуш excel"); RicoTranslate.addPhraseId('gridmenuHideShow',"Сховати/Показати"); RicoTranslate.addPhraseId('gridmenuChooseCols',"Виберіть колонку..."); RicoTranslate.addPhraseId('gridmenuHide',"Сховати: $1"); RicoTranslate.addPhraseId('gridmenuShow',"Показати: $1"); RicoTranslate.addPhraseId('gridmenuShowAll',"Показати всі"); // used in ricoLiveGridAjax.js RicoTranslate.addPhraseId('sessionExpireMinutes',"хвилин до закінчення сесії"); RicoTranslate.addPhraseId('sessionExpired',"МИНУЛА"); RicoTranslate.addPhraseId('requestTimedOut',"Перевищений інтервал очікування даних!"); RicoTranslate.addPhraseId('waitForData',"Очікування даних..."); RicoTranslate.addPhraseId('httpError',"Отримана HTTP помилка: $1"); RicoTranslate.addPhraseId('invalidResponse',"Сервер повернув неправильну відповідь"); // used in ricoLiveGridCommon.js RicoTranslate.addPhraseId('gridChooseCols',"Вибрати колонку"); RicoTranslate.addPhraseId('exportComplete',"Експорт завершений"); RicoTranslate.addPhraseId('exportInProgress',"Експортування..."); RicoTranslate.addPhraseId('showFilterRow',"Показати відфільтровані записи"); // img alt text RicoTranslate.addPhraseId('hideFilterRow',"Сховати відфільтровані записи"); // img alt text // used in ricoLiveGridForms.js RicoTranslate.addPhraseId('selectNone',"(нічого)"); RicoTranslate.addPhraseId('selectNewVal',"(нове значення)"); RicoTranslate.addPhraseId('record',"запис"); RicoTranslate.addPhraseId('thisRecord',"ця $1"); RicoTranslate.addPhraseId('confirmDelete',"Ви впевнені,що бажаєте видалити $1?"); RicoTranslate.addPhraseId('deleting',"Видалення..."); RicoTranslate.addPhraseId('formPleaseEnter',"Будь ласка, введіть значення для $1"); RicoTranslate.addPhraseId('formInvalidFmt',"Неправильний формат для $1"); RicoTranslate.addPhraseId('formOutOfRange',"Значення знаходиться поза діапазоном для $1"); RicoTranslate.addPhraseId('formNewValue',"нове значення:"); RicoTranslate.addPhraseId('saving',"Збереження..."); RicoTranslate.addPhraseId('clear',"очистити"); RicoTranslate.addPhraseId('close',"Закрити"); RicoTranslate.addPhraseId('saveRecord',"Зберегти $1"); RicoTranslate.addPhraseId('cancel',"Скасування"); RicoTranslate.addPhraseId('editRecord',"Редагувати цю $1"); RicoTranslate.addPhraseId('deleteRecord',"Вилучити цю $1"); RicoTranslate.addPhraseId('cloneRecord',"Копіювати цю $1"); RicoTranslate.addPhraseId('addRecord',"Додати нову $1"); RicoTranslate.addPhraseId('addedSuccessfully',"$1 додана успішно"); RicoTranslate.addPhraseId('deletedSuccessfully',"$1 вилучена успішно"); RicoTranslate.addPhraseId('updatedSuccessfully',"$1 оновлена успішно"); // used in ricoTree.js RicoTranslate.addPhraseId('treeSave',"Зберегти виділення"); RicoTranslate.addPhraseId('treeClear',"Очистити все"); // used in ricoCalendar.js RicoTranslate.addPhraseId('calToday',"Сьогодні $1 $2 $3"); // $1=day, $2=monthabbr, $3=year, $4=month number RicoTranslate.addPhraseId('calWeekHdg',"Тд"); RicoTranslate.addPhraseId('calYearRange',"Рік ($1-$2)"); RicoTranslate.addPhraseId('calInvalidYear',"Неправильний рік"); // Date & number formats RicoTranslate.thouSep="," RicoTranslate.decPoint="." RicoTranslate.dateFmt="dd/mm/yyyy" RicoTranslate.monthNames=['Січень','Лютий','Березень','Квітень','Травень','Червень','Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'] RicoTranslate.dayNames=['Неділя','Понеділок','Вівторок','Середа','Четвер','П'ятниця','Субота']<|fim▁end|>
RicoTranslate.langCode='ua'; // used in ricoLiveGrid.js
<|file_name|>plan.go<|end_file_name|><|fim▁begin|>package command import ( "context" "fmt" "strings" "github.com/hashicorp/terraform/backend" "github.com/hashicorp/terraform/config/module" ) // PlanCommand is a Command implementation that compares a Terraform // configuration to an actual infrastructure and shows the differences. type PlanCommand struct { Meta } func (c *PlanCommand) Run(args []string) int { var destroy, refresh, detailed bool var outPath string var moduleDepth int args = c.Meta.process(args, true) cmdFlags := c.Meta.flagSet("plan") cmdFlags.BoolVar(&destroy, "destroy", false, "destroy") cmdFlags.BoolVar(&refresh, "refresh", true, "refresh") c.addModuleDepthFlag(cmdFlags, &moduleDepth) cmdFlags.StringVar(&outPath, "out", "", "path") cmdFlags.IntVar( &c.Meta.parallelism, "parallelism", DefaultParallelism, "parallelism") cmdFlags.StringVar(&c.Meta.statePath, "state", "", "path") cmdFlags.BoolVar(&detailed, "detailed-exitcode", false, "detailed-exitcode") cmdFlags.BoolVar(&c.Meta.stateLock, "lock", true, "lock state") cmdFlags.Usage = func() { c.Ui.Error(c.Help()) } if err := cmdFlags.Parse(args); err != nil { return 1 } configPath, err := ModulePath(cmdFlags.Args()) if err != nil { c.Ui.Error(err.Error()) return 1 } // Check if the path is a plan plan, err := c.Plan(configPath) if err != nil { c.Ui.Error(err.Error()) return 1 } if plan != nil { // Disable refreshing no matter what since we only want to show the plan refresh = false // Set the config path to empty for backend loading configPath = "" } // Load the module if we don't have one yet (not running from plan) var mod *module.Tree if plan == nil { mod, err = c.Module(configPath) if err != nil { c.Ui.Error(fmt.Sprintf("Failed to load root config module: %s", err)) return 1 } } // Load the backend b, err := c.Backend(&BackendOpts{ ConfigPath: configPath, Plan: plan, }) if err != nil { c.Ui.Error(fmt.Sprintf("Failed to load backend: %s", err)) return 1 } // Build the operation opReq := c.Operation() opReq.Destroy = destroy opReq.Module = mod opReq.Plan = plan opReq.PlanRefresh = refresh opReq.PlanOutPath = outPath opReq.Type = backend.OperationTypePlan opReq.LockState = c.Meta.stateLock // Perform the operation op, err := b.Operation(context.Background(), opReq) if err != nil { c.Ui.Error(fmt.Sprintf("Error starting operation: %s", err)) return 1 } // Wait for the operation to complete <-op.Done() if err := op.Err; err != nil { c.Ui.Error(err.Error()) return 1 } /* err = terraform.SetDebugInfo(DefaultDataDir) if err != nil { c.Ui.Error(err.Error()) return 1 } */ if detailed && !op.PlanEmpty { return 2 } return 0<|fim▁hole|>} func (c *PlanCommand) Help() string { helpText := ` Usage: terraform plan [options] [DIR-OR-PLAN] Generates an execution plan for Terraform. This execution plan can be reviewed prior to running apply to get a sense for what Terraform will do. Optionally, the plan can be saved to a Terraform plan file, and apply can take this plan file to execute this plan exactly. If a saved plan is passed as an argument, this command will output the saved plan contents. It will not modify the given plan. Options: -destroy If set, a plan will be generated to destroy all resources managed by the given configuration and state. -detailed-exitcode Return detailed exit codes when the command exits. This will change the meaning of exit codes to: 0 - Succeeded, diff is empty (no changes) 1 - Errored 2 - Succeeded, there is a diff -input=true Ask for input for variables if not directly set. -lock=true Lock the state file when locking is supported. -module-depth=n Specifies the depth of modules to show in the output. This does not affect the plan itself, only the output shown. By default, this is -1, which will expand all. -no-color If specified, output won't contain any color. -out=path Write a plan file to the given path. This can be used as input to the "apply" command. -parallelism=n Limit the number of concurrent operations. Defaults to 10. -refresh=true Update state prior to checking for differences. -state=statefile Path to a Terraform state file to use to look up Terraform-managed resources. By default it will use the state "terraform.tfstate" if it exists. -target=resource Resource to target. Operation will be limited to this resource and its dependencies. This flag can be used multiple times. -var 'foo=bar' Set a variable in the Terraform configuration. This flag can be set multiple times. -var-file=foo Set variables in the Terraform configuration from a file. If "terraform.tfvars" is present, it will be automatically loaded if this flag is not specified. ` return strings.TrimSpace(helpText) } func (c *PlanCommand) Synopsis() string { return "Generate and show an execution plan" }<|fim▁end|>