prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>max-spec.ts<|end_file_name|><|fim▁begin|>import { expect } from 'chai'; import * as Rx from '../../src/internal/Rx'; import { hot, cold, expectObservable, expectSubscriptions } from '../helpers/marble-testing'; declare function asDiagram(arg: string): Function; const Observable = Rx.Observable; /** @test {max} */ describe('Observable.prototype.max', () => { asDiagram('max')('should find the max of values of an observable', () => { const e1 = hot('--a--b--c--|', { a: 42, b: -1, c: 3 }); const subs = '^ !'; const expected = '-----------(x|)'; expectObservable((<any>e1).max()).toBe(expected, { x: 42 }); expectSubscriptions(e1.subscriptions).toBe(subs); }); it('should be never when source is never', () => { const e1 = cold('-'); const e1subs = '^'; const expected = '-'; expectObservable((<any>e1).max()).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should be zero when source is empty', () => { const e1 = cold('|'); const e1subs = '(^!)'; const expected = '|'; expectObservable((<any>e1).max()).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should be never when source doesn\'t complete', () => { const e1 = hot('--x--^--y--'); const e1subs = '^ '; const expected = '------'; expectObservable((<any>e1).max()).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should be completes when source doesn\'t have values', () => { const e1 = hot('-x-^---|'); const e1subs = '^ !'; const expected = '----|'; expectObservable((<any>e1).max()).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should max the unique value of an observable', () => { const e1 = hot('-x-^--y--|', { y: 42 }); const e1subs = '^ !'; const expected = '------(w|)'; expectObservable((<any>e1).max()).toBe(expected, { w: 42 }); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should max the values of an ongoing hot observable', () => { const e1 = hot('--a-^-b--c--d--|', { a: 42, b: -1, c: 0, d: 666 }); const subs = '^ !'; const expected = '-----------(x|)'; expectObservable((<any>e1).max()).toBe(expected, { x: 666 }); expectSubscriptions(e1.subscriptions).toBe(subs); }); it('should allow unsubscribing explicitly and early', () => { const e1 = hot('--a--b--c--|', { a: 42, b: -1, c: 0 }); const unsub = ' ! '; const subs = '^ ! ';<|fim▁hole|> }); it('should not break unsubscription chains when result is unsubscribed explicitly', () => { const source = hot('--a--b--c--|', { a: 42, b: -1, c: 0 }); const subs = '^ ! '; const expected = '------- '; const unsub = ' ! '; const result = (<any>source) .mergeMap((x: string) => Observable.of(x)) .max() .mergeMap((x: string) => Observable.of(x)); expectObservable(result, unsub).toBe(expected, { x: 42 }); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should max a range() source observable', (done: MochaDone) => { (<any>Rx.Observable.range(1, 10000)).max().subscribe( (value: number) => { expect(value).to.equal(10000); }, (x) => { done(new Error('should not be called')); }, () => { done(); }); }); it('should max a range().skip(1) source observable', (done: MochaDone) => { (<any>Rx.Observable.range(1, 10)).skip(1).max().subscribe( (value: number) => { expect(value).to.equal(10); }, (x) => { done(new Error('should not be called')); }, () => { done(); }); }); it('should max a range().take(1) source observable', (done: MochaDone) => { (<any>Rx.Observable.range(1, 10)).take(1).max().subscribe( (value: number) => { expect(value).to.equal(1); }, (x) => { done(new Error('should not be called')); }, () => { done(); }); }); it('should work with error', () => { const e1 = hot('-x-^--y--z--#', { x: 1, y: 2, z: 3 }, 'too bad'); const e1subs = '^ !'; const expected = '---------#'; expectObservable((<any>e1).max()).toBe(expected, null, 'too bad'); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should work with throw', () => { const e1 = cold('#'); const e1subs = '(^!)'; const expected = '#'; expectObservable((<any>e1).max()).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a constant predicate on an empty hot observable', () => { const e1 = hot('-x-^---|'); const e1subs = '^ !'; const expected = '----|'; const predicate = function (x, y) { return 42; }; expectObservable((<any>e1).max(predicate)).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a constant predicate on an never hot observable', () => { const e1 = hot('-x-^----'); const e1subs = '^ '; const expected = '-----'; const predicate = function (x, y) { return 42; }; expectObservable((<any>e1).max(predicate)).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a constant predicate on a simple hot observable', () => { const e1 = hot('-x-^-a-|', { a: 1 }); const e1subs = '^ !'; const expected = '----(w|)'; const predicate = function () { return 42; }; expectObservable((<any>e1).max(predicate)).toBe(expected, { w: 1 }); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a reverse predicate on observable with many values', () => { const e1 = hot('-a-^-b--c--d-|', { a: 42, b: -1, c: 0, d: 666 }); const e1subs = '^ !'; const expected = '----------(w|)'; const predicate = function (x, y) { return x > y ? -1 : 1; }; expectObservable((<any>e1).max(predicate)).toBe(expected, { w: -1 }); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a predicate for string on observable with many values', () => { const e1 = hot('-a-^-b--c--d-|'); const e1subs = '^ !'; const expected = '----------(w|)'; const predicate = function (x, y) { return x > y ? -1 : 1; }; expectObservable((<any>e1).max(predicate)).toBe(expected, { w: 'b' }); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a constant predicate on observable that throws', () => { const e1 = hot('-1-^---#'); const e1subs = '^ !'; const expected = '----#'; const predicate = () => { return 42; }; expectObservable((<any>e1).max(predicate)).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a predicate that throws, on observable with many values', () => { const e1 = hot('-1-^-2--3--|'); const e1subs = '^ ! '; const expected = '-----# '; const predicate = function (x, y) { if (y === '3') { throw 'error'; } return x > y ? x : y; }; expectObservable((<any>e1).max(predicate)).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); });<|fim▁end|>
const expected = '------- '; expectObservable((<any>e1).max(), unsub).toBe(expected, { x: 42 }); expectSubscriptions(e1.subscriptions).toBe(subs);
<|file_name|>lazy-chunk-1.js<|end_file_name|><|fim▁begin|>setTimeout(() => { import(/* webpackPreload: true */ "./lazy-chunk-2.js").then((mod) => mod.test() );<|fim▁hole|><|fim▁end|>
}, 750);
<|file_name|>DialogClosedHandler.java<|end_file_name|><|fim▁begin|>/* * Copyright 2015 JBoss by Red Hat. <|fim▁hole|> * 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 org.uberfire.ext.widgets.common.client.colorpicker.dialog; import com.google.gwt.event.shared.EventHandler; public interface DialogClosedHandler extends EventHandler { void dialogClosed(DialogClosedEvent event); }<|fim▁end|>
* * Licensed under the Apache License, Version 2.0 (the "License");
<|file_name|>p215.py<|end_file_name|><|fim▁begin|>"""KDE of Temps.""" import calendar from datetime import date, datetime import pandas as pd from pyiem.plot.util import fitbox from pyiem.plot import figure from pyiem.util import get_autoplot_context, get_sqlalchemy_conn from pyiem.exceptions import NoDataFound from matplotlib.ticker import MaxNLocator from scipy.stats import gaussian_kde import numpy as np from sqlalchemy import text PDICT = { "high": "High Temperature [F]", "low": "Low Temperature [F]", "avgt": "Average Temperature [F]", } MDICT = dict( [ ("all", "No Month/Time Limit"), ("spring", "Spring (MAM)"), ("fall", "Fall (SON)"), ("winter", "Winter (DJF)"), ("summer", "Summer (JJA)"), ("jan", "January"), ("feb", "February"), ("mar", "March"),<|fim▁hole|> ("aug", "August"), ("sep", "September"), ("oct", "October"), ("nov", "November"), ("dec", "December"), ] ) def get_description(): """Return a dict describing how to call this plotter""" desc = {} desc["cache"] = 3600 desc["data"] = True desc[ "description" ] = """This autoplot generates some metrics on the distribution of temps over a given period of years. The plotted distribution in the upper panel is using a guassian kernel density estimate. """ desc["arguments"] = [ dict( type="station", name="station", default="IATDSM", label="Select station:", network="IACLIMATE", ), dict( type="select", options=PDICT, name="v", default="high", label="Daily Variable to Plot:", ), dict( type="select", name="month", default="all", label="Month Limiter", options=MDICT, ), dict( type="year", min=1880, name="sy1", default=1981, label="Inclusive Start Year for First Period of Years:", ), dict( type="year", min=1880, name="ey1", default=2010, label="Inclusive End Year for First Period of Years:", ), dict( type="year", min=1880, name="sy2", default=1991, label="Inclusive Start Year for Second Period of Years:", ), dict( type="year", min=1880, name="ey2", default=2020, label="Inclusive End Year for Second Period of Years:", ), ] return desc def get_df(ctx, period): """Get our data.""" table = "alldata_%s" % (ctx["station"][:2]) month = ctx["month"] ctx["mlabel"] = f"{month.capitalize()} Season" if month == "all": months = range(1, 13) ctx["mlabel"] = "All Year" elif month == "fall": months = [9, 10, 11] elif month == "winter": months = [12, 1, 2] elif month == "spring": months = [3, 4, 5] elif month == "summer": months = [6, 7, 8] else: ts = datetime.strptime("2000-" + month + "-01", "%Y-%b-%d") months = [ts.month] ctx["mlabel"] = calendar.month_name[ts.month] with get_sqlalchemy_conn("coop") as conn: df = pd.read_sql( text( f"SELECT high, low, (high+low)/2. as avgt from {table} WHERE " "day >= :d1 and day <= :d2 and station = :station " "and high is not null " "and low is not null and month in :months" ), conn, params={ "d1": date(ctx[f"sy{period}"], 1, 1), "d2": date(ctx[f"ey{period}"], 12, 31), "station": ctx["station"], "months": tuple(months), }, ) return df def f2s(value): """HAAAAAAAAAAAAACK.""" return ("%.5f" % value).rstrip("0").rstrip(".") def plotter(fdict): """Go""" ctx = get_autoplot_context(fdict, get_description()) df1 = get_df(ctx, "1") df2 = get_df(ctx, "2") if df1.empty or df2.empty: raise NoDataFound("Failed to find data for query!") kern1 = gaussian_kde(df1[ctx["v"]]) kern2 = gaussian_kde(df2[ctx["v"]]) xpos = np.arange( min([df1[ctx["v"]].min(), df2[ctx["v"]].min()]), max([df1[ctx["v"]].max(), df2[ctx["v"]].max()]) + 1, dtype="i", ) period1 = "%s-%s" % (ctx["sy1"], ctx["ey1"]) period2 = "%s-%s" % (ctx["sy2"], ctx["ey2"]) label1 = "%s-%s %s" % (ctx["sy1"], ctx["ey1"], ctx["v"]) label2 = "%s-%s %s" % (ctx["sy2"], ctx["ey2"], ctx["v"]) df = pd.DataFrame({label1: kern1(xpos), label2: kern2(xpos)}, index=xpos) fig = figure(apctx=ctx) title = "[%s] %s %s Distribution\n%s vs %s over %s" % ( ctx["station"], ctx["_nt"].sts[ctx["station"]]["name"], PDICT[ctx["v"]], period2, period1, ctx["mlabel"], ) fitbox(fig, title, 0.12, 0.9, 0.91, 0.99) ax = fig.add_axes([0.12, 0.38, 0.75, 0.52]) C1 = "blue" C2 = "red" alpha = 0.4 ax.plot( df.index.values, df[label1], lw=2, c=C1, label=rf"{label1} - $\mu$={df1[ctx['v']].mean():.2f}", zorder=4, ) ax.fill_between(xpos, 0, df[label1], color=C1, alpha=alpha, zorder=3) ax.axvline(df1[ctx["v"]].mean(), color=C1) ax.plot( df.index.values, df[label2], lw=2, c=C2, label=rf"{label2} - $\mu$={df2[ctx['v']].mean():.2f}", zorder=4, ) ax.fill_between(xpos, 0, df[label2], color=C2, alpha=alpha, zorder=3) ax.axvline(df2[ctx["v"]].mean(), color=C2) ax.set_ylabel("Guassian Kernel Density Estimate") ax.legend(loc="best") ax.grid(True) ax.xaxis.set_major_locator(MaxNLocator(20)) # Sub ax ax2 = fig.add_axes([0.12, 0.1, 0.75, 0.22]) delta = df[label2] - df[label1] ax2.plot(df.index.values, delta) dam = delta.abs().max() * 1.1 ax2.set_ylim(0 - dam, dam) ax2.set_xlabel(PDICT[ctx["v"]]) ax2.set_ylabel("%s minus\n%s" % (period2, period1)) ax2.grid(True) ax2.fill_between(xpos, 0, delta, where=delta > 0, color=C2, alpha=alpha) ax2.fill_between(xpos, 0, delta, where=delta < 0, color=C1, alpha=alpha) ax2.axhline(0, ls="--", lw=2, color="k") ax2.xaxis.set_major_locator(MaxNLocator(20)) # Percentiles levels = [0.001, 0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 0.75] levels.extend([0.9, 0.95, 0.99, 0.995, 0.999]) p1 = df1[ctx["v"]].describe(percentiles=levels) p2 = df2[ctx["v"]].describe(percentiles=levels) y = 0.8 fig.text(0.88, y, "Percentile", rotation=70) fig.text(0.91, y, period1, rotation=70) fig.text(0.945, y, period2, rotation=70) for ptile in levels: y -= 0.03 val = f2s(ptile * 100.0) fig.text(0.88, y, val) fig.text(0.91, y, "%.1f" % (p1[f"{val}%"],)) fig.text(0.95, y, "%.1f" % (p2[f"{val}%"],)) return fig, df if __name__ == "__main__": plotter(dict())<|fim▁end|>
("apr", "April"), ("may", "May"), ("jun", "June"), ("jul", "July"),
<|file_name|>weibo_bash.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 #coding:utf-8 __author__ = 'zhuzhezhe' ''' 功能实现:命令行下发布微博,获取最新微博 ''' from weibo import Client import getopt import sys import configparser versions = '0.1.5' # 写入用户数据 def write_data(uname, pwd): conf = configparser.ConfigParser() conf['LOGIN'] = {} conf['LOGIN']['username'] = uname conf['LOGIN']['password'] = pwd with open('config.ini', 'w') as configfile: conf.write(configfile) print('写入成功') # 读取用户数据 config = configparser.ConfigParser() config.read('config.ini') username = '' password = '' if 'LOGIN' in config: username = config['LOGIN']['username'] password = config['LOGIN']['password']<|fim▁hole|># 接入新浪接口基本信息 api_key = '3842240593' api_secret = '93f0c80150239e02c52011c858b20ce6' # 默认回调地址 redirect_url = 'https://api.weibo.com/oauth2/default.html' # 登陆验证 c = Client(api_key=api_key, api_secret=api_secret, redirect_uri=redirect_url, username=username, password=password) # 最新微博 def new_weibo(): try: data = c.get('statuses/friends_timeline')["statuses"] for i in range(len(data)): print("用户:"+data[i]["user"]["screen_name"]) print("微博:"+data[i]["text"]) print("\n") except Exception as err: print(err) print('确保已完成登陆.请填写用户名和密码.') # 发布微博 def add_weibo(words): try: c.post('statuses/update', status=words) print("发布成功!") except Exception as err: print(err) print('确保已完成登陆.请填写用户名和密码.') # 用法 def usage(): text = '--------weibobash使用帮助--------\n' \ '-h<--help>: 显示帮助信息\n' \ '-u<--user>: 输入用户名和密码\n' \ '-n<--new>: 显示20条最新微博\n' \ '-a<--add>: 发布一条微博\n' print(text) # 主程序 def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hna:vu", ["help", "new", "add=", "user"]) except getopt.GetoptError as err: print(err) sys.exit(2) for o, a in opts: if o == "-v": print(versions) elif o in ("-h", "--help"): usage() sys.exit() elif o in ("-n", "--new"): new_weibo() elif o in ("-a", "--add"): add_weibo(a) elif o in ("-u", "--user"): user = input("请输入用户名:") pwd = input("请输入密码:") write_data(user, pwd) else: assert False, "unhandled option" if __name__ == "__main__": main()<|fim▁end|>
else: print('确保已完成登陆.请填写用户名和密码.')
<|file_name|>test_mp4.py<|end_file_name|><|fim▁begin|>import os import shutil import struct from cStringIO import StringIO from tempfile import mkstemp from tests import TestCase, add from mutagen.mp4 import MP4, Atom, Atoms, MP4Tags, MP4Info, \ delete, MP4Cover, MP4MetadataError from mutagen._util import cdata try: from os.path import devnull except ImportError: devnull = "/dev/null" class TAtom(TestCase): uses_mmap = False def test_no_children(self): fileobj = StringIO("\x00\x00\x00\x08atom") atom = Atom(fileobj) self.failUnlessRaises(KeyError, atom.__getitem__, "test") def test_length_1(self): fileobj = StringIO("\x00\x00\x00\x01atom" "\x00\x00\x00\x00\x00\x00\x00\x08" + "\x00" * 8) self.failUnlessEqual(Atom(fileobj).length, 8) def test_render_too_big(self): class TooBig(str): def __len__(self): return 1L << 32 data = TooBig("test") try: len(data) except OverflowError: # Py_ssize_t is still only 32 bits on this system. self.failUnlessRaises(OverflowError, Atom.render, "data", data) else: data = Atom.render("data", data) self.failUnlessEqual(len(data), 4 + 4 + 8 + 4) def test_length_0(self): fileobj = StringIO("\x00\x00\x00\x00atom") Atom(fileobj) self.failUnlessEqual(fileobj.tell(), 8) add(TAtom) class TAtoms(TestCase): uses_mmap = False filename = os.path.join("tests", "data", "has-tags.m4a") def setUp(self): self.atoms = Atoms(file(self.filename, "rb")) def test___contains__(self): self.failUnless(self.atoms["moov"]) self.failUnless(self.atoms["moov.udta"]) self.failUnlessRaises(KeyError, self.atoms.__getitem__, "whee") def test_name(self): self.failUnlessEqual(self.atoms.atoms[0].name, "ftyp") def test_children(self): self.failUnless(self.atoms.atoms[2].children) def test_no_children(self): self.failUnless(self.atoms.atoms[0].children is None) def test_extra_trailing_data(self): data = StringIO(Atom.render("data", "whee") + "\x00\x00") self.failUnless(Atoms(data)) def test_repr(self): repr(self.atoms) add(TAtoms) class TMP4Info(TestCase): uses_mmap = False def test_no_soun(self): self.failUnlessRaises( IOError, self.test_mdhd_version_1, "vide") def test_mdhd_version_1(self, soun="soun"): mdhd = Atom.render("mdhd", ("\x01\x00\x00\x00" + "\x00" * 16 + "\x00\x00\x00\x02" + # 2 Hz "\x00\x00\x00\x00\x00\x00\x00\x10")) hdlr = Atom.render("hdlr", "\x00" * 8 + soun) mdia = Atom.render("mdia", mdhd + hdlr) trak = Atom.render("trak", mdia) moov = Atom.render("moov", trak) fileobj = StringIO(moov) atoms = Atoms(fileobj) info = MP4Info(atoms, fileobj) self.failUnlessEqual(info.length, 8) def test_multiple_tracks(self): hdlr = Atom.render("hdlr", "\x00" * 8 + "whee") mdia = Atom.render("mdia", hdlr) trak1 = Atom.render("trak", mdia) mdhd = Atom.render("mdhd", ("\x01\x00\x00\x00" + "\x00" * 16 + "\x00\x00\x00\x02" + # 2 Hz "\x00\x00\x00\x00\x00\x00\x00\x10")) hdlr = Atom.render("hdlr", "\x00" * 8 + "soun") mdia = Atom.render("mdia", mdhd + hdlr) trak2 = Atom.render("trak", mdia) moov = Atom.render("moov", trak1 + trak2) fileobj = StringIO(moov) atoms = Atoms(fileobj) info = MP4Info(atoms, fileobj) self.failUnlessEqual(info.length, 8) add(TMP4Info) class TMP4Tags(TestCase): uses_mmap = False def wrap_ilst(self, data): ilst = Atom.render("ilst", data) meta = Atom.render("meta", "\x00" * 4 + ilst) data = Atom.render("moov", Atom.render("udta", meta)) fileobj = StringIO(data) return MP4Tags(Atoms(fileobj), fileobj) def test_genre(self): data = Atom.render("data", "\x00" * 8 + "\x00\x01") genre = Atom.render("gnre", data) tags = self.wrap_ilst(genre) self.failIf("gnre" in tags) self.failUnlessEqual(tags["\xa9gen"], ["Blues"]) def test_empty_cpil(self): cpil = Atom.render("cpil", Atom.render("data", "\x00" * 8)) tags = self.wrap_ilst(cpil) self.failUnless("cpil" in tags) self.failIf(tags["cpil"]) def test_genre_too_big(self): data = Atom.render("data", "\x00" * 8 + "\x01\x00") genre = Atom.render("gnre", data) tags = self.wrap_ilst(genre) self.failIf("gnre" in tags) self.failIf("\xa9gen" in tags) def test_strips_unknown_types(self): data = Atom.render("data", "\x00" * 8 + "whee") foob = Atom.render("foob", data) tags = self.wrap_ilst(foob) self.failIf(tags) def test_bad_covr(self): data = Atom.render("foob", "\x00\x00\x00\x0E" + "\x00" * 4 + "whee") covr = Atom.render("covr", data) self.failUnlessRaises(MP4MetadataError, self.wrap_ilst, covr) def test_covr_blank_format(self): data = Atom.render("data", "\x00\x00\x00\x00" + "\x00" * 4 + "whee") covr = Atom.render("covr", data) tags = self.wrap_ilst(covr) self.failUnlessEqual(MP4Cover.FORMAT_JPEG, tags["covr"][0].format) def test_render_bool(self): self.failUnlessEqual(MP4Tags()._MP4Tags__render_bool('pgap', True), "\x00\x00\x00\x19pgap\x00\x00\x00\x11data" "\x00\x00\x00\x15\x00\x00\x00\x00\x01") self.failUnlessEqual(MP4Tags()._MP4Tags__render_bool('pgap', False), "\x00\x00\x00\x19pgap\x00\x00\x00\x11data" "\x00\x00\x00\x15\x00\x00\x00\x00\x00") def test_render_text(self): self.failUnlessEqual( MP4Tags()._MP4Tags__render_text('purl', ['http://foo/bar.xml'], 0), "\x00\x00\x00*purl\x00\x00\x00\"data\x00\x00\x00\x00\x00\x00" "\x00\x00http://foo/bar.xml") self.failUnlessEqual( MP4Tags()._MP4Tags__render_text('aART', [u'\u0041lbum Artist']), "\x00\x00\x00$aART\x00\x00\x00\x1cdata\x00\x00\x00\x01\x00\x00" "\x00\x00\x41lbum Artist") self.failUnlessEqual( MP4Tags()._MP4Tags__render_text('aART', [u'Album Artist', u'Whee']), "\x00\x00\x008aART\x00\x00\x00\x1cdata\x00\x00\x00\x01\x00\x00" "\x00\x00Album Artist\x00\x00\x00\x14data\x00\x00\x00\x01\x00" "\x00\x00\x00Whee") def test_render_data(self): self.failUnlessEqual( MP4Tags()._MP4Tags__render_data('aART', 1, ['whee']), "\x00\x00\x00\x1caART" "\x00\x00\x00\x14data\x00\x00\x00\x01\x00\x00\x00\x00whee") self.failUnlessEqual( MP4Tags()._MP4Tags__render_data('aART', 2, ['whee', 'wee']), "\x00\x00\x00/aART" "\x00\x00\x00\x14data\x00\x00\x00\x02\x00\x00\x00\x00whee" "\x00\x00\x00\x13data\x00\x00\x00\x02\x00\x00\x00\x00wee") def test_bad_text_data(self): data = Atom.render("datA", "\x00\x00\x00\x01\x00\x00\x00\x00whee") data = Atom.render("aART", data) self.failUnlessRaises(MP4MetadataError, self.wrap_ilst, data) def test_render_freeform(self): self.failUnlessEqual( MP4Tags()._MP4Tags__render_freeform( '----:net.sacredchao.Mutagen:test', ['whee', 'wee']), "\x00\x00\x00a----" "\x00\x00\x00\"mean\x00\x00\x00\x00net.sacredchao.Mutagen" "\x00\x00\x00\x10name\x00\x00\x00\x00test" "\x00\x00\x00\x14data\x00\x00\x00\x01\x00\x00\x00\x00whee" "\x00\x00\x00\x13data\x00\x00\x00\x01\x00\x00\x00\x00wee") def test_bad_freeform(self): mean = Atom.render("mean", "net.sacredchao.Mutagen") name = Atom.render("name", "empty test key") bad_freeform = Atom.render("----", "\x00" * 4 + mean + name) self.failUnlessRaises(MP4MetadataError, self.wrap_ilst, bad_freeform) def test_pprint_non_text_list(self): tags = MP4Tags() tags["tmpo"] = [120, 121] tags["trck"] = [(1, 2), (3, 4)] tags.pprint() add(TMP4Tags) class TMP4(TestCase): def setUp(self): fd, self.filename = mkstemp(suffix='.m4a') os.close(fd) shutil.copy(self.original, self.filename) self.audio = MP4(self.filename) def faad(self): if not have_faad: return value = os.system( "faad -w %s > %s 2> %s" % (self.filename, devnull, devnull)) self.failIf(value and value != NOTFOUND) def test_score(self): fileobj = file(self.filename) header = fileobj.read(128) self.failUnless(MP4.score(self.filename, fileobj, header)) def test_channels(self): self.failUnlessEqual(self.audio.info.channels, 2) def test_sample_rate(self): self.failUnlessEqual(self.audio.info.sample_rate, 44100) def test_bits_per_sample(self): self.failUnlessEqual(self.audio.info.bits_per_sample, 16) def test_bitrate(self): self.failUnlessEqual(self.audio.info.bitrate, 2914) def test_length(self): self.failUnlessAlmostEqual(3.7, self.audio.info.length, 1) def test_padding(self): self.audio["\xa9nam"] = u"wheeee" * 10 self.audio.save() size1 = os.path.getsize(self.audio.filename) audio = MP4(self.audio.filename) self.audio["\xa9nam"] = u"wheeee" * 11 self.audio.save() size2 = os.path.getsize(self.audio.filename) self.failUnless(size1, size2) def test_padding_2(self): self.audio["\xa9nam"] = u"wheeee" * 10 self.audio.save() # Reorder "free" and "ilst" atoms fileobj = file(self.audio.filename, "rb+") atoms = Atoms(fileobj) meta = atoms["moov", "udta", "meta"] meta_length1 = meta.length ilst = meta["ilst",] free = meta["free",] self.failUnlessEqual(ilst.offset + ilst.length, free.offset) fileobj.seek(ilst.offset) ilst_data = fileobj.read(ilst.length) fileobj.seek(free.offset) free_data = fileobj.read(free.length) fileobj.seek(ilst.offset) fileobj.write(free_data + ilst_data) fileobj.close() fileobj = file(self.audio.filename, "rb+") atoms = Atoms(fileobj) meta = atoms["moov", "udta", "meta"] ilst = meta["ilst",] free = meta["free",] self.failUnlessEqual(free.offset + free.length, ilst.offset) fileobj.close() # Save the file self.audio["\xa9nam"] = u"wheeee" * 11 self.audio.save() # Check the order of "free" and "ilst" atoms<|fim▁hole|> meta = atoms["moov", "udta", "meta"] ilst = meta["ilst",] free = meta["free",] self.failUnlessEqual(meta.length, meta_length1) self.failUnlessEqual(ilst.offset + ilst.length, free.offset) def set_key(self, key, value, result=None, faad=True): self.audio[key] = value self.audio.save() audio = MP4(self.audio.filename) self.failUnless(key in audio) self.failUnlessEqual(audio[key], result or value) if faad: self.faad() def test_save_text(self): self.set_key('\xa9nam', [u"Some test name"]) def test_save_texts(self): self.set_key('\xa9nam', [u"Some test name", u"One more name"]) def test_freeform(self): self.set_key('----:net.sacredchao.Mutagen:test key', ["whee"]) def test_freeform_2(self): self.set_key('----:net.sacredchao.Mutagen:test key', "whee", ["whee"]) def test_freeforms(self): self.set_key('----:net.sacredchao.Mutagen:test key', ["whee", "uhh"]) def test_tracknumber(self): self.set_key('trkn', [(1, 10)]) self.set_key('trkn', [(1, 10), (5, 20)], faad=False) self.set_key('trkn', []) def test_disk(self): self.set_key('disk', [(18, 0)]) self.set_key('disk', [(1, 10), (5, 20)], faad=False) self.set_key('disk', []) def test_tracknumber_too_small(self): self.failUnlessRaises(ValueError, self.set_key, 'trkn', [(-1, 0)]) self.failUnlessRaises(ValueError, self.set_key, 'trkn', [(2**18, 1)]) def test_disk_too_small(self): self.failUnlessRaises(ValueError, self.set_key, 'disk', [(-1, 0)]) self.failUnlessRaises(ValueError, self.set_key, 'disk', [(2**18, 1)]) def test_tracknumber_wrong_size(self): self.failUnlessRaises(ValueError, self.set_key, 'trkn', (1,)) self.failUnlessRaises(ValueError, self.set_key, 'trkn', (1, 2, 3,)) self.failUnlessRaises(ValueError, self.set_key, 'trkn', [(1,)]) self.failUnlessRaises(ValueError, self.set_key, 'trkn', [(1, 2, 3,)]) def test_disk_wrong_size(self): self.failUnlessRaises(ValueError, self.set_key, 'disk', [(1,)]) self.failUnlessRaises(ValueError, self.set_key, 'disk', [(1, 2, 3,)]) def test_tempo(self): self.set_key('tmpo', [150]) self.set_key('tmpo', []) def test_tempos(self): self.set_key('tmpo', [160, 200], faad=False) def test_tempo_invalid(self): for badvalue in [[10000000], [-1], 10, "foo"]: self.failUnlessRaises(ValueError, self.set_key, 'tmpo', badvalue) def test_compilation(self): self.set_key('cpil', True) def test_compilation_false(self): self.set_key('cpil', False) def test_gapless(self): self.set_key('pgap', True) def test_gapless_false(self): self.set_key('pgap', False) def test_podcast(self): self.set_key('pcst', True) def test_podcast_false(self): self.set_key('pcst', False) def test_cover(self): self.set_key('covr', ['woooo']) def test_cover_png(self): self.set_key('covr', [ MP4Cover('woooo', MP4Cover.FORMAT_PNG), MP4Cover('hoooo', MP4Cover.FORMAT_JPEG), ]) def test_podcast_url(self): self.set_key('purl', ['http://pdl.warnerbros.com/wbie/justiceleagueheroes/audio/JLH_EA.xml']) def test_episode_guid(self): self.set_key('catg', ['falling-star-episode-1']) def test_pprint(self): self.failUnless(self.audio.pprint()) def test_pprint_binary(self): self.audio["covr"] = "\x00\xa9\garbage" self.failUnless(self.audio.pprint()) def test_pprint_pair(self): self.audio["cpil"] = (1, 10) self.failUnless("cpil=(1, 10)" in self.audio.pprint()) def test_delete(self): self.audio.delete() audio = MP4(self.audio.filename) self.failIf(audio.tags) self.faad() def test_module_delete(self): delete(self.filename) audio = MP4(self.audio.filename) self.failIf(audio.tags) self.faad() def test_reads_unknown_text(self): self.set_key("foob", [u"A test"]) def __read_offsets(self, filename): fileobj = file(filename, 'rb') atoms = Atoms(fileobj) moov = atoms['moov'] samples = [] for atom in moov.findall('stco', True): fileobj.seek(atom.offset + 12) data = fileobj.read(atom.length - 12) fmt = ">%dI" % cdata.uint_be(data[:4]) offsets = struct.unpack(fmt, data[4:]) for offset in offsets: fileobj.seek(offset) samples.append(fileobj.read(8)) for atom in moov.findall('co64', True): fileobj.seek(atom.offset + 12) data = fileobj.read(atom.length - 12) fmt = ">%dQ" % cdata.uint_be(data[:4]) offsets = struct.unpack(fmt, data[4:]) for offset in offsets: fileobj.seek(offset) samples.append(fileobj.read(8)) try: for atom in atoms["moof"].findall('tfhd', True): data = fileobj.read(atom.length - 9) flags = cdata.uint_be("\x00" + data[:3]) if flags & 1: offset = cdata.ulonglong_be(data[7:15]) fileobj.seek(offset) samples.append(fileobj.read(8)) except KeyError: pass fileobj.close() return samples def test_update_offsets(self): aa = self.__read_offsets(self.original) self.audio["\xa9nam"] = "wheeeeeeee" self.audio.save() bb = self.__read_offsets(self.filename) for a, b in zip(aa, bb): self.failUnlessEqual(a, b) def test_mime(self): self.failUnless("audio/mp4" in self.audio.mime) def tearDown(self): os.unlink(self.filename) class TMP4HasTags(TMP4): original = os.path.join("tests", "data", "has-tags.m4a") def test_save_simple(self): self.audio.save() self.faad() def test_shrink(self): map(self.audio.__delitem__, self.audio.keys()) self.audio.save() audio = MP4(self.audio.filename) self.failIf(self.audio.tags) def test_has_tags(self): self.failUnless(self.audio.tags) def test_has_covr(self): self.failUnless('covr' in self.audio.tags) covr = self.audio.tags['covr'] self.failUnlessEqual(len(covr), 2) self.failUnlessEqual(covr[0].format, MP4Cover.FORMAT_PNG) self.failUnlessEqual(covr[1].format, MP4Cover.FORMAT_JPEG) def test_not_my_file(self): self.failUnlessRaises( IOError, MP4, os.path.join("tests", "data", "empty.ogg")) add(TMP4HasTags) class TMP4HasTags64Bit(TMP4HasTags): original = os.path.join("tests", "data", "truncated-64bit.mp4") def test_has_covr(self): pass def test_bitrate(self): self.failUnlessEqual(self.audio.info.bitrate, 128000) def test_length(self): self.failUnlessAlmostEqual(0.325, self.audio.info.length, 3) def faad(self): # This is only half a file, so FAAD segfaults. Can't test. :( pass add(TMP4HasTags64Bit) class TMP4NoTagsM4A(TMP4): original = os.path.join("tests", "data", "no-tags.m4a") def test_no_tags(self): self.failUnless(self.audio.tags is None) add(TMP4NoTagsM4A) class TMP4NoTags3G2(TMP4): original = os.path.join("tests", "data", "no-tags.3g2") def test_no_tags(self): self.failUnless(self.audio.tags is None) def test_sample_rate(self): self.failUnlessEqual(self.audio.info.sample_rate, 22050) def test_bitrate(self): self.failUnlessEqual(self.audio.info.bitrate, 32000) def test_length(self): self.failUnlessAlmostEqual(15, self.audio.info.length, 1) add(TMP4NoTags3G2) NOTFOUND = os.system("tools/notarealprogram 2> %s" % devnull) have_faad = True if os.system("faad 2> %s > %s" % (devnull, devnull)) == NOTFOUND: have_faad = False print "WARNING: Skipping FAAD reference tests."<|fim▁end|>
fileobj = file(self.audio.filename, "rb+") atoms = Atoms(fileobj) fileobj.close()
<|file_name|>max-depth.js<|end_file_name|><|fim▁begin|>/** * @fileoverview Tests for max-depth. * @author Ian Christian Myers */ //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslintTester = require("eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ <|fim▁hole|> { code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 3] }, "function foo() { if (true) { if (false) { if (true) { } } } }" ], invalid: [ { code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 2], errors: [{ message: "Blocks are nested too deeply (3).", type: "IfStatement"}] }, { code: "function foo() { if (true) {} else { for(;;) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "ForStatement"}] }, { code: "function foo() { while (true) { if (true) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}] }, { code: "function foo() { while (true) { if (true) { if (false) { } } } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}, { message: "Blocks are nested too deeply (3).", type: "IfStatement"}] } ] });<|fim▁end|>
eslintTester.addRuleTest("lib/rules/max-depth", { valid: [
<|file_name|>polyfill.js<|end_file_name|><|fim▁begin|>'use strict';<|fim▁hole|> , callable = require('es5-ext/object/valid-callable') , d = require('d') , ee = require('event-emitter') , Symbol = require('es6-symbol') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , Iterator = require('./lib/iterator') , isNative = require('./is-native-implemented') , call = Function.prototype.call, defineProperty = Object.defineProperty , SetPoly, getValues; module.exports = SetPoly = function (/*iterable*/) { var iterable = arguments[0]; if (!(this instanceof SetPoly)) return new SetPoly(iterable); if (this.__setData__ !== undefined) { throw new TypeError(this + " cannot be reinitialized"); } if (iterable != null) iterator(iterable); defineProperty(this, '__setData__', d('c', [])); if (!iterable) return; forOf(iterable, function (value) { if (eIndexOf.call(this, value) !== -1) return; this.push(value); }, this.__setData__); }; if (isNative) { if (setPrototypeOf) setPrototypeOf(SetPoly, Set); SetPoly.prototype = Object.create(Set.prototype, { constructor: d(SetPoly) }); } ee(Object.defineProperties(SetPoly.prototype, { add: d(function (value) { if (this.has(value)) return this; this.emit('_add', this.__setData__.push(value) - 1, value); return this; }), clear: d(function () { if (!this.__setData__.length) return; clear.call(this.__setData__); this.emit('_clear'); }), delete: d(function (value) { var index = eIndexOf.call(this.__setData__, value); if (index === -1) return false; this.__setData__.splice(index, 1); this.emit('_delete', index, value); return true; }), entries: d(function () { return new Iterator(this, 'key+value'); }), forEach: d(function (cb/*, thisArg*/) { var thisArg = arguments[1], iterator, result, value; callable(cb); iterator = this.values(); result = iterator._next(); while (result !== undefined) { value = iterator._resolve(result); call.call(cb, thisArg, value, value, this); result = iterator._next(); } }), has: d(function (value) { return (eIndexOf.call(this.__setData__, value) !== -1); }), keys: d(getValues = function () { return this.values(); }), size: d.gs(function () { return this.__setData__.length; }), values: d(function () { return new Iterator(this); }), toString: d(function () { return '[object Set]'; }) })); defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues)); defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));<|fim▁end|>
var clear = require('es5-ext/array/#/clear') , eIndexOf = require('es5-ext/array/#/e-index-of') , setPrototypeOf = require('es5-ext/object/set-prototype-of')
<|file_name|>PortCheckerPluginMock.py<|end_file_name|><|fim▁begin|>from random import randint from yapsy.IPlugin import IPlugin class PortCheckerPlugin(IPlugin): """ Mocked Version: Return random 0 or 1 as exit_code <|fim▁hole|> a TCP connection to that port. Output is success 0 or failure > 0 """ def execute(self, info): val = randint(0, 10) if val != 0: val = 1 info.output_values['exit_code'] = randint(0, 1)<|fim▁end|>
Takes an ip address and a port as inputs and trys to make
<|file_name|>import_star_definitions.py<|end_file_name|><|fim▁begin|>class Class(object): pass def func():<|fim▁hole|>CONSTANT = 42<|fim▁end|>
return 3.14
<|file_name|>opcode.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # # Manage JSON database of Micro-BESM opcodes. # import sys, json, codecs # Check parameters. if len(sys.argv) != 2: print "Usage:" print " opcode [option] file.json" print "Options:" print " TODO" sys.exit(1) opcode = [] # List of all opcodes # # Process the input file. # def main(filename): read_data(filename) write_results("output.json") # # Load opcode[] from JSON file. # def read_data(filename): global opcode try: file = open(filename) opcode = json.load(file) file.close() except: print "Fatal error: Cannot load file '" + filename + "'" sys.exit(1) print "Load file '"+filename+"':", print "%d opcodes" % len(opcode) #print "Opcodes:", opcode # # Write the data to another JSON file.<|fim▁hole|># def write_results(filename): file = codecs.open(filename, 'w', encoding="utf-8") json.dump(opcode, file, indent=4, sort_keys=True, ensure_ascii=False) file.close() print "Write file %s: %d opcodes" % (filename, len(opcode)) if __name__ == "__main__": main(sys.argv[1])<|fim▁end|>
<|file_name|>jwt.go<|end_file_name|><|fim▁begin|>package util import ( "net/http" "github.com/dgrijalva/jwt-go" "github.com/mb-dev/godo/config" ) func JWTMiddleware(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) { token, err := jwt.ParseFromRequest(req, func(token *jwt.Token) ([]byte, error) { return []byte(config.CurrentConfiguration.KeySecret), nil<|fim▁hole|> if err != nil || !token.Valid { rw.WriteHeader(http.StatusForbidden) return } ContextSetUserId(req, token.Claims["id"].(string)) next(rw, req) }<|fim▁end|>
})
<|file_name|>performance_timeline.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/. */ // XXX The spec says that the performance timeline task source should be // a low priority task and it should be processed during idle periods. // We are currently treating this task queue as a normal priority queue. use dom::bindings::refcounted::Trusted; use dom::globalscope::GlobalScope; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory}; use std::fmt; use std::result::Result; use task::{TaskCanceller, TaskOnce}; use task_source::TaskSource; #[derive(JSTraceable)] pub struct PerformanceTimelineTaskSource(pub Box<ScriptChan + Send + 'static>); impl Clone for PerformanceTimelineTaskSource { fn clone(&self) -> PerformanceTimelineTaskSource { PerformanceTimelineTaskSource(self.0.clone()) } } impl fmt::Debug for PerformanceTimelineTaskSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "PerformanceTimelineTaskSource(...)") }<|fim▁hole|> &self, task: T, canceller: &TaskCanceller, ) -> Result<(), ()> where T: TaskOnce + 'static, { let msg = CommonScriptMsg::Task( ScriptThreadEventCategory::PerformanceTimelineTask, Box::new(canceller.wrap_task(task)) ); self.0.send(msg).map_err(|_| ()) } } impl PerformanceTimelineTaskSource { pub fn queue_notification(&self, global: &GlobalScope) { let owner = Trusted::new(&*global.performance()); // FIXME(nox): Why are errors silenced here? let _ = self.queue( task!(notify_performance_observers: move || { owner.root().notify_observers(); }), global, ); } }<|fim▁end|>
} impl TaskSource for PerformanceTimelineTaskSource { fn queue_with_canceller<T>(
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod bodies; pub mod starsystem;<|fim▁hole|>#[cfg(test)] mod test;<|fim▁end|>
<|file_name|>flask_app.py<|end_file_name|><|fim▁begin|># Copyright 2019 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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.<|fim▁hole|># limitations under the License. # [START ndb_flask] from flask import Flask from google.cloud import ndb client = ndb.Client() def ndb_wsgi_middleware(wsgi_app): def middleware(environ, start_response): with client.context(): return wsgi_app(environ, start_response) return middleware app = Flask(__name__) app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app) # Wrap the app in middleware. class Book(ndb.Model): title = ndb.StringProperty() @app.route('/') def list_books(): books = Book.query() return str([book.to_dict() for book in books]) # [END ndb_flask]<|fim▁end|>
# See the License for the specific language governing permissions and
<|file_name|>isVATPayer.js<|end_file_name|><|fim▁begin|>import {TOGGLE_IS_VAT_PAYER} from '../actions'; export function isVATPayer(state = false, action) { switch (action.type) { case TOGGLE_IS_VAT_PAYER: return !state;<|fim▁hole|><|fim▁end|>
default: return state; } }
<|file_name|>app.config.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>import { EnvConfig } from '../../../tools/config/app.config' export const ENV_CONFIG = new InjectionToken<EnvConfig>('app.config')<|fim▁end|>
import { InjectionToken } from '@angular/core'
<|file_name|>countries-dropdown.ts<|end_file_name|><|fim▁begin|>import {PolymerElement, html} from '@polymer/polymer/polymer-element.js'; import {connect} from 'pwa-helpers/connect-mixin.js'; import {store, RootState} from '../../../store.js'; import '@unicef-polymer/etools-dropdown/etools-dropdown.js'; import EtoolsPageRefreshMixin from '@unicef-polymer/etools-behaviors/etools-page-refresh-mixin.js'; import EndpointsMixin from '../../endpoints/endpoints-mixin.js'; import {sendRequest} from '@unicef-polymer/etools-ajax/etools-ajax-request'; import {fireEvent} from '../../utils/fire-custom-event.js'; import {logError} from '@unicef-polymer/etools-behaviors/etools-logging'; import {property} from '@polymer/decorators'; import {GenericObject} from '../../../typings/globals.types.js'; import {EtoolsDropdownEl} from '@unicef-polymer/etools-dropdown/etools-dropdown.js'; /** * @polymer * @customElement * @mixinFunction * @appliesMixin EndpointsMixin * @appliesMixin EtoolsPageRefreshMixin */ class CountriesDropdown extends connect(store)(EtoolsPageRefreshMixin(EndpointsMixin(PolymerElement))) { public static get template() { // main template // language=HTML return html` <style> *[hidden] { display: none !important; } :host { display: block; --paper-input-container-shared-input-style_-_color: var(--countries-dropdown-color); } :host(:hover) { cursor: pointer; } etools-dropdown { width: 160px; --paper-listbox: { max-height: 600px; } --esmm-icons: { color: var(--countries-dropdown-color); cursor: pointer; } --paper-input-container-underline: { display: none; } --paper-input-container-underline-focus: { display: none; } --paper-input-container-underline-disabled: { display: none; } --paper-input-container-input: { color: var(--countries-dropdown-color); cursor: pointer; min-height: 24px;<|fim▁hole|> } --paper-menu-button-dropdown: { max-height: 380px; } } @media (max-width: 768px) { etools-dropdown { width: 130px; } } </style> <!-- shown options limit set to 250 as there are currently 195 countries in the UN council and about 230 total --> <etools-dropdown id="countrySelector" hidden$="[[!countrySelectorVisible]]" selected="[[currentCountry.id]]" placeholder="Country" allow-outside-scroll no-label-float options="[[countries]]" option-label="name" option-value="id" trigger-value-change-event on-etools-selected-item-changed="_countrySelected" shown-options-limit="250" hide-search ></etools-dropdown> `; } @property({type: Object}) currentCountry: GenericObject = {}; @property({type: Array, observer: '_countrySelectorUpdate'}) countries: any[] = []; @property({type: Boolean}) countrySelectorVisible = false; public connectedCallback() { super.connectedCallback(); setTimeout(() => { const fitInto = document.querySelector('app-shell')!.shadowRoot!.querySelector('#appHeadLayout'); (this.$.countrySelector as EtoolsDropdownEl).set('fitInto', fitInto); }, 0); } public stateChanged(state: RootState) { // TODO: polymer 3 do what? if (!state) { return; } } protected _countrySelected(e: any) { if (!e.detail.selectedItem) { return; } const selectedCountryId = parseInt(e.detail.selectedItem.id, 10); if (selectedCountryId !== this.currentCountry.id) { // send post request to change_coutry endpoint this._triggerCountryChangeRequest(selectedCountryId); } } protected _triggerCountryChangeRequest(countryId: any) { fireEvent(this, 'global-loading', { message: 'Please wait while country data is changing...', active: true, loadingSource: 'country-change' }); sendRequest({ endpoint: this.getEndpoint('changeCountry'), method: 'POST', body: {country: countryId} }) .then(() => { this._handleResponse(); }) .catch((error: any) => { this._handleError(error); }); } protected _handleResponse() { fireEvent(this, 'update-main-path', {path: 'partners'}); this.refresh(); } protected _countrySelectorUpdate(countries: any) { if (Array.isArray(countries) && countries.length > 1) { this.countrySelectorVisible = true; } } protected _handleError(error: any) { logError('Country change failed!', 'countries-dropdown', error); (this.$.countrySelector as EtoolsDropdownEl).set('selected', this.currentCountry.id); fireEvent(this, 'toast', { text: 'Something went wrong changing your workspace. Please try again' }); fireEvent(this, 'global-loading', { active: false, loadingSource: 'country-change' }); } } window.customElements.define('countries-dropdown', CountriesDropdown);<|fim▁end|>
text-align: right; line-height: 21px; /* for IE */
<|file_name|>epitopefinder_plotdistributioncomparison.py<|end_file_name|><|fim▁begin|>#!python """Script for plotting distributions of epitopes per site for two sets of sites. Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py. Written by Jesse Bloom.""" import os import sys import random import epitopefinder.io import epitopefinder.plot def main(): """Main body of script.""" random.seed(1) # seed random number generator in case P values are being computed if not epitopefinder.plot.PylabAvailable(): raise ImportError("Cannot import matplotlib / pylab, which are required by this script.") # output is written to out, currently set to standard out out = sys.stdout out.write("Beginning execution of epitopefinder_plotdistributioncomparison.py\n") # read input file and parse arguments args = sys.argv[1 : ] if len(args) != 1: raise IOError("Script must be called with exactly one argument specifying the input file") infilename = sys.argv[1] if not os.path.isfile(infilename):<|fim▁hole|> out.write("\nRead input arguments from %s\n" % infilename) out.write('Read the following key / value pairs:\n') for (key, value) in d.iteritems(): out.write("%s %s\n" % (key, value)) plotfile = epitopefinder.io.ParseStringValue(d, 'plotfile').strip() epitopesbysite1_list = [] epitopesbysite2_list = [] for (xlist, xf) in [(epitopesbysite1_list, 'epitopesfile1'), (epitopesbysite2_list, 'epitopesfile2')]: epitopesfile = epitopefinder.io.ParseFileList(d, xf) if len(epitopesfile) != 1: raise ValueError("%s specifies more than one file" % xf) epitopesfile = epitopesfile[0] for line in open(epitopesfile).readlines()[1 : ]: if not (line.isspace() or line[0] == '#'): (site, n) = line.split(',') (site, n) = (int(site), int(n)) xlist.append(n) if not xlist: raise ValueError("%s failed to specify information for any sites" % xf) set1name = epitopefinder.io.ParseStringValue(d, 'set1name') set2name = epitopefinder.io.ParseStringValue(d, 'set2name') title = epitopefinder.io.ParseStringValue(d, 'title').strip() if title.upper() in ['NONE', 'FALSE']: title = None pvalue = epitopefinder.io.ParseStringValue(d, 'pvalue') if pvalue.upper() in ['NONE', 'FALSE']: pvalue = None pvaluewithreplacement = None else: pvalue = int(pvalue) pvaluewithreplacement = epitopefinder.io.ParseBoolValue(d, 'pvaluewithreplacement') if pvalue < 1: raise ValueError("pvalue must be >= 1") if len(epitopesbysite2_list) >= len(epitopesbysite1_list): raise ValueError("You cannot use pvalue since epitopesbysite2_list is not a subset of epitopesbysite1_list -- it does not contain fewer sites with specified epitope counts.") ymax = None if 'ymax' in d: ymax = epitopefinder.io.ParseFloatValue(d, 'ymax') out.write('\nNow creating the plot file %s\n' % plotfile) epitopefinder.plot.PlotDistributionComparison(epitopesbysite1_list, epitopesbysite2_list, set1name, set2name, plotfile, 'number of epitopes', 'fraction of sites', title, pvalue, pvaluewithreplacement, ymax=ymax) out.write("\nScript is complete.\n") if __name__ == '__main__': main() # run the script<|fim▁end|>
raise IOError("Failed to find infile %s" % infilename) d = epitopefinder.io.ParseInfile(open(infilename))
<|file_name|>lstm_layer.hpp<|end_file_name|><|fim▁begin|>//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License.<|fim▁hole|>// http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "dll/neural/lstm/dyn_lstm_layer.hpp" #include "dll/neural/lstm/lstm_layer_impl.hpp" #include "dll/neural/lstm/lstm_layer_desc.hpp"<|fim▁end|>
// (See accompanying file LICENSE or copy at
<|file_name|>bases.py<|end_file_name|><|fim▁begin|>import re from functools import reduce from typing import Optional, Callable, Any, Type, Union import wx # type: ignore from gooey.gui import formatters, events from gooey.gui.util import wx_util from gooey.python_bindings.types import FormField from gooey.util.functional import getin, ifPresent from gooey.gui.validators import runValidator from gooey.gui.components.util.wrapped_static_text import AutoWrappedStaticText from gooey.gui.components.mouse import notifyMouseEvent from gooey.python_bindings import types as t class BaseWidget(wx.Panel): widget_class: Any def arrange(self, label, text): raise NotImplementedError def getWidget(self, parent: wx.Window, **options): return self.widget_class(parent, **options) def connectSignal(self): raise NotImplementedError def getSublayout(self, *args, **kwargs): raise NotImplementedError def setValue(self, value): raise NotImplementedError def setPlaceholder(self, value): raise NotImplementedError def receiveChange(self, *args, **kwargs): raise NotImplementedError def dispatchChange(self, value, **kwargs): raise NotImplementedError def formatOutput(self, metatdata, value): raise NotImplementedError class TextContainer(BaseWidget): # TODO: fix this busted-ass inheritance hierarchy. # Cracking at the seems for more advanced widgets # problems: # - all the usual textbook problems of inheritance # - assumes there will only ever be ONE widget created # - assumes those widgets are all created in `getWidget` # - all the above make for extremely awkward lifecycle management # - no clear point at which binding is correct. # - I think the core problem here is that I couple the interface # for shared presentation layout with the specification of # a behavioral interface # - This should be broken apart. # - presentation can be ad-hoc or composed # - behavioral just needs a typeclass of get/set/format for Gooey's purposes widget_class = None # type: ignore def __init__(self, parent, widgetInfo, *args, **kwargs): super(TextContainer, self).__init__(parent, *args, **kwargs) self.info = widgetInfo self._id = widgetInfo['id'] self.widgetInfo = widgetInfo self._meta = widgetInfo['data'] self._options = widgetInfo['options'] self.label = wx.StaticText(self, label=widgetInfo['data']['display_name']) self.help_text = AutoWrappedStaticText(self, label=widgetInfo['data']['help'] or '') self.error = AutoWrappedStaticText(self, label='') self.error.Hide() self.widget = self.getWidget(self) self.layout = self.arrange(*args, **kwargs) self.setColors() self.SetSizer(self.layout) self.bindMouseEvents() self.Bind(wx.EVT_SIZE, self.onSize) # 1.0.7 initial_value should supersede default when both are present <|fim▁hole|> if self._options.get('initial_value') is not None: self.setValue(self._options['initial_value']) # Checking for None instead of truthiness means False-evaluaded defaults can be used. elif self._meta['default'] is not None: self.setValue(self._meta['default']) if self._options.get('placeholder'): self.setPlaceholder(self._options.get('placeholder')) self.onComponentInitialized() def onComponentInitialized(self): pass def bindMouseEvents(self): """ Send any LEFT DOWN mouse events to interested listeners via pubsub. see: gooey.gui.mouse for background. """ self.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) self.label.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) self.help_text.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) self.error.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) self.widget.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) def arrange(self, *args, **kwargs): wx_util.make_bold(self.label) wx_util.withColor(self.label, self._options['label_color']) wx_util.withColor(self.help_text, self._options['help_color']) wx_util.withColor(self.error, self._options['error_color']) self.help_text.SetMinSize((0,-1)) layout = wx.BoxSizer(wx.VERTICAL) if self._options.get('show_label', True): layout.Add(self.label, 0, wx.EXPAND) else: self.label.Show(False) layout.AddStretchSpacer(1) layout.AddSpacer(2) if self.help_text and self._options.get('show_help', True): layout.Add(self.help_text, 1, wx.EXPAND) layout.AddSpacer(2) else: self.help_text.Show(False) layout.AddStretchSpacer(1) layout.Add(self.getSublayout(), 0, wx.EXPAND) layout.Add(self.error, 1, wx.EXPAND) # self.error.SetLabel("HELLOOOOO??") # self.error.Show() # print(self.error.Shown) return layout def setColors(self): wx_util.make_bold(self.label) wx_util.withColor(self.label, self._options['label_color']) wx_util.withColor(self.help_text, self._options['help_color']) wx_util.withColor(self.error, self._options['error_color']) if self._options.get('label_bg_color'): self.label.SetBackgroundColour(self._options.get('label_bg_color')) if self._options.get('help_bg_color'): self.help_text.SetBackgroundColour(self._options.get('help_bg_color')) if self._options.get('error_bg_color'): self.error.SetBackgroundColour(self._options.get('error_bg_color')) def getWidget(self, *args, **options): return self.widget_class(*args, **options) def getWidgetValue(self): raise NotImplementedError def getSublayout(self, *args, **kwargs): layout = wx.BoxSizer(wx.HORIZONTAL) layout.Add(self.widget, 1, wx.EXPAND) return layout def onSize(self, event): # print(self.GetSize()) # self.error.Wrap(self.GetSize().width) # self.help_text.Wrap(500) # self.Layout() event.Skip() def getUiState(self) -> t.FormField: return t.TextField( id=self._id, type=self.widgetInfo['type'], value=self.getWidgetValue(), placeholder=self.widget.widget.GetHint(), error=self.error.GetLabel().replace('\n', ' '), enabled=self.IsEnabled(), visible=self.IsShown() ) def syncUiState(self, state: FormField): # type: ignore self.widget.setValue(state['value']) # type: ignore self.error.SetLabel(state['error'] or '') self.error.Show(state['error'] is not None and state['error'] is not '') def getValue(self) -> t.FieldValue: regexFunc: Callable[[str], bool] = lambda x: bool(re.match(userValidator, x)) userValidator = getin(self._options, ['validator', 'test'], 'True') message = getin(self._options, ['validator', 'message'], '') testFunc = regexFunc \ if getin(self._options, ['validator', 'type'], None) == 'RegexValidator'\ else eval('lambda user_input: bool(%s)' % userValidator) satisfies = testFunc if self._meta['required'] else ifPresent(testFunc) value = self.getWidgetValue() return t.FieldValue( # type: ignore id=self._id, cmd=self.formatOutput(self._meta, value), meta=self._meta, rawValue= value, # type=self.info['type'], enabled=self.IsEnabled(), visible=self.IsShown(), test= runValidator(satisfies, value), error=None if runValidator(satisfies, value) else message, clitype=('positional' if self._meta['required'] and not self._meta['commands'] else 'optional') ) def setValue(self, value): self.widget.SetValue(value) def setPlaceholder(self, value): if getattr(self.widget, 'SetHint', None): self.widget.SetHint(value) def setErrorString(self, message): self.error.SetLabel(message) self.error.Wrap(self.Size.width) self.Layout() def showErrorString(self, b): self.error.Wrap(self.Size.width) self.error.Show(b) def setOptions(self, values): return None def receiveChange(self, metatdata, value): raise NotImplementedError def dispatchChange(self, value, **kwargs): raise NotImplementedError def formatOutput(self, metadata, value) -> str: raise NotImplementedError class BaseChooser(TextContainer): """ Base Class for the Chooser widget types """ def setValue(self, value): self.widget.setValue(value) def setPlaceholder(self, value): self.widget.SetHint(value) def getWidgetValue(self): return self.widget.getValue() def formatOutput(self, metatdata, value): return formatters.general(metatdata, value) def getUiState(self) -> t.FormField: btn: wx.Button = self.widget.button # type: ignore return t.Chooser( id=self._id, type=self.widgetInfo['type'], value=self.widget.getValue(), btn_label=btn.GetLabel(), error=self.error.GetLabel() or None, enabled=self.IsEnabled(), visible=self.IsShown() )<|fim▁end|>
<|file_name|>Thumbnail.client.controller.js<|end_file_name|><|fim▁begin|>app.controller('ThumbnailCtrl', function($http, Upload, $timeout, $location, $anchorScroll, $stateParams, $cookies){ thumbnailCtrl = this; thumbnailCtrl.sendEmail = function(){ $http.get('/api/sendEmail').success(function(response){ console.log('Ok') }).catch(function(err){ console.log(err) }); }; thumbnailCtrl.getThumbnails = function(){ thumbnailCtrl.loading=true; $http.get('/api/thumbnails').success(function(response){ thumbnailCtrl.thumbnailData = response.thumbnailsFound; thumbnailCtrl.actualPage = response.actualPage; articleLoader(); paginatorCalculator(response); getLastPosts(); thumbnailCtrl.loading = false; }).catch(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.responseError = response; }); }; thumbnailCtrl.postThumbnail = function(myFile){ thumbnailCtrl.loading=true; if(myFile){ Upload.upload({ url: '/api/thumbnails', method: 'POST', data: { file: Upload.dataUrltoBlob(myFile), thumbnailTitle: thumbnailCtrl.thumbnailTitle, thumbnailBody: thumbnailCtrl.thumbnailBody, articleTitle: thumbnailCtrl.articleTitle, articleBody: thumbnailCtrl.articleBody } }).then(function(response){ $timeout(function(){ myFile.result = response.data; thumbnailCtrl.loading = false; thumbnailCtrl.response = response.data.message; thumbnailCtrl.credentials = response.data.credentials; }); }, function(responseError){ if(responseError) thumbnailCtrl.responseError = responseError;<|fim▁hole|> } }; thumbnailCtrl.removeThumbnail = function(myTitle){ $http.delete('/api/thumbnails/'+myTitle).success(function(response){ thumbnailCtrl.getThumbnails(); }).catch(function(response){ thumbnailCtrl.responseError = 'Something went wrong'; }); }; thumbnailCtrl.editThumbnail = function(myTitle, editTitle, editBody){ $http.put('/api/thumbnails/'+myTitle, { thumbnailTitle: editTitle, thumbnailBody: editBody }).success(function(response){ thumbnailCtrl.getThumbnails(); }).catch(function(response){ console.log(response); thumbnailCtrl.responseError = 'Something went wrong'; }); }; thumbnailCtrl.getPage = function(pageQuery){ $http.get('/api/thumbnails?page='+pageQuery).success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.thumbnailData = response.thumbnailsFound; thumbnailCtrl.actualPage = response.actualPage; }).catch(function(response){ alert('Something went wrong'); }); }; thumbnailCtrl.selectIndex = function(index){ thumbnailCtrl.loading = true; for (var i = 0; i < thumbnailCtrl.thumbnailData.length; i++) { if(thumbnailCtrl.thumbnailData[i] == thumbnailCtrl.thumbnailData[index]){ thumbnailCtrl.articleFound = thumbnailCtrl.thumbnailData[i]; thumbnailCtrl.loading = false; return thumbnailCtrl.thumbnailData[i]; } } }; thumbnailCtrl.editArticle = function(editedTitle, editedBody){ thumbnailCtrl.loading = true; var myTitle = thumbnailCtrl.thumbnailData[$stateParams.id].thumbnailTitle; $http.put('/api/article/'+myTitle, { articleTitle: editedTitle, articleBody: editedBody }).success(function(response){ console.log(response) thumbnailCtrl.getThumbnails(); thumbnailCtrl.loading = false; }).catch(function(error){ console.log(error) }); }; thumbnailCtrl.getThumbnailsLimit = function(limitQuery, pageQuery){ thumbnailCtrl.loading=true; if(pageQuery){ $http.get('/api/thumbnails/search?limit='+limitQuery+'&page='+pageQuery).success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.thumbnailData = response.thumbnailsFound; }).catch(function(response){ alert('Something went wrong'); }); }else{ $http.get('/api/thumbnails/search?limit='+limitQuery).success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.thumbnailData = response.thumbnailsFound; }).catch(function(response){ alert('Something went wrong'); }); } }; thumbnailCtrl.scrollToTop = function(){ $location.hash('scrollTop'); $anchorScroll(); }; thumbnailCtrl.currentParamsId = function(){ return $stateParams.id; }; thumbnailCtrl.isLogged = function(){ if($cookies.get('username')){ return true; }else{ return false; } } function paginatorCalculator(response){ //Paginator calculation var totalPages = Math.ceil(response.totalPages/18); var range = []; for (var i = 1; i <= totalPages; i++) { range.push(i); } thumbnailCtrl.pagesArray = range; } function articleLoader(){ if(Object.keys($stateParams).length != 0){ //the id object is defined in the routes app.js thumbnailCtrl.selectIndex($stateParams.id); } }; function getLastPosts(){ $http.get('/api/thumbnails?lastPosts=10').success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.lastPosts = response.thumbnailsFound; }).catch(function(response){ console.log('error'+response.error); }); }; });<|fim▁end|>
});
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; function Square(props) { return ( <button className="square" onClick={props.onClick}> {props.value} </button> ); } class Board extends React.Component { renderSquare(i) { return ( <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} /> ); } render() { return ( <div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); } } class Game extends React.Component { constructor(props) { super(props); this.state = { history: [{ squares: Array(9).fill(null) }], xIsNext: true }; } handleClick(i) { const history = this.state.history; const current = history[history.length - 1]; const squares = current.squares.slice(); if (calculateWinner(squares) || squares[i]) { return; } squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState({ history: history.concat([{ squares: squares }]), xIsNext: !this.state.xIsNext, });<|fim▁hole|> render() { const history = this.state.history; const current = history[history.length - 1]; const winner = calculateWinner(current.squares); let status; if (winner) { status = 'Winner: ' + winner; } else { status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O'); } return ( <div className="game"> <div className="game-board"> <Board squares={current.squares} onClick={(i) => this.handleClick(i)} /> </div> <div className="game-info"> <div>{status}</div> <ol>{/* TODO */}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; }<|fim▁end|>
}
<|file_name|>grammar2.py<|end_file_name|><|fim▁begin|>import re from collections import OrderedDict import compiler.lang as lang doc_next = None doc_prev_component = None doc_root_component = None class CustomParser(object): def match(self, next): raise Exception("Expression should implement match method") escape_re = re.compile(r"[\0\n\r\v\t\b\f]") escape_map = { '\0': '\\0', '\n': '\\n', '\r': '\\r', '\v': '\\v', '\t': '\\t', '\b': '\\b', '\f': '\\f' } def escape(str): return escape_re.sub(lambda m: escape_map[m.group(0)], str) class StringParser(CustomParser): def match(self, next): n = len(next) if n < 2: return quote = next[0] if quote != "'" and quote != "\"": return pos = 1 while next[pos] != quote: if next[pos] == "\\": pos += 2 else: pos += 1 if pos >= n: raise Exception("Unexpected EOF while parsing string") return next[:pos + 1] skip_re = re.compile(r'(?:\s+|/\*.*?\*/|//[^\n]*(?:$|\n))', re.DOTALL) COMPONENT_NAME = r'(?:[a-z][a-zA-Z0-9._]*\.)?[A-Z][A-Za-z0-9]*' component_name = re.compile(COMPONENT_NAME) component_name_lookahead = re.compile(COMPONENT_NAME + r'\s*{') identifier_re = re.compile(r'[a-z_][A-Za-z0-9_]*') property_type_re = re.compile(r'[a-z][a-z0-9]*', re.IGNORECASE) nested_identifier_re = re.compile(r'[a-z_][A-Za-z0-9_\.]*') function_name_re = re.compile(r'[a-z_][a-z0-9_\.]*', re.IGNORECASE) string_re = StringParser() kw_re = re.compile(r'(?:true|false|null)') NUMBER_RE = r"(?:\d+\.\d+(e[+-]?\d+)?|(?:0x)?[0-9]+)" number_re = re.compile(NUMBER_RE, re.IGNORECASE) percent_number_re = re.compile(NUMBER_RE + r'%', re.IGNORECASE) scale_number_re = re.compile(NUMBER_RE + r's', re.IGNORECASE) rest_of_the_line_re = re.compile(r".*$", re.MULTILINE) json_object_value_delimiter_re = re.compile(r"[,;]") dep_var = re.compile(r"\${(.*?)}") class Expression(object): __slots__ = ('op', 'args') def __init__(self, op, *args): self.op, self.args = op, args def __repr__(self): return "Expression %s { %s }" %(self.op, ", ".join(map(repr, self.args))) def __str__(self): args = self.args n = len(args) if n == 1: return "(%s %s)" %(self.op, args[0]) elif n == 2: return "(%s %s %s)" %(args[0], self.op, args[1]) elif n == 3: op = self.op return "(%s %s %s %s %s)" %(args[0], op[0], args[1], op[1], args[2]) else: raise Exception("invalid argument counter") class Call(object): __slots__ = ('func', 'args') def __init__(self, func, args): self.func = func self.args = args def __repr__(self): return "Call %s { %s }" %(self.func, self.args) def __str__(self): if isinstance(self.func, Literal): name = self.func.term if name[0].islower(): if '.' in name: name = '${%s}' %name else: name = '$this._context.%s' %name else: name = str(self.func) #if lhs is not an literal, than we can't process deps, removing ${xxx} name = dep_var.sub(lambda m: m.group(1), name) return "%s(%s)" %(name, ",".join(map(str, self.args))) class Dereference(object): __slots__ = ('array', 'index') def __init__(self, array, index): self.array = array self.index = index def __str__(self): return "(%s[%s])" %(self.array, self.index) class Literal(object): __slots__ = ('lbp', 'term', 'identifier') def __init__(self, term, string = False, identifier = False): self.term = escape(term) if string else term self.lbp = 0 self.identifier = identifier def nud(self, state): return self def __repr__(self): return "Literal { %s }" %self.term def __str__(self): return "${%s}" %self.term if self.identifier and self.term[0].islower() else self.term class PrattParserState(object): def __init__(self, parent, parser, token): self.parent, self.parser, self.token = parent, parser, token class PrattParser(object): def __init__(self, ops): symbols = [(x.term, x) for x in ops] symbols.sort(key=lambda x: len(x[0]), reverse=True) self.symbols = symbols def next(self, parser): parser._skip() next = parser.next next_n = len(next) for term, sym in self.symbols: n = len(term) if n > next_n: continue keyword = term[-1].isalnum() if next.startswith(term): if keyword and n < next_n and next[n].isalnum(): continue<|fim▁hole|> if next: return Literal(next) next = parser.maybe(percent_number_re) if next: next = next[:-1] return Literal("((%s) / 100 * ${parent.<property-name>})" %next) if next != 100 else "(${parent.<property-name>})" next = parser.maybe(scale_number_re) if next: next = next[:-1] return Literal("((%s) * ${context.<scale-property-name>})" %next) next = parser.maybe(number_re) if next: return Literal(next) next = parser.maybe(function_name_re) if next: return Literal(next, identifier=True) next = parser.maybe(string_re) if next: return Literal(next, string=True) return None def advance(self, state, expect = None): if expect is not None: state.parser.read(expect, "Expected %s in expression" %expect) state.token = self.next(state.parser) def expression(self, state, rbp = 0): parser = state.parser t = state.token state.token = self.next(parser) if state.token is None: return t left = t.nud(state) while state.token is not None and rbp < state.token.lbp: t = state.token self.advance(state) left = t.led(state, left) return left def parse(self, parser): token = self.next(parser) if token is None: parser.error("Unexpected expression") state = PrattParserState(self, parser, token) return self.expression(state) class UnsupportedOperator(object): __slots__ = ('term', 'lbp', 'rbp') def __init__(self, term, lbp = 0, rbp = 0): self.term, self.lbp, self.rbp = term, lbp, rbp def nud(self, state): state.parser.error("Unsupported prefix operator %s" %self.term) def led(self, state, left): state.parser.error("Unsupported postfix operator %s" %self.term) def __repr__(self): return "UnsupportedOperator { %s %s }" %(self.term, self.lbp) class Operator(object): __slots__ = ('term', 'lbp', 'rbp') def __init__(self, term, lbp = 0, rbp = None): self.term, self.lbp, self.rbp = term, lbp, rbp def nud(self, state): if self.rbp is not None: return Expression(self.term, state.parent.expression(state, self.rbp)) state.parser.error("Unexpected token in infix expression: '%s'" %self.term) def led(self, state, left): if self.lbp is not None: return Expression(self.term, left, state.parent.expression(state, self.lbp)) else: state.parser.error("No left-associative operator defined") def __repr__(self): return "Operator { %s %s %s }" %(self.term, self.lbp, self.rbp) class Conditional(object): __slots__ = ('term', 'lbp') def __init__(self, lbp): self.term = '?' self.lbp = lbp def nud(self, state): state.parser.error("Conditional operator can't be used as unary") def led(self, state, left): true = state.parent.expression(state) state.parent.advance(state, ':') false = state.parent.expression(state) return Expression(('?', ':'), left, true, false) def __repr__(self): return "Conditional { }" class LeftParenthesis(object): __slots__ = ('term', 'lbp') def __init__(self, lbp): self.term = '(' self.lbp = lbp def nud(self, state): expr = state.parent.expression(state) state.parent.advance(state, ')') return expr def led(self, state, left): args = [] next = state.token if next.term != ')': while True: args.append(state.parent.expression(state)) if state.token is not None: state.parser.error("Unexpected token %s" %state.token) if not state.parser.maybe(','): break state.parent.advance(state) state.parent.advance(state, ')') return Call(left, args) def __repr__(self): return "LeftParenthesis { %d }" %self.lbp class LeftSquareBracket(object): __slots__ = ('term', 'lbp') def __init__(self, lbp): self.term = '[' self.lbp = lbp def nud(self, state): state.parser.error("Invalid [] expression") def led(self, state, left): arg = state.parent.expression(state) if state.token is not None: state.parser.error("Unexpected token %s" %state.token) state.parent.advance(state, ']') return Dereference(left, arg) def __repr__(self): return "LeftSquareBracket { %d }" %self.lbp infix_parser = PrattParser([ Operator('.', 19), LeftParenthesis(19), LeftSquareBracket(19), UnsupportedOperator('++', 17, 16), UnsupportedOperator('--', 17, 16), UnsupportedOperator('void', None, 16), UnsupportedOperator('delete', None, 16), UnsupportedOperator('await', None, 16), Operator('typeof', None, 16), Operator('!', None, 16), Operator('~', None, 16), Operator('+', 13, 16), Operator('-', 13, 16), Operator('typeof', None, 16), Operator('**', 15), Operator('*', 14), Operator('/', 14), Operator('%', 14), Operator('<<', 12), Operator('>>', 12), Operator('>>>', 12), Operator('<', 11), Operator('<=', 11), Operator('>', 11), Operator('>=', 11), Operator('in', 11), Operator('instanceof', 11), Operator('==', 10), Operator('!=', 10), Operator('===', 10), Operator('!==', 10), Operator('&', 9), Operator('^', 8), Operator('|', 7), Operator('&&', 6), Operator('||', 5), Conditional(4), ]) class Parser(object): def __init__(self, text): self.__text = text self.__pos = 0 self.__lineno = 1 self.__colno = 1 self.__last_object = None self.__next_doc = None @property def at_end(self): return self.__pos >= len(self.__text) @property def next(self): return self.__text[self.__pos:] @property def current_line(self): text = self.__text pos = self.__pos begin = text.rfind('\n', 0, pos) end = text.find('\n', pos) if begin < 0: begin = 0 else: begin += 1 if end < 0: end = len(text) return text[begin:end] def advance(self, n): text = self.__text pos = self.__pos for i in range(n): if text[pos] == '\n': self.__lineno += 1 self.__colno = 1 else: self.__colno += 1 pos += 1 self.__pos = pos def __docstring(self, text, prev): if prev: if self.__last_object: if self.__last_object.doc is not None: self.__last_object.doc = lang.DocumentationString(self.__last_object.doc.text + " " + text) else: self.__last_object.doc = lang.DocumentationString(text) else: self.error("Found docstring without previous object") else: if self.__next_doc is not None: self.__next_doc += " " + text else: self.__next_doc = text def __get_next_doc(self): if self.__next_doc is None: return doc = lang.DocumentationString(self.__next_doc) self.__next_doc = None return doc def __return(self, object, doc): if doc: if object.doc: object.doc = lang.DocumentationString(object.doc.text + " " + doc.text) else: object.doc = doc self.__last_object = object return object def _skip(self): while True: m = skip_re.match(self.next) if m is not None: text = m.group(0).strip() if text.startswith('///<'): self.__docstring(text[4:], True) elif text.startswith('///'): self.__docstring(text[3:], False) elif text.startswith('/**'): end = text.rfind('*/') self.__docstring(text[3:end], False) self.advance(m.end()) else: break def error(self, msg): lineno, col, line = self.__lineno, self.__colno, self.current_line pointer = re.sub(r'\S', ' ', line)[:col - 1] + '^-- ' + msg raise Exception("at line %d:%d:\n%s\n%s" %(lineno, col, self.current_line, pointer)) def lookahead(self, exp): if self.at_end: return self._skip() next = self.next if isinstance(exp, str): keyword = exp[-1].isalnum() n, next_n = len(exp), len(next) if n > next_n: return if next.startswith(exp): #check that exp ends on word boundary if keyword and n < next_n and next[n].isalnum(): return else: return exp elif isinstance(exp, CustomParser): return exp.match(next) else: m = exp.match(next) if m: return m.group(0) def maybe(self, exp): value = self.lookahead(exp) if value is not None: self.advance(len(value)) return value def read(self, exp, error): value = self.maybe(exp) if value is None: self.error(error) return value def __read_statement_end(self): self.read(';', "Expected ; at the end of the statement") def __read_list(self, exp, delimiter, error): result = [] result.append(self.read(exp, error)) while self.maybe(delimiter): result.append(self.read(exp, error)) return result def __read_nested(self, begin, end, error): begin_off = self.__pos self.read(begin, error) counter = 1 while not self.at_end: if self.maybe(begin): counter += 1 elif self.maybe(end): counter -= 1 if counter == 0: end_off = self.__pos value = self.__text[begin_off: end_off] return value else: if not self.maybe(string_re): self.advance(1) def __read_code(self): return self.__read_nested('{', '}', "Expected code block") def __read_expression(self, terminate = True): if self.maybe('['): values = [] while not self.maybe(']'): values.append(self.__read_expression(terminate = False)) if self.maybe(']'): break self.read(',', "Expected ',' as an array delimiter") if terminate: self.__read_statement_end() return "[%s]" % (",".join(map(str, values))) else: value = infix_parser.parse(self) if terminate: self.__read_statement_end() return str(value) def __read_property(self): if self.lookahead(':'): return self.__read_rules_with_id(["property"]) doc = self.__get_next_doc() type = self.read(property_type_re, "Expected type after property keyword") if type == 'enum': type = self.read(identifier_re, "Expected type after enum keyword") self.read('{', "Expected { after property enum") values = self.__read_list(component_name, ',', "Expected capitalised enum element") self.read('}', "Expected } after enum element declaration") if self.maybe(':'): def_value = self.read(component_name, "Expected capitalised default enum value") else: def_value = None self.__read_statement_end() return self.__return(lang.EnumProperty(type, values, def_value), doc) if type == 'const': name = self.read(identifier_re, "Expected const property name") self.read(':', "Expected : before const property code") code = self.__read_code() return self.__return(lang.Property("const", [(name, code)]), doc) if type == 'alias': name = self.read(identifier_re, "Expected alias property name") self.read(':', "Expected : before alias target") target = self.read(nested_identifier_re, "Expected identifier as an alias target") self.__read_statement_end() return self.__return(lang.AliasProperty(name, target), doc) names = self.__read_list(identifier_re, ',', "Expected identifier in property list") if len(names) == 1: #Allow initialisation for the single property def_value = None if self.maybe(':'): if self.lookahead(component_name_lookahead): def_value = self.__read_comp() else: def_value = self.__read_expression() else: self.__read_statement_end() name = names[0] return self.__return(lang.Property(type, [(name, def_value)]), doc) else: self.read(';', 'Expected ; at the end of property declaration') return self.__return(lang.Property(type, map(lambda name: (name, None), names)), doc) def __read_rules_with_id(self, identifiers): args = [] doc = self.__get_next_doc() if self.maybe('('): if not self.maybe(')'): args = self.__read_list(identifier_re, ',', "Expected argument list") self.read(')', "Expected () as an argument list") if self.maybe(':'): if self.lookahead('{'): code = self.__read_code() return self.__return(lang.Method(identifiers, args, code, True, False), doc) if len(identifiers) > 1: self.error("Multiple identifiers are not allowed in assignment") if self.lookahead(component_name_lookahead): return self.__return(lang.Assignment(identifiers[0], self.__read_comp()), doc) value = self.__read_expression() return self.__return(lang.Assignment(identifiers[0], value), doc) elif self.maybe('{'): if len(identifiers) > 1: self.error("Multiple identifiers are not allowed in assignment scope") values = [] while not self.maybe('}'): name = self.read(nested_identifier_re, "Expected identifier in assignment scope") self.read(':', "Expected : after identifier in assignment scope") value = self.__read_expression() values.append(lang.Assignment(name, value)) return self.__return(lang.AssignmentScope(identifiers[0], values), doc) else: self.error("Unexpected identifier(s): %s" %",".join(identifiers)) def __read_function(self, async_f = False): doc = self.__get_next_doc() name = self.read(identifier_re, "Expected identifier") args = [] self.read('(', "Expected (argument-list) in function declaration") if not self.maybe(')'): args = self.__read_list(identifier_re, ',', "Expected argument list") self.read(')', "Expected ) at the end of argument list") code = self.__read_code() return self.__return(lang.Method([name], args, code, False, async_f), doc) def __read_json_value(self): value = self.maybe(kw_re) if value is not None: return value value = self.maybe(number_re) if value is not None: return value value = self.maybe(string_re) if value is not None: return lang.unescape_string(value[1:-1]) if self.lookahead('{'): return self.__read_json_object() if self.lookahead('['): return self.__read_json_list def __read_json_list(self): self.read('[', "Expect JSON list starts with [") result = [] while not self.maybe(']'): result.append(self.__read_json_value) if self.maybe(']'): break self.read(',', "Expected , as a JSON list delimiter") return result def __read_json_object(self): self.read('{', "Expected JSON object starts with {") object = OrderedDict() while not self.maybe('}'): name = self.maybe(identifier_re) if not name: name = self.read(string_re, "Expected string or identifier as property name") self.read(':', "Expected : after property name") value = self.__read_json_value() object[name] = value self.maybe(json_object_value_delimiter_re) return object def __read_scope_decl(self): if self.maybe('ListElement'): doc = self.__get_next_doc() return self.__return(lang.ListElement(self.__read_json_object()), doc) elif self.maybe('Behavior'): self.read("on", "Expected on keyword after Behavior declaration") doc = self.__get_next_doc() targets = self.__read_list(nested_identifier_re, ",", "Expected identifier list after on keyword") self.read("{", "Expected { after identifier list in behavior declaration") comp = self.__read_comp() self.read("}", "Expected } after behavior animation declaration") return self.__return(lang.Behavior(targets, comp), doc) elif self.maybe('signal'): doc = self.__get_next_doc() name = self.read(identifier_re, "Expected identifier in signal declaration") self.__read_statement_end() return self.__return(lang.Signal(name), doc) elif self.maybe('property'): return self.__read_property() elif self.maybe('id'): doc = self.__get_next_doc() self.read(':', "Expected : after id keyword") name = self.read(identifier_re, "Expected identifier in id assignment") self.__read_statement_end() return self.__return(lang.IdAssignment(name), doc) elif self.maybe('const'): doc = self.__get_next_doc() type = self.read(property_type_re, "Expected type after const keyword") name = self.read(component_name, "Expected Capitalised const name") self.read(':', "Expected : after const identifier") value = self.__read_json_value() self.__read_statement_end() return self.__return(lang.Const(type, name, value), doc) elif self.maybe('async'): self.error("async fixme") elif self.maybe('function'): return self.__read_function() elif self.maybe('async'): self.read('function', "Expected function after async") return self.__read_function(async_f = True) elif self.lookahead(component_name_lookahead): return self.__read_comp() else: identifiers = self.__read_list(nested_identifier_re, ",", "Expected identifier (or identifier list)") return self.__read_rules_with_id(identifiers) def __read_comp(self): doc = self.__get_next_doc() comp_name = self.read(component_name, "Expected component name") self.read(r'{', "Expected {") children = [] while not self.maybe('}'): children.append(self.__read_scope_decl()) return self.__return(lang.Component(comp_name, children), doc) def parse(self, parse_all = True): while self.maybe('import'): self.read(rest_of_the_line_re, "Skip to the end of the line failed") r = [self.__read_comp()] self._skip() if parse_all: if self.__pos < len(self.__text): self.error("Extra text after component declaration") return r def parse(data): global doc_root_component doc_root_component = None parser = Parser(data) return parser.parse()<|fim▁end|>
parser.advance(len(term)) return sym next = parser.maybe(kw_re)
<|file_name|>defs.go<|end_file_name|><|fim▁begin|>package lib // Various constants used throughout the tools. const ( // ExitSuccess is the successful exit status. // // It should be called on successful exit.<|fim▁hole|> ExitSuccess = 0 // ExitFailure is the failing exit status. ExitFailure = 1 )<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import # Copyright (c) 2010-2015 openpyxl <|fim▁hole|><|fim▁end|>
from .formatting import ConditionalFormatting from .rule import Rule
<|file_name|>edxnotes.py<|end_file_name|><|fim▁begin|>""" LMS edxnotes page """ from __future__ import absolute_import from bok_choy.page_object import PageLoadError, PageObject, unguarded from bok_choy.promise import BrokenPromise, EmptyPromise from selenium.webdriver.common.action_chains import ActionChains from common.test.acceptance.pages.common.paging import PaginatedUIMixin from common.test.acceptance.pages.lms.course_page import CoursePage from common.test.acceptance.tests.helpers import disable_animations class NoteChild(PageObject): url = None BODY_SELECTOR = None def __init__(self, browser, item_id): super(NoteChild, self).__init__(browser) self.item_id = item_id def is_browser_on_page(self): return self.q(css="{}#{}".format(self.BODY_SELECTOR, self.item_id)).present def _bounded_selector(self, selector): """ Return `selector`, but limited to this particular `NoteChild` context """ return u"{}#{} {}".format( self.BODY_SELECTOR, self.item_id, selector, ) def _get_element_text(self, selector): element = self.q(css=self._bounded_selector(selector)).first if element: return element.text[0] else: return None class EdxNotesChapterGroup(NoteChild): """ Helper class that works with chapter (section) grouping of notes in the Course Structure view on the Note page. """ BODY_SELECTOR = ".note-group" @property def title(self): return self._get_element_text(".course-title") @property def subtitles(self): return [section.title for section in self.children] @property def children(self): children = self.q(css=self._bounded_selector('.note-section')) return [EdxNotesSubsectionGroup(self.browser, child.get_attribute("id")) for child in children] class EdxNotesGroupMixin(object): """ Helper mixin that works with note groups (used for subsection and tag groupings). """ @property def title(self): return self._get_element_text(self.TITLE_SELECTOR) @property def children(self): children = self.q(css=self._bounded_selector('.note')) return [EdxNotesPageItem(self.browser, child.get_attribute("id")) for child in children] @property def notes(self): return [section.text for section in self.children] class EdxNotesSubsectionGroup(NoteChild, EdxNotesGroupMixin): """ Helper class that works with subsection grouping of notes in the Course Structure view on the Note page. """ BODY_SELECTOR = ".note-section" TITLE_SELECTOR = ".course-subtitle" class EdxNotesTagsGroup(NoteChild, EdxNotesGroupMixin): """ Helper class that works with tags grouping of notes in the Tags view on the Note page. """ BODY_SELECTOR = ".note-group" TITLE_SELECTOR = ".tags-title" def scrolled_to_top(self, group_index): """ Returns True if the group with supplied group)index is scrolled near the top of the page (expects 10 px padding). The group_index must be supplied because JQuery must be used to get this information, and it does not have access to the bounded selector. """ title_selector = "$('" + self.TITLE_SELECTOR + "')[" + str(group_index) + "]" top_script = "return " + title_selector + ".getBoundingClientRect().top;" EmptyPromise( lambda: 8 < self.browser.execute_script(top_script) < 12, u"Expected tag title '{}' to scroll to top, but was at location {}".format( self.title, self.browser.execute_script(top_script) ) ).fulfill() # Now also verify that focus has moved to this title (for screen readers): active_script = "return " + title_selector + " === document.activeElement;" return self.browser.execute_script(active_script) class EdxNotesPageItem(NoteChild): """ Helper class that works with note items on Note page of the course. """ BODY_SELECTOR = ".note" UNIT_LINK_SELECTOR = "a.reference-unit-link" TAG_SELECTOR = "span.reference-tags" def go_to_unit(self, unit_page=None): self.q(css=self._bounded_selector(self.UNIT_LINK_SELECTOR)).click() if unit_page is not None: unit_page.wait_for_page() @property def unit_name(self): return self._get_element_text(self.UNIT_LINK_SELECTOR) @property def text(self): return self._get_element_text(".note-comment-p") @property def quote(self): return self._get_element_text(".note-excerpt") @property def time_updated(self): return self._get_element_text(".reference-updated-date") @property def tags(self): """ The tags associated with this note. """ tag_links = self.q(css=self._bounded_selector(self.TAG_SELECTOR)) if len(tag_links) == 0: return None return[tag_link.text for tag_link in tag_links] def go_to_tag(self, tag_name): """ Clicks a tag associated with the note to change to the tags view (and scroll to the tag group). """ self.q(css=self._bounded_selector(self.TAG_SELECTOR)).filter(lambda el: tag_name in el.text).click() class EdxNotesPageView(PageObject): """ Base class for EdxNotes views: Recent Activity, Location in Course, Search Results. """ url = None BODY_SELECTOR = ".tab-panel" TAB_SELECTOR = ".tab" CHILD_SELECTOR = ".note" CHILD_CLASS = EdxNotesPageItem @unguarded def visit(self): """ Open the page containing this page object in the browser. Raises: PageLoadError: The page did not load successfully.<|fim▁hole|> """ self.q(css=self.TAB_SELECTOR).first.click() try: return self.wait_for_page() except BrokenPromise: raise PageLoadError(u"Timed out waiting to load page '{!r}'".format(self)) def is_browser_on_page(self): return all([ self.q(css="{}".format(self.BODY_SELECTOR)).present, self.q(css="{}.is-active".format(self.TAB_SELECTOR)).present, not self.q(css=".ui-loading").visible, ]) @property def is_closable(self): """ Indicates if tab is closable or not. """ return self.q(css=u"{} .action-close".format(self.TAB_SELECTOR)).present def close(self): """ Closes the tab. """ self.q(css=u"{} .action-close".format(self.TAB_SELECTOR)).first.click() @property def children(self): """ Returns all notes on the page. """ children = self.q(css=self.CHILD_SELECTOR) return [self.CHILD_CLASS(self.browser, child.get_attribute("id")) for child in children] class RecentActivityView(EdxNotesPageView): """ Helper class for Recent Activity view. """ BODY_SELECTOR = "#recent-panel" TAB_SELECTOR = ".tab#view-recent-activity" class CourseStructureView(EdxNotesPageView): """ Helper class for Location in Course view. """ BODY_SELECTOR = "#structure-panel" TAB_SELECTOR = ".tab#view-course-structure" CHILD_SELECTOR = ".note-group" CHILD_CLASS = EdxNotesChapterGroup class TagsView(EdxNotesPageView): """ Helper class for Tags view. """ BODY_SELECTOR = "#tags-panel" TAB_SELECTOR = ".tab#view-tags" CHILD_SELECTOR = ".note-group" CHILD_CLASS = EdxNotesTagsGroup class SearchResultsView(EdxNotesPageView): """ Helper class for Search Results view. """ BODY_SELECTOR = "#search-results-panel" TAB_SELECTOR = ".tab#view-search-results" class EdxNotesPage(CoursePage, PaginatedUIMixin): """ EdxNotes page. """ url_path = "edxnotes/" MAPPING = { "recent": RecentActivityView, "structure": CourseStructureView, "tags": TagsView, "search": SearchResultsView, } def __init__(self, *args, **kwargs): super(EdxNotesPage, self).__init__(*args, **kwargs) self.current_view = self.MAPPING["recent"](self.browser) def is_browser_on_page(self): return self.q(css=".wrapper-student-notes .note-group").visible def switch_to_tab(self, tab_name): """ Switches to the appropriate tab `tab_name(str)`. """ self.current_view = self.MAPPING[tab_name](self.browser) self.current_view.visit() def close_tab(self): """ Closes the current view. """ self.current_view.close() self.current_view = self.MAPPING["recent"](self.browser) def search(self, text): """ Runs search with `text(str)` query. """ self.q(css="#search-notes-form #search-notes-input").first.fill(text) self.q(css='#search-notes-form .search-notes-submit').first.click() # Frontend will automatically switch to Search results tab when search # is running, so the view also needs to be changed. self.current_view = self.MAPPING["search"](self.browser) if text.strip(): self.current_view.wait_for_page() @property def tabs(self): """ Returns all tabs on the page. """ tabs = self.q(css=".tabs .tab-label") if tabs: return [x.replace("Current tab\n", "") for x in tabs.text] else: return None @property def is_error_visible(self): """ Indicates whether error message is visible or not. """ return self.q(css=".inline-error").visible @property def error_text(self): """ Returns error message. """ element = self.q(css=".inline-error").first if element and self.is_error_visible: return element.text[0] else: return None @property def notes(self): """ Returns all notes on the page. """ children = self.q(css='.note') return [EdxNotesPageItem(self.browser, child.get_attribute("id")) for child in children] @property def chapter_groups(self): """ Returns all chapter groups on the page. """ children = self.q(css='.note-group') return [EdxNotesChapterGroup(self.browser, child.get_attribute("id")) for child in children] @property def subsection_groups(self): """ Returns all subsection groups on the page. """ children = self.q(css='.note-section') return [EdxNotesSubsectionGroup(self.browser, child.get_attribute("id")) for child in children] @property def tag_groups(self): """ Returns all tag groups on the page. """ children = self.q(css='.note-group') return [EdxNotesTagsGroup(self.browser, child.get_attribute("id")) for child in children] def count(self): """ Returns the total number of notes in the list """ return len(self.q(css='div.wrapper-note-excerpts').results) class EdxNotesPageNoContent(CoursePage): """ EdxNotes page -- when no notes have been added. """ url_path = "edxnotes/" def is_browser_on_page(self): return self.q(css=".wrapper-student-notes .is-empty").visible @property def no_content_text(self): """ Returns no content message. """ element = self.q(css=".is-empty").first if element: return element.text[0] else: return None class EdxNotesUnitPage(CoursePage): """ Page for the Unit with EdxNotes. """ url_path = "courseware/" def is_browser_on_page(self): return self.q(css="body.courseware .edx-notes-wrapper").present def move_mouse_to(self, selector): """ Moves mouse to the element that matches `selector(str)`. """ body = self.q(css=selector)[0] ActionChains(self.browser).move_to_element(body).perform() return self def click(self, selector): """ Clicks on the element that matches `selector(str)`. """ self.q(css=selector).first.click() return self def toggle_visibility(self): """ Clicks on the "Show notes" checkbox. """ self.q(css=".action-toggle-notes").first.click() return self @property def components(self): """ Returns a list of annotatable components. """ components = self.q(css=".edx-notes-wrapper") return [AnnotatableComponent(self.browser, component.get_attribute("id")) for component in components] @property def notes(self): """ Returns a list of notes for the page. """ notes = [] for component in self.components: notes.extend(component.notes) return notes def refresh(self): """ Refreshes the page and returns a list of annotatable components. """ self.browser.refresh() return self.components class AnnotatableComponent(NoteChild): """ Helper class that works with annotatable components. """ BODY_SELECTOR = ".edx-notes-wrapper" @property def notes(self): """ Returns a list of notes for the component. """ notes = self.q(css=self._bounded_selector(".annotator-hl")) return [EdxNoteHighlight(self.browser, note, self.item_id) for note in notes] def create_note(self, selector=".annotate-id"): """ Create the note by the selector, return a context manager that will show and save the note popup. """ for element in self.q(css=self._bounded_selector(selector)): note = EdxNoteHighlight(self.browser, element, self.item_id) note.select_and_click_adder() yield note note.save() def edit_note(self, selector=".annotator-hl"): """ Edit the note by the selector, return a context manager that will show and save the note popup. """ for element in self.q(css=self._bounded_selector(selector)): note = EdxNoteHighlight(self.browser, element, self.item_id) note.show().edit() yield note note.save() def remove_note(self, selector=".annotator-hl"): """ Removes the note by the selector. """ for element in self.q(css=self._bounded_selector(selector)): note = EdxNoteHighlight(self.browser, element, self.item_id) note.show().remove() class EdxNoteHighlight(NoteChild): """ Helper class that works with notes. """ BODY_SELECTOR = "" ADDER_SELECTOR = ".annotator-adder" VIEWER_SELECTOR = ".annotator-viewer" EDITOR_SELECTOR = ".annotator-editor" NOTE_SELECTOR = ".annotator-note" def __init__(self, browser, element, parent_id): super(EdxNoteHighlight, self).__init__(browser, parent_id) self.element = element self.item_id = parent_id disable_animations(self) @property def is_visible(self): """ Returns True if the note is visible. """ viewer_is_visible = self.q(css=self._bounded_selector(self.VIEWER_SELECTOR)).visible editor_is_visible = self.q(css=self._bounded_selector(self.EDITOR_SELECTOR)).visible return viewer_is_visible or editor_is_visible def wait_for_adder_visibility(self): """ Waiting for visibility of note adder button. """ self.wait_for_element_visibility( self._bounded_selector(self.ADDER_SELECTOR), "Adder is visible." ) def wait_for_viewer_visibility(self): """ Waiting for visibility of note viewer. """ self.wait_for_element_visibility( self._bounded_selector(self.VIEWER_SELECTOR), "Note Viewer is visible." ) def wait_for_editor_visibility(self): """ Waiting for visibility of note editor. """ self.wait_for_element_visibility( self._bounded_selector(self.EDITOR_SELECTOR), "Note Editor is visible." ) def wait_for_notes_invisibility(self, text="Notes are hidden"): """ Waiting for invisibility of all notes. """ selector = self._bounded_selector(".annotator-outer") self.wait_for_element_invisibility(selector, text) def select_and_click_adder(self): """ Creates selection for the element and clicks `add note` button. """ ActionChains(self.browser).double_click(self.element).perform() self.wait_for_adder_visibility() self.q(css=self._bounded_selector(self.ADDER_SELECTOR)).first.click() self.wait_for_editor_visibility() return self def click_on_highlight(self): """ Clicks on the highlighted text. """ ActionChains(self.browser).move_to_element(self.element).click().perform() return self def click_on_viewer(self): """ Clicks on the note viewer. """ self.q(css=self.NOTE_SELECTOR).first.click() return self def show(self): """ Hover over highlighted text -> shows note. """ ActionChains(self.browser).move_to_element(self.element).perform() self.wait_for_viewer_visibility() return self def cancel(self): """ Clicks cancel button. """ self.q(css=self._bounded_selector(".annotator-close")).first.click() self.wait_for_notes_invisibility("Note is canceled.") return self def save(self): """ Clicks save button. """ self.q(css=self._bounded_selector(".annotator-save")).first.click() self.wait_for_notes_invisibility("Note is saved.") self.wait_for_ajax() return self def remove(self): """ Clicks delete button. """ self.q(css=self._bounded_selector(".annotator-delete")).first.click() self.wait_for_notes_invisibility("Note is removed.") self.wait_for_ajax() return self def edit(self): """ Clicks edit button. """ self.q(css=self._bounded_selector(".annotator-edit")).first.click() self.wait_for_editor_visibility() return self @property def text(self): """ Returns text of the note. """ self.show() element = self.q(css=self._bounded_selector(".annotator-annotation > div.annotator-note")) if element: text = element.text[0].strip() else: text = None self.cancel() return text @text.setter def text(self, value): """ Sets text for the note. """ self.q(css=self._bounded_selector(".annotator-item textarea")).first.fill(value) @property def tags(self): """ Returns the tags associated with the note. Tags are returned as a list of strings, with each tag as an individual string. """ tag_text = [] self.show() tags = self.q(css=self._bounded_selector(".annotator-annotation > div.annotator-tags > span.annotator-tag")) if tags: for tag in tags: tag_text.append(tag.text) self.cancel() return tag_text @tags.setter def tags(self, tags): """ Sets tags for the note. Tags should be supplied as a list of strings, with each tag as an individual string. """ self.q(css=self._bounded_selector(".annotator-item input")).first.fill(" ".join(tags)) def has_sr_label(self, sr_index, field_index, expected_text): """ Returns true iff a screen reader label (of index sr_index) exists for the annotator field with the specified field_index and text. """ label_exists = False EmptyPromise( lambda: len(self.q(css=self._bounded_selector("li.annotator-item > label.sr"))) > sr_index, u"Expected more than '{}' sr labels".format(sr_index) ).fulfill() annotator_field_label = self.q(css=self._bounded_selector("li.annotator-item > label.sr"))[sr_index] for_attrib_correct = annotator_field_label.get_attribute("for") == "annotator-field-" + str(field_index) if for_attrib_correct and (annotator_field_label.text == expected_text): label_exists = True self.q(css="body").first.click() self.wait_for_notes_invisibility() return label_exists<|fim▁end|>
Returns: PageObject
<|file_name|>StringScriptFieldRangeQuery.java<|end_file_name|><|fim▁begin|>/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.runtimefields.query; import org.apache.lucene.search.QueryVisitor; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.automaton.Automata; import org.apache.lucene.util.automaton.ByteRunAutomaton; import org.elasticsearch.script.Script; import org.elasticsearch.xpack.runtimefields.mapper.StringFieldScript; import java.util.List; import java.util.Objects; public class StringScriptFieldRangeQuery extends AbstractStringScriptFieldQuery { private final String lowerValue; private final String upperValue; private final boolean includeLower; private final boolean includeUpper; public StringScriptFieldRangeQuery( Script script, StringFieldScript.LeafFactory leafFactory, String fieldName, String lowerValue, String upperValue, boolean includeLower, boolean includeUpper ) { super(script, leafFactory, fieldName); this.lowerValue = Objects.requireNonNull(lowerValue); this.upperValue = Objects.requireNonNull(upperValue); this.includeLower = includeLower; this.includeUpper = includeUpper; assert lowerValue.compareTo(upperValue) <= 0; }<|fim▁hole|> protected boolean matches(List<String> values) { for (String value : values) { int lct = lowerValue.compareTo(value); boolean lowerOk = includeLower ? lct <= 0 : lct < 0; if (lowerOk) { int uct = upperValue.compareTo(value); boolean upperOk = includeUpper ? uct >= 0 : uct > 0; if (upperOk) { return true; } } } return false; } @Override public void visit(QueryVisitor visitor) { if (visitor.acceptField(fieldName())) { visitor.consumeTermsMatching( this, fieldName(), () -> new ByteRunAutomaton( Automata.makeBinaryInterval(new BytesRef(lowerValue), includeLower, new BytesRef(upperValue), includeUpper) ) ); } } @Override public final String toString(String field) { StringBuilder b = new StringBuilder(); if (false == fieldName().contentEquals(field)) { b.append(fieldName()).append(':'); } b.append(includeLower ? '[' : '{'); b.append(lowerValue).append(" TO ").append(upperValue); b.append(includeUpper ? ']' : '}'); return b.toString(); } @Override public int hashCode() { return Objects.hash(super.hashCode(), lowerValue, upperValue, includeLower, includeUpper); } @Override public boolean equals(Object obj) { if (false == super.equals(obj)) { return false; } StringScriptFieldRangeQuery other = (StringScriptFieldRangeQuery) obj; return lowerValue.equals(other.lowerValue) && upperValue.equals(other.upperValue) && includeLower == other.includeLower && includeUpper == other.includeUpper; } String lowerValue() { return lowerValue; } String upperValue() { return upperValue; } boolean includeLower() { return includeLower; } boolean includeUpper() { return includeUpper; } }<|fim▁end|>
@Override
<|file_name|>editor.js<|end_file_name|><|fim▁begin|>// dependencies define(['mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/ui/ui-portlet', 'utils/utils', 'plugin/models/chart', 'plugin/models/group', 'plugin/views/group', 'plugin/views/settings', 'plugin/views/types'], function(Tabs, Ui, Portlet, Utils, Chart, Group, GroupView, SettingsView, TypesView) { /** * The charts editor holds the tabs for selecting chart types, chart configuration * and data group selections. */ return Backbone.View.extend({ // initialize initialize: function(app, options){ // link this var self = this; // link application this.app = app; // get current chart object this.chart = this.app.chart; // message element this.message = new Ui.Message(); // create portlet this.portlet = new Portlet.View({ icon : 'fa-bar-chart-o', title: 'Editor', operations : { 'save' : new Ui.ButtonIcon({ icon : 'fa-save', tooltip : 'Draw Chart', title : 'Draw', onclick : function() { self._saveChart(); } }), 'back' : new Ui.ButtonIcon({ icon : 'fa-caret-left', tooltip : 'Return to Viewer', title : 'Cancel', onclick : function() { // show viewer/viewport self.app.go('viewer'); // reset chart self.app.storage.load(); } }) } }); // // grid with chart types // this.types = new TypesView(app, { onchange : function(chart_type) { // get chart definition var chart_definition = self.app.types.get(chart_type); if (!chart_definition) { console.debug('FAILED - Editor::onchange() - Chart type not supported.'); } // parse chart definition self.chart.definition = chart_definition; // reset type relevant chart content self.chart.settings.clear(); // update chart type self.chart.set({type: chart_type}); // set modified flag self.chart.set('modified', true); // log console.debug('Editor::onchange() - Switched chart type.'); }, ondblclick : function(chart_id) { self._saveChart(); } }); // // tabs // this.tabs = new Tabs.View({ title_new : 'Add Data', onnew : function() { var group = self._addGroupModel(); self.tabs.show(group.id); } }); // // main/default tab // // construct elements this.title = new Ui.Input({ placeholder: 'Chart title', onchange: function() { self.chart.set('title', self.title.value()); } }); // append element var $main = $('<div/>'); $main.append(Utils.wrap((new Ui.Label({ title : 'Provide a chart title:'})).$el)); $main.append(Utils.wrap(this.title.$el)); $main.append(Utils.wrap(this.types.$el)); // add tab this.tabs.add({ id : 'main', title : 'Start', $el : $main }); // // main settings tab // // create settings view this.settings = new SettingsView(this.app); // add tab this.tabs.add({ id : 'settings', title : 'Configuration', $el : this.settings.$el }); // append tabs this.portlet.append(this.message.$el); this.portlet.append(this.tabs.$el); // elements this.setElement(this.portlet.$el); // hide back button on startup this.tabs.hideOperation('back'); // chart events var self = this; this.chart.on('change:title', function(chart) { self._refreshTitle(); }); this.chart.on('change:type', function(chart) { self.types.value(chart.get('type')); }); this.chart.on('reset', function(chart) { self._resetChart(); }); this.app.chart.on('redraw', function(chart) { self.portlet.showOperation('back'); }); // groups events this.app.chart.groups.on('add', function(group) { self._addGroup(group); }); this.app.chart.groups.on('remove', function(group) { self._removeGroup(group); }); this.app.chart.groups.on('reset', function(group) { self._removeAllGroups(); }); this.app.chart.groups.on('change:key', function(group) { self._refreshGroupKey(); }); // reset this._resetChart(); }, // hide show: function() { this.$el.show(); }, // hide hide: function() { this.$el.hide(); }, // refresh title _refreshTitle: function() { var title = this.chart.get('title'); this.portlet.title(title); this.title.value(title); }, // refresh group _refreshGroupKey: function() { var self = this; var counter = 0; this.chart.groups.each(function(group) { var title = group.get('key', ''); if (title == '') { title = 'Data label'; } self.tabs.title(group.id, ++counter + ': ' + title); }); }, // add group model _addGroupModel: function() { var group = new Group({ id : Utils.uuid() }); this.chart.groups.add(group); return group; }, // add group tab _addGroup: function(group) { // link this var self = this; // create view var group_view = new GroupView(this.app, {group: group}); // add new tab this.tabs.add({ id : group.id, $el : group_view.$el, ondel : function() { self.chart.groups.remove(group.id); } }); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeGroup: function(group) { this.tabs.del(group.id); // update titles this._refreshGroupKey(); // reset this.chart.set('modified', true); }, // remove group _removeAllGroups: function(group) { this.tabs.delRemovable(); }, // reset _resetChart: function() { // reset chart details this.chart.set('id', Utils.uuid()); this.chart.set('type', 'nvd3_bar'); this.chart.set('dataset_id', this.app.options.config.dataset_id); this.chart.set('title', 'New Chart'); // reset back button this.portlet.hideOperation('back'); }, // create chart _saveChart: function() { // update chart data this.chart.set({ type : this.types.value(), title : this.title.value(), date : Utils.time() }); // make sure that at least one data group is available if (this.chart.groups.length == 0) { this.message.update({message: 'Please select data columns before drawing the chart.'}); var group = this._addGroupModel();<|fim▁hole|> return; } // make sure that all necessary columns are assigned var self = this; var valid = true; var chart_def = this.chart.definition; this.chart.groups.each(function(group) { if (!valid) { return; } for (var key in chart_def.columns) { if (group.attributes[key] == 'null') { self.message.update({status: 'danger', message: 'This chart type requires column types not found in your tabular file.'}); self.tabs.show(group.id); valid = false; return; } } }); // validate if columns have been selected if (!valid) { return; } // show viewport this.app.go('viewer'); // wait until chart is ready var self = this; this.app.deferred.execute(function() { // save self.app.storage.save(); // trigger redraw self.chart.trigger('redraw'); }); } }); });<|fim▁end|>
this.tabs.show(group.id);
<|file_name|>error.rs<|end_file_name|><|fim▁begin|>use std::error; use std::fmt; use std::io; use std::result; use std::sync; #[cfg(all(feature = "ssl", not(any(target_os = "windows", target_os = "macos"))))] use openssl::ssl::error::SslError; #[cfg(all(feature = "ssl", target_os = "macos"))] use security_framework::base::Error as SslError; use super::conn::Row; use super::value::Value; use url::ParseError; #[derive(Eq, PartialEq, Clone)] pub struct MySqlError { pub state: String, pub message: String, pub code: u16, } impl fmt::Display for MySqlError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ERROR {} ({}): {}", self.code, self.state, self.message) } } impl fmt::Debug for MySqlError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl error::Error for MySqlError { fn description(&self) -> &str { "Error returned by a server" } } pub enum Error { IoError(io::Error), MySqlError(MySqlError), DriverError(DriverError), UrlError(UrlError), #[cfg(all(feature = "ssl", any(unix, macos)))] SslError(SslError), FromValueError(Value), FromRowError(Row), } impl Error { #[doc(hidden)] pub fn is_connectivity_error(&self) -> bool { match self { &Error::IoError(_) | &Error::DriverError(_) => true, #[cfg(all(feature = "ssl", any(unix, macos)))] &Error::SslError(_) => true, &Error::MySqlError(_) | &Error::UrlError(_) | &Error::FromValueError(_) | &Error::FromRowError(_) => false, } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::IoError(_) => "I/O Error", Error::MySqlError(_) => "MySql server error", Error::DriverError(_) => "driver error", Error::UrlError(_) => "url error", #[cfg(all(feature = "ssl", any(unix, macos)))] Error::SslError(_) => "ssl error", Error::FromRowError(_) => "from row conversion error", Error::FromValueError(_) => "from value conversion error", } } fn cause(&self) -> Option<&error::Error> { match *self { Error::IoError(ref err) => Some(err), Error::DriverError(ref err) => Some(err), Error::MySqlError(ref err) => Some(err), Error::UrlError(ref err) => Some(err), #[cfg(all(feature = "ssl", any(unix, macos)))] Error::SslError(ref err) => Some(err), _ => None } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IoError(err) } } impl From<DriverError> for Error { fn from(err: DriverError) -> Error { Error::DriverError(err) } } impl From<MySqlError> for Error { fn from(x: MySqlError) -> Error { Error::MySqlError(x) } } #[cfg(all(feature = "ssl", any(unix, macos)))] impl From<SslError> for Error { fn from(err: SslError) -> Error { Error::SslError(err) } } impl From<UrlError> for Error { fn from(err: UrlError) -> Error { Error::UrlError(err) } } impl<T> From<sync::PoisonError<T>> for Error { fn from(_: sync::PoisonError<T>) -> Error { Error::DriverError(DriverError::PoisonedPoolMutex) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::IoError(ref err) => write!(f, "IoError {{ {} }}", err), Error::MySqlError(ref err) => write!(f, "MySqlError {{ {} }}", err), Error::DriverError(ref err) => write!(f, "DriverError {{ {} }}", err), Error::UrlError(ref err) => write!(f, "UrlError {{ {} }}", err), #[cfg(all(feature = "ssl", any(unix, macos)))] Error::SslError(ref err) => write!(f, "SslError {{ {} }}", err), Error::FromRowError(_) => "from row conversion error".fmt(f), Error::FromValueError(_) => "from value conversion error".fmt(f), } } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } #[derive(Eq, PartialEq, Clone)] pub enum DriverError { // (address, description) CouldNotConnect(Option<(String, String, io::ErrorKind)>), UnsupportedProtocol(u8), PacketOutOfSync, PacketTooLarge, Protocol41NotSet, UnexpectedPacket, MismatchedStmtParams(u16, usize), InvalidPoolConstraints, SetupError, SslNotSupported, CouldNotParseVersion, ReadOnlyTransNotSupported, PoisonedPoolMutex, Timeout, MissingNamedParameter(String), NamedParamsForPositionalQuery, MixedParams, } impl error::Error for DriverError { fn description(&self) -> &str { "MySql driver error" } } impl fmt::Display for DriverError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DriverError::CouldNotConnect(None) => { write!(f, "Could not connect: address not specified") } DriverError::CouldNotConnect(Some((ref addr, ref desc, _))) => { write!(f, "Could not connect to address `{}': {}", addr, desc) } DriverError::UnsupportedProtocol(proto_version) => { write!(f, "Unsupported protocol version {}", proto_version) } DriverError::PacketOutOfSync => { write!(f, "Packet out of sync") } DriverError::PacketTooLarge => { write!(f, "Packet too large") } DriverError::Protocol41NotSet => { write!(f, "Server must set CLIENT_PROTOCOL_41 flag") } DriverError::UnexpectedPacket => { write!(f, "Unexpected packet") } DriverError::MismatchedStmtParams(exp, prov) => { write!(f, "Statement takes {} parameters but {} was supplied", exp, prov) } DriverError::InvalidPoolConstraints => { write!(f, "Invalid pool constraints") }, DriverError::SetupError => { write!(f, "Could not setup connection") }, DriverError::SslNotSupported => { write!(f, "Client requires secure connection but server \ does not have this capability") }, DriverError::CouldNotParseVersion => { write!(f, "Could not parse MySQL version") }, DriverError::ReadOnlyTransNotSupported => { write!(f, "Read-only transactions does not supported in your MySQL version") }, DriverError::PoisonedPoolMutex => { write!(f, "Poisoned pool mutex") }, DriverError::Timeout => { write!(f, "Operation timed out") }, DriverError::MissingNamedParameter(ref name) => { write!(f, "Missing named parameter `{}' for statement", name) }, DriverError::NamedParamsForPositionalQuery => { write!(f, "Can not pass named parameters to positional query") }, DriverError::MixedParams => { write!(f, "Can not mix named and positional parameters in one statement") }, } } } impl fmt::Debug for DriverError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } #[derive(Eq, PartialEq, Clone)] pub enum UrlError { ParseError(ParseError), UnsupportedScheme(String), /// (feature_name, parameter_name) FeatureRequired(String, String), /// (feature_name, value) InvalidValue(String, String), UnknownParameter(String), BadUrl, } impl error::Error for UrlError { fn description(&self) -> &str { "Database connection URL error" } } impl fmt::Display for UrlError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { UrlError::ParseError(ref err) => write!(f, "URL ParseError {{ {} }}", err), UrlError::UnsupportedScheme(ref s) => write!(f, "URL scheme `{}' is not supported", s), UrlError::FeatureRequired(ref feature, ref parameter) => { write!(f, "Url parameter `{}' requires {} feature", parameter, feature) }, UrlError::InvalidValue(ref parameter, ref value) => { write!(f, "Invalid value `{}' for URL parameter `{}'", value, parameter) }, UrlError::UnknownParameter(ref parameter) => { write!(f, "Unknown URL parameter `{}'", parameter) }, UrlError::BadUrl => { write!(f, "Invalid or incomplete connection URL") } } } } impl fmt::Debug for UrlError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl From<ParseError> for UrlError { fn from(x: ParseError) -> UrlError { UrlError::ParseError(x) } } pub type Result<T> = result::Result<T, Error>; /// Server error codes (u16) #[allow(non_camel_case_types)] #[derive(Clone, Eq, PartialEq, Debug, Copy)] #[repr(u16)] pub enum ServerError { ER_HASHCHK = 1000u16, ER_NISAMCHK = 1001u16, ER_NO = 1002u16, ER_YES = 1003u16, ER_CANT_CREATE_FILE = 1004u16, ER_CANT_CREATE_TABLE = 1005u16, ER_CANT_CREATE_DB = 1006u16, ER_DB_CREATE_EXISTS = 1007u16, ER_DB_DROP_EXISTS = 1008u16, ER_DB_DROP_DELETE = 1009u16, ER_DB_DROP_RMDIR = 1010u16, ER_CANT_DELETE_FILE = 1011u16, ER_CANT_FIND_SYSTEM_REC = 1012u16, ER_CANT_GET_STAT = 1013u16, ER_CANT_GET_WD = 1014u16, ER_CANT_LOCK = 1015u16, ER_CANT_OPEN_FILE = 1016u16, ER_FILE_NOT_FOUND = 1017u16, ER_CANT_READ_DIR = 1018u16, ER_CANT_SET_WD = 1019u16, ER_CHECKREAD = 1020u16, ER_DISK_FULL = 1021u16, ER_DUP_KEY = 1022u16, ER_ERROR_ON_CLOSE = 1023u16, ER_ERROR_ON_READ = 1024u16, ER_ERROR_ON_RENAME = 1025u16, ER_ERROR_ON_WRITE = 1026u16, ER_FILE_USED = 1027u16, ER_FILSORT_ABORT = 1028u16, ER_FORM_NOT_FOUND = 1029u16, ER_GET_ERRNO = 1030u16, ER_ILLEGAL_HA = 1031u16, ER_KEY_NOT_FOUND = 1032u16, ER_NOT_FORM_FILE = 1033u16, ER_NOT_KEYFILE = 1034u16, ER_OLD_KEYFILE = 1035u16, ER_OPEN_AS_READONLY = 1036u16, ER_OUTOFMEMORY = 1037u16, ER_OUT_OF_SORTMEMORY = 1038u16, ER_UNEXPECTED_EOF = 1039u16, ER_CON_COUNT_ERROR = 1040u16, ER_OUT_OF_RESOURCES = 1041u16, ER_BAD_HOST_ERROR = 1042u16, ER_HANDSHAKE_ERROR = 1043u16, ER_DBACCESS_DENIED_ERROR = 1044u16, ER_ACCESS_DENIED_ERROR = 1045u16, ER_NO_DB_ERROR = 1046u16, ER_UNKNOWN_COM_ERROR = 1047u16, ER_BAD_NULL_ERROR = 1048u16, ER_BAD_DB_ERROR = 1049u16, ER_TABLE_EXISTS_ERROR = 1050u16, ER_BAD_TABLE_ERROR = 1051u16, ER_NON_UNIQ_ERROR = 1052u16, ER_SERVER_SHUTDOWN = 1053u16, ER_BAD_FIELD_ERROR = 1054u16, ER_WRONG_FIELD_WITH_GROUP = 1055u16, ER_WRONG_GROUP_FIELD = 1056u16, ER_WRONG_SUM_SELECT = 1057u16, ER_WRONG_VALUE_COUNT = 1058u16, ER_TOO_LONG_IDENT = 1059u16, ER_DUP_FIELDNAME = 1060u16, ER_DUP_KEYNAME = 1061u16, ER_DUP_ENTRY = 1062u16, ER_WRONG_FIELD_SPEC = 1063u16, ER_PARSE_ERROR = 1064u16, ER_EMPTY_QUERY = 1065u16, ER_NONUNIQ_TABLE = 1066u16, ER_INVALID_DEFAULT = 1067u16, ER_MULTIPLE_PRI_KEY = 1068u16,<|fim▁hole|> ER_KEY_COLUMN_DOES_NOT_EXITS = 1072u16, ER_BLOB_USED_AS_KEY = 1073u16, ER_TOO_BIG_FIELDLENGTH = 1074u16, ER_WRONG_AUTO_KEY = 1075u16, ER_READY = 1076u16, ER_NORMAL_SHUTDOWN = 1077u16, ER_GOT_SIGNAL = 1078u16, ER_SHUTDOWN_COMPLETE = 1079u16, ER_FORCING_CLOSE = 1080u16, ER_IPSOCK_ERROR = 1081u16, ER_NO_SUCH_INDEX = 1082u16, ER_WRONG_FIELD_TERMINATORS = 1083u16, ER_BLOBS_AND_NO_TERMINATED = 1084u16, ER_TEXTFILE_NOT_READABLE = 1085u16, ER_FILE_EXISTS_ERROR = 1086u16, ER_LOAD_INFO = 1087u16, ER_ALTER_INFO = 1088u16, ER_WRONG_SUB_KEY = 1089u16, ER_CANT_REMOVE_ALL_FIELDS = 1090u16, ER_CANT_DROP_FIELD_OR_KEY = 1091u16, ER_INSERT_INFO = 1092u16, ER_UPDATE_TABLE_USED = 1093u16, ER_NO_SUCH_THREAD = 1094u16, ER_KILL_DENIED_ERROR = 1095u16, ER_NO_TABLES_USED = 1096u16, ER_TOO_BIG_SET = 1097u16, ER_NO_UNIQUE_LOGFILE = 1098u16, ER_TABLE_NOT_LOCKED_FOR_WRITE = 1099u16, ER_TABLE_NOT_LOCKED = 1100u16, ER_BLOB_CANT_HAVE_DEFAULT = 1101u16, ER_WRONG_DB_NAME = 1102u16, ER_WRONG_TABLE_NAME = 1103u16, ER_TOO_BIG_SELECT = 1104u16, ER_UNKNOWN_ERROR = 1105u16, ER_UNKNOWN_PROCEDURE = 1106u16, ER_WRONG_PARAMCOUNT_TO_PROCEDURE = 1107u16, ER_WRONG_PARAMETERS_TO_PROCEDURE = 1108u16, ER_UNKNOWN_TABLE = 1109u16, ER_FIELD_SPECIFIED_TWICE = 1110u16, ER_INVALID_GROUP_FUNC_USE = 1111u16, ER_UNSUPPORTED_EXTENSION = 1112u16, ER_TABLE_MUST_HAVE_COLUMNS = 1113u16, ER_RECORD_FILE_FULL = 1114u16, ER_UNKNOWN_CHARACTER_SET = 1115u16, ER_TOO_MANY_TABLES = 1116u16, ER_TOO_MANY_FIELDS = 1117u16, ER_TOO_BIG_ROWSIZE = 1118u16, ER_STACK_OVERRUN = 1119u16, ER_WRONG_OUTER_JOIN = 1120u16, ER_NULL_COLUMN_IN_INDEX = 1121u16, ER_CANT_FIND_UDF = 1122u16, ER_CANT_INITIALIZE_UDF = 1123u16, ER_UDF_NO_PATHS = 1124u16, ER_UDF_EXISTS = 1125u16, ER_CANT_OPEN_LIBRARY = 1126u16, ER_CANT_FIND_DL_ENTRY = 1127u16, ER_FUNCTION_NOT_DEFINED = 1128u16, ER_HOST_IS_BLOCKED = 1129u16, ER_HOST_NOT_PRIVILEGED = 1130u16, ER_PASSWORD_ANONYMOUS_USER = 1131u16, ER_PASSWORD_NOT_ALLOWED = 1132u16, ER_PASSWORD_NO_MATCH = 1133u16, ER_UPDATE_INFO = 1134u16, ER_CANT_CREATE_THREAD = 1135u16, ER_WRONG_VALUE_COUNT_ON_ROW = 1136u16, ER_CANT_REOPEN_TABLE = 1137u16, ER_INVALID_USE_OF_NULL = 1138u16, ER_REGEXP_ERROR = 1139u16, ER_MIX_OF_GROUP_FUNC_AND_FIELDS = 1140u16, ER_NONEXISTING_GRANT = 1141u16, ER_TABLEACCESS_DENIED_ERROR = 1142u16, ER_COLUMNACCESS_DENIED_ERROR = 1143u16, ER_ILLEGAL_GRANT_FOR_TABLE = 1144u16, ER_GRANT_WRONG_HOST_OR_USER = 1145u16, ER_NO_SUCH_TABLE = 1146u16, ER_NONEXISTING_TABLE_GRANT = 1147u16, ER_NOT_ALLOWED_COMMAND = 1148u16, ER_SYNTAX_ERROR = 1149u16, ER_DELAYED_CANT_CHANGE_LOCK = 1150u16, ER_TOO_MANY_DELAYED_THREADS = 1151u16, ER_ABORTING_CONNECTION = 1152u16, ER_NET_PACKET_TOO_LARGE = 1153u16, ER_NET_READ_ERROR_FROM_PIPE = 1154u16, ER_NET_FCNTL_ERROR = 1155u16, ER_NET_PACKETS_OUT_OF_ORDER = 1156u16, ER_NET_UNCOMPRESS_ERROR = 1157u16, ER_NET_READ_ERROR = 1158u16, ER_NET_READ_INTERRUPTED = 1159u16, ER_NET_ERROR_ON_WRITE = 1160u16, ER_NET_WRITE_INTERRUPTED = 1161u16, ER_TOO_LONG_STRING = 1162u16, ER_TABLE_CANT_HANDLE_BLOB = 1163u16, ER_TABLE_CANT_HANDLE_AUTO_INCREMENT = 1164u16, ER_DELAYED_INSERT_TABLE_LOCKED = 1165u16, ER_WRONG_COLUMN_NAME = 1166u16, ER_WRONG_KEY_COLUMN = 1167u16, ER_WRONG_MRG_TABLE = 1168u16, ER_DUP_UNIQUE = 1169u16, ER_BLOB_KEY_WITHOUT_LENGTH = 1170u16, ER_PRIMARY_CANT_HAVE_NULL = 1171u16, ER_TOO_MANY_ROWS = 1172u16, ER_REQUIRES_PRIMARY_KEY = 1173u16, ER_NO_RAID_COMPILED = 1174u16, ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE = 1175u16, ER_KEY_DOES_NOT_EXITS = 1176u16, ER_CHECK_NO_SUCH_TABLE = 1177u16, ER_CHECK_NOT_IMPLEMENTED = 1178u16, ER_CANT_DO_THIS_DURING_AN_TRANSACTION = 1179u16, ER_ERROR_DURING_COMMIT = 1180u16, ER_ERROR_DURING_ROLLBACK = 1181u16, ER_ERROR_DURING_FLUSH_LOGS = 1182u16, ER_ERROR_DURING_CHECKPOINT = 1183u16, ER_NEW_ABORTING_CONNECTION = 1184u16, ER_DUMP_NOT_IMPLEMENTED = 1185u16, ER_FLUSH_MASTER_BINLOG_CLOSED = 1186u16, ER_INDEX_REBUILD = 1187u16, ER_MASTER = 1188u16, ER_MASTER_NET_READ = 1189u16, ER_MASTER_NET_WRITE = 1190u16, ER_FT_MATCHING_KEY_NOT_FOUND = 1191u16, ER_LOCK_OR_ACTIVE_TRANSACTION = 1192u16, ER_UNKNOWN_SYSTEM_VARIABLE = 1193u16, ER_CRASHED_ON_USAGE = 1194u16, ER_CRASHED_ON_REPAIR = 1195u16, ER_WARNING_NOT_COMPLETE_ROLLBACK = 1196u16, ER_TRANS_CACHE_FULL = 1197u16, ER_SLAVE_MUST_STOP = 1198u16, ER_SLAVE_NOT_RUNNING = 1199u16, ER_BAD_SLAVE = 1200u16, ER_MASTER_INFO = 1201u16, ER_SLAVE_THREAD = 1202u16, ER_TOO_MANY_USER_CONNECTIONS = 1203u16, ER_SET_CONSTANTS_ONLY = 1204u16, ER_LOCK_WAIT_TIMEOUT = 1205u16, ER_LOCK_TABLE_FULL = 1206u16, ER_READ_ONLY_TRANSACTION = 1207u16, ER_DROP_DB_WITH_READ_LOCK = 1208u16, ER_CREATE_DB_WITH_READ_LOCK = 1209u16, ER_WRONG_ARGUMENTS = 1210u16, ER_NO_PERMISSION_TO_CREATE_USER = 1211u16, ER_UNION_TABLES_IN_DIFFERENT_DIR = 1212u16, ER_LOCK_DEADLOCK = 1213u16, ER_TABLE_CANT_HANDLE_FT = 1214u16, ER_CANNOT_ADD_FOREIGN = 1215u16, ER_NO_REFERENCED_ROW = 1216u16, ER_ROW_IS_REFERENCED = 1217u16, ER_CONNECT_TO_MASTER = 1218u16, ER_QUERY_ON_MASTER = 1219u16, ER_ERROR_WHEN_EXECUTING_COMMAND = 1220u16, ER_WRONG_USAGE = 1221u16, ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT = 1222u16, ER_CANT_UPDATE_WITH_READLOCK = 1223u16, ER_MIXING_NOT_ALLOWED = 1224u16, ER_DUP_ARGUMENT = 1225u16, ER_USER_LIMIT_REACHED = 1226u16, ER_SPECIFIC_ACCESS_DENIED_ERROR = 1227u16, ER_LOCAL_VARIABLE = 1228u16, ER_GLOBAL_VARIABLE = 1229u16, ER_NO_DEFAULT = 1230u16, ER_WRONG_VALUE_FOR_VAR = 1231u16, ER_WRONG_TYPE_FOR_VAR = 1232u16, ER_VAR_CANT_BE_READ = 1233u16, ER_CANT_USE_OPTION_HERE = 1234u16, ER_NOT_SUPPORTED_YET = 1235u16, ER_MASTER_FATAL_ERROR_READING_BINLOG = 1236u16, ER_SLAVE_IGNORED_TABLE = 1237u16, ER_INCORRECT_GLOBAL_LOCAL_VAR = 1238u16, ER_WRONG_FK_DEF = 1239u16, ER_KEY_REF_DO_NOT_MATCH_TABLE_REF = 1240u16, ER_OPERAND_COLUMNS = 1241u16, ER_SUBQUERY_NO_1_ROW = 1242u16, ER_UNKNOWN_STMT_HANDLER = 1243u16, ER_CORRUPT_HELP_DB = 1244u16, ER_CYCLIC_REFERENCE = 1245u16, ER_AUTO_CONVERT = 1246u16, ER_ILLEGAL_REFERENCE = 1247u16, ER_DERIVED_MUST_HAVE_ALIAS = 1248u16, ER_SELECT_REDUCED = 1249u16, ER_TABLENAME_NOT_ALLOWED_HERE = 1250u16, ER_NOT_SUPPORTED_AUTH_MODE = 1251u16, ER_SPATIAL_CANT_HAVE_NULL = 1252u16, ER_COLLATION_CHARSET_MISMATCH = 1253u16, ER_SLAVE_WAS_RUNNING = 1254u16, ER_SLAVE_WAS_NOT_RUNNING = 1255u16, ER_TOO_BIG_FOR_UNCOMPRESS = 1256u16, ER_ZLIB_Z_MEM_ERROR = 1257u16, ER_ZLIB_Z_BUF_ERROR = 1258u16, ER_ZLIB_Z_DATA_ERROR = 1259u16, ER_CUT_VALUE_GROUP_CONCAT = 1260u16, ER_WARN_TOO_FEW_RECORDS = 1261u16, ER_WARN_TOO_MANY_RECORDS = 1262u16, ER_WARN_NULL_TO_NOTNULL = 1263u16, ER_WARN_DATA_OUT_OF_RANGE = 1264u16, WARN_DATA_TRUNCATED = 1265u16, ER_WARN_USING_OTHER_HANDLER = 1266u16, ER_CANT_AGGREGATE_2COLLATIONS = 1267u16, ER_DROP_USER = 1268u16, ER_REVOKE_GRANTS = 1269u16, ER_CANT_AGGREGATE_3COLLATIONS = 1270u16, ER_CANT_AGGREGATE_NCOLLATIONS = 1271u16, ER_VARIABLE_IS_NOT_STRUCT = 1272u16, ER_UNKNOWN_COLLATION = 1273u16, ER_SLAVE_IGNORED_SSL_PARAMS = 1274u16, ER_SERVER_IS_IN_SECURE_AUTH_MODE = 1275u16, ER_WARN_FIELD_RESOLVED = 1276u16, ER_BAD_SLAVE_UNTIL_COND = 1277u16, ER_MISSING_SKIP_SLAVE = 1278u16, ER_UNTIL_COND_IGNORED = 1279u16, ER_WRONG_NAME_FOR_INDEX = 1280u16, ER_WRONG_NAME_FOR_CATALOG = 1281u16, ER_WARN_QC_RESIZE = 1282u16, ER_BAD_FT_COLUMN = 1283u16, ER_UNKNOWN_KEY_CACHE = 1284u16, ER_WARN_HOSTNAME_WONT_WORK = 1285u16, ER_UNKNOWN_STORAGE_ENGINE = 1286u16, ER_WARN_DEPRECATED_SYNTAX = 1287u16, ER_NON_UPDATABLE_TABLE = 1288u16, ER_FEATURE_DISABLED = 1289u16, ER_OPTION_PREVENTS_STATEMENT = 1290u16, ER_DUPLICATED_VALUE_IN_TYPE = 1291u16, ER_TRUNCATED_WRONG_VALUE = 1292u16, ER_TOO_MUCH_AUTO_TIMESTAMP_COLS = 1293u16, ER_INVALID_ON_UPDATE = 1294u16, ER_UNSUPPORTED_PS = 1295u16, ER_GET_ERRMSG = 1296u16, ER_GET_TEMPORARY_ERRMSG = 1297u16, ER_UNKNOWN_TIME_ZONE = 1298u16, ER_WARN_INVALID_TIMESTAMP = 1299u16, ER_INVALID_CHARACTER_STRING = 1300u16, ER_WARN_ALLOWED_PACKET_OVERFLOWED = 1301u16, ER_CONFLICTING_DECLARATIONS = 1302u16, ER_SP_NO_RECURSIVE_CREATE = 1303u16, ER_SP_ALREADY_EXISTS = 1304u16, ER_SP_DOES_NOT_EXIST = 1305u16, ER_SP_DROP_FAILED = 1306u16, ER_SP_STORE_FAILED = 1307u16, ER_SP_LILABEL_MISMATCH = 1308u16, ER_SP_LABEL_REDEFINE = 1309u16, ER_SP_LABEL_MISMATCH = 1310u16, ER_SP_UNINIT_VAR = 1311u16, ER_SP_BADSELECT = 1312u16, ER_SP_BADRETURN = 1313u16, ER_SP_BADSTATEMENT = 1314u16, ER_UPDATE_LOG_DEPRECATED_IGNORED = 1315u16, ER_UPDATE_LOG_DEPRECATED_TRANSLATED = 1316u16, ER_QUERY_INTERRUPTED = 1317u16, ER_SP_WRONG_NO_OF_ARGS = 1318u16, ER_SP_COND_MISMATCH = 1319u16, ER_SP_NORETURN = 1320u16, ER_SP_NORETURNEND = 1321u16, ER_SP_BAD_CURSOR_QUERY = 1322u16, ER_SP_BAD_CURSOR_SELECT = 1323u16, ER_SP_CURSOR_MISMATCH = 1324u16, ER_SP_CURSOR_ALREADY_OPEN = 1325u16, ER_SP_CURSOR_NOT_OPEN = 1326u16, ER_SP_UNDECLARED_VAR = 1327u16, ER_SP_WRONG_NO_OF_FETCH_ARGS = 1328u16, ER_SP_FETCH_NO_DATA = 1329u16, ER_SP_DUP_PARAM = 1330u16, ER_SP_DUP_VAR = 1331u16, ER_SP_DUP_COND = 1332u16, ER_SP_DUP_CURS = 1333u16, ER_SP_CANT_ALTER = 1334u16, ER_SP_SUBSELECT_NYI = 1335u16, ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG = 1336u16, ER_SP_VARCOND_AFTER_CURSHNDLR = 1337u16, ER_SP_CURSOR_AFTER_HANDLER = 1338u16, ER_SP_CASE_NOT_FOUND = 1339u16, ER_FPARSER_TOO_BIG_FILE = 1340u16, ER_FPARSER_BAD_HEADER = 1341u16, ER_FPARSER_EOF_IN_COMMENT = 1342u16, ER_FPARSER_ERROR_IN_PARAMETER = 1343u16, ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER = 1344u16, ER_VIEW_NO_EXPLAIN = 1345u16, ER_FRM_UNKNOWN_TYPE = 1346u16, ER_WRONG_OBJECT = 1347u16, ER_NONUPDATEABLE_COLUMN = 1348u16, ER_VIEW_SELECT_DERIVED = 1349u16, ER_VIEW_SELECT_CLAUSE = 1350u16, ER_VIEW_SELECT_VARIABLE = 1351u16, ER_VIEW_SELECT_TMPTABLE = 1352u16, ER_VIEW_WRONG_LIST = 1353u16, ER_WARN_VIEW_MERGE = 1354u16, ER_WARN_VIEW_WITHOUT_KEY = 1355u16, ER_VIEW_INVALID = 1356u16, ER_SP_NO_DROP_SP = 1357u16, ER_SP_GOTO_IN_HNDLR = 1358u16, ER_TRG_ALREADY_EXISTS = 1359u16, ER_TRG_DOES_NOT_EXIST = 1360u16, ER_TRG_ON_VIEW_OR_TEMP_TABLE = 1361u16, ER_TRG_CANT_CHANGE_ROW = 1362u16, ER_TRG_NO_SUCH_ROW_IN_TRG = 1363u16, ER_NO_DEFAULT_FOR_FIELD = 1364u16, ER_DIVISION_BY_ZERO = 1365u16, ER_TRUNCATED_WRONG_VALUE_FOR_FIELD = 1366u16, ER_ILLEGAL_VALUE_FOR_TYPE = 1367u16, ER_VIEW_NONUPD_CHECK = 1368u16, ER_VIEW_CHECK_FAILED = 1369u16, ER_PROCACCESS_DENIED_ERROR = 1370u16, ER_RELAY_LOG_FAIL = 1371u16, ER_PASSWD_LENGTH = 1372u16, ER_UNKNOWN_TARGET_BINLOG = 1373u16, ER_IO_ERR_LOG_INDEX_READ = 1374u16, ER_BINLOG_PURGE_PROHIBITED = 1375u16, ER_FSEEK_FAIL = 1376u16, ER_BINLOG_PURGE_FATAL_ERR = 1377u16, ER_LOG_IN_USE = 1378u16, ER_LOG_PURGE_UNKNOWN_ERR = 1379u16, ER_RELAY_LOG_INIT = 1380u16, ER_NO_BINARY_LOGGING = 1381u16, ER_RESERVED_SYNTAX = 1382u16, ER_WSAS_FAILED = 1383u16, ER_DIFF_GROUPS_PROC = 1384u16, ER_NO_GROUP_FOR_PROC = 1385u16, ER_ORDER_WITH_PROC = 1386u16, ER_LOGGING_PROHIBIT_CHANGING_OF = 1387u16, ER_NO_FILE_MAPPING = 1388u16, ER_WRONG_MAGIC = 1389u16, ER_PS_MANY_PARAM = 1390u16, ER_KEY_PART_0 = 1391u16, ER_VIEW_CHECKSUM = 1392u16, ER_VIEW_MULTIUPDATE = 1393u16, ER_VIEW_NO_INSERT_FIELD_LIST = 1394u16, ER_VIEW_DELETE_MERGE_VIEW = 1395u16, ER_CANNOT_USER = 1396u16, ER_XAER_NOTA = 1397u16, ER_XAER_INVAL = 1398u16, ER_XAER_RMFAIL = 1399u16, ER_XAER_OUTSIDE = 1400u16, ER_XAER_RMERR = 1401u16, ER_XA_RBROLLBACK = 1402u16, ER_NONEXISTING_PROC_GRANT = 1403u16, ER_PROC_AUTO_GRANT_FAIL = 1404u16, ER_PROC_AUTO_REVOKE_FAIL = 1405u16, ER_DATA_TOO_LONG = 1406u16, ER_SP_BAD_SQLSTATE = 1407u16, ER_STARTUP = 1408u16, ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR = 1409u16, ER_CANT_CREATE_USER_WITH_GRANT = 1410u16, ER_WRONG_VALUE_FOR_TYPE = 1411u16, ER_TABLE_DEF_CHANGED = 1412u16, ER_SP_DUP_HANDLER = 1413u16, ER_SP_NOT_VAR_ARG = 1414u16, ER_SP_NO_RETSET = 1415u16, ER_CANT_CREATE_GEOMETRY_OBJECT = 1416u16, ER_FAILED_ROUTINE_BREAK_BINLOG = 1417u16, ER_BINLOG_UNSAFE_ROUTINE = 1418u16, ER_BINLOG_CREATE_ROUTINE_NEED_SUPER = 1419u16, ER_EXEC_STMT_WITH_OPEN_CURSOR = 1420u16, ER_STMT_HAS_NO_OPEN_CURSOR = 1421u16, ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG = 1422u16, ER_NO_DEFAULT_FOR_VIEW_FIELD = 1423u16, ER_SP_NO_RECURSION = 1424u16, ER_TOO_BIG_SCALE = 1425u16, ER_TOO_BIG_PRECISION = 1426u16, ER_M_BIGGER_THAN_D = 1427u16, ER_WRONG_LOCK_OF_SYSTEM_TABLE = 1428u16, ER_CONNECT_TO_FOREIGN_DATA_SOURCE = 1429u16, ER_QUERY_ON_FOREIGN_DATA_SOURCE = 1430u16, ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST = 1431u16, ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE = 1432u16, ER_FOREIGN_DATA_STRING_INVALID = 1433u16, ER_CANT_CREATE_FEDERATED_TABLE = 1434u16, ER_TRG_IN_WRONG_SCHEMA = 1435u16, ER_STACK_OVERRUN_NEED_MORE = 1436u16, ER_TOO_LONG_BODY = 1437u16, ER_WARN_CANT_DROP_DEFAULT_KEYCACHE = 1438u16, ER_TOO_BIG_DISPLAYWIDTH = 1439u16, ER_XAER_DUPID = 1440u16, ER_DATETIME_FUNCTION_OVERFLOW = 1441u16, ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG = 1442u16, ER_VIEW_PREVENT_UPDATE = 1443u16, ER_PS_NO_RECURSION = 1444u16, ER_SP_CANT_SET_AUTOCOMMIT = 1445u16, ER_MALFORMED_DEFINER = 1446u16, ER_VIEW_FRM_NO_USER = 1447u16, ER_VIEW_OTHER_USER = 1448u16, ER_NO_SUCH_USER = 1449u16, ER_FORBID_SCHEMA_CHANGE = 1450u16, ER_ROW_IS_REFERENCED_2 = 1451u16, ER_NO_REFERENCED_ROW_2 = 1452u16, ER_SP_BAD_VAR_SHADOW = 1453u16, ER_TRG_NO_DEFINER = 1454u16, ER_OLD_FILE_FORMAT = 1455u16, ER_SP_RECURSION_LIMIT = 1456u16, ER_SP_PROC_TABLE_CORRUPT = 1457u16, ER_SP_WRONG_NAME = 1458u16, ER_TABLE_NEEDS_UPGRADE = 1459u16, ER_SP_NO_AGGREGATE = 1460u16, ER_MAX_PREPARED_STMT_COUNT_REACHED = 1461u16, ER_VIEW_RECURSIVE = 1462u16, ER_NON_GROUPING_FIELD_USED = 1463u16, ER_TABLE_CANT_HANDLE_SPKEYS = 1464u16, ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA = 1465u16, ER_REMOVED_SPACES = 1466u16, ER_AUTOINC_READ_FAILED = 1467u16, ER_USERNAME = 1468u16, ER_HOSTNAME = 1469u16, ER_WRONG_STRING_LENGTH = 1470u16, ER_NON_INSERTABLE_TABLE = 1471u16, ER_ADMIN_WRONG_MRG_TABLE = 1472u16, ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT = 1473u16, ER_NAME_BECOMES_EMPTY = 1474u16, ER_AMBIGUOUS_FIELD_TERM = 1475u16, ER_FOREIGN_SERVER_EXISTS = 1476u16, ER_FOREIGN_SERVER_DOESNT_EXIST = 1477u16, ER_ILLEGAL_HA_CREATE_OPTION = 1478u16, ER_PARTITION_REQUIRES_VALUES_ERROR = 1479u16, ER_PARTITION_WRONG_VALUES_ERROR = 1480u16, ER_PARTITION_MAXVALUE_ERROR = 1481u16, ER_PARTITION_SUBPARTITION_ERROR = 1482u16, ER_PARTITION_SUBPART_MIX_ERROR = 1483u16, ER_PARTITION_WRONG_NO_PART_ERROR = 1484u16, ER_PARTITION_WRONG_NO_SUBPART_ERROR = 1485u16, ER_CONST_EXPR_IN_PARTITION_FUNC_ERROR = 1486u16, ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR = 1487u16, ER_FIELD_NOT_FOUND_PART_ERROR = 1488u16, ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR = 1489u16, ER_INCONSISTENT_PARTITION_INFO_ERROR = 1490u16, ER_PARTITION_FUNC_NOT_ALLOWED_ERROR = 1491u16, ER_PARTITIONS_MUST_BE_DEFINED_ERROR = 1492u16, ER_RANGE_NOT_INCREASING_ERROR = 1493u16, ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR = 1494u16, ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR = 1495u16, ER_PARTITION_ENTRY_ERROR = 1496u16, ER_MIX_HANDLER_ERROR = 1497u16, ER_PARTITION_NOT_DEFINED_ERROR = 1498u16, ER_TOO_MANY_PARTITIONS_ERROR = 1499u16, ER_SUBPARTITION_ERROR = 1500u16, ER_CANT_CREATE_HANDLER_FILE = 1501u16, ER_BLOB_FIELD_IN_PART_FUNC_ERROR = 1502u16, ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF = 1503u16, ER_NO_PARTS_ERROR = 1504u16, ER_PARTITION_MGMT_ON_NONPARTITIONED = 1505u16, ER_FOREIGN_KEY_ON_PARTITIONED = 1506u16, ER_DROP_PARTITION_NON_EXISTENT = 1507u16, ER_DROP_LAST_PARTITION = 1508u16, ER_COALESCE_ONLY_ON_HASH_PARTITION = 1509u16, ER_REORG_HASH_ONLY_ON_SAME_NO = 1510u16, ER_REORG_NO_PARAM_ERROR = 1511u16, ER_ONLY_ON_RANGE_LIST_PARTITION = 1512u16, ER_ADD_PARTITION_SUBPART_ERROR = 1513u16, ER_ADD_PARTITION_NO_NEW_PARTITION = 1514u16, ER_COALESCE_PARTITION_NO_PARTITION = 1515u16, ER_REORG_PARTITION_NOT_EXIST = 1516u16, ER_SAME_NAME_PARTITION = 1517u16, ER_NO_BINLOG_ERROR = 1518u16, ER_CONSECUTIVE_REORG_PARTITIONS = 1519u16, ER_REORG_OUTSIDE_RANGE = 1520u16, ER_PARTITION_FUNCTION_FAILURE = 1521u16, ER_PART_STATE_ERROR = 1522u16, ER_LIMITED_PART_RANGE = 1523u16, ER_PLUGIN_IS_NOT_LOADED = 1524u16, ER_WRONG_VALUE = 1525u16, ER_NO_PARTITION_FOR_GIVEN_VALUE = 1526u16, ER_FILEGROUP_OPTION_ONLY_ONCE = 1527u16, ER_CREATE_FILEGROUP_FAILED = 1528u16, ER_DROP_FILEGROUP_FAILED = 1529u16, ER_TABLESPACE_AUTO_EXTEND_ERROR = 1530u16, ER_WRONG_SIZE_NUMBER = 1531u16, ER_SIZE_OVERFLOW_ERROR = 1532u16, ER_ALTER_FILEGROUP_FAILED = 1533u16, ER_BINLOG_ROW_LOGGING_FAILED = 1534u16, ER_BINLOG_ROW_WRONG_TABLE_DEF = 1535u16, ER_BINLOG_ROW_RBR_TO_SBR = 1536u16, ER_EVENT_ALREADY_EXISTS = 1537u16, ER_EVENT_STORE_FAILED = 1538u16, ER_EVENT_DOES_NOT_EXIST = 1539u16, ER_EVENT_CANT_ALTER = 1540u16, ER_EVENT_DROP_FAILED = 1541u16, ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG = 1542u16, ER_EVENT_ENDS_BEFORE_STARTS = 1543u16, ER_EVENT_EXEC_TIME_IN_THE_PAST = 1544u16, ER_EVENT_OPEN_TABLE_FAILED = 1545u16, ER_EVENT_NEITHER_M_EXPR_NOR_M_AT = 1546u16, ER_COL_COUNT_DOESNT_MATCH_CORRUPTED = 1547u16, ER_CANNOT_LOAD_FROM_TABLE = 1548u16, ER_EVENT_CANNOT_DELETE = 1549u16, ER_EVENT_COMPILE_ERROR = 1550u16, ER_EVENT_SAME_NAME = 1551u16, ER_EVENT_DATA_TOO_LONG = 1552u16, ER_DROP_INDEX_FK = 1553u16, ER_WARN_DEPRECATED_SYNTAX_WITH_VER = 1554u16, ER_CANT_WRITE_LOCK_LOG_TABLE = 1555u16, ER_CANT_LOCK_LOG_TABLE = 1556u16, ER_FOREIGN_DUPLICATE_KEY = 1557u16, ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE = 1558u16, ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR = 1559u16, ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1560u16, ER_NDB_CANT_SWITCH_BINLOG_FORMAT = 1561u16, ER_PARTITION_NO_TEMPORARY = 1562u16, ER_PARTITION_CONST_DOMAIN_ERROR = 1563u16, ER_PARTITION_FUNCTION_IS_NOT_ALLOWED = 1564u16, ER_DDL_LOG_ERROR = 1565u16, ER_NULL_IN_VALUES_LESS_THAN = 1566u16, ER_WRONG_PARTITION_NAME = 1567u16, ER_CANT_CHANGE_TX_ISOLATION = 1568u16, ER_DUP_ENTRY_AUTOINCREMENT_CASE = 1569u16, ER_EVENT_MODIFY_QUEUE_ERROR = 1570u16, ER_EVENT_SET_VAR_ERROR = 1571u16, ER_PARTITION_MERGE_ERROR = 1572u16, ER_CANT_ACTIVATE_LOG = 1573u16, ER_RBR_NOT_AVAILABLE = 1574u16, ER_BASE64_DECODE_ERROR = 1575u16, ER_EVENT_RECURSION_FORBIDDEN = 1576u16, ER_EVENTS_DB_ERROR = 1577u16, ER_ONLY_INTEGERS_ALLOWED = 1578u16, ER_UNSUPORTED_LOG_ENGINE = 1579u16, ER_BAD_LOG_STATEMENT = 1580u16, ER_CANT_RENAME_LOG_TABLE = 1581u16, ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT = 1582u16, ER_WRONG_PARAMETERS_TO_NATIVE_FCT = 1583u16, ER_WRONG_PARAMETERS_TO_STORED_FCT = 1584u16, ER_NATIVE_FCT_NAME_COLLISION = 1585u16, ER_DUP_ENTRY_WITH_KEY_NAME = 1586u16, ER_BINLOG_PURGE_EMFILE = 1587u16, ER_EVENT_CANNOT_CREATE_IN_THE_PAST = 1588u16, ER_EVENT_CANNOT_ALTER_IN_THE_PAST = 1589u16, ER_SLAVE_INCIDENT = 1590u16, ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT = 1591u16, ER_BINLOG_UNSAFE_STATEMENT = 1592u16, ER_SLAVE_FATAL_ERROR = 1593u16, ER_SLAVE_RELAY_LOG_READ_FAILURE = 1594u16, ER_SLAVE_RELAY_LOG_WRITE_FAILURE = 1595u16, ER_SLAVE_CREATE_EVENT_FAILURE = 1596u16, ER_SLAVE_MASTER_COM_FAILURE = 1597u16, ER_BINLOG_LOGGING_IMPOSSIBLE = 1598u16, ER_VIEW_NO_CREATION_CTX = 1599u16, ER_VIEW_INVALID_CREATION_CTX = 1600u16, ER_SR_INVALID_CREATION_CTX = 1601u16, ER_TRG_CORRUPTED_FILE = 1602u16, ER_TRG_NO_CREATION_CTX = 1603u16, ER_TRG_INVALID_CREATION_CTX = 1604u16, ER_EVENT_INVALID_CREATION_CTX = 1605u16, ER_TRG_CANT_OPEN_TABLE = 1606u16, ER_CANT_CREATE_SROUTINE = 1607u16, ER_SLAVE_AMBIGOUS_EXEC_MODE = 1608u16, ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT = 1609u16, ER_SLAVE_CORRUPT_EVENT = 1610u16, ER_LOAD_DATA_INVALID_COLUMN = 1611u16, ER_LOG_PURGE_NO_FILE = 1612u16, ER_XA_RBTIMEOUT = 1613u16, ER_XA_RBDEADLOCK = 1614u16, ER_NEED_REPREPARE = 1615u16, ER_DELAYED_NOT_SUPPORTED = 1616u16, WARN_NO_MASTER_INFO = 1617u16, WARN_OPTION_IGNORED = 1618u16, WARN_PLUGIN_DELETE_BUILTIN = 1619u16, WARN_PLUGIN_BUSY = 1620u16, ER_VARIABLE_IS_READONLY = 1621u16, ER_WARN_ENGINE_TRANSACTION_ROLLBACK = 1622u16, ER_SLAVE_HEARTBEAT_FAILURE = 1623u16, ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE = 1624u16, ER_NDB_REPLICATION_SCHEMA_ERROR = 1625u16, ER_CONFLICT_FN_PARSE_ERROR = 1626u16, ER_EXCEPTIONS_WRITE_ERROR = 1627u16, ER_TOO_LONG_TABLE_COMMENT = 1628u16, ER_TOO_LONG_FIELD_COMMENT = 1629u16, ER_FUNC_INEXISTENT_NAME_COLLISION = 1630u16, ER_DATABASE_NAME = 1631u16, ER_TABLE_NAME = 1632u16, ER_PARTITION_NAME = 1633u16, ER_SUBPARTITION_NAME = 1634u16, ER_TEMPORARY_NAME = 1635u16, ER_RENAMED_NAME = 1636u16, ER_TOO_MANY_CONCURRENT_TRXS = 1637u16, WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED = 1638u16, ER_DEBUG_SYNC_TIMEOUT = 1639u16, ER_DEBUG_SYNC_HIT_LIMIT = 1640u16, ER_DUP_SIGNAL_SET = 1641u16, ER_SIGNAL_WARN = 1642u16, ER_SIGNAL_NOT_FOUND = 1643u16, ER_SIGNAL_EXCEPTION = 1644u16, ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER = 1645u16, ER_SIGNAL_BAD_CONDITION_TYPE = 1646u16, WARN_COND_ITEM_TRUNCATED = 1647u16, ER_COND_ITEM_TOO_LONG = 1648u16, ER_UNKNOWN_LOCALE = 1649u16, ER_SLAVE_IGNORE_SERVER_IDS = 1650u16, ER_QUERY_CACHE_DISABLED = 1651u16, ER_SAME_NAME_PARTITION_FIELD = 1652u16, ER_PARTITION_COLUMN_LIST_ERROR = 1653u16, ER_WRONG_TYPE_COLUMN_VALUE_ERROR = 1654u16, ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR = 1655u16, ER_MAXVALUE_IN_VALUES_IN = 1656u16, ER_TOO_MANY_VALUES_ERROR = 1657u16, ER_ROW_SINGLE_PARTITION_FIELD_ERROR = 1658u16, ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD = 1659u16, ER_PARTITION_FIELDS_TOO_LONG = 1660u16, ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE = 1661u16, ER_BINLOG_ROW_MODE_AND_STMT_ENGINE = 1662u16, ER_BINLOG_UNSAFE_AND_STMT_ENGINE = 1663u16, ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE = 1664u16, ER_BINLOG_STMT_MODE_AND_ROW_ENGINE = 1665u16, ER_BINLOG_ROW_INJECTION_AND_STMT_MODE = 1666u16, ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1667u16, ER_BINLOG_UNSAFE_LIMIT = 1668u16, ER_BINLOG_UNSAFE_INSERT_DELAYED = 1669u16, ER_BINLOG_UNSAFE_SYSTEM_TABLE = 1670u16, ER_BINLOG_UNSAFE_AUTOINC_COLUMNS = 1671u16, ER_BINLOG_UNSAFE_UDF = 1672u16, ER_BINLOG_UNSAFE_SYSTEM_VARIABLE = 1673u16, ER_BINLOG_UNSAFE_SYSTEM_FUNCTION = 1674u16, ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS = 1675u16, ER_MESSAGE_AND_STATEMENT = 1676u16, ER_SLAVE_CONVERSION_FAILED = 1677u16, ER_SLAVE_CANT_CREATE_CONVERSION = 1678u16, ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1679u16, ER_PATH_LENGTH = 1680u16, ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT = 1681u16, ER_WRONG_NATIVE_TABLE_STRUCTURE = 1682u16, ER_WRONG_PERFSCHEMA_USAGE = 1683u16, ER_WARN_I_S_SKIPPED_TABLE = 1684u16, ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1685u16, ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1686u16, ER_SPATIAL_MUST_HAVE_GEOM_COL = 1687u16, ER_TOO_LONG_INDEX_COMMENT = 1688u16, ER_LOCK_ABORTED = 1689u16, ER_DATA_OUT_OF_RANGE = 1690u16, ER_WRONG_SPVAR_TYPE_IN_LIMIT = 1691u16, ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1692u16, ER_BINLOG_UNSAFE_MIXED_STATEMENT = 1693u16, ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1694u16, ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1695u16, ER_FAILED_READ_FROM_PAR_FILE = 1696u16, ER_VALUES_IS_NOT_INT_TYPE_ERROR = 1697u16, ER_ACCESS_DENIED_NO_PASSWORD_ERROR = 1698u16, ER_SET_PASSWORD_AUTH_PLUGIN = 1699u16, ER_GRANT_PLUGIN_USER_EXISTS = 1700u16, ER_TRUNCATE_ILLEGAL_FK = 1701u16, ER_PLUGIN_IS_PERMANENT = 1702u16, ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN = 1703u16, ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX = 1704u16, ER_STMT_CACHE_FULL = 1705u16, ER_MULTI_UPDATE_KEY_CONFLICT = 1706u16, ER_TABLE_NEEDS_REBUILD = 1707u16, WARN_OPTION_BELOW_LIMIT = 1708u16, ER_INDEX_COLUMN_TOO_LONG = 1709u16, ER_ERROR_IN_TRIGGER_BODY = 1710u16, ER_ERROR_IN_UNKNOWN_TRIGGER_BODY = 1711u16, ER_INDEX_CORRUPT = 1712u16, ER_UNDO_RECORD_TOO_BIG = 1713u16, ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT = 1714u16, ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE = 1715u16, ER_BINLOG_UNSAFE_REPLACE_SELECT = 1716u16, ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT = 1717u16, ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT = 1718u16, ER_BINLOG_UNSAFE_UPDATE_IGNORE = 1719u16, ER_PLUGIN_NO_UNINSTALL = 1720u16, ER_PLUGIN_NO_INSTALL = 1721u16, ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT = 1722u16, ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC = 1723u16, ER_BINLOG_UNSAFE_INSERT_TWO_KEYS = 1724u16, ER_TABLE_IN_FK_CHECK = 1725u16, ER_UNSUPPORTED_ENGINE = 1726u16, ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST = 1727u16, }<|fim▁end|>
ER_TOO_MANY_KEYS = 1069u16, ER_TOO_MANY_KEY_PARTS = 1070u16, ER_TOO_LONG_KEY = 1071u16,
<|file_name|>scenarios.js<|end_file_name|><|fim▁begin|>describe('my app', function() { it('should redirect `index.html` to `index.html#!/countries/countries', function() { browser.get('index.html'); expect(browser.getLocationAbsUrl()).toBe('/home'); }); describe('home', function() { beforeEach(function() { browser.get('index.html'); }); it('should filter the country list as a user types into the search box', function() { var countryList = element.all(by.repeater('country in $ctrl.countries')); var query = element(by.model('$ctrl.query')); expect(countryList.count()).toBe(11); query.sendKeys('vietnam'); expect(countryList.count()).toBe(1); query.clear(); query.sendKeys('Brunei'); expect(countryList.count()).toBe(1); query.clear(); query.sendKeys('Indien'); expect(countryList.count()).toBe(0); }); it('should render country specific links', function() { var query = element(by.model('$ctrl.query'));<|fim▁hole|> }); }); describe('View: Country details', function() { beforeEach(function() { browser.get('index.html#!/countries/countries/BN'); }); it('should display country with title `translations.de`', function() { expect(element(by.binding('$ctrl.country.translations.de')).getText()).toBe('Brunei'); }); }); });<|fim▁end|>
query.sendKeys('Brunei'); element.all(by.css('.thumbDescription a')).first().click(); expect(browser.getLocationAbsUrl()).toBe('/countries/countries/BN');
<|file_name|>relay.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|> class Relay(object): _mcp23017_chip = {} # Conceivably, we could have up to 8 of these as there are a possibility of 8 MCP chips on a bus. def __init__(self, mcp_pin, i2c_address=0x27): """ Initialize a relay :param mcp_pin: BCM gpio number that is connected to a relay :return: """ self.ON = 0 self.OFF = 1 self._i2c_address = i2c_address self._mcp_pin = mcp_pin if GPIO.RPI_REVISION == 1: i2c_busnum = 0 else: i2c_busnum = 1 if not self._mcp23017_chip.has_key(self._i2c_address): self._mcp23017_chip[self._i2c_address] = Adafruit_MCP230XX(busnum=i2c_busnum, address=self._i2c_address, num_gpios=16) self._relay = self._mcp23017_chip[self._i2c_address] self._relay.config(self._mcp_pin, self._relay.OUTPUT) self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF def set_state(self, state): """ Set the state of the relay. relay.ON, relay.OFF :param state: :return: """ if state == self.ON: self._relay.output(self._mcp_pin, self.ON) self.state = self.ON elif state == self.OFF: self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF def toggle(self): """ Toggle the state of a relay :return: """ if self.state == self.ON: self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF else: self._relay.output(self._mcp_pin, self.ON) self.state = self.ON def get_state(self): return self.state if __name__ == '__main__': import time pause = .15 for pin in range(16): print("Pin: %s" % pin) r = Relay(pin) r.set_state(r.ON) time.sleep(pause) r.set_state(r.OFF) time.sleep(pause) r.toggle() time.sleep(pause) r.toggle() time.sleep(pause) r1 = Relay(10) r2 = Relay(2) r3 = Relay(15) r1.set_state(r1.ON) print(r1._mcp_pin) r2.set_state(r2.ON) print(r2._mcp_pin) r3.set_state(r3.ON) print(r3._mcp_pin) time.sleep(1) r1.set_state(r1.OFF) r2.set_state(r2.OFF) r3.set_state(r3.OFF)<|fim▁end|>
# A Raspberry Pi GPIO based relay device import RPi.GPIO as GPIO from common.adafruit.Adafruit_MCP230xx.Adafruit_MCP230xx import Adafruit_MCP230XX
<|file_name|>IncorrectMultilineIndexException.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.maxcube.internal.exceptions; /** * Will be thrown when there is an attempt to put a new message line into the message processor, * but the processor is currently processing an other message type. * <|fim▁hole|> * @author Christian Rockrohr <[email protected]> */ public class IncorrectMultilineIndexException extends Exception { private static final long serialVersionUID = -2261755876987011907L; }<|fim▁end|>
<|file_name|>ui_lib.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # JewelCraft jewelry design toolkit for Blender. # Copyright (C) 2015-2022 Mikhail Rachinskiy # # 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<|fim▁hole|># (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 <https://www.gnu.org/licenses/>. # # ##### END GPL LICENSE BLOCK ##### import bpy def popup_list(op, title: str, msgs: list, icon: str = "INFO") -> None: def draw(self, context): for text in msgs: self.layout.label(text=text) op.report({"INFO"}, f"{title}:") for text in msgs: op.report({"INFO"}, text) bpy.context.window_manager.popup_menu(draw, title=title, icon=icon)<|fim▁end|>
# the Free Software Foundation, either version 3 of the License, or
<|file_name|>accumulator_factory.rs<|end_file_name|><|fim▁begin|>use std::ops::Add; pub fn accum<'a, T>(mut n: T) -> Box<FnMut(T) -> T + 'a> where T: 'a + Add<T, Output=T> + Copy { Box::new(move |i: T| { n = n + i; n }) } #[cfg(not(test))] pub fn main() { println!("{}", accumulate()); } #[test] pub fn test() { assert_eq!(8.3, accumulate()); }<|fim▁hole|> // switching at the moment). let mut g = accum(1f32); g(5.); accum(3i32); g(2.3) }<|fim▁end|>
fn accumulate() -> f32 { // Deviation: works with all types implementing addition, but not a mixture // of types (it is possible to handle mixed types, but would require type
<|file_name|>issue-86465.rs<|end_file_name|><|fim▁begin|>#![feature(type_alias_impl_trait)] <|fim▁hole|> fn f<'t, 'u>(a: &'t u32, b: &'u u32) -> (X<'t, 'u>, X<'u, 't>) { //~^ ERROR concrete type differs from previous defining opaque type use (a, a) } fn main() {}<|fim▁end|>
type X<'a, 'b> = impl std::fmt::Debug;
<|file_name|>application.js<|end_file_name|><|fim▁begin|>//= require wow //= require formvalidation.min //= require formvalidation/framework/bootstrap.min //= require formvalidation/language/pt_BR<|fim▁hole|><|fim▁end|>
//= require_self //= require_tree ./autoload
<|file_name|>fetch_repos.py<|end_file_name|><|fim▁begin|>""" To use this, create a settings.py file and make these variables: TOKEN=<oath token for github> ORG=<your org in github> DEST=<Path to download to> """ from github import Github from subprocess import call import os from settings import TOKEN, ORG, DEST def download(): """Quick and Dirty Download all repos function""" <|fim▁hole|> repos = [] for repo in g.get_organization(ORG).get_repos(): print "Fetching Repo Name: %s" % repo.name repos.append("[email protected]:%s/%s.git" % (ORG, repo.name)) total = len(repos) print "Found %s repos" % total count = 0 for repo in repos: count +=1 print "Cloning Repo [%s]/[%s]: %s" % (count, total, repo) call([u'git', u'clone', repo]) download()<|fim▁end|>
os.chdir(DEST) print "Downloading to destination: ", os.getcwd() g = Github(TOKEN)
<|file_name|>error.rs<|end_file_name|><|fim▁begin|>//! rzw specific error types //! //! These error type is compatible with the rust standard io `ErrorKind`. pub type Result<T> = std::result::Result<T, Error>; /// Categories of errors that can occur when interacting with z-Wave. /// /// This list is intended to grow over time and it is not recommended to exhaustively match against it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ErrorKind { /// The controller is not available. /// /// This could indicate that the controller is in use by another process or was disconnected while /// performing I/O. NoController, /// A parameter was incorrect. InvalidInput, /// A unknown Z-Wave syntax was sent. UnknownZWave, /// This functionallity is not implemented. NotImplemented, /// An I/O error occured. /// /// The type of I/O error is determined by the inner `io::ErrorKind`. Io(std::io::ErrorKind), } /// An error type for Z-Wave operations. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Error { kind: ErrorKind, description: String, } impl Error { /// Create a new error with a given type and description pub fn new<T: Into<String>>(kind: ErrorKind, description: T) -> Self { Error { kind: kind, description: description.into(), } } /// Returns the corresponding `ErrorKind` for this error. pub fn kind(&self) -> ErrorKind { self.kind } } impl std::fmt::Display for Error { /// How to print the error fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> { fmt.write_str(&self.description) } } impl std::error::Error for Error { /// Get the error description fn description(&self) -> &str { &self.description } } impl From<std::io::Error> for Error { /// Transform std io errors to this crate error fn from(io_error: std::io::Error) -> Error { Error::new(ErrorKind::Io(io_error.kind()), format!("{}", io_error)) } } impl From<Error> for std::io::Error { /// Transform this error to a std io error fn from(error: Error) -> std::io::Error { let kind = match error.kind { ErrorKind::NoController => std::io::ErrorKind::NotFound, ErrorKind::InvalidInput => std::io::ErrorKind::InvalidInput, ErrorKind::UnknownZWave => std::io::ErrorKind::InvalidData, ErrorKind::NotImplemented => std::io::ErrorKind::Other, ErrorKind::Io(kind) => kind, }; std::io::Error::new(kind, error.description) } } impl From<serial::Error> for Error { /// Transform from a serial error fn from(ser_error: serial::Error) -> Error { use std::error::Error;<|fim▁hole|> serial::ErrorKind::Io(kind) => ErrorKind::Io(kind), }; crate::error::Error::new(kind, ser_error.description()) } }<|fim▁end|>
let kind = match ser_error.kind() { serial::ErrorKind::NoDevice => ErrorKind::NoController, serial::ErrorKind::InvalidInput => ErrorKind::InvalidInput,
<|file_name|>review.py<|end_file_name|><|fim▁begin|># Part of Patient Flow. # See LICENSE file for full copyright and licensing details. from openerp.osv import orm, fields, osv from openerp import SUPERUSER_ID import logging _logger = logging.getLogger(__name__) class nh_etake_list_review(orm.Model): _name = "nh.etake_list.review" _inherits = {'nh.activity': 'activity_id'} _description = "Review View" _rec_name = 'patient_id' _auto = False _table = "nh_etake_list_review" _state_selection = [['To be Reviewed', 'To be Reviewed'], ['PTWR', 'PTWR'], ['Discharged', 'Discharged'], ['To be Discharged', 'To be Discharged'], ['Other', 'Other']] _columns = { 'activity_id': fields.many2one('nh.activity', 'Activity', required=1, ondelete='restrict'), 'location_id': fields.many2one('nh.clinical.location', 'Ward'), 'patient_id': fields.many2one('nh.clinical.patient', 'Patient'), 'hospital_number': fields.text('Hospital Number'), 'nhs_number': fields.text('NHS Number'), 'state': fields.selection(_state_selection, 'State'), 'date_started': fields.datetime('Started'), 'date_terminated': fields.datetime('Completed'), 'user_id': fields.many2one('res.users', 'Asignee'), 'doctor_task_ids': fields.one2many('nh.activity', 'parent_id', string='Doctor Tasks', domain="[['data_model','=','nh.clinical.doctor.task']]"), 'ptwr_id': fields.many2one('nh.activity', 'PTWR Activity'), 'diagnosis': fields.text('Diagnosis'), 'plan': fields.text('Plan') } def _get_review_groups(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None): res = [['To be Reviewed', 'To be Reviewed'], ['To be Discharged', 'To be Discharged'], ['PTWR', 'PTWR']] fold = {r[0]: False for r in res} return res, fold _group_by_full = { 'state': _get_review_groups, } def create_task(self, cr, uid, ids, context=None): data = self.browse(cr, uid, ids[0], context=context) context.update({'default_patient_id': data.patient_id.id, 'default_spell_id': data.id}) return { 'name': 'Add Task', 'type': 'ir.actions.act_window', 'res_model': 'nh.clinical.doctor_task_wizard', 'view_mode': 'form', 'view_type': 'form',<|fim▁hole|> } def init(self, cr): cr.execute(""" drop view if exists %s; create or replace view %s as ( select spell_activity.id as id, review_activity.id as activity_id, case when discharge_activity.state is not null and discharge_activity.state = 'completed' then 'Discharged' when discharge_activity.state is not null and discharge_activity.state != 'completed' then 'To be Discharged' when ptwr_activity.state is not null then 'PTWR' when review_activity.state = 'scheduled' then 'To be Reviewed' else 'Other' end as state, review_activity.date_started as date_started, review_activity.date_terminated as date_terminated, review_activity.user_id as user_id, ptwr_activity.id as ptwr_id, spell.patient_id as patient_id, spell.diagnosis as diagnosis, spell.doctor_plan as plan, location.id as location_id, patient.other_identifier as hospital_number, patient.patient_identifier as nhs_number from nh_clinical_spell spell inner join nh_activity spell_activity on spell_activity.id = spell.activity_id inner join nh_clinical_patient patient on spell.patient_id = patient.id inner join nh_activity review_activity on review_activity.parent_id = spell_activity.id and review_activity.data_model = 'nh.clinical.patient.review' left join nh_activity discharge_activity on discharge_activity.parent_id = spell_activity.id and discharge_activity.data_model = 'nh.clinical.adt.patient.discharge' left join nh_activity ptwr_activity on ptwr_activity.parent_id = spell_activity.id and ptwr_activity.data_model = 'nh.clinical.ptwr' and ptwr_activity.state != 'completed' left join nh_clinical_location location on location.id = spell.location_id ) """ % (self._table, self._table)) def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): if 'doctor_task_ids' in fields: activity_pool = self.pool['nh.activity'] fields.remove('doctor_task_ids') read_values = super(nh_etake_list_review, self).read(cr, uid, ids, fields, context, load) for rv in read_values: rv['doctor_task_ids'] = activity_pool.search(cr, uid, [['parent_id', '=', rv['id']], ['data_model', '=', 'nh.clinical.doctor.task']], context=context) return read_values return super(nh_etake_list_review, self).read(cr, uid, ids, fields, context, load) def write(self, cr, uid, ids, vals, context=None): activity_pool = self.pool['nh.activity'] for review in self.browse(cr, uid, ids, context=context): if 'diagnosis' in vals: activity_pool.submit(cr, uid, review.activity_id.id, {'diagnosis': vals['diagnosis']}, context=context) activity_pool.submit(cr, uid, review.id, {'diagnosis': vals['diagnosis']}, context=context) if 'plan' in vals: activity_pool.submit(cr, uid, review.activity_id.id, {'plan': vals['plan']}, context=context) activity_pool.submit(cr, uid, review.id, {'doctor_plan': vals['plan']}, context=context) if 'doctor_task_ids' in vals: for dt in vals['doctor_task_ids']: if dt[2]: activity_pool.write(cr, uid, dt[1], dt[2], context=context) return True def transfer(self, cr, uid, ids, context=None): ptwr_pool = self.pool['nh.clinical.ptwr'] api_pool = self.pool['nh.clinical.api'] activity_pool = self.pool['nh.activity'] for review in self.browse(cr, uid, ids, context=context): spell_activity_id = api_pool.get_patient_spell_activity_id(cr, SUPERUSER_ID, review.patient_id.id, context=context) if not spell_activity_id: raise osv.except_osv("Error!", "Spell not found!") ptwr_id = ptwr_pool.create_activity(cr, uid, { 'parent_id': spell_activity_id, 'creator_id': review.id }, {}, context=context) activity_pool.submit(cr, uid, review.activity_id.id, {'location_id': review.location_id.id}, context=context) activity_pool.complete(cr, uid, review.activity_id.id, context=context) return True def discharge(self, cr, uid, ids, context=None): discharge_pool = self.pool['nh.clinical.adt.patient.discharge'] api_pool = self.pool['nh.clinical.api'] activity_pool = self.pool['nh.activity'] for review in self.browse(cr, uid, ids, context=context): spell_activity_id = api_pool.get_patient_spell_activity_id(cr, SUPERUSER_ID, review.patient_id.id, context=context) if not spell_activity_id: raise osv.except_osv("Error!", "Spell not found!") discharge_id = discharge_pool.create_activity(cr, uid, { 'parent_id': spell_activity_id, 'creator_id': review.id }, {'other_identifier': review.patient_id.other_identifier}, context=context) activity_pool.submit(cr, uid, review.activity_id.id, {'location_id': review.location_id.id}, context=context) activity_pool.complete(cr, uid, review.activity_id.id, context=context) return True def ptwr_complete(self, cr, uid, ids, context=None): activity_pool = self.pool['nh.activity'] for review in self.browse(cr, uid, ids, context=context): activity_pool.submit(cr, uid, review.ptwr_id.id, {}, context=context) activity_pool.complete(cr, uid, review.ptwr_id.id, context=context) return True<|fim▁end|>
'target': 'new', 'context': context
<|file_name|>brspnd.rs<|end_file_name|><|fim▁begin|>#[doc = "Register `BRSPND[%s]` reader"] pub struct R(crate::R<BRSPND_SPEC>); impl core::ops::Deref for R { type Target = crate::R<BRSPND_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<BRSPND_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<BRSPND_SPEC>) -> Self { R(reader) } } #[doc = "Register `BRSPND[%s]` writer"] pub struct W(crate::W<BRSPND_SPEC>); impl core::ops::Deref for W { type Target = crate::W<BRSPND_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<BRSPND_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<BRSPND_SPEC>) -> Self { W(writer) } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG0_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"] VALUE2 = 1, } impl From<CHPNDG0_A> for bool { #[inline(always)] fn from(variant: CHPNDG0_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG0` reader - Channels Pending Group x"] pub struct CHPNDG0_R(crate::FieldReader<bool, CHPNDG0_A>); impl CHPNDG0_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG0_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG0_A { match self.bits { false => CHPNDG0_A::VALUE1, true => CHPNDG0_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG0_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG0_A::VALUE2 } } impl core::ops::Deref for CHPNDG0_R { type Target = crate::FieldReader<bool, CHPNDG0_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG0` writer - Channels Pending Group x"] pub struct CHPNDG0_W<'a> { w: &'a mut W, } impl<'a> CHPNDG0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG0_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG0_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG0_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG1_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"] VALUE2 = 1, } impl From<CHPNDG1_A> for bool { #[inline(always)] fn from(variant: CHPNDG1_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG1` reader - Channels Pending Group x"] pub struct CHPNDG1_R(crate::FieldReader<bool, CHPNDG1_A>); impl CHPNDG1_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG1_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG1_A { match self.bits { false => CHPNDG1_A::VALUE1, true => CHPNDG1_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG1_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG1_A::VALUE2 } } impl core::ops::Deref for CHPNDG1_R { type Target = crate::FieldReader<bool, CHPNDG1_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG1` writer - Channels Pending Group x"] pub struct CHPNDG1_W<'a> { w: &'a mut W, } impl<'a> CHPNDG1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG1_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG1_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG1_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1); self.w } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG2_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"] VALUE2 = 1, } impl From<CHPNDG2_A> for bool { #[inline(always)] fn from(variant: CHPNDG2_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG2` reader - Channels Pending Group x"] pub struct CHPNDG2_R(crate::FieldReader<bool, CHPNDG2_A>); impl CHPNDG2_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG2_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG2_A { match self.bits { false => CHPNDG2_A::VALUE1, true => CHPNDG2_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG2_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG2_A::VALUE2 } } impl core::ops::Deref for CHPNDG2_R { type Target = crate::FieldReader<bool, CHPNDG2_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG2` writer - Channels Pending Group x"] pub struct CHPNDG2_W<'a> { w: &'a mut W, } impl<'a> CHPNDG2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG2_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG2_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG2_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2); self.w } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG3_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"] VALUE2 = 1, } impl From<CHPNDG3_A> for bool { #[inline(always)] fn from(variant: CHPNDG3_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG3` reader - Channels Pending Group x"] pub struct CHPNDG3_R(crate::FieldReader<bool, CHPNDG3_A>); impl CHPNDG3_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG3_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG3_A { match self.bits { false => CHPNDG3_A::VALUE1, true => CHPNDG3_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG3_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG3_A::VALUE2 } } impl core::ops::Deref for CHPNDG3_R { type Target = crate::FieldReader<bool, CHPNDG3_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG3` writer - Channels Pending Group x"] pub struct CHPNDG3_W<'a> { w: &'a mut W, } impl<'a> CHPNDG3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG3_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG3_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG3_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3); self.w } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG4_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"] VALUE2 = 1, } impl From<CHPNDG4_A> for bool { #[inline(always)] fn from(variant: CHPNDG4_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG4` reader - Channels Pending Group x"] pub struct CHPNDG4_R(crate::FieldReader<bool, CHPNDG4_A>); impl CHPNDG4_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG4_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG4_A { match self.bits { false => CHPNDG4_A::VALUE1, true => CHPNDG4_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG4_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG4_A::VALUE2 } } impl core::ops::Deref for CHPNDG4_R { type Target = crate::FieldReader<bool, CHPNDG4_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG4` writer - Channels Pending Group x"] pub struct CHPNDG4_W<'a> { w: &'a mut W, } impl<'a> CHPNDG4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG4_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG4_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG4_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4); self.w } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG5_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"] VALUE2 = 1, } impl From<CHPNDG5_A> for bool { #[inline(always)] fn from(variant: CHPNDG5_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG5` reader - Channels Pending Group x"] pub struct CHPNDG5_R(crate::FieldReader<bool, CHPNDG5_A>); impl CHPNDG5_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG5_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG5_A { match self.bits { false => CHPNDG5_A::VALUE1, true => CHPNDG5_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG5_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG5_A::VALUE2 } } impl core::ops::Deref for CHPNDG5_R { type Target = crate::FieldReader<bool, CHPNDG5_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG5` writer - Channels Pending Group x"] pub struct CHPNDG5_W<'a> { w: &'a mut W, } impl<'a> CHPNDG5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG5_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG5_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG5_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5); self.w } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG6_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"]<|fim▁hole|>} impl From<CHPNDG6_A> for bool { #[inline(always)] fn from(variant: CHPNDG6_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG6` reader - Channels Pending Group x"] pub struct CHPNDG6_R(crate::FieldReader<bool, CHPNDG6_A>); impl CHPNDG6_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG6_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG6_A { match self.bits { false => CHPNDG6_A::VALUE1, true => CHPNDG6_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG6_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG6_A::VALUE2 } } impl core::ops::Deref for CHPNDG6_R { type Target = crate::FieldReader<bool, CHPNDG6_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG6` writer - Channels Pending Group x"] pub struct CHPNDG6_W<'a> { w: &'a mut W, } impl<'a> CHPNDG6_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG6_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG6_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG6_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | ((value as u32 & 0x01) << 6); self.w } } #[doc = "Channels Pending Group x\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CHPNDG7_A { #[doc = "0: Ignore this channel"] VALUE1 = 0, #[doc = "1: Request conversion of this channel"] VALUE2 = 1, } impl From<CHPNDG7_A> for bool { #[inline(always)] fn from(variant: CHPNDG7_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CHPNDG7` reader - Channels Pending Group x"] pub struct CHPNDG7_R(crate::FieldReader<bool, CHPNDG7_A>); impl CHPNDG7_R { pub(crate) fn new(bits: bool) -> Self { CHPNDG7_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CHPNDG7_A { match self.bits { false => CHPNDG7_A::VALUE1, true => CHPNDG7_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == CHPNDG7_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == CHPNDG7_A::VALUE2 } } impl core::ops::Deref for CHPNDG7_R { type Target = crate::FieldReader<bool, CHPNDG7_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHPNDG7` writer - Channels Pending Group x"] pub struct CHPNDG7_W<'a> { w: &'a mut W, } impl<'a> CHPNDG7_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CHPNDG7_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Ignore this channel"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(CHPNDG7_A::VALUE1) } #[doc = "Request conversion of this channel"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(CHPNDG7_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7); self.w } } impl R { #[doc = "Bit 0 - Channels Pending Group x"] #[inline(always)] pub fn chpndg0(&self) -> CHPNDG0_R { CHPNDG0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Channels Pending Group x"] #[inline(always)] pub fn chpndg1(&self) -> CHPNDG1_R { CHPNDG1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Channels Pending Group x"] #[inline(always)] pub fn chpndg2(&self) -> CHPNDG2_R { CHPNDG2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Channels Pending Group x"] #[inline(always)] pub fn chpndg3(&self) -> CHPNDG3_R { CHPNDG3_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Channels Pending Group x"] #[inline(always)] pub fn chpndg4(&self) -> CHPNDG4_R { CHPNDG4_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Channels Pending Group x"] #[inline(always)] pub fn chpndg5(&self) -> CHPNDG5_R { CHPNDG5_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Channels Pending Group x"] #[inline(always)] pub fn chpndg6(&self) -> CHPNDG6_R { CHPNDG6_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Channels Pending Group x"] #[inline(always)] pub fn chpndg7(&self) -> CHPNDG7_R { CHPNDG7_R::new(((self.bits >> 7) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Channels Pending Group x"] #[inline(always)] pub fn chpndg0(&mut self) -> CHPNDG0_W { CHPNDG0_W { w: self } } #[doc = "Bit 1 - Channels Pending Group x"] #[inline(always)] pub fn chpndg1(&mut self) -> CHPNDG1_W { CHPNDG1_W { w: self } } #[doc = "Bit 2 - Channels Pending Group x"] #[inline(always)] pub fn chpndg2(&mut self) -> CHPNDG2_W { CHPNDG2_W { w: self } } #[doc = "Bit 3 - Channels Pending Group x"] #[inline(always)] pub fn chpndg3(&mut self) -> CHPNDG3_W { CHPNDG3_W { w: self } } #[doc = "Bit 4 - Channels Pending Group x"] #[inline(always)] pub fn chpndg4(&mut self) -> CHPNDG4_W { CHPNDG4_W { w: self } } #[doc = "Bit 5 - Channels Pending Group x"] #[inline(always)] pub fn chpndg5(&mut self) -> CHPNDG5_W { CHPNDG5_W { w: self } } #[doc = "Bit 6 - Channels Pending Group x"] #[inline(always)] pub fn chpndg6(&mut self) -> CHPNDG6_W { CHPNDG6_W { w: self } } #[doc = "Bit 7 - Channels Pending Group x"] #[inline(always)] pub fn chpndg7(&mut self) -> CHPNDG7_W { CHPNDG7_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Background Request Source Pending Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [brspnd](index.html) module"] pub struct BRSPND_SPEC; impl crate::RegisterSpec for BRSPND_SPEC { type Ux = u32; } #[doc = "`read()` method returns [brspnd::R](R) reader structure"] impl crate::Readable for BRSPND_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [brspnd::W](W) writer structure"] impl crate::Writable for BRSPND_SPEC { type Writer = W; } #[doc = "`reset()` method sets BRSPND[%s] to value 0"] impl crate::Resettable for BRSPND_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }<|fim▁end|>
VALUE2 = 1,
<|file_name|>getos.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # STARLING PROJECT # # LIRIS - Laboratoire d'InfoRmatique en Image et Systèmes d'information # # Copyright: 2012 - 2015 Eric Lombardi ([email protected]), LIRIS (liris.cnrs.fr), CNRS (www.cnrs.fr) # # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. #<|fim▁hole|># # Get OS version informations. # import platform fullOsVersion = platform.platform() if 'x86_64-with-Ubuntu-16.04' in fullOsVersion: shortVersion = 'u1604-64' elif 'x86_64-with-Ubuntu-14.04' in fullOsVersion: shortVersion = 'u1404-64' elif 'x86_64-with-Ubuntu-12.04' in fullOsVersion: shortVersion = 'u1204-64' elif 'Windows-7' in fullOsVersion: shortVersion = 'w7' else: shortVersion = 'unknown' print shortVersion<|fim▁end|>
# For further information, check the COPYING file distributed with this software. # #----------------------------------------------------------------------
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import MAXDB_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.maxdb.enumeration import Enumeration from plugins.dbms.maxdb.filesystem import Filesystem from plugins.dbms.maxdb.fingerprint import Fingerprint from plugins.dbms.maxdb.syntax import Syntax from plugins.dbms.maxdb.takeover import Takeover from plugins.generic.misc import Miscellaneous class MaxDBMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines SAP MaxDB methods """ def __init__(self): self.excludeDbsList = MAXDB_SYSTEM_DBS<|fim▁hole|> Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.MAXDB] = Syntax.escape<|fim▁end|>
<|file_name|>function-call.rs<|end_file_name|><|fim▁begin|>// This test does not passed with gdb < 8.0. See #53497. // min-gdb-version: 10.1 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print fun(45, true) // gdb-check:$1 = true // gdb-command:print fun(444, false) // gdb-check:$2 = false // gdb-command:print r.get_x() // gdb-check:$3 = 4 #![allow(dead_code, unused_variables)] struct RegularStruct { x: i32 } impl RegularStruct { fn get_x(&self) -> i32 { self.x } } fn main() { let _ = fun(4, true); let r = RegularStruct{x: 4}; let _ = r.get_x(); zzz(); // #break } fn fun(x: isize, y: bool) -> bool { y }<|fim▁hole|>fn zzz() { () }<|fim▁end|>
<|file_name|>const.py<|end_file_name|><|fim▁begin|>"""Define constants for the SimpliSafe component.""" from datetime import timedelta DOMAIN = "simplisafe"<|fim▁hole|>DEFAULT_SCAN_INTERVAL = timedelta(seconds=30) TOPIC_UPDATE = "update"<|fim▁end|>
DATA_CLIENT = "client"
<|file_name|>parameters.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
export { default } from 'ember-fhir/models/parameters';
<|file_name|>mpe.ts<|end_file_name|><|fim▁begin|>import { ModuleTitle, ModuleCode } from './modules'; export type MpePreference = {<|fim▁hole|> moduleType: '01' | '02' | '03' | '04'; }; export type MpeSubmission = { nusExchangeId?: string; intendedMCs: number; preferences: Array<MpePreference>; }; export type MpeModule = { title: ModuleTitle; moduleCode: ModuleCode; moduleCredit: string; inS1MPE?: boolean; inS2MPE?: boolean; }; interface ModuleTypeInfo { label: string; } export const MODULE_TYPES: Record<MpePreference['moduleType'], ModuleTypeInfo> = { '01': { label: 'Essential Major', }, '02': { label: 'Essential Second Major', }, '03': { label: 'Elective', }, '04': { label: 'Unrestricted Elective', }, };<|fim▁end|>
rank?: number; moduleTitle?: ModuleTitle; moduleCredits?: number; moduleCode: ModuleCode;
<|file_name|>tensor.rs<|end_file_name|><|fim▁begin|>// This file is generated by rust-protobuf 2.25.1. Do not edit // @generated // https://github.com/rust-lang/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_imports)] #![allow(unused_results)] //! Generated file from `tensorflow/core/framework/tensor.proto` /// Generated files are compatible only with the same version /// of protobuf runtime. // const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_25_1; #[derive(PartialEq,Clone,Default)] pub struct TensorProto { // message fields pub dtype: super::types::DataType, pub tensor_shape: ::protobuf::SingularPtrField<super::tensor_shape::TensorShapeProto>, pub version_number: i32, pub tensor_content: ::std::vec::Vec<u8>, pub half_val: ::std::vec::Vec<i32>, pub float_val: ::std::vec::Vec<f32>, pub double_val: ::std::vec::Vec<f64>, pub int_val: ::std::vec::Vec<i32>, pub string_val: ::protobuf::RepeatedField<::std::vec::Vec<u8>>, pub scomplex_val: ::std::vec::Vec<f32>, pub int64_val: ::std::vec::Vec<i64>, pub bool_val: ::std::vec::Vec<bool>, pub dcomplex_val: ::std::vec::Vec<f64>, pub resource_handle_val: ::protobuf::RepeatedField<super::resource_handle::ResourceHandleProto>, pub variant_val: ::protobuf::RepeatedField<VariantTensorDataProto>, pub uint32_val: ::std::vec::Vec<u32>, pub uint64_val: ::std::vec::Vec<u64>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a TensorProto { fn default() -> &'a TensorProto { <TensorProto as ::protobuf::Message>::default_instance() } } impl TensorProto { pub fn new() -> TensorProto { ::std::default::Default::default() } // .tensorflow.DataType dtype = 1; pub fn get_dtype(&self) -> super::types::DataType { self.dtype } pub fn clear_dtype(&mut self) { self.dtype = super::types::DataType::DT_INVALID; } // Param is passed by value, moved pub fn set_dtype(&mut self, v: super::types::DataType) { self.dtype = v; } // .tensorflow.TensorShapeProto tensor_shape = 2; pub fn get_tensor_shape(&self) -> &super::tensor_shape::TensorShapeProto { self.tensor_shape.as_ref().unwrap_or_else(|| <super::tensor_shape::TensorShapeProto as ::protobuf::Message>::default_instance()) } pub fn clear_tensor_shape(&mut self) { self.tensor_shape.clear(); } pub fn has_tensor_shape(&self) -> bool { self.tensor_shape.is_some() } // Param is passed by value, moved pub fn set_tensor_shape(&mut self, v: super::tensor_shape::TensorShapeProto) { self.tensor_shape = ::protobuf::SingularPtrField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_tensor_shape(&mut self) -> &mut super::tensor_shape::TensorShapeProto { if self.tensor_shape.is_none() { self.tensor_shape.set_default(); } self.tensor_shape.as_mut().unwrap() } // Take field pub fn take_tensor_shape(&mut self) -> super::tensor_shape::TensorShapeProto { self.tensor_shape.take().unwrap_or_else(|| super::tensor_shape::TensorShapeProto::new()) } // int32 version_number = 3; pub fn get_version_number(&self) -> i32 { self.version_number } pub fn clear_version_number(&mut self) { self.version_number = 0; } // Param is passed by value, moved pub fn set_version_number(&mut self, v: i32) { self.version_number = v; } // bytes tensor_content = 4; pub fn get_tensor_content(&self) -> &[u8] { &self.tensor_content } pub fn clear_tensor_content(&mut self) { self.tensor_content.clear(); } // Param is passed by value, moved pub fn set_tensor_content(&mut self, v: ::std::vec::Vec<u8>) { self.tensor_content = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_tensor_content(&mut self) -> &mut ::std::vec::Vec<u8> { &mut self.tensor_content } // Take field pub fn take_tensor_content(&mut self) -> ::std::vec::Vec<u8> { ::std::mem::replace(&mut self.tensor_content, ::std::vec::Vec::new()) } // repeated int32 half_val = 13; pub fn get_half_val(&self) -> &[i32] { &self.half_val } pub fn clear_half_val(&mut self) { self.half_val.clear(); } // Param is passed by value, moved pub fn set_half_val(&mut self, v: ::std::vec::Vec<i32>) { self.half_val = v; } // Mutable pointer to the field. pub fn mut_half_val(&mut self) -> &mut ::std::vec::Vec<i32> { &mut self.half_val } // Take field pub fn take_half_val(&mut self) -> ::std::vec::Vec<i32> { ::std::mem::replace(&mut self.half_val, ::std::vec::Vec::new()) } // repeated float float_val = 5; pub fn get_float_val(&self) -> &[f32] { &self.float_val } pub fn clear_float_val(&mut self) { self.float_val.clear(); } // Param is passed by value, moved pub fn set_float_val(&mut self, v: ::std::vec::Vec<f32>) { self.float_val = v; } // Mutable pointer to the field. pub fn mut_float_val(&mut self) -> &mut ::std::vec::Vec<f32> { &mut self.float_val } // Take field pub fn take_float_val(&mut self) -> ::std::vec::Vec<f32> { ::std::mem::replace(&mut self.float_val, ::std::vec::Vec::new()) } // repeated double double_val = 6; pub fn get_double_val(&self) -> &[f64] { &self.double_val } pub fn clear_double_val(&mut self) { self.double_val.clear(); } // Param is passed by value, moved pub fn set_double_val(&mut self, v: ::std::vec::Vec<f64>) { self.double_val = v; } // Mutable pointer to the field. pub fn mut_double_val(&mut self) -> &mut ::std::vec::Vec<f64> { &mut self.double_val } // Take field pub fn take_double_val(&mut self) -> ::std::vec::Vec<f64> { ::std::mem::replace(&mut self.double_val, ::std::vec::Vec::new()) } // repeated int32 int_val = 7; pub fn get_int_val(&self) -> &[i32] { &self.int_val } pub fn clear_int_val(&mut self) { self.int_val.clear(); } // Param is passed by value, moved pub fn set_int_val(&mut self, v: ::std::vec::Vec<i32>) { self.int_val = v; } // Mutable pointer to the field. pub fn mut_int_val(&mut self) -> &mut ::std::vec::Vec<i32> { &mut self.int_val } // Take field pub fn take_int_val(&mut self) -> ::std::vec::Vec<i32> { ::std::mem::replace(&mut self.int_val, ::std::vec::Vec::new()) } // repeated bytes string_val = 8; pub fn get_string_val(&self) -> &[::std::vec::Vec<u8>] { &self.string_val } pub fn clear_string_val(&mut self) { self.string_val.clear(); } // Param is passed by value, moved pub fn set_string_val(&mut self, v: ::protobuf::RepeatedField<::std::vec::Vec<u8>>) { self.string_val = v; } // Mutable pointer to the field. pub fn mut_string_val(&mut self) -> &mut ::protobuf::RepeatedField<::std::vec::Vec<u8>> { &mut self.string_val } // Take field pub fn take_string_val(&mut self) -> ::protobuf::RepeatedField<::std::vec::Vec<u8>> { ::std::mem::replace(&mut self.string_val, ::protobuf::RepeatedField::new()) } // repeated float scomplex_val = 9; pub fn get_scomplex_val(&self) -> &[f32] { &self.scomplex_val } pub fn clear_scomplex_val(&mut self) { self.scomplex_val.clear(); } // Param is passed by value, moved pub fn set_scomplex_val(&mut self, v: ::std::vec::Vec<f32>) { self.scomplex_val = v; } // Mutable pointer to the field. pub fn mut_scomplex_val(&mut self) -> &mut ::std::vec::Vec<f32> { &mut self.scomplex_val } // Take field pub fn take_scomplex_val(&mut self) -> ::std::vec::Vec<f32> { ::std::mem::replace(&mut self.scomplex_val, ::std::vec::Vec::new()) } // repeated int64 int64_val = 10; pub fn get_int64_val(&self) -> &[i64] { &self.int64_val } pub fn clear_int64_val(&mut self) { self.int64_val.clear(); } // Param is passed by value, moved pub fn set_int64_val(&mut self, v: ::std::vec::Vec<i64>) { self.int64_val = v; } // Mutable pointer to the field. pub fn mut_int64_val(&mut self) -> &mut ::std::vec::Vec<i64> { &mut self.int64_val } // Take field pub fn take_int64_val(&mut self) -> ::std::vec::Vec<i64> { ::std::mem::replace(&mut self.int64_val, ::std::vec::Vec::new()) } // repeated bool bool_val = 11; pub fn get_bool_val(&self) -> &[bool] { &self.bool_val } pub fn clear_bool_val(&mut self) { self.bool_val.clear(); } // Param is passed by value, moved pub fn set_bool_val(&mut self, v: ::std::vec::Vec<bool>) { self.bool_val = v; } // Mutable pointer to the field. pub fn mut_bool_val(&mut self) -> &mut ::std::vec::Vec<bool> { &mut self.bool_val } // Take field pub fn take_bool_val(&mut self) -> ::std::vec::Vec<bool> { ::std::mem::replace(&mut self.bool_val, ::std::vec::Vec::new()) } // repeated double dcomplex_val = 12; pub fn get_dcomplex_val(&self) -> &[f64] { &self.dcomplex_val } pub fn clear_dcomplex_val(&mut self) { self.dcomplex_val.clear(); } // Param is passed by value, moved pub fn set_dcomplex_val(&mut self, v: ::std::vec::Vec<f64>) { self.dcomplex_val = v; } // Mutable pointer to the field. pub fn mut_dcomplex_val(&mut self) -> &mut ::std::vec::Vec<f64> { &mut self.dcomplex_val } // Take field pub fn take_dcomplex_val(&mut self) -> ::std::vec::Vec<f64> { ::std::mem::replace(&mut self.dcomplex_val, ::std::vec::Vec::new()) } // repeated .tensorflow.ResourceHandleProto resource_handle_val = 14; pub fn get_resource_handle_val(&self) -> &[super::resource_handle::ResourceHandleProto] { &self.resource_handle_val } pub fn clear_resource_handle_val(&mut self) { self.resource_handle_val.clear(); } // Param is passed by value, moved pub fn set_resource_handle_val(&mut self, v: ::protobuf::RepeatedField<super::resource_handle::ResourceHandleProto>) { self.resource_handle_val = v; } // Mutable pointer to the field. pub fn mut_resource_handle_val(&mut self) -> &mut ::protobuf::RepeatedField<super::resource_handle::ResourceHandleProto> { &mut self.resource_handle_val } // Take field pub fn take_resource_handle_val(&mut self) -> ::protobuf::RepeatedField<super::resource_handle::ResourceHandleProto> { ::std::mem::replace(&mut self.resource_handle_val, ::protobuf::RepeatedField::new()) } // repeated .tensorflow.VariantTensorDataProto variant_val = 15; pub fn get_variant_val(&self) -> &[VariantTensorDataProto] { &self.variant_val } pub fn clear_variant_val(&mut self) { self.variant_val.clear(); } // Param is passed by value, moved pub fn set_variant_val(&mut self, v: ::protobuf::RepeatedField<VariantTensorDataProto>) { self.variant_val = v; } // Mutable pointer to the field. pub fn mut_variant_val(&mut self) -> &mut ::protobuf::RepeatedField<VariantTensorDataProto> { &mut self.variant_val } // Take field pub fn take_variant_val(&mut self) -> ::protobuf::RepeatedField<VariantTensorDataProto> { ::std::mem::replace(&mut self.variant_val, ::protobuf::RepeatedField::new()) } // repeated uint32 uint32_val = 16; pub fn get_uint32_val(&self) -> &[u32] { &self.uint32_val } pub fn clear_uint32_val(&mut self) { self.uint32_val.clear(); } // Param is passed by value, moved pub fn set_uint32_val(&mut self, v: ::std::vec::Vec<u32>) { self.uint32_val = v; } // Mutable pointer to the field. pub fn mut_uint32_val(&mut self) -> &mut ::std::vec::Vec<u32> { &mut self.uint32_val } // Take field pub fn take_uint32_val(&mut self) -> ::std::vec::Vec<u32> { ::std::mem::replace(&mut self.uint32_val, ::std::vec::Vec::new()) } // repeated uint64 uint64_val = 17; pub fn get_uint64_val(&self) -> &[u64] { &self.uint64_val } pub fn clear_uint64_val(&mut self) { self.uint64_val.clear(); } // Param is passed by value, moved pub fn set_uint64_val(&mut self, v: ::std::vec::Vec<u64>) { self.uint64_val = v; } // Mutable pointer to the field. pub fn mut_uint64_val(&mut self) -> &mut ::std::vec::Vec<u64> { &mut self.uint64_val } // Take field pub fn take_uint64_val(&mut self) -> ::std::vec::Vec<u64> { ::std::mem::replace(&mut self.uint64_val, ::std::vec::Vec::new()) } } impl ::protobuf::Message for TensorProto { fn is_initialized(&self) -> bool { for v in &self.tensor_shape { if !v.is_initialized() { return false; } }; for v in &self.resource_handle_val { if !v.is_initialized() { return false; } }; for v in &self.variant_val { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.dtype, 1, &mut self.unknown_fields)? }, 2 => { ::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.tensor_shape)?; }, 3 => { if wire_type != ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_int32()?; self.version_number = tmp; }, 4 => { ::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.tensor_content)?; }, 13 => { ::protobuf::rt::read_repeated_int32_into(wire_type, is, &mut self.half_val)?; }, 5 => { ::protobuf::rt::read_repeated_float_into(wire_type, is, &mut self.float_val)?; }, 6 => { ::protobuf::rt::read_repeated_double_into(wire_type, is, &mut self.double_val)?; }, 7 => { ::protobuf::rt::read_repeated_int32_into(wire_type, is, &mut self.int_val)?; }, 8 => { ::protobuf::rt::read_repeated_bytes_into(wire_type, is, &mut self.string_val)?; }, 9 => { ::protobuf::rt::read_repeated_float_into(wire_type, is, &mut self.scomplex_val)?; }, 10 => { ::protobuf::rt::read_repeated_int64_into(wire_type, is, &mut self.int64_val)?; }, 11 => { ::protobuf::rt::read_repeated_bool_into(wire_type, is, &mut self.bool_val)?; }, 12 => { ::protobuf::rt::read_repeated_double_into(wire_type, is, &mut self.dcomplex_val)?; }, 14 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.resource_handle_val)?; }, 15 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.variant_val)?; }, 16 => { ::protobuf::rt::read_repeated_uint32_into(wire_type, is, &mut self.uint32_val)?; }, 17 => { ::protobuf::rt::read_repeated_uint64_into(wire_type, is, &mut self.uint64_val)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.dtype != super::types::DataType::DT_INVALID { my_size += ::protobuf::rt::enum_size(1, self.dtype); } if let Some(ref v) = self.tensor_shape.as_ref() { let len = v.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; } if self.version_number != 0 { my_size += ::protobuf::rt::value_size(3, self.version_number, ::protobuf::wire_format::WireTypeVarint); } if !self.tensor_content.is_empty() { my_size += ::protobuf::rt::bytes_size(4, &self.tensor_content); } if !self.half_val.is_empty() { my_size += ::protobuf::rt::vec_packed_varint_size(13, &self.half_val); } if !self.float_val.is_empty() { my_size += 1 + ::protobuf::rt::compute_raw_varint32_size((self.float_val.len() * 4) as u32) + (self.float_val.len() * 4) as u32; } if !self.double_val.is_empty() { my_size += 1 + ::protobuf::rt::compute_raw_varint32_size((self.double_val.len() * 8) as u32) + (self.double_val.len() * 8) as u32; } if !self.int_val.is_empty() { my_size += ::protobuf::rt::vec_packed_varint_size(7, &self.int_val); } for value in &self.string_val { my_size += ::protobuf::rt::bytes_size(8, &value); }; if !self.scomplex_val.is_empty() { my_size += 1 + ::protobuf::rt::compute_raw_varint32_size((self.scomplex_val.len() * 4) as u32) + (self.scomplex_val.len() * 4) as u32; } if !self.int64_val.is_empty() { my_size += ::protobuf::rt::vec_packed_varint_size(10, &self.int64_val); } if !self.bool_val.is_empty() { my_size += 1 + ::protobuf::rt::compute_raw_varint32_size((self.bool_val.len() * 1) as u32) + (self.bool_val.len() * 1) as u32; } if !self.dcomplex_val.is_empty() { my_size += 1 + ::protobuf::rt::compute_raw_varint32_size((self.dcomplex_val.len() * 8) as u32) + (self.dcomplex_val.len() * 8) as u32; } for value in &self.resource_handle_val { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.variant_val { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; if !self.uint32_val.is_empty() { my_size += ::protobuf::rt::vec_packed_varint_size(16, &self.uint32_val); } if !self.uint64_val.is_empty() { my_size += ::protobuf::rt::vec_packed_varint_size(17, &self.uint64_val); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if self.dtype != super::types::DataType::DT_INVALID { os.write_enum(1, ::protobuf::ProtobufEnum::value(&self.dtype))?; } if let Some(ref v) = self.tensor_shape.as_ref() { os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; } if self.version_number != 0 { os.write_int32(3, self.version_number)?; } if !self.tensor_content.is_empty() { os.write_bytes(4, &self.tensor_content)?; } if !self.half_val.is_empty() { os.write_tag(13, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32(::protobuf::rt::vec_packed_varint_data_size(&self.half_val))?; for v in &self.half_val { os.write_int32_no_tag(*v)?; }; } if !self.float_val.is_empty() { os.write_tag(5, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32((self.float_val.len() * 4) as u32)?; for v in &self.float_val { os.write_float_no_tag(*v)?; };<|fim▁hole|> // TODO: Data size is computed again, it should be cached os.write_raw_varint32((self.double_val.len() * 8) as u32)?; for v in &self.double_val { os.write_double_no_tag(*v)?; }; } if !self.int_val.is_empty() { os.write_tag(7, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32(::protobuf::rt::vec_packed_varint_data_size(&self.int_val))?; for v in &self.int_val { os.write_int32_no_tag(*v)?; }; } for v in &self.string_val { os.write_bytes(8, &v)?; }; if !self.scomplex_val.is_empty() { os.write_tag(9, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32((self.scomplex_val.len() * 4) as u32)?; for v in &self.scomplex_val { os.write_float_no_tag(*v)?; }; } if !self.int64_val.is_empty() { os.write_tag(10, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32(::protobuf::rt::vec_packed_varint_data_size(&self.int64_val))?; for v in &self.int64_val { os.write_int64_no_tag(*v)?; }; } if !self.bool_val.is_empty() { os.write_tag(11, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32((self.bool_val.len() * 1) as u32)?; for v in &self.bool_val { os.write_bool_no_tag(*v)?; }; } if !self.dcomplex_val.is_empty() { os.write_tag(12, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32((self.dcomplex_val.len() * 8) as u32)?; for v in &self.dcomplex_val { os.write_double_no_tag(*v)?; }; } for v in &self.resource_handle_val { os.write_tag(14, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.variant_val { os.write_tag(15, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; if !self.uint32_val.is_empty() { os.write_tag(16, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32(::protobuf::rt::vec_packed_varint_data_size(&self.uint32_val))?; for v in &self.uint32_val { os.write_uint32_no_tag(*v)?; }; } if !self.uint64_val.is_empty() { os.write_tag(17, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32(::protobuf::rt::vec_packed_varint_data_size(&self.uint64_val))?; for v in &self.uint64_val { os.write_uint64_no_tag(*v)?; }; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> TensorProto { TensorProto::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum<super::types::DataType>>( "dtype", |m: &TensorProto| { &m.dtype }, |m: &mut TensorProto| { &mut m.dtype }, )); fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<super::tensor_shape::TensorShapeProto>>( "tensor_shape", |m: &TensorProto| { &m.tensor_shape }, |m: &mut TensorProto| { &mut m.tensor_shape }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "version_number", |m: &TensorProto| { &m.version_number }, |m: &mut TensorProto| { &mut m.version_number }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "tensor_content", |m: &TensorProto| { &m.tensor_content }, |m: &mut TensorProto| { &mut m.tensor_content }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "half_val", |m: &TensorProto| { &m.half_val }, |m: &mut TensorProto| { &mut m.half_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeFloat>( "float_val", |m: &TensorProto| { &m.float_val }, |m: &mut TensorProto| { &mut m.float_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeDouble>( "double_val", |m: &TensorProto| { &m.double_val }, |m: &mut TensorProto| { &mut m.double_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "int_val", |m: &TensorProto| { &m.int_val }, |m: &mut TensorProto| { &mut m.int_val }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "string_val", |m: &TensorProto| { &m.string_val }, |m: &mut TensorProto| { &mut m.string_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeFloat>( "scomplex_val", |m: &TensorProto| { &m.scomplex_val }, |m: &mut TensorProto| { &mut m.scomplex_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeInt64>( "int64_val", |m: &TensorProto| { &m.int64_val }, |m: &mut TensorProto| { &mut m.int64_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeBool>( "bool_val", |m: &TensorProto| { &m.bool_val }, |m: &mut TensorProto| { &mut m.bool_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeDouble>( "dcomplex_val", |m: &TensorProto| { &m.dcomplex_val }, |m: &mut TensorProto| { &mut m.dcomplex_val }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<super::resource_handle::ResourceHandleProto>>( "resource_handle_val", |m: &TensorProto| { &m.resource_handle_val }, |m: &mut TensorProto| { &mut m.resource_handle_val }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<VariantTensorDataProto>>( "variant_val", |m: &TensorProto| { &m.variant_val }, |m: &mut TensorProto| { &mut m.variant_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( "uint32_val", |m: &TensorProto| { &m.uint32_val }, |m: &mut TensorProto| { &mut m.uint32_val }, )); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeUint64>( "uint64_val", |m: &TensorProto| { &m.uint64_val }, |m: &mut TensorProto| { &mut m.uint64_val }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<TensorProto>( "TensorProto", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TensorProto { static instance: ::protobuf::rt::LazyV2<TensorProto> = ::protobuf::rt::LazyV2::INIT; instance.get(TensorProto::new) } } impl ::protobuf::Clear for TensorProto { fn clear(&mut self) { self.dtype = super::types::DataType::DT_INVALID; self.tensor_shape.clear(); self.version_number = 0; self.tensor_content.clear(); self.half_val.clear(); self.float_val.clear(); self.double_val.clear(); self.int_val.clear(); self.string_val.clear(); self.scomplex_val.clear(); self.int64_val.clear(); self.bool_val.clear(); self.dcomplex_val.clear(); self.resource_handle_val.clear(); self.variant_val.clear(); self.uint32_val.clear(); self.uint64_val.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for TensorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for TensorProto { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct VariantTensorDataProto { // message fields pub type_name: ::std::string::String, pub metadata: ::std::vec::Vec<u8>, pub tensors: ::protobuf::RepeatedField<TensorProto>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a VariantTensorDataProto { fn default() -> &'a VariantTensorDataProto { <VariantTensorDataProto as ::protobuf::Message>::default_instance() } } impl VariantTensorDataProto { pub fn new() -> VariantTensorDataProto { ::std::default::Default::default() } // string type_name = 1; pub fn get_type_name(&self) -> &str { &self.type_name } pub fn clear_type_name(&mut self) { self.type_name.clear(); } // Param is passed by value, moved pub fn set_type_name(&mut self, v: ::std::string::String) { self.type_name = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_type_name(&mut self) -> &mut ::std::string::String { &mut self.type_name } // Take field pub fn take_type_name(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.type_name, ::std::string::String::new()) } // bytes metadata = 2; pub fn get_metadata(&self) -> &[u8] { &self.metadata } pub fn clear_metadata(&mut self) { self.metadata.clear(); } // Param is passed by value, moved pub fn set_metadata(&mut self, v: ::std::vec::Vec<u8>) { self.metadata = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_metadata(&mut self) -> &mut ::std::vec::Vec<u8> { &mut self.metadata } // Take field pub fn take_metadata(&mut self) -> ::std::vec::Vec<u8> { ::std::mem::replace(&mut self.metadata, ::std::vec::Vec::new()) } // repeated .tensorflow.TensorProto tensors = 3; pub fn get_tensors(&self) -> &[TensorProto] { &self.tensors } pub fn clear_tensors(&mut self) { self.tensors.clear(); } // Param is passed by value, moved pub fn set_tensors(&mut self, v: ::protobuf::RepeatedField<TensorProto>) { self.tensors = v; } // Mutable pointer to the field. pub fn mut_tensors(&mut self) -> &mut ::protobuf::RepeatedField<TensorProto> { &mut self.tensors } // Take field pub fn take_tensors(&mut self) -> ::protobuf::RepeatedField<TensorProto> { ::std::mem::replace(&mut self.tensors, ::protobuf::RepeatedField::new()) } } impl ::protobuf::Message for VariantTensorDataProto { fn is_initialized(&self) -> bool { for v in &self.tensors { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.type_name)?; }, 2 => { ::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.metadata)?; }, 3 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.tensors)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if !self.type_name.is_empty() { my_size += ::protobuf::rt::string_size(1, &self.type_name); } if !self.metadata.is_empty() { my_size += ::protobuf::rt::bytes_size(2, &self.metadata); } for value in &self.tensors { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if !self.type_name.is_empty() { os.write_string(1, &self.type_name)?; } if !self.metadata.is_empty() { os.write_bytes(2, &self.metadata)?; } for v in &self.tensors { os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> VariantTensorDataProto { VariantTensorDataProto::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "type_name", |m: &VariantTensorDataProto| { &m.type_name }, |m: &mut VariantTensorDataProto| { &mut m.type_name }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "metadata", |m: &VariantTensorDataProto| { &m.metadata }, |m: &mut VariantTensorDataProto| { &mut m.metadata }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TensorProto>>( "tensors", |m: &VariantTensorDataProto| { &m.tensors }, |m: &mut VariantTensorDataProto| { &mut m.tensors }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<VariantTensorDataProto>( "VariantTensorDataProto", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static VariantTensorDataProto { static instance: ::protobuf::rt::LazyV2<VariantTensorDataProto> = ::protobuf::rt::LazyV2::INIT; instance.get(VariantTensorDataProto::new) } } impl ::protobuf::Clear for VariantTensorDataProto { fn clear(&mut self) { self.type_name.clear(); self.metadata.clear(); self.tensors.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for VariantTensorDataProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for VariantTensorDataProto { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n&tensorflow/core/framework/tensor.proto\x12\ntensorflow\x1a/tensorflow\ /core/framework/resource_handle.proto\x1a,tensorflow/core/framework/tens\ or_shape.proto\x1a%tensorflow/core/framework/types.proto\"\xd1\x05\n\x0b\ TensorProto\x12*\n\x05dtype\x18\x01\x20\x01(\x0e2\x14.tensorflow.DataTyp\ eR\x05dtype\x12?\n\x0ctensor_shape\x18\x02\x20\x01(\x0b2\x1c.tensorflow.\ TensorShapeProtoR\x0btensorShape\x12%\n\x0eversion_number\x18\x03\x20\ \x01(\x05R\rversionNumber\x12%\n\x0etensor_content\x18\x04\x20\x01(\x0cR\ \rtensorContent\x12\x1d\n\x08half_val\x18\r\x20\x03(\x05R\x07halfValB\ \x02\x10\x01\x12\x1f\n\tfloat_val\x18\x05\x20\x03(\x02R\x08floatValB\x02\ \x10\x01\x12!\n\ndouble_val\x18\x06\x20\x03(\x01R\tdoubleValB\x02\x10\ \x01\x12\x1b\n\x07int_val\x18\x07\x20\x03(\x05R\x06intValB\x02\x10\x01\ \x12\x1d\n\nstring_val\x18\x08\x20\x03(\x0cR\tstringVal\x12%\n\x0cscompl\ ex_val\x18\t\x20\x03(\x02R\x0bscomplexValB\x02\x10\x01\x12\x1f\n\tint64_\ val\x18\n\x20\x03(\x03R\x08int64ValB\x02\x10\x01\x12\x1d\n\x08bool_val\ \x18\x0b\x20\x03(\x08R\x07boolValB\x02\x10\x01\x12%\n\x0cdcomplex_val\ \x18\x0c\x20\x03(\x01R\x0bdcomplexValB\x02\x10\x01\x12O\n\x13resource_ha\ ndle_val\x18\x0e\x20\x03(\x0b2\x1f.tensorflow.ResourceHandleProtoR\x11re\ sourceHandleVal\x12C\n\x0bvariant_val\x18\x0f\x20\x03(\x0b2\".tensorflow\ .VariantTensorDataProtoR\nvariantVal\x12!\n\nuint32_val\x18\x10\x20\x03(\ \rR\tuint32ValB\x02\x10\x01\x12!\n\nuint64_val\x18\x11\x20\x03(\x04R\tui\ nt64ValB\x02\x10\x01\"\x84\x01\n\x16VariantTensorDataProto\x12\x1b\n\tty\ pe_name\x18\x01\x20\x01(\tR\x08typeName\x12\x1a\n\x08metadata\x18\x02\ \x20\x01(\x0cR\x08metadata\x121\n\x07tensors\x18\x03\x20\x03(\x0b2\x17.t\ ensorflow.TensorProtoR\x07tensorsB|\n\x18org.tensorflow.frameworkB\x0cTe\ nsorProtosP\x01ZMgithub.com/tensorflow/tensorflow/tensorflow/go/core/fra\ mework/tensor_go_proto\xf8\x01\x01b\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) }<|fim▁end|>
} if !self.double_val.is_empty() { os.write_tag(6, ::protobuf::wire_format::WireTypeLengthDelimited)?;
<|file_name|>SignupSpec.js<|end_file_name|><|fim▁begin|>// Copyright 2014 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by 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. /** * @fileoverview Unit tests for the editor prerequisites page. */ describe('Signup controller', function() { describe('SignupCtrl', function() { var scope, ctrl, $httpBackend, rootScope, mockAlertsService, urlParams; beforeEach(module('oppia', GLOBALS.TRANSLATOR_PROVIDER_FOR_TESTS)); beforeEach(inject(function(_$httpBackend_, $http, $rootScope, $controller) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('/signuphandler/data').respond({ username: 'myUsername', has_agreed_to_latest_terms: false }); rootScope = $rootScope; mockAlertsService = { addWarning: function() {} }; spyOn(mockAlertsService, 'addWarning'); scope = { getUrlParams: function() { return { return_url: 'return_url' }; } }; ctrl = $controller('Signup', { $scope: scope, $http: $http, $rootScope: rootScope, alertsService: mockAlertsService }); })); it('should show warning if user has not agreed to terms', function() { scope.submitPrerequisitesForm(false, null); expect(mockAlertsService.addWarning).toHaveBeenCalledWith( 'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS'); }); it('should get data correctly from the server', function() {<|fim▁hole|> expect(scope.hasAgreedToLatestTerms).toBe(false); }); it('should show a loading message until the data is retrieved', function() { expect(rootScope.loadingMessage).toBe('I18N_SIGNUP_LOADING'); $httpBackend.flush(); expect(rootScope.loadingMessage).toBeFalsy(); }); it('should show warning if terms are not agreed to', function() { scope.submitPrerequisitesForm(false, ''); expect(mockAlertsService.addWarning).toHaveBeenCalledWith( 'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS'); }); it('should show warning if no username provided', function() { scope.updateWarningText(''); expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME'); scope.submitPrerequisitesForm(false); expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME'); }); it('should show warning if username is too long', function() { scope.updateWarningText( 'abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba'); expect(scope.warningI18nCode).toEqual( 'I18N_SIGNUP_ERROR_USERNAME_MORE_50_CHARS'); }); it('should show warning if username has non-alphanumeric characters', function() { scope.updateWarningText('a-a'); expect(scope.warningI18nCode).toEqual( 'I18N_SIGNUP_ERROR_USERNAME_ONLY_ALPHANUM'); }); it('should show warning if username has \'admin\' in it', function() { scope.updateWarningText('administrator'); expect(scope.warningI18nCode).toEqual( 'I18N_SIGNUP_ERROR_USERNAME_WITH_ADMIN'); }); }); });<|fim▁end|>
$httpBackend.flush(); expect(scope.username).toBe('myUsername');
<|file_name|>it.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.1"> <context> <name>AboutDialog</name> <message> <source>About LMMS</source> <translation>Informazioni su LMMS</translation> </message> <message> <source>Version %1 (%2/%3, Qt %4, %5)</source> <translation>Versione %1 (%2/%3, Qt %4, %5)</translation> </message> <message> <source>About</source> <translation>Informazioni su</translation> </message> <message> <source>LMMS - easy music production for everyone</source> <translation>LMMS - Produzione musicale semplice per tutti</translation> </message> <message> <source>Authors</source> <translation>Autori</translation> </message> <message> <source>Translation</source> <translation>Traduzione</translation> </message> <message> <source>Current language not translated (or native English). If you&apos;re interested in translating LMMS in another language or want to improve existing translations, you&apos;re welcome to help us! Simply contact the maintainer!</source> <translation>Roberto Giaconia &lt;[email protected]&gt; Se sei interessato a tradurre LMMS o vuoi migliorare una traduzione esistente, sei il benvenuto!</translation> </message> <message> <source>License</source> <translation>Licenza</translation> </message> <message> <source>LMMS</source> <translation>LMMS</translation> </message> <message> <source>Involved</source> <translation>Coinvolti</translation> </message> <message> <source>Contributors ordered by number of commits:</source> <translation>Hanno collaborato (ordinati per numero di contributi):</translation> </message> <message> <source>Copyright © %1</source> <translation>Copyright © %1</translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;https://lmms.io&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0000ff;&quot;&gt;https://lmms.io&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;https://lmms.io&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0000ff;&quot;&gt;https://lmms.io&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> </context> <context> <name>AmplifierControlDialog</name> <message> <source>VOL</source> <translation>VOL</translation> </message> <message> <source>Volume:</source> <translation>Volume:</translation> </message> <message> <source>PAN</source> <translation>BIL</translation> </message> <message> <source>Panning:</source> <translation>Bilanciamento:</translation> </message> <message> <source>LEFT</source> <translation>SX</translation> </message> <message> <source>Left gain:</source> <translation>Guadagno a sinistra:</translation> </message> <message> <source>RIGHT</source> <translation>DX</translation> </message> <message> <source>Right gain:</source> <translation>Guadagno a destra:</translation> </message> </context> <context> <name>AmplifierControls</name> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Panning</source> <translation>Bilanciamento</translation> </message> <message> <source>Left gain</source> <translation>Guadagno a sinistra</translation> </message> <message> <source>Right gain</source> <translation>Guadagno a destra</translation> </message> </context> <context> <name>AudioAlsaSetupWidget</name> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> <message> <source>CHANNELS</source> <translation>CANALI</translation> </message> </context> <context> <name>AudioFileProcessorView</name> <message> <source>Open other sample</source> <translation>Apri un altro campione</translation> </message> <message> <source>Click here, if you want to open another audio-file. A dialog will appear where you can select your file. Settings like looping-mode, start and end-points, amplify-value, and so on are not reset. So, it may not sound like the original sample.</source> <translation>Clicca qui per aprire un altro file audio. Apparirà una finestra di dialogo dove sarà possibile scegliere il file. Impostazioni come la modalità ripetizione, amplificazione e così via non vengono reimpostate, pertanto potrebbe non suonare come il file originale.</translation> </message> <message> <source>Reverse sample</source> <translation>Inverti il campione</translation> </message> <message> <source>If you enable this button, the whole sample is reversed. This is useful for cool effects, e.g. a reversed crash.</source> <translation>Attivando questo pulsante, l&apos;intero campione viene invertito. Ciò è utile per effetti particolari, ad es. un crash invertito.</translation> </message> <message> <source>Amplify:</source> <translation>Amplificazione:</translation> </message> <message> <source>With this knob you can set the amplify ratio. When you set a value of 100% your sample isn&apos;t changed. Otherwise it will be amplified up or down (your actual sample-file isn&apos;t touched!)</source> <translation>Questa manopola regola l&apos;amplificaione. Con un valore pari a 100% il campione non viene modificato, altrimenti verrà amplificato della percentuale specificata (il file originale non viene modificato!)</translation> </message> <message> <source>Startpoint:</source> <translation>Punto di inizio:</translation> </message> <message> <source>Endpoint:</source> <translation>Punto di fine:</translation> </message> <message> <source>Continue sample playback across notes</source> <translation>Continua la ripetizione del campione tra le note</translation> </message> <message> <source>Enabling this option makes the sample continue playing across different notes - if you change pitch, or the note length stops before the end of the sample, then the next note played will continue where it left off. To reset the playback to the start of the sample, insert a note at the bottom of the keyboard (&lt; 20 Hz)</source> <translation>Attivando questa opzione, il campione audio viene riprodotto tra note differenti: se cambi l&apos;altezza, o la nota finisce prima del punto di fine del campione, allora la nota seguente riprodurrà il campione da dove si era fermata la precedente. Se invece si vuol far ripartire il campione dal punto d&apos;inizio, bisogna inserire una nota molto grave (&lt; 20 Hz)</translation> </message> <message> <source>Disable loop</source> <translation>Disabilità ripetizione</translation> </message> <message> <source>This button disables looping. The sample plays only once from start to end. </source> <translation>Questo pulsante disabilità la ripetizione. Il suono viene eseguito solo una volta dall&apos;inizio alla fine.</translation> </message> <message> <source>Enable loop</source> <translation>Abilita ripetizione</translation> </message> <message> <source>This button enables forwards-looping. The sample loops between the end point and the loop point.</source> <translation>Questo pulsante abilità la ripetizione diretta. Il suono viene ripetuto indefinitamente dal loop point al punto di fine.</translation> </message> <message> <source>This button enables ping-pong-looping. The sample loops backwards and forwards between the end point and the loop point.</source> <translation>Questo pulsante abilita la ripetizione ing-pong. Il suono viene eseguito avanti e indietro tra il punto di fine e il loop point.</translation> </message> <message> <source>With this knob you can set the point where AudioFileProcessor should begin playing your sample. </source> <translation>Con questa manopola puoi impostare il punto da cui AudioFileProcessor inizia a riprodurre il suono.</translation> </message> <message> <source>With this knob you can set the point where AudioFileProcessor should stop playing your sample. </source> <translation>Con questa manopola puoi impostare il punti in cui AudioFileProcessor finisce di riprodurre il suono.</translation> </message> <message> <source>Loopback point:</source> <translation>Punto LoopBack:</translation> </message> <message> <source>With this knob you can set the point where the loop starts. </source> <translation>Con questa modalità puoi impostare il punto dove la ripetizione comincia: la parte del suono tra il LoopBack e il punto di fine è quella che verà ripetuta.</translation> </message> </context> <context> <name>AudioFileProcessorWaveView</name> <message> <source>Sample length:</source> <translation>Lunghezza del campione:</translation> </message> </context> <context> <name>AudioJack</name> <message> <source>JACK client restarted</source> <translation>Il client JACK è ripartito</translation> </message> <message> <source>LMMS was kicked by JACK for some reason. Therefore the JACK backend of LMMS has been restarted. You will have to make manual connections again.</source> <translation>LMMS è stato kickato da JACK per qualche motivo. Quindi il collegamento JACK di LMMS è ripartito. Dovrai rifare le connessioni.</translation> </message> <message> <source>JACK server down</source> <translation>Il server JACK è down</translation> </message> <message> <source>The JACK server seems to have been shutdown and starting a new instance failed. Therefore LMMS is unable to proceed. You should save your project and restart JACK and LMMS.</source> <translation>Il server JACK sembra essere stato spento e non sono partite nuove istanze. Quindi LMMS non è in grado di procedere. Salva il progetto attivo e fai ripartire JACK ed LMMS.</translation> </message> <message> <source>CLIENT-NAME</source> <translation>NOME DEL CLIENT</translation> </message> <message> <source>CHANNELS</source> <translation>CANALI</translation> </message> </context> <context> <name>AudioOss::setupWidget</name> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> <message> <source>CHANNELS</source> <translation>CANALI</translation> </message> </context> <context> <name>AudioPortAudio::setupWidget</name> <message> <source>BACKEND</source> <translation>USCITA POSTERIORE</translation> </message> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> </context> <context> <name>AudioPulseAudio::setupWidget</name> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> <message> <source>CHANNELS</source> <translation>CANALI</translation> </message> </context> <context> <name>AudioSdl::setupWidget</name> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> </context> <context> <name>AudioSndio::setupWidget</name> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> <message> <source>CHANNELS</source> <translation>CANALI</translation> </message> </context> <context> <name>AudioSoundIo::setupWidget</name> <message> <source>BACKEND</source> <translation>INTERFACCIA</translation> </message> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> </context> <context> <name>AutomatableModel</name> <message> <source>&amp;Reset (%1%2)</source> <translation>&amp;Reimposta (%1%2)</translation> </message> <message> <source>&amp;Copy value (%1%2)</source> <translation>&amp;Copia valore (%1%2)</translation> </message> <message> <source>&amp;Paste value (%1%2)</source> <translation>&amp;Incolla valore (%1%2)</translation> </message> <message> <source>Edit song-global automation</source> <translation>Modifica l&apos;automazione globale della traccia</translation> </message> <message> <source>Connected to %1</source> <translation>Connesso a %1</translation> </message> <message> <source>Connected to controller</source> <translation>Connesso a un controller</translation> </message> <message> <source>Edit connection...</source> <translation>Modifica connessione...</translation> </message> <message> <source>Remove connection</source> <translation>Rimuovi connessione</translation> </message> <message> <source>Connect to controller...</source> <translation>Connetti a un controller...</translation> </message> <message> <source>Remove song-global automation</source> <translation>Rimuovi l&apos;automazione globale della traccia</translation> </message> <message> <source>Remove all linked controls</source> <translation>Rimuovi tutti i controlli collegati</translation> </message> </context> <context> <name>AutomationEditor</name> <message> <source>Please open an automation pattern with the context menu of a control!</source> <translation>È necessario aprire un pattern di automazione con il menu contestuale di un controllo!</translation> </message> <message> <source>Values copied</source> <translation>Valori copiati</translation> </message> <message> <source>All selected values were copied to the clipboard.</source> <translation>Tutti i valori sono stati copiati nella clipboard.</translation> </message> </context> <context> <name>AutomationEditorWindow</name> <message> <source>Play/pause current pattern (Space)</source> <translation>Riproduci/metti in pausa il beat/bassline selezionato (Spazio)</translation> </message> <message> <source>Click here if you want to play the current pattern. This is useful while editing it. The pattern is automatically looped when the end is reached.</source> <translation>Cliccando qui si riproduce il pattern selezionato. Questo è utile mentre lo si modifica. Il pattern viene automaticamente ripetuto quando finisce.</translation> </message> <message> <source>Stop playing of current pattern (Space)</source> <translation>Ferma il beat/bassline selezionato (Spazio)</translation> </message> <message> <source>Click here if you want to stop playing of the current pattern.</source> <translation>Cliccando qui si ferma la riproduzione del pattern attivo.</translation> </message> <message> <source>Draw mode (Shift+D)</source> <translation>Modalità disegno (Shift+D)</translation> </message> <message> <source>Erase mode (Shift+E)</source> <translation>Modalità cancella (Shift+E)</translation> </message> <message> <source>Flip vertically</source> <translation>Contrario</translation> </message> <message> <source>Flip horizontally</source> <translation>Retrogrado</translation> </message> <message> <source>Click here and the pattern will be inverted.The points are flipped in the y direction. </source> <translation>Clicca per mettere riposizionare i punti al contrario verticalmente.</translation> </message> <message> <source>Click here and the pattern will be reversed. The points are flipped in the x direction.</source> <translation>Clicca per riposizionare i punti come se venissero letti da destra a sinistra.</translation> </message> <message> <source>Click here and draw-mode will be activated. In this mode you can add and move single values. This is the default mode which is used most of the time. You can also press &apos;Shift+D&apos; on your keyboard to activate this mode.</source> <translation>Cliccando qui si attiva la modalità disegno. In questa modalità è possibile aggiungere e spostare singoli valori. Questa è la modalità predefinita, che viene usata la maggior parte del tempo. Questa modalità si attiva anche premendo la combinazione di tasti &apos;Shift+D&apos;.</translation> </message> <message> <source>Click here and erase-mode will be activated. In this mode you can erase single values. You can also press &apos;Shift+E&apos; on your keyboard to activate this mode.</source> <translation>Cliccando qui si attiva la modalità cancellazione. In questa modalità è possibile cancellare singoli valori. Questa modalità si attiva anche premendo la combinazione di tasti &apos;Shift+E&apos;.</translation> </message> <message> <source>Discrete progression</source> <translation>Progressione discreta</translation> </message> <message> <source>Linear progression</source> <translation>Progressione lineare</translation> </message> <message> <source>Cubic Hermite progression</source> <translation>Progressione a cubica di Hermite</translation> </message> <message> <source>Tension value for spline</source> <translation>Valore di tensione delle curve</translation> </message> <message> <source>A higher tension value may make a smoother curve but overshoot some values. A low tension value will cause the slope of the curve to level off at each control point.</source> <translation>Una tensione alta garantisce una curva più morbida, ma potrebbe tralasciare alcuni valori. Abbassando la tensione, invece, la curva si fletterà per sostare per più tempo sui valori indicati dai punti.</translation> </message> <message> <source>Click here to choose discrete progressions for this automation pattern. The value of the connected object will remain constant between control points and be set immediately to the new value when each control point is reached.</source> <translation>Clicca qui per scegliere il metodo di progressione discreta per questo pattern di automazione. Il valore della variabile connessa rimarrà costante tra i punti disegnati, cambierà immediatamente non appena raggiunto ogni punto.</translation> </message> <message> <source>Click here to choose linear progressions for this automation pattern. The value of the connected object will change at a steady rate over time between control points to reach the correct value at each control point without a sudden change.</source> <translation>Clicca qui per scegliere il metodo di progressione lineare per questo pattern di automazione. Il valore della variabile connessa cambierà in modo costante nel tempo tra i punti disegnati per arrivare al valore di ogni punto senza cambiamenti bruschi.</translation> </message> <message> <source>Click here to choose cubic hermite progressions for this automation pattern. The value of the connected object will change in a smooth curve and ease in to the peaks and valleys.</source> <translation>Clicca qui per scegliere il metodo di progressione a cubica di Hermite per questo pattern di automazione. Il valore della variabile connessa cambierà seguendo una curva morbida.</translation> </message> <message> <source>Cut selected values (%1+X)</source> <translation>Taglia i valori selezionati (%1+X)</translation> </message> <message> <source>Copy selected values (%1+C)</source> <translation>Copia i valori selezionati (%1+C)</translation> </message> <message> <source>Paste values from clipboard (%1+V)</source> <translation>Incolla i valori dagli appunti (%1+V)</translation> </message> <message> <source>Click here and selected values will be cut into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation>Cliccando qui i valori selezionati vengono spostati negli appunti. È possibile incollarli ovunque, in qualsiasi pattern, cliccando il pulsante Incolla.</translation> </message> <message> <source>Click here and selected values will be copied into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation>Cliccando qui i valori selezionati vengono copiati negli appunti. È possibile incollarli ovunque, in qualsiasi pattern, cliccando il pulsante Incolla.</translation> </message> <message> <source>Click here and the values from the clipboard will be pasted at the first visible measure.</source> <translation>Cliccando qui i valori negli appunti vengono incollati alla prima battuta visibile.</translation> </message> <message> <source>Tension: </source> <translation>Tensione: </translation> </message> <message> <source>Automation Editor - no pattern</source> <translation>Editor dell&apos;automazione - nessun pattern</translation> </message> <message> <source>Automation Editor - %1</source> <translation>Editor dell&apos;automazione - %1</translation> </message> <message> <source>Edit actions</source> <translation>Modalità di modifica</translation> </message> <message> <source>Interpolation controls</source> <translation>Modalità Interpolazione</translation> </message> <message> <source>Timeline controls</source> <translation>Controlla griglia</translation> </message> <message> <source>Zoom controls</source> <translation>Opzioni di zoom</translation> </message> <message> <source>Quantization controls</source> <translation>Controlli di quantizzazione</translation> </message> <message> <source>Model is already connected to this pattern.</source> <translation>Il controllo è già connesso a questo pattern.</translation> </message> <message> <source>Quantization</source> <translation>Quantizzazione</translation> </message> <message> <source>Quantization. Sets the smallest step size for the Automation Point. By default this also sets the length, clearing out other points in the range. Press &lt;Ctrl&gt; to override this behaviour.</source> <translation>Quantizzazione. Imposta la massima precisione dei punti di Automazione. Controlla anche la lunghezza, cancellando quindi i punti che sono entro tale lunghezza. Puoi comunque ignorare questa funzione premendo &lt;Ctrl&gt;.</translation> </message> </context> <context> <name>AutomationPattern</name> <message> <source>Drag a control while pressing &lt;%1&gt;</source> <translation>Trascina un controllo tenendo premuto &lt;%1&gt;</translation> </message> </context> <context> <name>AutomationPatternView</name> <message> <source>Open in Automation editor</source> <translation>Apri nell&apos;editor dell&apos;Automazione</translation> </message> <message> <source>Clear</source> <translation>Pulisci</translation> </message> <message> <source>Reset name</source> <translation>Reimposta nome</translation> </message> <message> <source>Change name</source> <translation>Rinomina</translation> </message> <message> <source>%1 Connections</source> <translation>%1 connessioni</translation> </message> <message> <source>Disconnect &quot;%1&quot;</source> <translation>Disconnetti &quot;%1&quot;</translation> </message> <message> <source>Set/clear record</source> <translation>Accendi/spegni registrazione</translation> </message> <message> <source>Flip Vertically (Visible)</source> <translation>Contrario</translation> </message> <message> <source>Flip Horizontally (Visible)</source> <translation>Retrogrado</translation> </message> <message> <source>Model is already connected to this pattern.</source> <translation>Il controllo è già connesso a questo pattern.</translation> </message> </context> <context> <name>AutomationTrack</name> <message> <source>Automation track</source> <translation>Traccia di automazione</translation> </message> </context> <context> <name>BBEditor</name> <message> <source>Beat+Bassline Editor</source> <translation>Beat+Bassline Editor</translation> </message> <message> <source>Play/pause current beat/bassline (Space)</source> <translation>Riproduci/metti in pausa il beat/bassline selezionato (Spazio)</translation> </message> <message> <source>Stop playback of current beat/bassline (Space)</source> <translation>Ferma il beat/bassline attuale (Spazio)</translation> </message> <message> <source>Click here to play the current beat/bassline. The beat/bassline is automatically looped when its end is reached.</source> <translation>Cliccando qui si riprodurre il beat/bassline selezionato. Il beat/bassline ricomincia automaticamente quando finisce.</translation> </message> <message> <source>Click here to stop playing of current beat/bassline.</source> <translation>Cliccando qui si ferma la riproduzione del beat/bassline attivo.</translation> </message> <message> <source>Add beat/bassline</source> <translation>Aggiungi beat/bassline</translation> </message> <message> <source>Add automation-track</source> <translation>Aggiungi una traccia di automazione</translation> </message> <message> <source>Remove steps</source> <translation>Elimina note</translation> </message> <message> <source>Add steps</source> <translation>Aggiungi note</translation> </message> <message> <source>Beat selector</source> <translation>Selezione del Beat</translation> </message> <message> <source>Track and step actions</source> <translation>Controlli tracce e step</translation> </message> <message> <source>Clone Steps</source> <translation>Clona gli step</translation> </message> <message> <source>Add sample-track</source> <translation>Aggiungi traccia campione</translation> </message> </context> <context> <name>BBTCOView</name> <message> <source>Open in Beat+Bassline-Editor</source> <translation>Apri nell&apos;editor di Beat+Bassline</translation> </message> <message> <source>Reset name</source> <translation>Reimposta nome</translation> </message> <message> <source>Change name</source> <translation>Rinomina</translation> </message> <message> <source>Change color</source> <translation>Cambia colore</translation> </message> <message> <source>Reset color to default</source> <translation>Reimposta il colore a default</translation> </message> </context> <context> <name>BBTrack</name> <message> <source>Beat/Bassline %1</source> <translation>Beat/Bassline %1</translation> </message> <message> <source>Clone of %1</source> <translation>Clone di %1</translation> </message> </context> <context> <name>BassBoosterControlDialog</name> <message> <source>FREQ</source> <translation>FREQ</translation> </message> <message> <source>Frequency:</source> <translation>Frequenza:</translation> </message> <message> <source>GAIN</source> <translation>GUAD</translation> </message> <message> <source>Gain:</source> <translation>Guadagno:</translation> </message> <message> <source>RATIO</source> <translation>RAPP</translation> </message> <message> <source>Ratio:</source> <translation>Rapporto:</translation> </message> </context> <context> <name>BassBoosterControls</name> <message> <source>Frequency</source> <translation>Frequenza</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>Ratio</source> <translation>Rapporto dinamico</translation> </message> </context> <context> <name>BitcrushControlDialog</name> <message> <source>IN</source> <translation>IN</translation> </message> <message> <source>OUT</source> <translation>OUT</translation> </message> <message> <source>GAIN</source> <translation>GUAD</translation> </message> <message> <source>Input Gain:</source> <translation>Guadagno in Input:</translation> </message> <message> <source>Input Noise:</source> <translation>Rumore in Input:</translation> </message> <message> <source>Output Gain:</source> <translation>Guadagno in Output:</translation> </message> <message> <source>CLIP</source> <translation>CLIP</translation> </message> <message> <source>Output Clip:</source> <translation>Clip in Output:</translation> </message> <message> <source>Rate Enabled</source> <translation>Abilita Frequenza</translation> </message> <message> <source>Enable samplerate-crushing</source> <translation>Abilità la riduzione di frequnza di campionamento</translation> </message> <message> <source>Depth Enabled</source> <translation>Abilita Risoluzione</translation> </message> <message> <source>Enable bitdepth-crushing</source> <translation>Abilità la riduzione di bit di quantizzazione</translation> </message> <message> <source>Sample rate:</source> <translation>Frequenza di campionamento:</translation> </message> <message> <source>Stereo difference:</source> <translation>Differenza stereo:</translation> </message> <message> <source>Levels:</source> <translation>Livelli di quantizzazione:</translation> </message> <message> <source>NOISE</source> <translation>RUMORE</translation> </message> <message> <source>FREQ</source> <translation>FREQ</translation> </message> <message> <source>STEREO</source> <translation type="unfinished"/> </message> <message> <source>QUANT</source> <translation type="unfinished"/> </message> </context> <context> <name>CaptionMenu</name> <message> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <source>Help (not available)</source> <translation>Aiuto (non disponibile)</translation> </message> </context> <context> <name>CarlaInstrumentView</name> <message> <source>Show GUI</source> <translation>Mostra GUI</translation> </message> <message> <source>Click here to show or hide the graphical user interface (GUI) of Carla.</source> <translation>Clicca qui per mostrare o nascondere l&apos;interfaccia grafica (GUI) di Carla.</translation> </message> </context> <context> <name>Controller</name> <message> <source>Controller %1</source> <translation>Controller %1</translation> </message> </context> <context> <name>ControllerConnectionDialog</name> <message> <source>Connection Settings</source> <translation>Impostazioni connessione</translation> </message> <message> <source>MIDI CONTROLLER</source> <translation>CONTROLLER MIDI</translation> </message> <message> <source>Input channel</source> <translation>Canale di ingresso</translation> </message> <message> <source>CHANNEL</source> <translation>CANALE</translation> </message> <message> <source>Input controller</source> <translation>Controller di input</translation> </message> <message> <source>CONTROLLER</source> <translation>CONTROLLER</translation> </message> <message> <source>Auto Detect</source> <translation>Rilevamento automatico</translation> </message> <message> <source>MIDI-devices to receive MIDI-events from</source> <translation>Le periferiche MIDI ricevono eventi MIDI da</translation> </message> <message> <source>USER CONTROLLER</source> <translation>CONTROLLER PERSONALIZZATO</translation> </message> <message> <source>MAPPING FUNCTION</source> <translation>FUNZIONE DI MAPPATURA</translation> </message> <message> <source>OK</source> <translation>OK</translation> </message> <message> <source>Cancel</source> <translation>Annulla</translation> </message> <message> <source>LMMS</source> <translation>LMMS</translation> </message> <message> <source>Cycle Detected.</source> <translation>Ciclo rilevato.</translation> </message> </context> <context> <name>ControllerRackView</name> <message> <source>Controller Rack</source> <translation>Rack di Controller</translation> </message> <message> <source>Add</source> <translation>Aggiungi</translation> </message> <message> <source>Confirm Delete</source> <translation>Conferma eliminazione</translation> </message> <message> <source>Confirm delete? There are existing connection(s) associated with this controller. There is no way to undo.</source> <translation>Confermi l&apos;eliminazione? Ci sono connessioni associate a questo controller: non sarà possibile ripristinarle.</translation> </message> </context> <context> <name>ControllerView</name> <message> <source>Controls</source> <translation>Controlli</translation> </message> <message> <source>Controllers are able to automate the value of a knob, slider, and other controls.</source> <translation>I controller possono automatizzare il valore di una manopola, di uno slider e di altri controlli.</translation> </message> <message> <source>Rename controller</source> <translation>Rinomina controller</translation> </message> <message> <source>Enter the new name for this controller</source> <translation>Inserire il nuovo nome di questo controller</translation> </message> <message> <source>&amp;Remove this controller</source> <translation>&amp;Rimuovi questo controller</translation> </message> <message> <source>Re&amp;name this controller</source> <translation>Ri&amp;nomina questo controller</translation> </message> <message> <source>LFO</source> <translation>LFO</translation> </message> </context> <context> <name>CrossoverEQControlDialog</name> <message> <source>Band 1/2 Crossover:</source> <translation>Punto di separazione 1/2:</translation> </message> <message> <source>Band 2/3 Crossover:</source> <translation>Punto di separazione 2/3:</translation> </message> <message> <source>Band 3/4 Crossover:</source> <translation>Punto di separazione 3/4:</translation> </message> <message> <source>Band 1 Gain:</source> <translation>Guadagno banda 1:</translation> </message> <message> <source>Band 2 Gain:</source> <translation>Guadagno banda 2:</translation> </message> <message> <source>Band 3 Gain:</source> <translation>Guadagno banda 3:</translation> </message> <message> <source>Band 4 Gain:</source> <translation>Guadagno banda 4:</translation> </message> <message> <source>Band 1 Mute</source> <translation>Muto Banda 1</translation> </message> <message> <source>Mute Band 1</source> <translation>Muto Banda 1</translation> </message> <message> <source>Band 2 Mute</source> <translation>Muto Banda 2</translation> </message> <message> <source>Mute Band 2</source> <translation>Muto Banda 2</translation> </message> <message> <source>Band 3 Mute</source> <translation>Muto Banda 3</translation> </message> <message> <source>Mute Band 3</source> <translation>Muto Banda 3</translation> </message> <message> <source>Band 4 Mute</source> <translation>Muto Banda 4</translation> </message> <message> <source>Mute Band 4</source> <translation>Muto Banda 4</translation> </message> </context> <context> <name>DelayControls</name> <message> <source>Delay Samples</source> <translation>Campioni di Delay</translation> </message> <message> <source>Feedback</source> <translation>Feedback</translation> </message> <message> <source>Lfo Frequency</source> <translation>Frequenza Lfo</translation> </message> <message> <source>Lfo Amount</source> <translation>Ampiezza Lfo</translation> </message> <message> <source>Output gain</source> <translation>Guadagno in output</translation> </message> </context> <context> <name>DelayControlsDialog</name> <message> <source>Lfo Amt</source> <translation>Quantità Lfo</translation> </message> <message> <source>Delay Time</source> <translation>Tempo di ritardo</translation> </message> <message> <source>Feedback Amount</source> <translation>Quantità di Feedback</translation> </message> <message> <source>Lfo</source> <translation>Lfo</translation> </message> <message> <source>Out Gain</source> <translation>Guadagno in output</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>DELAY</source> <translation>RITARDO</translation> </message> <message> <source>FDBK</source> <translation>FDBK</translation> </message> <message> <source>RATE</source> <translation>FREQUENZA</translation> </message> <message> <source>AMNT</source> <translation>Q.TÀ</translation> </message> </context> <context> <name>DualFilterControlDialog</name> <message> <source>Filter 1 enabled</source> <translation>Abilita filtro 1</translation> </message> <message> <source>Filter 2 enabled</source> <translation>Abilita filtro 2</translation> </message> <message> <source>Click to enable/disable Filter 1</source> <translation>Clicca qui per abilitare/disabilitare il filtro 1</translation> </message> <message> <source>Click to enable/disable Filter 2</source> <translation>Clicca qui per abilitare/disabilitare il filtro 2</translation> </message> <message> <source>FREQ</source> <translation>FREQ</translation> </message> <message> <source>Cutoff frequency</source> <translation>Frequenza di taglio</translation> </message> <message> <source>RESO</source> <translation>RISO</translation> </message> <message> <source>Resonance</source> <translation>Risonanza</translation> </message> <message> <source>GAIN</source> <translation>GUAD</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>MIX</source> <translation>MIX</translation> </message> <message> <source>Mix</source> <translation>Mix</translation> </message> </context> <context> <name>DualFilterControls</name> <message> <source>Filter 1 enabled</source> <translation>Attiva Filtro 1</translation> </message> <message> <source>Filter 1 type</source> <translation>Tipo del Filtro 1</translation> </message> <message> <source>Cutoff 1 frequency</source> <translation>Frequenza di taglio Filtro 1</translation> </message> <message> <source>Q/Resonance 1</source> <translation>Risonanza Filtro 1</translation> </message> <message> <source>Gain 1</source> <translation>Guadagno Filtro 1</translation> </message> <message> <source>Mix</source> <translation>Mix</translation> </message> <message> <source>Filter 2 enabled</source> <translation>Abilita Filtro 2</translation> </message> <message> <source>Filter 2 type</source> <translation>Tipo del Filtro 2</translation> </message> <message> <source>Cutoff 2 frequency</source> <translation>Frequenza di taglio Filtro 2</translation> </message> <message> <source>Q/Resonance 2</source> <translation>Risonanza Filtro 2</translation> </message> <message> <source>Gain 2</source> <translation>Guadagno Filtro 2</translation> </message> <message> <source>LowPass</source> <translation>PassaBasso</translation> </message> <message> <source>HiPass</source> <translation>PassaAlto</translation> </message> <message> <source>BandPass csg</source> <translation>PassaBanda csg</translation> </message> <message> <source>BandPass czpg</source> <translation>PassaBanda czpg</translation> </message> <message> <source>Notch</source> <translation>Notch</translation> </message> <message> <source>Allpass</source> <translation>Passatutto</translation> </message> <message> <source>Moog</source> <translation>Moog</translation> </message> <message> <source>2x LowPass</source> <translation>PassaBasso 2x</translation> </message> <message> <source>RC LowPass 12dB</source> <translation>RC PassaBasso 12dB</translation> </message> <message> <source>RC BandPass 12dB</source> <translation>RC PassaBanda 12dB</translation> </message> <message> <source>RC HighPass 12dB</source> <translation>RC PassaAlto 12dB</translation> </message> <message> <source>RC LowPass 24dB</source> <translation>RC PassaBasso 24dB</translation> </message> <message> <source>RC BandPass 24dB</source> <translation>RC PassaBanda 24dB</translation> </message> <message> <source>RC HighPass 24dB</source> <translation>RC PassaAlto 24dB</translation> </message> <message> <source>Vocal Formant Filter</source> <translation>Filtro a Formante di Voce</translation> </message> <message> <source>2x Moog</source> <translation>2x Moog</translation> </message> <message> <source>SV LowPass</source> <translation>PassaBasso SV</translation> </message> <message> <source>SV BandPass</source> <translation>PassaBanda SV</translation> </message> <message> <source>SV HighPass</source> <translation>PassaAlto SV</translation> </message> <message> <source>SV Notch</source> <translation>Notch SV</translation> </message> <message> <source>Fast Formant</source> <translation>Formante veloce</translation> </message> <message> <source>Tripole</source> <translation>Tre poli</translation> </message> </context> <context> <name>Editor</name> <message> <source>Play (Space)</source> <translation>Play (Spazio)</translation> </message> <message> <source>Stop (Space)</source> <translation>Fermo (Spazio)</translation> </message> <message> <source>Record</source> <translation>Registra</translation> </message> <message><|fim▁hole|> </message> <message> <source>Transport controls</source> <translation>Controlli trasporto</translation> </message> </context> <context> <name>Effect</name> <message> <source>Effect enabled</source> <translation>Effetto attivo</translation> </message> <message> <source>Wet/Dry mix</source> <translation>Bilanciamento Wet/Dry</translation> </message> <message> <source>Gate</source> <translation>Gate</translation> </message> <message> <source>Decay</source> <translation>Decadimento</translation> </message> </context> <context> <name>EffectChain</name> <message> <source>Effects enabled</source> <translation>Effetti abilitati</translation> </message> </context> <context> <name>EffectRackView</name> <message> <source>EFFECTS CHAIN</source> <translation>CATENA DI EFFETTI</translation> </message> <message> <source>Add effect</source> <translation>Aggiungi effetto</translation> </message> </context> <context> <name>EffectSelectDialog</name> <message> <source>Add effect</source> <translation>Aggiungi effetto</translation> </message> <message> <source>Name</source> <translation>Nome</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Description</source> <translation>Descrizione</translation> </message> <message> <source>Author</source> <translation>Autore</translation> </message> </context> <context> <name>EffectView</name> <message> <source>Toggles the effect on or off.</source> <translation>Abilita o disabilita l&apos;effetto.</translation> </message> <message> <source>On/Off</source> <translation>On/Off</translation> </message> <message> <source>W/D</source> <translation>W/D</translation> </message> <message> <source>Wet Level:</source> <translation>Livello del segnale modificato:</translation> </message> <message> <source>The Wet/Dry knob sets the ratio between the input signal and the effect signal that forms the output.</source> <translation>La manopola Wet/Dry imposta il rapporto tra il segnale in ingresso e la quantità di effetto udibile in uscita.</translation> </message> <message> <source>DECAY</source> <translation>DECAY</translation> </message> <message> <source>Time:</source> <translation>Tempo:</translation> </message> <message> <source>The Decay knob controls how many buffers of silence must pass before the plugin stops processing. Smaller values will reduce the CPU overhead but run the risk of clipping the tail on delay and reverb effects.</source> <translation>La manopola Decadimento controlla quanto silenzio deve esserci prima che il plugin si fermi. Valori più piccoli riducono il carico del processore ma rischiano di troncare la parte finale degli effetti di delay.</translation> </message> <message> <source>GATE</source> <translation>GATE</translation> </message> <message> <source>Gate:</source> <translation>Gate:</translation> </message> <message> <source>The Gate knob controls the signal level that is considered to be &apos;silence&apos; while deciding when to stop processing signals.</source> <translation>La manopola Gate controlla il livello del segnale che è considerato &apos;silenzio&apos; per decidere quando smettere di processare i segnali.</translation> </message> <message> <source>Controls</source> <translation>Controlli</translation> </message> <message> <source>Effect plugins function as a chained series of effects where the signal will be processed from top to bottom. The On/Off switch allows you to bypass a given plugin at any point in time. The Wet/Dry knob controls the balance between the input signal and the effected signal that is the resulting output from the effect. The input for the stage is the output from the previous stage. So, the 'dry' signal for effects lower in the chain contains all of the previous effects. The Decay knob controls how long the signal will continue to be processed after the notes have been released. The effect will stop processing signals when the volume has dropped below a given threshold for a given length of time. This knob sets the 'given length of time'. Longer times will require more CPU, so this number should be set low for most effects. It needs to be bumped up for effects that produce lengthy periods of silence, e.g. delays. The Gate knob controls the 'given threshold' for the effect's auto shutdown. The clock for the 'given length of time' will begin as soon as the processed signal level drops below the level specified with this knob. The Controls button opens a dialog for editing the effect's parameters. Right clicking will bring up a context menu where you can change the order in which the effects are processed or delete an effect altogether.</source> <translation>I plugin di effetti funzionano come una catena di effetti sottoposti al segnale dall&apos;alto verso il basso. L&apos;interruttore On/Off permette di saltare un certo plugin in qualsiasi momento. La manopola Wet/Dry controlla il bilanciamento tra il segnale in ingresso e quello processato che viene emesso dall&apos;effetto. L&apos;ingresso di ogni stadio è costituito dall&apos;uscita dello stadio precedente, così il segnale &apos;dry&apos; degli effetti sottostanti contiene tutti i precedenti effetti. La manopola Decadimento controlla il tempo per cui il segnale viene processato dopo che le note sono state rilasciate. L&apos;effetto smette di processare il segnale quando questo scende sotto una certa soglia per un certo periodo ti tempo. La manopola imposta questo periodo di tempo. Tempi maggiori richiedono una maggiore potenza del processore, quindi il tempo dovrebbe rimanere basso per la maggior parte degli effetti. È necessario aumentarlo per effetti che producono lunghi periodi di silenzio, ad es. i delay. La manopola Gate regola la soglia sotto la quale l&apos;effetto smette di processare il segnale. Il conteggio del tempo di silenzio necessario inizia non appena il sengale processato scende sotto la soglia specificata. Il pulsante Controlli apre una finestra per modificare i parametri dell&apos;effetto. Con il click destro si apre un menu conestuale che permette di cambiare l&apos;ordine degli effetti o di eliminarli.</translation> </message> <message> <source>Move &amp;up</source> <translation>Sposta verso l&apos;&amp;alto</translation> </message> <message> <source>Move &amp;down</source> <translation>Sposta verso il &amp;basso</translation> </message> <message> <source>&amp;Remove this plugin</source> <translation>&amp;Elimina questo plugin</translation> </message> </context> <context> <name>EnvelopeAndLfoParameters</name> <message> <source>Predelay</source> <translation>Ritardo iniziale</translation> </message> <message> <source>Attack</source> <translation>Attacco</translation> </message> <message> <source>Hold</source> <translation>Mantenimento</translation> </message> <message> <source>Decay</source> <translation>Decadimento</translation> </message> <message> <source>Sustain</source> <translation>Sostegno</translation> </message> <message> <source>Release</source> <translation>Rilascio</translation> </message> <message> <source>Modulation</source> <translation>Modulazione</translation> </message> <message> <source>LFO Predelay</source> <translation>Ritardo iniziale dell&apos;LFO</translation> </message> <message> <source>LFO Attack</source> <translation>Attacco dell&apos;LFO</translation> </message> <message> <source>LFO speed</source> <translation>Velocità dell&apos;LFO</translation> </message> <message> <source>LFO Modulation</source> <translation>Modulazione dell&apos;LFO</translation> </message> <message> <source>LFO Wave Shape</source> <translation>Forma d&apos;onda dell&apos;LFO</translation> </message> <message> <source>Freq x 100</source> <translation>Freq x 100</translation> </message> <message> <source>Modulate Env-Amount</source> <translation>Modula la quantità di Env</translation> </message> </context> <context> <name>EnvelopeAndLfoView</name> <message> <source>DEL</source> <translation>RIT</translation> </message> <message> <source>Predelay:</source> <translation>Ritardo iniziale:</translation> </message> <message> <source>Use this knob for setting predelay of the current envelope. The bigger this value the longer the time before start of actual envelope.</source> <translation>Questa manopola imposta il ritardo iniziale dell&apos;envelope selezionato. Più grande è questo valore più tempo passerà prima che l&apos;envelope effettivo inizi.</translation> </message> <message> <source>ATT</source> <translation>ATT</translation> </message> <message> <source>Attack:</source> <translation>Attacco:</translation> </message> <message> <source>Use this knob for setting attack-time of the current envelope. The bigger this value the longer the envelope needs to increase to attack-level. Choose a small value for instruments like pianos and a big value for strings.</source> <translation>Questa manopola imposta il tempo di attacco dell&apos;envelope selezionato. Più grande è questo valore più tempo passa prima di raggiungere il livello di attacco. Scegliere un valore contenuto per strumenti come pianoforti e un valore grande per gli archi.</translation> </message> <message> <source>HOLD</source> <translation>MANT</translation> </message> <message> <source>Hold:</source> <translation>Mantenimento:</translation> </message> <message> <source>Use this knob for setting hold-time of the current envelope. The bigger this value the longer the envelope holds attack-level before it begins to decrease to sustain-level.</source> <translation>Questa manopola imposta il tempo di mantenimento dell&apos;envelope selezionato. Più grande è questo valore più a lungo l&apos;envelope manterrà il livello di attacco prima di cominciare a scendere verso il livello di sostegno.</translation> </message> <message> <source>DEC</source> <translation>DEC</translation> </message> <message> <source>Decay:</source> <translation>Decadimento:</translation> </message> <message> <source>Use this knob for setting decay-time of the current envelope. The bigger this value the longer the envelope needs to decrease from attack-level to sustain-level. Choose a small value for instruments like pianos.</source> <translation>Questa manopola imposta il tempo di decdimento dell&apos;envelope selezionato. Più grande è questo valore più lentamente l&apos;envelope decadrà dal livello di attacco a quello di sustain. Scegliere un valore piccolo per strumenti come i pianoforti.</translation> </message> <message> <source>SUST</source> <translation>SOST</translation> </message> <message> <source>Sustain:</source> <translation>Sostegno:</translation> </message> <message> <source>Use this knob for setting sustain-level of the current envelope. The bigger this value the higher the level on which the envelope stays before going down to zero.</source> <translation>Questa manopola imposta il livello di sostegno dell&apos;envelope selezionato. Più grande è questo valore più sarà alto il livello che l&apos;envelope manterrà prima di scendere a zero.</translation> </message> <message> <source>REL</source> <translation>RIL</translation> </message> <message> <source>Release:</source> <translation>Rilascio:</translation> </message> <message> <source>Use this knob for setting release-time of the current envelope. The bigger this value the longer the envelope needs to decrease from sustain-level to zero. Choose a big value for soft instruments like strings.</source> <translation>Questa manopola imposta il tempo di rilascio dell&apos;anvelope selezionato. Più grande è questo valore più tempo l&apos;envelope impiegherà per scendere dal livello di sustain a zero. Scegliere un valore grande per strumenti dal suono morbido, come gli archi.</translation> </message> <message> <source>AMT</source> <translation>Q.TÀ</translation> </message> <message> <source>Modulation amount:</source> <translation>Quantità di modulazione:</translation> </message> <message> <source>Use this knob for setting modulation amount of the current envelope. The bigger this value the more the according size (e.g. volume or cutoff-frequency) will be influenced by this envelope.</source> <translation>Questa manopola imposta la quantità di modulazione dell&apos;envelope selezionato. Più grande è questo valore, più la grandezza corrispondente (ad es. il volume o la frequenza di taglio) sarà influenzata da questo envelope.</translation> </message> <message> <source>LFO predelay:</source> <translation>Ritardo iniziale dell&apos;LFO:</translation> </message> <message> <source>Use this knob for setting predelay-time of the current LFO. The bigger this value the the time until the LFO starts to oscillate.</source> <translation>Questa manopola imposta il ritardo iniziale dell&apos;LFO selezionato. Più grande è questo valore più tempo passerà prima che l&apos;LFO inizi a oscillare.</translation> </message> <message> <source>LFO- attack:</source> <translation>Attacco dell&apos;LFO:</translation> </message> <message> <source>Use this knob for setting attack-time of the current LFO. The bigger this value the longer the LFO needs to increase its amplitude to maximum.</source> <translation>Questa manopola imposta il tempo di attaco dell&apos;LFO selezionato. Più grande è questo valore più tempo l&apos;LFO impiegherà per raggiungere la massima ampiezza.</translation> </message> <message> <source>SPD</source> <translation>VEL</translation> </message> <message> <source>LFO speed:</source> <translation>Velocità dell&apos;LFO:</translation> </message> <message> <source>Use this knob for setting speed of the current LFO. The bigger this value the faster the LFO oscillates and the faster will be your effect.</source> <translation>Questa manopola imposta la velocità dell&apos;LFO selezionato. Più grande è questo valore più velocemente l&apos;LFO oscillerà e più veloce sarà l&apos;effetto.</translation> </message> <message> <source>Use this knob for setting modulation amount of the current LFO. The bigger this value the more the selected size (e.g. volume or cutoff-frequency) will be influenced by this LFO.</source> <translation>Questa manopola imposta la quantità di modulazione dell&apos;LFO selezionato. Più grande è questo valore più la grandezza selezionata (ad es. il volume o la frequenza di taglio) sarà influenzata da questo LFO.</translation> </message> <message> <source>Click here for a sine-wave.</source> <translation>Cliccando qui si ha un&apos;onda sinusoidale.</translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda triangolare.</translation> </message> <message> <source>Click here for a saw-wave for current.</source> <translation>Cliccando qui si ha un&apos;onda a dente di sega.</translation> </message> <message> <source>Click here for a square-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda quadra.</translation> </message> <message> <source>Click here for a user-defined wave. Afterwards, drag an according sample-file onto the LFO graph.</source> <translation>Cliccando qui è possibile definire una forma d&apos;onda personalizzata. Successivamente è possibile trascinare un file di campione nel grafico dell&apos;LFO.</translation> </message> <message> <source>FREQ x 100</source> <translation>FREQ x 100</translation> </message> <message> <source>Click here if the frequency of this LFO should be multiplied by 100.</source> <translation>Cliccando qui la frequenza di questo LFO viene moltiplicata per 100.</translation> </message> <message> <source>multiply LFO-frequency by 100</source> <translation>moltiplica la frequenza dell&apos;LFO per 100</translation> </message> <message> <source>MODULATE ENV-AMOUNT</source> <translation>MODULA LA QUANTITA&apos; DI ENVELOPE</translation> </message> <message> <source>Click here to make the envelope-amount controlled by this LFO.</source> <translation>Cliccando qui questo LFO controlla la quantità di envelope.</translation> </message> <message> <source>control envelope-amount by this LFO</source> <translation>controlla la quantità di envelope con questo LFO</translation> </message> <message> <source>ms/LFO:</source> <translation>ms/LFO:</translation> </message> <message> <source>Hint</source> <translation>Suggerimento</translation> </message> <message> <source>Drag a sample from somewhere and drop it in this window.</source> <translation>È possibile trascinare un campione in questa finestra.</translation> </message> <message> <source>Click here for random wave.</source> <translation>Clicca qui per un&apos;onda randomica.</translation> </message> </context> <context> <name>EqControls</name> <message> <source>Input gain</source> <translation>Guadagno in input</translation> </message> <message> <source>Output gain</source> <translation>Guadagno in output</translation> </message> <message> <source>Low shelf gain</source> <translation>Guadagno basse frequenze</translation> </message> <message> <source>Peak 1 gain</source> <translation>Guadagno picco 1</translation> </message> <message> <source>Peak 2 gain</source> <translation>Guadagno picco 2</translation> </message> <message> <source>Peak 3 gain</source> <translation>Guadagno Picco 3</translation> </message> <message> <source>Peak 4 gain</source> <translation>Guadagno picco 4</translation> </message> <message> <source>High Shelf gain</source> <translation>Guadagno alte frequenze</translation> </message> <message> <source>HP res</source> <translation>Ris Passa Alto</translation> </message> <message> <source>Low Shelf res</source> <translation>Ris basse frequenze</translation> </message> <message> <source>Peak 1 BW</source> <translation>LB Picco 1</translation> </message> <message> <source>Peak 2 BW</source> <translation>LB Picco 2</translation> </message> <message> <source>Peak 3 BW</source> <translation>LB Picco 3</translation> </message> <message> <source>Peak 4 BW</source> <translation>LB Picco 4</translation> </message> <message> <source>High Shelf res</source> <translation>Ris alte frequenze </translation> </message> <message> <source>LP res</source> <translation>Ris Passa Basso</translation> </message> <message> <source>HP freq</source> <translation>Freq Passa Alto</translation> </message> <message> <source>Low Shelf freq</source> <translation>Freq basse frequenze</translation> </message> <message> <source>Peak 1 freq</source> <translation>Frequenza picco 1</translation> </message> <message> <source>Peak 2 freq</source> <translation>Frequenza picco 2</translation> </message> <message> <source>Peak 3 freq</source> <translation>Frequenza picco 3</translation> </message> <message> <source>Peak 4 freq</source> <translation>Frequenza picco 4</translation> </message> <message> <source>High shelf freq</source> <translation>Freq alte frequenze</translation> </message> <message> <source>LP freq</source> <translation>Freq Passa Basso</translation> </message> <message> <source>HP active</source> <translation>Attiva Passa Alto</translation> </message> <message> <source>Low shelf active</source> <translation>Attiva basse frequenze</translation> </message> <message> <source>Peak 1 active</source> <translation>Attiva picco 1</translation> </message> <message> <source>Peak 2 active</source> <translation>Attiva picco 2</translation> </message> <message> <source>Peak 3 active</source> <translation>Attiva picco 3</translation> </message> <message> <source>Peak 4 active</source> <translation>Attiva picco 4</translation> </message> <message> <source>High shelf active</source> <translation>Attiva alte frequenze</translation> </message> <message> <source>LP active</source> <translation>Attiva Passa Basso</translation> </message> <message> <source>LP 12</source> <translation>Passa Basso 12 dB</translation> </message> <message> <source>LP 24</source> <translation>Passa Basso 24 dB</translation> </message> <message> <source>LP 48</source> <translation>Passa Basso 48 dB</translation> </message> <message> <source>HP 12</source> <translation>Passa Alto 12 dB</translation> </message> <message> <source>HP 24</source> <translation>Passa Alto 24 dB</translation> </message> <message> <source>HP 48</source> <translation>Passa Alto 48 dB</translation> </message> <message> <source>low pass type</source> <translation>Tipo di passa basso</translation> </message> <message> <source>high pass type</source> <translation>Tipo di passa alto</translation> </message> <message> <source>Analyse IN</source> <translation>Analizza Input</translation> </message> <message> <source>Analyse OUT</source> <translation>Analizza Output</translation> </message> </context> <context> <name>EqControlsDialog</name> <message> <source>HP</source> <translation>PA</translation> </message> <message> <source>Low Shelf</source> <translation>Bassi</translation> </message> <message> <source>Peak 1</source> <translation>Picco 1</translation> </message> <message> <source>Peak 2</source> <translation>Picco 2</translation> </message> <message> <source>Peak 3</source> <translation>Picco 3</translation> </message> <message> <source>Peak 4</source> <translation>Picco 4</translation> </message> <message> <source>High Shelf</source> <translation>Acuti</translation> </message> <message> <source>LP</source> <translation>PB</translation> </message> <message> <source>In Gain</source> <translation>Guadagno in input</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>Out Gain</source> <translation>Guadagno in output</translation> </message> <message> <source>Bandwidth: </source> <translation>Larghezza di banda:</translation> </message> <message> <source>Resonance : </source> <translation>Risonanza:</translation> </message> <message> <source>Frequency:</source> <translation>Frequenza:</translation> </message> <message> <source>lp grp</source> <translation>lp grp</translation> </message> <message> <source>hp grp</source> <translation>hp grp</translation> </message> <message> <source> Octave</source> <translation>Ottave</translation> </message> </context> <context> <name>EqHandle</name> <message> <source>Reso: </source> <translation>Risonanza:</translation> </message> <message> <source>BW: </source> <translation>Largh:</translation> </message> <message> <source>Freq: </source> <translation>Freq:</translation> </message> </context> <context> <name>ExportProjectDialog</name> <message> <source>Export project</source> <translation>Esporta il progetto</translation> </message> <message> <source>Output</source> <translation>Codifica</translation> </message> <message> <source>File format:</source> <translation>Formato file:</translation> </message> <message> <source>Samplerate:</source> <translation>Frequenza di campionamento:</translation> </message> <message> <source>44100 Hz</source> <translation>44100 Hz</translation> </message> <message> <source>48000 Hz</source> <translation>48000 Hz</translation> </message> <message> <source>88200 Hz</source> <translation>88200 Hz</translation> </message> <message> <source>96000 Hz</source> <translation>96000 Hz</translation> </message> <message> <source>192000 Hz</source> <translation>192000 Hz</translation> </message> <message> <source>Bitrate:</source> <translation>Bitrate:</translation> </message> <message> <source>64 KBit/s</source> <translation>64 KBit/s</translation> </message> <message> <source>128 KBit/s</source> <translation>128 KBit/s</translation> </message> <message> <source>160 KBit/s</source> <translation>160 KBit/s</translation> </message> <message> <source>192 KBit/s</source> <translation>192 KBit/s</translation> </message> <message> <source>256 KBit/s</source> <translation>256 KBit/s</translation> </message> <message> <source>320 KBit/s</source> <translation>320 KBit/s</translation> </message> <message> <source>Depth:</source> <translation>Risoluzione Bit:</translation> </message> <message> <source>16 Bit Integer</source> <translation>Interi 16 Bit</translation> </message> <message> <source>32 Bit Float</source> <translation>Virgola mobile 32 Bit</translation> </message> <message> <source>Quality settings</source> <translation>Impostazioni qualità</translation> </message> <message> <source>Interpolation:</source> <translation>Interpolazione:</translation> </message> <message> <source>Zero Order Hold</source> <translation>Zero Order Hold</translation> </message> <message> <source>Sinc Fastest</source> <translation>Più veloce</translation> </message> <message> <source>Sinc Medium (recommended)</source> <translation>Sinc Medium (suggerito)</translation> </message> <message> <source>Sinc Best (very slow!)</source> <translation>Sinc Best (molto lento!)</translation> </message> <message> <source>Oversampling (use with care!):</source> <translation>Oversampling (usare con cura!):</translation> </message> <message> <source>1x (None)</source> <translation>1x (Nessuna)</translation> </message> <message> <source>2x</source> <translation>2x</translation> </message> <message> <source>4x</source> <translation>4x</translation> </message> <message> <source>8x</source> <translation>8x</translation> </message> <message> <source>Start</source> <translation>Inizia</translation> </message> <message> <source>Cancel</source> <translation>Annulla</translation> </message> <message> <source>Export as loop (remove end silence)</source> <translation>Esporta come loop (rimuove il silenzio finale)</translation> </message> <message> <source>Export between loop markers</source> <translation>Esporta solo tra i punti di loop</translation> </message> <message> <source>Could not open file</source> <translation>Non è stato possibile aprire il file</translation> </message> <message> <source>Export project to %1</source> <translation>Esporta il progetto in %1</translation> </message> <message> <source>Error</source> <translation>Errore</translation> </message> <message> <source>Error while determining file-encoder device. Please try to choose a different output format.</source> <translation>Si è verificato un errore nel tentativo di determinare il dispositivo per la codifica del file. Si prega di selezionare un formato differente.</translation> </message> <message> <source>Rendering: %1%</source> <translation>Renderizzazione: %1%</translation> </message> <message> <source>Could not open file %1 for writing. Please make sure you have write permission to the file and the directory containing the file and try again!</source> <translation>Impossibile scrivere sul file %1. Si prega di controllare i permessi di scrittura sul file e la cartella che lo contiene, e poi riprovare!</translation> </message> <message> <source>24 Bit Integer</source> <translation>Interi 24 Bit</translation> </message> <message> <source>Use variable bitrate</source> <translation>Usa bitrate variabile</translation> </message> <message> <source>Stereo mode:</source> <translation type="unfinished"/> </message> <message> <source>Stereo</source> <translation type="unfinished"/> </message> <message> <source>Joint Stereo</source> <translation type="unfinished"/> </message> <message> <source>Mono</source> <translation type="unfinished"/> </message> <message> <source>Compression level:</source> <translation type="unfinished"/> </message> <message> <source>(fastest)</source> <translation type="unfinished"/> </message> <message> <source>(default)</source> <translation type="unfinished"/> </message> <message> <source>(smallest)</source> <translation type="unfinished"/> </message> </context> <context> <name>Expressive</name> <message> <source>Selected graph</source> <translation>Grafico selezionato</translation> </message> <message> <source>A1</source> <translation type="unfinished"/> </message> <message> <source>A2</source> <translation type="unfinished"/> </message> <message> <source>A3</source> <translation type="unfinished"/> </message> <message> <source>W1 smoothing</source> <translation type="unfinished"/> </message> <message> <source>W2 smoothing</source> <translation type="unfinished"/> </message> <message> <source>W3 smoothing</source> <translation type="unfinished"/> </message> <message> <source>PAN1</source> <translation type="unfinished"/> </message> <message> <source>PAN2</source> <translation type="unfinished"/> </message> <message> <source>REL TRANS</source> <translation type="unfinished"/> </message> </context> <context> <name>Fader</name> <message> <source>Please enter a new value between %1 and %2:</source> <translation>Inserire un valore compreso tra %1 e %2:</translation> </message> </context> <context> <name>FileBrowser</name> <message> <source>Browser</source> <translation>Browser</translation> </message> <message> <source>Search</source> <translation type="unfinished"/> </message> <message> <source>Refresh list</source> <translation type="unfinished"/> </message> </context> <context> <name>FileBrowserTreeWidget</name> <message> <source>Send to active instrument-track</source> <translation>Sostituisci questo strumento alla traccia attiva</translation> </message> <message> <source>Open in new instrument-track/B+B Editor</source> <translation>Usa in una nuova traccia nel B+B Editor</translation> </message> <message> <source>Loading sample</source> <translation>Caricamento campione</translation> </message> <message> <source>Please wait, loading sample for preview...</source> <translation>Attendere, stiamo caricando il file per l&apos;anteprima...</translation> </message> <message> <source>--- Factory files ---</source> <translation>--- File di fabbrica ---</translation> </message> <message> <source>Open in new instrument-track/Song Editor</source> <translation>Usa in una nuova traccia nel Song-Editor</translation> </message> <message> <source>Error</source> <translation>Errore</translation> </message> <message> <source>does not appear to be a valid</source> <translation>non sembra essere un file</translation> </message> <message> <source>file</source> <translation>valido</translation> </message> </context> <context> <name>FlangerControls</name> <message> <source>Delay Samples</source> <translation>Campioni di Delay</translation> </message> <message> <source>Lfo Frequency</source> <translation>Frequenza Lfo</translation> </message> <message> <source>Seconds</source> <translation>Secondi</translation> </message> <message> <source>Regen</source> <translation>Regen</translation> </message> <message> <source>Noise</source> <translation>Rumore</translation> </message> <message> <source>Invert</source> <translation>Inverti</translation> </message> </context> <context> <name>FlangerControlsDialog</name> <message> <source>Delay Time:</source> <translation>Tempo di Ritardo:</translation> </message> <message> <source>Feedback Amount:</source> <translation>Quantità di Feedback:</translation> </message> <message> <source>White Noise Amount:</source> <translation>Quantità di Rumore Bianco:</translation> </message> <message> <source>DELAY</source> <translation>RITARDO</translation> </message> <message> <source>RATE</source> <translation>FREQUENZA</translation> </message> <message> <source>AMNT</source> <translation>Q.TÀ</translation> </message> <message> <source>Amount:</source> <translation>Quantità:</translation> </message> <message> <source>FDBK</source> <translation>FDBK</translation> </message> <message> <source>NOISE</source> <translation>RUMORE</translation> </message> <message> <source>Invert</source> <translation>INVERTI</translation> </message> <message> <source>Period:</source> <translation type="unfinished"/> </message> </context> <context> <name>FxLine</name> <message> <source>Channel send amount</source> <translation>Quantità di segnale inviata dal canale</translation> </message> <message> <source>The FX channel receives input from one or more instrument tracks. It in turn can be routed to multiple other FX channels. LMMS automatically takes care of preventing infinite loops for you and doesn't allow making a connection that would result in an infinite loop. In order to route the channel to another channel, select the FX channel and click on the &quot;send&quot; button on the channel you want to send to. The knob under the send button controls the level of signal that is sent to the channel. You can remove and move FX channels in the context menu, which is accessed by right-clicking the FX channel. </source> <translation>Il canale FX riceve input da uno o più tracce strumentali. Il segnale così ricevuto può essere girato ad altri canali FX. LMMS eviterà che si creino cicli infiniti non permettendo la creazione di connessioni pericolose in tal senso. Per inviare il suono di un canale ad un altro, seleziona il canale FX e premi sul pulsante &quot;send&quot; su un altro canale a cui vuoi inviare segnale. La manopola sotto il pulsante send controlla il livello di segnale che viene ricevuto dal canale. Puoi rimuovere e muovere i canali con il menù contestuale, cliccando con il tasto destro su un canale FX.</translation> </message> <message> <source>Move &amp;left</source> <translation>Sposta a &amp;sinistra</translation> </message> <message> <source>Move &amp;right</source> <translation>Sposta a $destra</translation> </message> <message> <source>Rename &amp;channel</source> <translation>Rinomina &amp;canale</translation> </message> <message> <source>R&amp;emove channel</source> <translation>R&amp;imuovi canale</translation> </message> <message> <source>Remove &amp;unused channels</source> <translation>Rimuovi i canali in&amp;utilizzati</translation> </message> </context> <context> <name>FxMixer</name> <message> <source>Master</source> <translation>Master</translation> </message> <message> <source>FX %1</source> <translation>FX %1</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Mute</source> <translation>Muto</translation> </message> <message> <source>Solo</source> <translation>Solo</translation> </message> </context> <context> <name>FxMixerView</name> <message> <source>FX-Mixer</source> <translation>Mixer FX</translation> </message> <message> <source>FX Fader %1</source> <translation>Volume FX %1</translation> </message> <message> <source>Mute</source> <translation>Muto</translation> </message> <message> <source>Mute this FX channel</source> <translation>Silenzia questo canale FX</translation> </message> <message> <source>Solo</source> <translation>Solo</translation> </message> <message> <source>Solo FX channel</source> <translation>Ascolta questo canale da solo</translation> </message> </context> <context> <name>FxRoute</name> <message> <source>Amount to send from channel %1 to channel %2</source> <translation>Quantità da mandare dal canale %1 al canale %2</translation> </message> </context> <context> <name>GigInstrument</name> <message> <source>Bank</source> <translation>Banco</translation> </message> <message> <source>Patch</source> <translation>Patch</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> </context> <context> <name>GigInstrumentView</name> <message> <source>Open other GIG file</source> <translation>Apri un altro file GIG</translation> </message> <message> <source>Click here to open another GIG file</source> <translation>Clicca per aprire un nuovo file GIG</translation> </message> <message> <source>Choose the patch</source> <translation>Seleziona il patch</translation> </message> <message> <source>Click here to change which patch of the GIG file to use</source> <translation>Clicca per scegliere quale patch del file GIG usare</translation> </message> <message> <source>Change which instrument of the GIG file is being played</source> <translation>Cambia lo strumento del file GIG da suonare</translation> </message> <message> <source>Which GIG file is currently being used</source> <translation>Strumento del file GIG attualmente in uso</translation> </message> <message> <source>Which patch of the GIG file is currently being used</source> <translation>Patch del file GIG attualmente in uso</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>Factor to multiply samples by</source> <translation>Moltiplica i campioni per questo fattore</translation> </message> <message> <source>Open GIG file</source> <translation>Apri file GIG</translation> </message> <message> <source>GIG Files (*.gig)</source> <translation>File GIG (*.gig)</translation> </message> </context> <context> <name>GuiApplication</name> <message> <source>Working directory</source> <translation>Directory di lavoro</translation> </message> <message> <source>The LMMS working directory %1 does not exist. Create it now? You can change the directory later via Edit -&gt; Settings.</source> <translation>La directory di lavoro di LMMS %1 non esiste. La creo adesso? Questa directory può essere cambiata in un secondo momento dal menu Modifica -&gt; Impostazioni.</translation> </message> <message> <source>Preparing UI</source> <translation>Caricamento interfaccia</translation> </message> <message> <source>Preparing song editor</source> <translation>Caricamento Song Editor</translation> </message> <message> <source>Preparing mixer</source> <translation>Caricamento Mixer</translation> </message> <message> <source>Preparing controller rack</source> <translation>Caricamento rack di Controller</translation> </message> <message> <source>Preparing project notes</source> <translation>Caricamento note del progetto</translation> </message> <message> <source>Preparing beat/bassline editor</source> <translation>Caricamento beat e bassline editor</translation> </message> <message> <source>Preparing piano roll</source> <translation>Caricamento Piano Roll</translation> </message> <message> <source>Preparing automation editor</source> <translation>Caricamento Editor di Automazione</translation> </message> </context> <context> <name>InstrumentFunctionArpeggio</name> <message> <source>Arpeggio</source> <translation>Arpeggio</translation> </message> <message> <source>Arpeggio type</source> <translation>Tipo di arpeggio</translation> </message> <message> <source>Arpeggio range</source> <translation>Ampiezza dell&apos;arpeggio</translation> </message> <message> <source>Arpeggio time</source> <translation>Tempo dell&apos;arpeggio</translation> </message> <message> <source>Arpeggio gate</source> <translation>Gate dell&apos;arpeggio</translation> </message> <message> <source>Arpeggio direction</source> <translation>Direzione dell&apos;arpeggio</translation> </message> <message> <source>Arpeggio mode</source> <translation>Modo dell&apos;arpeggio</translation> </message> <message> <source>Up</source> <translation>Su</translation> </message> <message> <source>Down</source> <translation>Giù</translation> </message> <message> <source>Up and down</source> <translation>Su e giù</translation> </message> <message> <source>Random</source> <translation>Casuale</translation> </message> <message> <source>Free</source> <translation>Libero</translation> </message> <message> <source>Sort</source> <translation>Ordinato</translation> </message> <message> <source>Sync</source> <translation>Sincronizzato</translation> </message> <message> <source>Down and up</source> <translation>Giù e su</translation> </message> <message> <source>Skip rate</source> <translation>Frequanza di Salto</translation> </message> <message> <source>Miss rate</source> <translation>Frequanza di Sbaglio</translation> </message> <message> <source>Cycle steps</source> <translation>Note ruotate</translation> </message> </context> <context> <name>InstrumentFunctionArpeggioView</name> <message> <source>ARPEGGIO</source> <translation>ARPEGGIO</translation> </message> <message> <source>An arpeggio is a method playing (especially plucked) instruments, which makes the music much livelier. The strings of such instruments (e.g. harps) are plucked like chords. The only difference is that this is done in a sequential order, so the notes are not played at the same time. Typical arpeggios are major or minor triads, but there are a lot of other possible chords, you can select.</source> <translation>Un arpeggio è un modo di suonare alcuni strumenti (pizzicati in particolare), che rende la musica più viva. Le corde di tali strumenti (ad es. un&apos;arpa) vengono pizzicate come accordi. L&apos;unica differenza è che ciò viene fatto in ordine sequenziale, in modo che le note non vengano suonate allo stesso tempo. Arpeggi tipici sono quelli sulle triadi maggiore o minore, ma ci sono molte altre possibilità tra le quali si può scegliere.</translation> </message> <message> <source>RANGE</source> <translation>AMPIEZZA</translation> </message> <message> <source>Arpeggio range:</source> <translation>Ampiezza dell&apos;arpeggio:</translation> </message> <message> <source>octave(s)</source> <translation>ottava(e)</translation> </message> <message> <source>Use this knob for setting the arpeggio range in octaves. The selected arpeggio will be played within specified number of octaves.</source> <translation>Questa manopola imposta l&apos;ampiezza in ottave dell&apos;arpeggio. L&apos;arpeggio selezionato verrà suonato all&apos;interno del numero di ottave impostato.</translation> </message> <message> <source>TIME</source> <translation>TEMPO</translation> </message> <message> <source>Arpeggio time:</source> <translation>Tempo dell&apos;arpeggio:</translation> </message> <message> <source>ms</source> <translation>ms</translation> </message> <message> <source>Use this knob for setting the arpeggio time in milliseconds. The arpeggio time specifies how long each arpeggio-tone should be played.</source> <translation>Questa manopola imposta l&apos;ampiezza dell&apos;arpeggio in millisecondi. Il tempo dell&apos;arpeggio specifica per quanto tempo ogni nota dell&apos;arpeggio deve essere eseguita.</translation> </message> <message> <source>GATE</source> <translation>GATE</translation> </message> <message> <source>Arpeggio gate:</source> <translation>Gate dell&apos;arpeggio:</translation> </message> <message> <source>%</source> <translation>%</translation> </message> <message> <source>Use this knob for setting the arpeggio gate. The arpeggio gate specifies the percent of a whole arpeggio-tone that should be played. With this you can make cool staccato arpeggios.</source> <translation>Questa manopola imposta il gate dell&apos;arpeggio. Il gate dell&apos;arpeggio specifica la percentuale di ogni nota che deve essere eseguita. In questo modo si possono creare arpeggi particolari, con le note staccate.</translation> </message> <message> <source>Chord:</source> <translation>Tipo di arpeggio:</translation> </message> <message> <source>Direction:</source> <translation>Direzione:</translation> </message> <message> <source>Mode:</source> <translation>Modo:</translation> </message> <message> <source>SKIP</source> <translation>SALTA</translation> </message> <message> <source>Skip rate:</source> <translation>Frequanza di Salto:</translation> </message> <message> <source>The skip function will make the arpeggiator pause one step randomly. From its start in full counter clockwise position and no effect it will gradually progress to full amnesia at maximum setting.</source> <translation>Con la funzione di salto, l&apos;arpeggiatore metterà in pausa uno step in modo casuale. Alla posizione minima non verrà applicata alcuna variazione. Aumentando il valore, invece, si arriva gradualmente ad una completa casualità dell&apos;effetto.</translation> </message> <message> <source>MISS</source> <translation>SBAGLIA</translation> </message> <message> <source>Miss rate:</source> <translation>Frequanza di Sbaglio:</translation> </message> <message> <source>The miss function will make the arpeggiator miss the intended note.</source> <translation>La funzione di sbaglio farà &quot;sbagliare&quot; l&apos;arpeggiatore, che suonerà un&apos;altra nota rispetto a quella normalmente prevista.</translation> </message> <message> <source>CYCLE</source> <translation>RUOTA</translation> </message> <message> <source>Cycle notes:</source> <translation>Note ruotate:</translation> </message> <message> <source>note(s)</source> <translation>nota(e)</translation> </message> <message> <source>Jumps over n steps in the arpeggio and cycles around if we&apos;re over the note range. If the total note range is evenly divisible by the number of steps jumped over you will get stuck in a shorter arpeggio or even on one note.</source> <translation>Salta n note dell&apos;arpeggio e torna indietro quando supera l&apos;ampiezza. Se il numero di note totali è divisibile per il numero di note saltate, l&apos;arpeggio risulterà più piccolo, eventualmente di una sola nota.</translation> </message> </context> <context> <name>InstrumentFunctionNoteStacking</name> <message> <source>octave</source> <translation>ottava</translation> </message> <message> <source>Major</source> <translation>Maggiore</translation> </message> <message> <source>Majb5</source> <translation>Majb5</translation> </message> <message> <source>minor</source> <translation>minore</translation> </message> <message> <source>minb5</source> <translation>minb5</translation> </message> <message> <source>sus2</source> <translation>sus2</translation> </message> <message> <source>sus4</source> <translation>sus4</translation> </message> <message> <source>aug</source> <translation>aug</translation> </message> <message> <source>augsus4</source> <translation>augsus4</translation> </message> <message> <source>tri</source> <translation>triade</translation> </message> <message> <source>6</source> <translation>6</translation> </message> <message> <source>6sus4</source> <translation>6sus4</translation> </message> <message> <source>6add9</source> <translation>6add9</translation> </message> <message> <source>m6</source> <translation>m6</translation> </message> <message> <source>m6add9</source> <translation>m6add9</translation> </message> <message> <source>7</source> <translation>7</translation> </message> <message> <source>7sus4</source> <translation>7sus4</translation> </message> <message> <source>7#5</source> <translation>7#5</translation> </message> <message> <source>7b5</source> <translation>7b5</translation> </message> <message> <source>7#9</source> <translation>7#9</translation> </message> <message> <source>7b9</source> <translation>7b9</translation> </message> <message> <source>7#5#9</source> <translation>7#5#9</translation> </message> <message> <source>7#5b9</source> <translation>7#5b9</translation> </message> <message> <source>7b5b9</source> <translation>7b5b9</translation> </message> <message> <source>7add11</source> <translation>7add11</translation> </message> <message> <source>7add13</source> <translation>7add13</translation> </message> <message> <source>7#11</source> <translation>7#11</translation> </message> <message> <source>Maj7</source> <translation>Maj7</translation> </message> <message> <source>Maj7b5</source> <translation>Maj7b5</translation> </message> <message> <source>Maj7#5</source> <translation>Maj7#5</translation> </message> <message> <source>Maj7#11</source> <translation>Maj7#11</translation> </message> <message> <source>Maj7add13</source> <translation>Maj7add13</translation> </message> <message> <source>m7</source> <translation>m7</translation> </message> <message> <source>m7b5</source> <translation>m7b5</translation> </message> <message> <source>m7b9</source> <translation>m7b9</translation> </message> <message> <source>m7add11</source> <translation>m7add11</translation> </message> <message> <source>m7add13</source> <translation>m7add13</translation> </message> <message> <source>m-Maj7</source> <translation>m-Maj7</translation> </message> <message> <source>m-Maj7add11</source> <translation>m-Maj7add11</translation> </message> <message> <source>m-Maj7add13</source> <translation>m-Maj7add13</translation> </message> <message> <source>9</source> <translation>9</translation> </message> <message> <source>9sus4</source> <translation>9sus4</translation> </message> <message> <source>add9</source> <translation>add9</translation> </message> <message> <source>9#5</source> <translation>9#5</translation> </message> <message> <source>9b5</source> <translation>9b5</translation> </message> <message> <source>9#11</source> <translation>9#11</translation> </message> <message> <source>9b13</source> <translation>9b13</translation> </message> <message> <source>Maj9</source> <translation>Maj9</translation> </message> <message> <source>Maj9sus4</source> <translation>Maj9sus4</translation> </message> <message> <source>Maj9#5</source> <translation>Maj9#5</translation> </message> <message> <source>Maj9#11</source> <translation>Maj9#11</translation> </message> <message> <source>m9</source> <translation>m9</translation> </message> <message> <source>madd9</source> <translation>madd9</translation> </message> <message> <source>m9b5</source> <translation>m9b5</translation> </message> <message> <source>m9-Maj7</source> <translation>m9-Maj7</translation> </message> <message> <source>11</source> <translation>11</translation> </message> <message> <source>11b9</source> <translation>11b9</translation> </message> <message> <source>Maj11</source> <translation>Maj11</translation> </message> <message> <source>m11</source> <translation>m11</translation> </message> <message> <source>m-Maj11</source> <translation>m-Maj11</translation> </message> <message> <source>13</source> <translation>13</translation> </message> <message> <source>13#9</source> <translation>13#9</translation> </message> <message> <source>13b9</source> <translation>13b9</translation> </message> <message> <source>13b5b9</source> <translation>13b5b9</translation> </message> <message> <source>Maj13</source> <translation>Maj13</translation> </message> <message> <source>m13</source> <translation>m13</translation> </message> <message> <source>m-Maj13</source> <translation>m-Maj13</translation> </message> <message> <source>Harmonic minor</source> <translation>Minore armonica</translation> </message> <message> <source>Melodic minor</source> <translation>Minore melodica</translation> </message> <message> <source>Whole tone</source> <translation>Toni interi</translation> </message> <message> <source>Diminished</source> <translation>Diminuita</translation> </message> <message> <source>Major pentatonic</source> <translation>Pentatonica maggiore</translation> </message> <message> <source>Minor pentatonic</source> <translation>Pentatonica minore</translation> </message> <message> <source>Jap in sen</source> <translation>Jap in sen</translation> </message> <message> <source>Major bebop</source> <translation>Bebop maggiore</translation> </message> <message> <source>Dominant bebop</source> <translation>Bebop dominante</translation> </message> <message> <source>Blues</source> <translation>Blues</translation> </message> <message> <source>Arabic</source> <translation>Araba</translation> </message> <message> <source>Enigmatic</source> <translation>Enigmatica</translation> </message> <message> <source>Neopolitan</source> <translation>Napoletana</translation> </message> <message> <source>Neopolitan minor</source> <translation>Napoletana minore</translation> </message> <message> <source>Hungarian minor</source> <translation>Ungherese minore</translation> </message> <message> <source>Dorian</source> <translation>Dorica</translation> </message> <message> <source>Phrygolydian</source> <translation>Frigia</translation> </message> <message> <source>Lydian</source> <translation>Lidia</translation> </message> <message> <source>Mixolydian</source> <translation>Misolidia</translation> </message> <message> <source>Aeolian</source> <translation>Eolia</translation> </message> <message> <source>Locrian</source> <translation>Locria</translation> </message> <message> <source>Chords</source> <translation>Accordi</translation> </message> <message> <source>Chord type</source> <translation>Tipo di accordo</translation> </message> <message> <source>Chord range</source> <translation>Ampiezza dell&apos;accordo</translation> </message> <message> <source>Minor</source> <translation>Minore</translation> </message> <message> <source>Chromatic</source> <translation>Cromatica</translation> </message> <message> <source>Half-Whole Diminished</source> <translation>Diminuita semitono-tono</translation> </message> <message> <source>5</source> <translation>Quinta</translation> </message> <message> <source>Phrygian dominant</source> <translation>Frigia dominante</translation> </message> <message> <source>Persian</source> <translation>Persiana</translation> </message> </context> <context> <name>InstrumentFunctionNoteStackingView</name> <message> <source>RANGE</source> <translation>AMPIEZZA</translation> </message> <message> <source>Chord range:</source> <translation>Ampiezza degli accordi:</translation> </message> <message> <source>octave(s)</source> <translation>ottava(e)</translation> </message> <message> <source>Use this knob for setting the chord range in octaves. The selected chord will be played within specified number of octaves.</source> <translation>Questa manopola imposta l&apos;ampiezza degli accordi in ottave. L&apos;accordo selezionato verrà eseguito all&apos;interno del numero di ottave impostato.</translation> </message> <message> <source>STACKING</source> <translation>ACCORDI</translation> </message> <message> <source>Chord:</source> <translation>Tipo di accordo:</translation> </message> </context> <context> <name>InstrumentMidiIOView</name> <message> <source>ENABLE MIDI INPUT</source> <translation>ABILITA INGRESSO MIDI</translation> </message> <message> <source>CHANNEL</source> <translation>CANALE</translation> </message> <message> <source>VELOCITY</source> <translation>VALOCITY</translation> </message> <message> <source>ENABLE MIDI OUTPUT</source> <translation>ABILITA USCITA MIDI</translation> </message> <message> <source>PROGRAM</source> <translation>PROGRAMMA</translation> </message> <message> <source>MIDI devices to receive MIDI events from</source> <translation>Periferica MIDI da cui ricevere segnali MIDi</translation> </message> <message> <source>MIDI devices to send MIDI events to</source> <translation>Periferica MIDI a cui mandare segnali MIDI</translation> </message> <message> <source>NOTE</source> <translation>NOTA</translation> </message> <message> <source>CUSTOM BASE VELOCITY</source> <translation>VELOCITY BASE PERSONALIZZATA</translation> </message> <message> <source>Specify the velocity normalization base for MIDI-based instruments at 100% note velocity</source> <translation>Specifica la normalizzazione della velocity per strumenti MIDI al volume della nota 100%</translation> </message> <message> <source>BASE VELOCITY</source> <translation>VELOCITY BASE</translation> </message> </context> <context> <name>InstrumentMiscView</name> <message> <source>MASTER PITCH</source> <translation>TRASPORTO</translation> </message> <message> <source>Enables the use of Master Pitch</source> <translation>Abilita l&apos;uso del Trasporto</translation> </message> </context> <context> <name>InstrumentSoundShaping</name> <message> <source>VOLUME</source> <translation>VOLUME</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>CUTOFF</source> <translation>CUTOFF</translation> </message> <message> <source>Cutoff frequency</source> <translation>Frequenza di taglio</translation> </message> <message> <source>RESO</source> <translation>RISO</translation> </message> <message> <source>Resonance</source> <translation>Risonanza</translation> </message> <message> <source>Envelopes/LFOs</source> <translation>Envelope/LFO</translation> </message> <message> <source>Filter type</source> <translation>Tipo di filtro</translation> </message> <message> <source>Q/Resonance</source> <translation>Q/Risonanza</translation> </message> <message> <source>LowPass</source> <translation>PassaBasso</translation> </message> <message> <source>HiPass</source> <translation>PassaAlto</translation> </message> <message> <source>BandPass csg</source> <translation>PassaBanda csg</translation> </message> <message> <source>BandPass czpg</source> <translation>PassaBanda czpg</translation> </message> <message> <source>Notch</source> <translation>Notch</translation> </message> <message> <source>Allpass</source> <translation>Passatutto</translation> </message> <message> <source>Moog</source> <translation>Moog</translation> </message> <message> <source>2x LowPass</source> <translation>PassaBasso 2x</translation> </message> <message> <source>RC LowPass 12dB</source> <translation>RC PassaBasso 12dB</translation> </message> <message> <source>RC BandPass 12dB</source> <translation>RC PassaBanda 12dB</translation> </message> <message> <source>RC HighPass 12dB</source> <translation>RC PassaAlto 12dB</translation> </message> <message> <source>RC LowPass 24dB</source> <translation>RC PassaBasso 24dB</translation> </message> <message> <source>RC BandPass 24dB</source> <translation>RC PassaBanda 24dB</translation> </message> <message> <source>RC HighPass 24dB</source> <translation>RC PassaAlto 24dB</translation> </message> <message> <source>Vocal Formant Filter</source> <translation>Filtro a Formante di Voce</translation> </message> <message> <source>2x Moog</source> <translation>2x Moog</translation> </message> <message> <source>SV LowPass</source> <translation>PassaBasso SV</translation> </message> <message> <source>SV BandPass</source> <translation>PassaBanda SV</translation> </message> <message> <source>SV HighPass</source> <translation>PassaAlto SV</translation> </message> <message> <source>SV Notch</source> <translation>Notch SV</translation> </message> <message> <source>Fast Formant</source> <translation>Formante veloce</translation> </message> <message> <source>Tripole</source> <translation>Tre poli</translation> </message> </context> <context> <name>InstrumentSoundShapingView</name> <message> <source>TARGET</source> <translation>OBIETTIVO</translation> </message> <message> <source>These tabs contain envelopes. They&apos;re very important for modifying a sound, in that they are almost always necessary for substractive synthesis. For example if you have a volume envelope, you can set when the sound should have a specific volume. If you want to create some soft strings then your sound has to fade in and out very softly. This can be done by setting large attack and release times. It&apos;s the same for other envelope targets like panning, cutoff frequency for the used filter and so on. Just monkey around with it! You can really make cool sounds out of a saw-wave with just some envelopes...!</source> <translation>Queste schede contengono envelopes. Sono molto importanti per modificare i suoni, senza contare che sono quasi sempre necessarie per la sintesi sottrattiva. Per esempio se si usa un envelope per il volume, si può impostare quando un suono avrà un certo volume. Si potrebbero voler creare archi dal suono morbido, allora il suono deve iniziare e finire in modo molto morbido; ciò si ottiene impostando tempi di attacco e di rilascio ampi. Lo stesso vale per le altre funzioni degli envelope, come il panning, la frequenza di taglio dei filtri e così via. Bisogna semplicemente giocarci un po&apos;! Si possono ottenere suoni veramente interessanti a partire da un&apos;onda a dente di sega usando soltanto qualche envelope...!</translation> </message> <message> <source>FILTER</source> <translation>FILTRO</translation> </message> <message> <source>Here you can select the built-in filter you want to use for this instrument-track. Filters are very important for changing the characteristics of a sound.</source> <translation>Qui è possibile selezionare il filtro da usare per questa traccia. I filtri sono molto importanti per cambiare le caratteristiche del suono.</translation> </message> <message> <source>Hz</source> <translation>Hz</translation> </message> <message> <source>Use this knob for setting the cutoff frequency for the selected filter. The cutoff frequency specifies the frequency for cutting the signal by a filter. For example a lowpass-filter cuts all frequencies above the cutoff frequency. A highpass-filter cuts all frequencies below cutoff frequency, and so on...</source> <translation>Questa manopola imposta la frequenza di taglio del filtro. La frequenza di taglio specifica la frequenza a cui viene tagliato il segnate di un filtro. Per esempio un filtro passa-basso taglia tutte le frequenze sopra la frequenza di taglio, mentre un filtro passa-alto taglia tutte le frequenza al di sotto della frequenza di taglio e così via...</translation> </message> <message> <source>RESO</source> <translation>RISO</translation> </message> <message> <source>Resonance:</source> <translation>Risonanza:</translation> </message> <message> <source>Use this knob for setting Q/Resonance for the selected filter. Q/Resonance tells the filter how much it should amplify frequencies near Cutoff-frequency.</source> <translation>Questa manopola imposta il parametro (Q) per la risonanza del filtro selezionato. Il parametro per la risonanza specifica l&apos;ampiezza della campana di frequenze intorno alla frequenza di taglio che devono essere amplificate.</translation> </message> <message> <source>FREQ</source> <translation>FREQ</translation> </message> <message> <source>cutoff frequency:</source> <translation>Frequenza del cutoff:</translation> </message> <message> <source>Envelopes, LFOs and filters are not supported by the current instrument.</source> <translation>Gli inviluppi, gli LFO e i filtri non sono supportati dallo strumento corrente.</translation> </message> </context> <context> <name>InstrumentTrack</name> <message> <source>unnamed_track</source> <translation>traccia_senza_nome</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Panning</source> <translation>Panning</translation> </message> <message> <source>Pitch</source> <translation>Altezza</translation> </message> <message> <source>FX channel</source> <translation>Canale FX</translation> </message> <message> <source>Default preset</source> <translation>Impostazioni predefinite</translation> </message> <message> <source>With this knob you can set the volume of the opened channel.</source> <translation>Questa manopola imposta il volume del canale.</translation> </message> <message> <source>Base note</source> <translation>Nota base</translation> </message> <message> <source>Pitch range</source> <translation>Estenzione dell&apos;altezza</translation> </message> <message> <source>Master Pitch</source> <translation>Trasporto</translation> </message> </context> <context> <name>InstrumentTrackView</name> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Volume:</source> <translation>Volume:</translation> </message> <message> <source>VOL</source> <translation>VOL</translation> </message> <message> <source>Panning</source> <translation>Panning</translation> </message> <message> <source>Panning:</source> <translation>Panning:</translation> </message> <message> <source>PAN</source> <translation>PAN</translation> </message> <message> <source>MIDI</source> <translation>MIDI</translation> </message> <message> <source>Input</source> <translation>Ingresso</translation> </message> <message> <source>Output</source> <translation>Uscita</translation> </message> <message> <source>FX %1: %2</source> <translation>FX %1: %2</translation> </message> </context> <context> <name>InstrumentTrackWindow</name> <message> <source>GENERAL SETTINGS</source> <translation>IMPOSTAZIONI GENERALI</translation> </message> <message> <source>Instrument volume</source> <translation>Volume dello strumento</translation> </message> <message> <source>Volume:</source> <translation>Volume:</translation> </message> <message> <source>VOL</source> <translation>VOL</translation> </message> <message> <source>Panning</source> <translation>Panning</translation> </message> <message> <source>Panning:</source> <translation>Panning:</translation> </message> <message> <source>PAN</source> <translation>PAN</translation> </message> <message> <source>Pitch</source> <translation>Altezza</translation> </message> <message> <source>Pitch:</source> <translation>Altezza:</translation> </message> <message> <source>cents</source> <translation>centesimi</translation> </message> <message> <source>PITCH</source> <translation>ALTEZZA</translation> </message> <message> <source>FX channel</source> <translation>Canale FX</translation> </message> <message> <source>FX</source> <translation>FX</translation> </message> <message> <source>Save preset</source> <translation>Salva il preset</translation> </message> <message> <source>XML preset file (*.xpf)</source> <translation>File di preset XML (*.xpf)</translation> </message> <message> <source>Pitch range (semitones)</source> <translation>Ampiezza dell&apos;altezza (in semitoni)</translation> </message> <message> <source>RANGE</source> <translation>AMPIEZZA</translation> </message> <message> <source>Save current instrument track settings in a preset file</source> <translation>Salva le impostazioni di questa traccia in un file preset</translation> </message> <message> <source>Click here, if you want to save current instrument track settings in a preset file. Later you can load this preset by double-clicking it in the preset-browser.</source> <translation>Clicca qui per salvare lo strumento corrente come preset. Al prossimo avvio, questo preset sarà visibile nel preset browser (&quot;I miei preset&quot;).</translation> </message> <message> <source>Use these controls to view and edit the next/previous track in the song editor.</source> <translation>Usa questi controlli per visualizzare e modificare la prossima traccia o quella precedente nel Song Editor</translation> </message> <message> <source>SAVE</source> <translation>SALVA</translation> </message> <message> <source>Envelope, filter &amp; LFO</source> <translation type="unfinished"/> </message> <message> <source>Chord stacking &amp; arpeggio</source> <translation type="unfinished"/> </message> <message> <source>Effects</source> <translation type="unfinished"/> </message> <message> <source>MIDI settings</source> <translation>Impostazioni MIDI</translation> </message> <message> <source>Miscellaneous</source> <translation type="unfinished"/> </message> <message> <source>Plugin</source> <translation type="unfinished"/> </message> </context> <context> <name>Knob</name> <message> <source>Set linear</source> <translation>Modalità lineare</translation> </message> <message> <source>Set logarithmic</source> <translation>Modalità logaritmica</translation> </message> <message> <source>Please enter a new value between %1 and %2:</source> <translation>Inserire un valore compreso tra %1 e %2:</translation> </message> <message> <source>Please enter a new value between -96.0 dBFS and 6.0 dBFS:</source> <translation>Inserire un nuovo valore tra -96.0 dBFS e 6.0 dBFS:</translation> </message> </context> <context> <name>LadspaControl</name> <message> <source>Link channels</source> <translation>Abbina i canali</translation> </message> </context> <context> <name>LadspaControlDialog</name> <message> <source>Link Channels</source> <translation>Canali abbinati</translation> </message> <message> <source>Channel </source> <translation>Canale</translation> </message> </context> <context> <name>LadspaControlView</name> <message> <source>Link channels</source> <translation>Abbina i canali</translation> </message> <message> <source>Value:</source> <translation>Valore:</translation> </message> <message> <source>Sorry, no help available.</source> <translation>Spiacente, nessun aiuto disponibile.</translation> </message> </context> <context> <name>LadspaEffect</name> <message> <source>Unknown LADSPA plugin %1 requested.</source> <translation>Il plugin LADSPA %1 richiesto è sconosciuto.</translation> </message> </context> <context> <name>LcdSpinBox</name> <message> <source>Please enter a new value between %1 and %2:</source> <translation>Inserire un valore compreso tra %1 e %2:</translation> </message> </context> <context> <name>LeftRightNav</name> <message> <source>Previous</source> <translation>Precedente</translation> </message> <message> <source>Next</source> <translation>Successivo</translation> </message> <message> <source>Previous (%1)</source> <translation>Precedente (%1)</translation> </message> <message> <source>Next (%1)</source> <translation>Successivo (%1)</translation> </message> </context> <context> <name>LfoController</name> <message> <source>LFO Controller</source> <translation>Controller dell&apos;LFO</translation> </message> <message> <source>Base value</source> <translation>Valore di base</translation> </message> <message> <source>Oscillator speed</source> <translation>Velocità dell&apos;oscillatore</translation> </message> <message> <source>Oscillator amount</source> <translation>Quantità di oscillatore</translation> </message> <message> <source>Oscillator phase</source> <translation>Fase dell&apos;oscillatore</translation> </message> <message> <source>Oscillator waveform</source> <translation>Forma d&apos;onda dell&apos;oscillatore</translation> </message> <message> <source>Frequency Multiplier</source> <translation>Moltiplicatore della frequenza</translation> </message> </context> <context> <name>LfoControllerDialog</name> <message> <source>LFO</source> <translation>LFO</translation> </message> <message> <source>LFO Controller</source> <translation>Controller dell&apos;LFO</translation> </message> <message> <source>BASE</source> <translation>BASE</translation> </message> <message> <source>Base amount:</source> <translation>Quantità di base:</translation> </message> <message> <source>todo</source> <translation>da fare</translation> </message> <message> <source>SPD</source> <translation>VEL</translation> </message> <message> <source>LFO-speed:</source> <translation>Velocità dell&apos;LFO:</translation> </message> <message> <source>Use this knob for setting speed of the LFO. The bigger this value the faster the LFO oscillates and the faster the effect.</source> <translation>Questa manopola imposta la velocità dell&apos;LFO selezionato. Più grande è questo valore più velocemente l&apos;LFO oscillerà e più veloce sarà l&apos;effetto.</translation> </message> <message> <source>Modulation amount:</source> <translation>Quantità di modulazione:</translation> </message> <message> <source>Use this knob for setting modulation amount of the LFO. The bigger this value, the more the connected control (e.g. volume or cutoff-frequency) will be influenced by the LFO.</source> <translation>Questa manopola imposta la quantità di modulazione dell&apos;LFO selezionato. Più grande è questo valore più la variabile selezionata (ad es. il volume o la frequenza di taglio) sarà influenzata da questo LFO.</translation> </message> <message> <source>PHS</source> <translation>FASE</translation> </message> <message> <source>Phase offset:</source> <translation>Scostamento della fase:</translation> </message> <message> <source>degrees</source> <translation>gradi</translation> </message> <message> <source>With this knob you can set the phase offset of the LFO. That means you can move the point within an oscillation where the oscillator begins to oscillate. For example if you have a sine-wave and have a phase-offset of 180 degrees the wave will first go down. It&apos;s the same with a square-wave.</source> <translation>Questa manopola regola lo scostamento della fase per l&apos;LFO. Ciò significa spostare il punto dell&apos;oscillazione da cui parte l&apos;oscillatore. Per esempio, con un&apos;onda sinusoidale e uno scostamento della fase di 180 gradi, l&apos;onda inizierà scendendo. Lo stesso vale per un&apos;onda quadra.</translation> </message> <message> <source>Click here for a sine-wave.</source> <translation>Cliccando qui si ha un&apos;onda sinusoidale.</translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda triangolare.</translation> </message> <message> <source>Click here for a saw-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda a dente di sega.</translation> </message> <message> <source>Click here for a square-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda quadra.</translation> </message> <message> <source>Click here for an exponential wave.</source> <translation>Cliccando qui si ha un&apos;onda esponenziale.</translation> </message> <message> <source>Click here for white-noise.</source> <translation>Cliccando qui si ottiene rumore bianco.</translation> </message> <message> <source>Click here for a user-defined shape. Double click to pick a file.</source> <translation>Cliccando qui si usa un&apos;onda definita dall&apos;utente. Fare doppio click per scegliere il file dell&apos;onda.</translation> </message> <message> <source>Click here for a moog saw-wave.</source> <translation>Clicca per usare un&apos;onda Moog a banda limitata.</translation> </message> <message> <source>AMNT</source> <translation>Q.TÀ</translation> </message> </context> <context> <name>LmmsCore</name> <message> <source>Generating wavetables</source> <translation>Generazione wavetable</translation> </message> <message> <source>Initializing data structures</source> <translation>Inizializzazione strutture dati</translation> </message> <message> <source>Opening audio and midi devices</source> <translation>Accesso ai dispositivi audio e midi</translation> </message> <message> <source>Launching mixer threads</source> <translation>Accensione dei thread del mixer</translation> </message> </context> <context> <name>MainWindow</name> <message> <source>&amp;New</source> <translation>&amp;Nuovo</translation> </message> <message> <source>&amp;Open...</source> <translation>&amp;Apri...</translation> </message> <message> <source>&amp;Save</source> <translation>&amp;Salva</translation> </message> <message> <source>Save &amp;As...</source> <translation>Salva &amp;Con Nome...</translation> </message> <message> <source>Import...</source> <translation>Importa...</translation> </message> <message> <source>E&amp;xport...</source> <translation>E&amp;sporta...</translation> </message> <message> <source>&amp;Quit</source> <translation>&amp;Esci</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <source>Settings</source> <translation>Impostazioni</translation> </message> <message> <source>&amp;Tools</source> <translation>S&amp;trumenti</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <source>Help</source> <translation>Aiuto</translation> </message> <message> <source>What&apos;s this?</source> <translation>Cos&apos;è questo?</translation> </message> <message> <source>About</source> <translation>Informazioni su</translation> </message> <message> <source>Create new project</source> <translation>Crea un nuovo progetto</translation> </message> <message> <source>Create new project from template</source> <translation>Crea un nuovo progetto da un modello</translation> </message> <message> <source>Open existing project</source> <translation>Apri un progetto esistente</translation> </message> <message> <source>Recently opened projects</source> <translation>Progetti aperti di recente</translation> </message> <message> <source>Save current project</source> <translation>Salva questo progetto</translation> </message> <message> <source>Export current project</source> <translation>Esporta questo progetto</translation> </message> <message> <source>Song Editor</source> <translation>Mostra/nascondi il Song-Editor</translation> </message> <message> <source>By pressing this button, you can show or hide the Song-Editor. With the help of the Song-Editor you can edit song-playlist and specify when which track should be played. You can also insert and move samples (e.g. rap samples) directly into the playlist.</source> <translation>Questo pulsante mostra o nasconde il Song-Editor. Con l&apos;aiuto del Song-Editor è possibile modificare la playlist e specificare quando ogni traccia viene riprodotta. Si possono anche inserire e spostare i campioni (ad es. campioni rap) direttamente nella lista di riproduzione.</translation> </message> <message> <source>Beat+Bassline Editor</source> <translation>Beat+Bassline Editor</translation> </message> <message> <source>By pressing this button, you can show or hide the Beat+Bassline Editor. The Beat+Bassline Editor is needed for creating beats, and for opening, adding, and removing channels, and for cutting, copying and pasting beat and bassline-patterns, and for other things like that.</source> <translation>Questo pulsante mostra o nasconde il Beat+Bassline Editor. Il Beat+Bassline Editor serve per creare beats, aprire, aggiungere e togliere canali, tagliare, copiare e incollare pattern beat e pattern bassline.</translation> </message> <message> <source>Piano Roll</source> <translation>Mostra/nascondi il Piano-Roll</translation> </message> <message> <source>Click here to show or hide the Piano-Roll. With the help of the Piano-Roll you can edit melodies in an easy way.</source> <translation>Questo pulsante mostra o nasconde il Piano-Roll. Con l&apos;aiuto del Piano-Roll è possibile modificare sequenze melodiche in modo semplice.</translation> </message> <message> <source>Automation Editor</source> <translation>Mostra/nascondi l&apos;Editor dell&apos;automazione</translation> </message> <message> <source>Click here to show or hide the Automation Editor. With the help of the Automation Editor you can edit dynamic values in an easy way.</source> <translation>Questo pulsante mostra o nasconde l&apos;editor dell&apos;automazione. Con l&apos;aiuto dell&apos;editor dell&apos;automazione è possibile rendere dinamici alcuni valori in modo semplice.</translation> </message> <message> <source>FX Mixer</source> <translation>Mostra/nascondi il mixer degli effetti</translation> </message> <message> <source>Click here to show or hide the FX Mixer. The FX Mixer is a very powerful tool for managing effects for your song. You can insert effects into different effect-channels.</source> <translation>Questo pulsante mostra o nasconde il mixer degli effetti. Il mixer degli effetti è uno strumento molto potente per gestire gli effetti della canzone. È possibile inserire effetti in più canali.</translation> </message> <message> <source>Project Notes</source> <translation>Mostra/nascondi le note del progetto</translation> </message> <message> <source>Click here to show or hide the project notes window. In this window you can put down your project notes.</source> <translation>Questo pulsante mostra o nasconde la finestra delle note del progetto. Qui è possibile scrivere le note per il progetto.</translation> </message> <message> <source>Controller Rack</source> <translation>Mostra/nascondi il rack di controller</translation> </message> <message> <source>Untitled</source> <translation>Senza_nome</translation> </message> <message> <source>LMMS %1</source> <translation>LMMS %1</translation> </message> <message> <source>Project not saved</source> <translation>Progetto non salvato</translation> </message> <message> <source>The current project was modified since last saving. Do you want to save it now?</source> <translation>Questo progetto è stato modificato dopo l&apos;ultimo salvataggio. Vuoi salvarlo adesso?</translation> </message> <message> <source>Help not available</source> <translation>Aiuto non disponibile</translation> </message> <message> <source>Currently there's no help available in LMMS. Please visit http://lmms.sf.net/wiki for documentation on LMMS.</source> <translation>Al momento non è disponibile alcun aiuto in LMMS. Visitare http://lmms.sf.net/wiki per la documentazione di LMMS.</translation> </message> <message> <source>LMMS (*.mmp *.mmpz)</source> <translation>LMMS (*.mmp *.mmpz)</translation> </message> <message> <source>Version %1</source> <translation>Versione %1</translation> </message> <message> <source>Configuration file</source> <translation>File di configurazione</translation> </message> <message> <source>Error while parsing configuration file at line %1:%2: %3</source> <translation>Si è riscontrato un errore nell&apos;analisi del file di configurazione alle linee %1:%2: %3</translation> </message> <message> <source>Volumes</source> <translation>Volumi</translation> </message> <message> <source>Undo</source> <translation>Annulla</translation> </message> <message> <source>Redo</source> <translation>Rifai</translation> </message> <message> <source>My Projects</source> <translation>I miei Progetti</translation> </message> <message> <source>My Samples</source> <translation>I miei Campioni</translation> </message> <message> <source>My Presets</source> <translation>I miei Preset</translation> </message> <message> <source>My Home</source> <translation>Directory di Lavoro</translation> </message> <message> <source>My Computer</source> <translation>Computer</translation> </message> <message> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <source>&amp;Recently Opened Projects</source> <translation>Progetti &amp;Recenti</translation> </message> <message> <source>Save as New &amp;Version</source> <translation>Salva come nuova &amp;Versione</translation> </message> <message> <source>E&amp;xport Tracks...</source> <translation>E&amp;sporta Tracce...</translation> </message> <message> <source>Online Help</source> <translation>Aiuto Online</translation> </message> <message> <source>What&apos;s This?</source> <translation>Cos&apos;è questo?</translation> </message> <message> <source>Open Project</source> <translation>Apri Progetto</translation> </message> <message> <source>Save Project</source> <translation>Salva Progetto</translation> </message> <message> <source>Project recovery</source> <translation>Recupero del progetto</translation> </message> <message> <source>There is a recovery file present. It looks like the last session did not end properly or another instance of LMMS is already running. Do you want to recover the project of this session?</source> <translation>E&apos; stato trovato un file di recupero. Questo accade se la sessione precedente non è stata ben chiusa o se ce n&apos;è un&apos;altra in esecuzione. Vuoi usare il progetto di recupero?</translation> </message> <message> <source>Recover</source> <translation>Recupera</translation> </message> <message> <source>Recover the file. Please don&apos;t run multiple instances of LMMS when you do this.</source> <translation>Recupera il file. Non usare più instanze di LMMS quando effettui il recupero.</translation> </message> <message> <source>Discard</source> <translation>Elimina</translation> </message> <message> <source>Launch a default session and delete the restored files. This is not reversible.</source> <translation>Fai partire una sessione normale, cancellando il file di recupero in modo irreversibile.</translation> </message> <message> <source>Preparing plugin browser</source> <translation>Caricamento browser dei plugin</translation> </message> <message> <source>Preparing file browsers</source> <translation>Caricamento browser dei file</translation> </message> <message> <source>Root directory</source> <translation>Directory principale</translation> </message> <message> <source>Loading background artwork</source> <translation>Caricamento sfondo</translation> </message> <message> <source>New from template</source> <translation>Nuovo da modello</translation> </message> <message> <source>Save as default template</source> <translation>Salva come progetto default</translation> </message> <message> <source>&amp;View</source> <translation>&amp;Visualizza</translation> </message> <message> <source>Toggle metronome</source> <translation>Metronomo on/off</translation> </message> <message> <source>Show/hide Song-Editor</source> <translation>Mostra/nascondi il Song-Editor</translation> </message> <message> <source>Show/hide Beat+Bassline Editor</source> <translation>Mostra/nascondi il Beat+Bassline Editor</translation> </message> <message> <source>Show/hide Piano-Roll</source> <translation>Mostra/nascondi il Piano-Roll</translation> </message> <message> <source>Show/hide Automation Editor</source> <translation>Mostra/nascondi l&apos;Editor dell&apos;automazione</translation> </message> <message> <source>Show/hide FX Mixer</source> <translation>Mostra/nascondi il mixer degli effetti</translation> </message> <message> <source>Show/hide project notes</source> <translation>Mostra/nascondi le note del progetto</translation> </message> <message> <source>Show/hide controller rack</source> <translation>Mostra/nascondi il rack di controller</translation> </message> <message> <source>Recover session. Please save your work!</source> <translation>Sessione di recupero. Salva al più presto!</translation> </message> <message> <source>Recovered project not saved</source> <translation>Progetto recuperato non salvato</translation> </message> <message> <source>This project was recovered from the previous session. It is currently unsaved and will be lost if you don&apos;t save it. Do you want to save it now?</source> <translation>Il progetto è stato recuperato dalla sessione precedente. Attualmente non è stato salvato. Vuoi salvarlo adesso per evitare di perderlo?</translation> </message> <message> <source>LMMS Project</source> <translation>Progetto LMMS</translation> </message> <message> <source>LMMS Project Template</source> <translation>Modello di Progetto LMMS</translation> </message> <message> <source>Overwrite default template?</source> <translation>Sovrascrivere il progetto default?</translation> </message> <message> <source>This will overwrite your current default template.</source> <translation>In questo modo verrà modificato il tuo progetto di default corrente.</translation> </message> <message> <source>Smooth scroll</source> <translation>Scorrimento morbido</translation> </message> <message> <source>Enable note labels in piano roll</source> <translation>Abilita l&apos;etichetta delle note nel piano roll</translation> </message> <message> <source>Save project template</source> <translation>Salva come modello di progetto</translation> </message> <message> <source>Volume as dBFS</source> <translation>Volume in dBFS</translation> </message> <message> <source>Could not open file</source> <translation>Non è stato possibile aprire il file</translation> </message> <message> <source>Could not open file %1 for writing. Please make sure you have write permission to the file and the directory containing the file and try again!</source> <translation>Impossibile scrivere sul file %1. Si prega di controllare i permessi di scrittura sul file e la cartella che lo contiene, e poi riprovare!</translation> </message> </context> <context> <name>MeterDialog</name> <message> <source>Meter Numerator</source> <translation>Numeratore della misura</translation> </message> <message> <source>Meter Denominator</source> <translation>Denominatore della misura</translation> </message> <message> <source>TIME SIG</source> <translation>TEMPO</translation> </message> </context> <context> <name>MeterModel</name> <message> <source>Numerator</source> <translation>Numeratore</translation> </message> <message> <source>Denominator</source> <translation>Denominatore</translation> </message> </context> <context> <name>MidiController</name> <message> <source>MIDI Controller</source> <translation>Controller MIDI</translation> </message> <message> <source>unnamed_midi_controller</source> <translation>controller_midi_senza_nome</translation> </message> </context> <context> <name>MidiImport</name> <message> <source>Setup incomplete</source> <translation>Impostazioni incomplete</translation> </message> <message> <source>You do not have set up a default soundfont in the settings dialog (Edit-&gt;Settings). Therefore no sound will be played back after importing this MIDI file. You should download a General MIDI soundfont, specify it in settings dialog and try again.</source> <translation>Non hai impostato un soundfont di base (Modifica-&gt;Impostazioni). Quindi non sarà riprodotto alcun suono dopo aver importato questo file MIDI. Prova a scaricare un soundfont MIDI generico, specifica la sua posizione nelle impostazioni e prova di nuovo.</translation> </message> <message> <source>You did not compile LMMS with support for SoundFont2 player, which is used to add default sound to imported MIDI files. Therefore no sound will be played back after importing this MIDI file.</source> <translation>Non hai compilato LMMS con il supporto per SoundFont2 Player, che viene usato per aggiungere suoni predefiniti ai file MIDI importati. Quindi, nessun suono verrà riprodotto dopo aver aperto questo file MIDI.</translation> </message> <message> <source>Track</source> <translation>Traccia</translation> </message> </context> <context> <name>MidiJack</name> <message> <source>JACK server down</source> <extracomment>When JACK(JACK Audio Connection Kit) disconnects, it will show the following message (title)</extracomment> <translation>Il server JACK è down</translation> </message> <message> <source>The JACK server seems to be shuted down.</source> <extracomment>When JACK(JACK Audio Connection Kit) disconnects, it will show the following message (dialog message)</extracomment> <translation>Il server JACK sembra spento.</translation> </message> </context> <context> <name>MidiPort</name> <message> <source>Input channel</source> <translation>Canale di ingresso</translation> </message> <message> <source>Output channel</source> <translation>Canale di uscita</translation> </message> <message> <source>Input controller</source> <translation>Controller in entrata</translation> </message> <message> <source>Output controller</source> <translation>Controller in uscita</translation> </message> <message> <source>Fixed input velocity</source> <translation>Velocity fissa in ingresso</translation> </message> <message> <source>Fixed output velocity</source> <translation>Velocity fissa in uscita</translation> </message> <message> <source>Output MIDI program</source> <translation>Programma MIDI in uscita</translation> </message> <message> <source>Receive MIDI-events</source> <translation>Ricevi eventi MIDI</translation> </message> <message> <source>Send MIDI-events</source> <translation>Invia eventi MIDI</translation> </message> <message> <source>Fixed output note</source> <translation>Nota fissa in uscita</translation> </message> <message> <source>Base velocity</source> <translation>Velocity base</translation> </message> </context> <context> <name>MidiSetupWidget</name> <message> <source>DEVICE</source> <translation>PERIFERICA</translation> </message> </context> <context> <name>MonstroInstrument</name> <message> <source>Osc 1 Volume</source> <translation>Osc 1 Volume</translation> </message> <message> <source>Osc 1 Panning</source> <translation>Osc 1 Bilanciamento</translation> </message> <message> <source>Osc 1 Coarse detune</source> <translation>Osc 1 Intonazione Grezza</translation> </message> <message> <source>Osc 1 Fine detune left</source> <translation>Osc 1 Intonazione precisa sinistra</translation> </message> <message> <source>Osc 1 Fine detune right</source> <translation>Osc 1 Intonazione precisa destra</translation> </message> <message> <source>Osc 1 Stereo phase offset</source> <translation>Osc 1 Spostamento di fase stereo</translation> </message> <message> <source>Osc 1 Pulse width</source> <translation>Osc 1 Profondità impulso</translation> </message> <message> <source>Osc 1 Sync send on rise</source> <translation>Osc 1 Manda sync in salita</translation> </message> <message> <source>Osc 1 Sync send on fall</source> <translation>Osc 1 Manda sync in discesa</translation> </message> <message> <source>Osc 2 Volume</source> <translation>Osc 2 Volume</translation> </message> <message> <source>Osc 2 Panning</source> <translation>Osc 2 Bilanciamento</translation> </message> <message> <source>Osc 2 Coarse detune</source> <translation>Osc 2 Intonazione Grezza</translation> </message> <message> <source>Osc 2 Fine detune left</source> <translation>Osc 2 Intonazione precisa sinistra</translation> </message> <message> <source>Osc 2 Fine detune right</source> <translation>Osc 2 Intonazione precisa destra</translation> </message> <message> <source>Osc 2 Stereo phase offset</source> <translation>Osc 2 Spostamento di fase stereo</translation> </message> <message> <source>Osc 2 Waveform</source> <translation>Osc 2 Forma d&apos;onda</translation> </message> <message> <source>Osc 2 Sync Hard</source> <translation>Osc 2 Sync pesante</translation> </message> <message> <source>Osc 2 Sync Reverse</source> <translation>Osc 2 Sync inverso</translation> </message> <message> <source>Osc 3 Volume</source> <translation>Osc 3 Volume</translation> </message> <message> <source>Osc 3 Panning</source> <translation>Osc 3 Bilanciamento</translation> </message> <message> <source>Osc 3 Coarse detune</source> <translation>Osc 3 Intonazione Grezza</translation> </message> <message> <source>Osc 3 Stereo phase offset</source> <translation>Osc 3 Spostamento di fase stereo</translation> </message> <message> <source>Osc 3 Sub-oscillator mix</source> <translation>Osc 3 Miscela sub-oscillatori</translation> </message> <message> <source>Osc 3 Waveform 1</source> <translation>Osc 3 Forma d&apos;onda 1</translation> </message> <message> <source>Osc 3 Waveform 2</source> <translation>Osc 3 Forma d&apos;onda 2</translation> </message> <message> <source>Osc 3 Sync Hard</source> <translation>Osc 3 Sync pesante</translation> </message> <message> <source>Osc 3 Sync Reverse</source> <translation>Osc 3 Sync inverso</translation> </message> <message> <source>LFO 1 Waveform</source> <translation>LFO 1 Forma d&apos;onda</translation> </message> <message> <source>LFO 1 Attack</source> <translation>LFO 1 Attacco</translation> </message> <message> <source>LFO 1 Rate</source> <translation>LFO 1 Rate</translation> </message> <message> <source>LFO 1 Phase</source> <translation>LFO 1 Fase</translation> </message> <message> <source>LFO 2 Waveform</source> <translation>LFO 2 Forma d&apos;onda</translation> </message> <message> <source>LFO 2 Attack</source> <translation>LFO 2 Attacco</translation> </message> <message> <source>LFO 2 Rate</source> <translation>LFO 2 Rate</translation> </message> <message> <source>LFO 2 Phase</source> <translation>LFO 2 Fase</translation> </message> <message> <source>Env 1 Pre-delay</source> <translation>Env 1 Pre-ritardo</translation> </message> <message> <source>Env 1 Attack</source> <translation>Env 1 Attacco</translation> </message> <message> <source>Env 1 Hold</source> <translation>Env 1 Mantenimento</translation> </message> <message> <source>Env 1 Decay</source> <translation>Env 1 Decadimento</translation> </message> <message> <source>Env 1 Sustain</source> <translation>Env 1 Sostegno</translation> </message> <message> <source>Env 1 Release</source> <translation>Env 1 Rilascio</translation> </message> <message> <source>Env 1 Slope</source> <translation>Env 1 Inclinazione</translation> </message> <message> <source>Env 2 Pre-delay</source> <translation>Env 2 Pre-ritardo</translation> </message> <message> <source>Env 2 Attack</source> <translation>Env 2 Attacco</translation> </message> <message> <source>Env 2 Hold</source> <translation>Env 2 Mantenimento</translation> </message> <message> <source>Env 2 Decay</source> <translation>Env 2 Decadimento</translation> </message> <message> <source>Env 2 Sustain</source> <translation>Env 2 Sostegno</translation> </message> <message> <source>Env 2 Release</source> <translation>Env 2 Rilascio</translation> </message> <message> <source>Env 2 Slope</source> <translation>Env 2 Inclinazione</translation> </message> <message> <source>Osc2-3 modulation</source> <translation>Modulazione Osc2-3</translation> </message> <message> <source>Selected view</source> <translation>Seleziona vista</translation> </message> <message> <source>Vol1-Env1</source> <translation>Vol1-Inv1</translation> </message> <message> <source>Vol1-Env2</source> <translation>Vol1-Inv2</translation> </message> <message> <source>Vol1-LFO1</source> <translation>Vol1-LFO1</translation> </message> <message> <source>Vol1-LFO2</source> <translation>Vol1-LFO2</translation> </message> <message> <source>Vol2-Env1</source> <translation>Vol2-Inv1</translation> </message> <message> <source>Vol2-Env2</source> <translation>Vol2-Inv2</translation> </message> <message> <source>Vol2-LFO1</source> <translation>Vol2-LFO1</translation> </message> <message> <source>Vol2-LFO2</source> <translation>Vol2-LFO2</translation> </message> <message> <source>Vol3-Env1</source> <translation>Vol3-Inv1</translation> </message> <message> <source>Vol3-Env2</source> <translation>Vol3-Inv2</translation> </message> <message> <source>Vol3-LFO1</source> <translation>Vol3-LFO1</translation> </message> <message> <source>Vol3-LFO2</source> <translation>Vol3-LFO2</translation> </message> <message> <source>Phs1-Env1</source> <translation>Fas1-Inv1</translation> </message> <message> <source>Phs1-Env2</source> <translation>Fas1-Inv2</translation> </message> <message> <source>Phs1-LFO1</source> <translation>Fas1-LFO1</translation> </message> <message> <source>Phs1-LFO2</source> <translation>Fas1-LFO2</translation> </message> <message> <source>Phs2-Env1</source> <translation>Fas2-Inv1</translation> </message> <message> <source>Phs2-Env2</source> <translation>Fas2-Inv2</translation> </message> <message> <source>Phs2-LFO1</source> <translation>Fas2-LFO1</translation> </message> <message> <source>Phs2-LFO2</source> <translation>Fas2-LFO2</translation> </message> <message> <source>Phs3-Env1</source> <translation>Fas3-Inv1</translation> </message> <message> <source>Phs3-Env2</source> <translation>Fas3-Inv2</translation> </message> <message> <source>Phs3-LFO1</source> <translation>Fas3-LFO1</translation> </message> <message> <source>Phs3-LFO2</source> <translation>Fas3-LFO2</translation> </message> <message> <source>Pit1-Env1</source> <translation>Alt1-Inv1</translation> </message> <message> <source>Pit1-Env2</source> <translation>Alt1-Inv2</translation> </message> <message> <source>Pit1-LFO1</source> <translation>Alt1-LFO1</translation> </message> <message> <source>Pit1-LFO2</source> <translation>Alt1-LFO2</translation> </message> <message> <source>Pit2-Env1</source> <translation>Alt2-Inv1</translation> </message> <message> <source>Pit2-Env2</source> <translation>Alt2-Inv2</translation> </message> <message> <source>Pit2-LFO1</source> <translation>Alt2-LFO1</translation> </message> <message> <source>Pit2-LFO2</source> <translation>Alt2-LFO2</translation> </message> <message> <source>Pit3-Env1</source> <translation>Alt3-Inv1</translation> </message> <message> <source>Pit3-Env2</source> <translation>Alt3-Inv2</translation> </message> <message> <source>Pit3-LFO1</source> <translation>Alt3-LFO1</translation> </message> <message> <source>Pit3-LFO2</source> <translation>Alt3-LFO2</translation> </message> <message> <source>PW1-Env1</source> <translation>LI1-Inv1</translation> </message> <message> <source>PW1-Env2</source> <translation>LI1-Inv2</translation> </message> <message> <source>PW1-LFO1</source> <translation>LI1-LFO1</translation> </message> <message> <source>PW1-LFO2</source> <translation>LI1-LFO2</translation> </message> <message> <source>Sub3-Env1</source> <translation>Sub3-Inv1</translation> </message> <message> <source>Sub3-Env2</source> <translation>Sub3-Inv2</translation> </message> <message> <source>Sub3-LFO1</source> <translation>Sub3-LFO1</translation> </message> <message> <source>Sub3-LFO2</source> <translation>Sub3-LFO2</translation> </message> <message> <source>Sine wave</source> <translation>Onda sinusoidale</translation> </message> <message> <source>Bandlimited Triangle wave</source> <translation>Onda triangolare limitata</translation> </message> <message> <source>Bandlimited Saw wave</source> <translation>Onda a dente di sega limitata</translation> </message> <message> <source>Bandlimited Ramp wave</source> <translation>Onda a rampa limitata</translation> </message> <message> <source>Bandlimited Square wave</source> <translation>Onda quadra limitata</translation> </message> <message> <source>Bandlimited Moog saw wave</source> <translation>Onda Moog limitata</translation> </message> <message> <source>Soft square wave</source> <translation>Onda quadra morbida</translation> </message> <message> <source>Absolute sine wave</source> <translation>Onda sinusoidale assoluta</translation> </message> <message> <source>Exponential wave</source> <translation>Onda esponenziale</translation> </message> <message> <source>White noise</source> <translation>Rumore bianco</translation> </message> <message> <source>Digital Triangle wave</source> <translation>Onda triangolare digitale</translation> </message> <message> <source>Digital Saw wave</source> <translation>Onda a dente di sega digitale</translation> </message> <message> <source>Digital Ramp wave</source> <translation>Onda a rampa digitale</translation> </message> <message> <source>Digital Square wave</source> <translation>Onda quadra digitale</translation> </message> <message> <source>Digital Moog saw wave</source> <translation>Onda Moog digitale</translation> </message> <message> <source>Triangle wave</source> <translation>Onda triangolare</translation> </message> <message> <source>Saw wave</source> <translation>Onda a dente di sega</translation> </message> <message> <source>Ramp wave</source> <translation>Onda a rampa</translation> </message> <message> <source>Square wave</source> <translation>Onda quadra</translation> </message> <message> <source>Moog saw wave</source> <translation>Onda Moog</translation> </message> <message> <source>Abs. sine wave</source> <translation>Sinusoide Ass.</translation> </message> <message> <source>Random</source> <translation>Casuale</translation> </message> <message> <source>Random smooth</source> <translation>Casuale morbida</translation> </message> </context> <context> <name>MonstroView</name> <message> <source>Operators view</source> <translation>Vista operatori</translation> </message> <message> <source>The Operators view contains all the operators. These include both audible operators (oscillators) and inaudible operators, or modulators: Low-frequency oscillators and Envelopes. Knobs and other widgets in the Operators view have their own what&apos;s this -texts, so you can get more specific help for them that way. </source> <translation>La vista operatori contiene tutti gli operatori. Vi sono sia operatori udibili (oscillatori), che silenziosi, o modulatori: LFO e inviluppi. Usa il &quot;Cos&apos;è questo?&quot; su tutte le manopole di questa vista per avere informazioni specifiche su di esse.</translation> </message> <message> <source>Matrix view</source> <translation>Vista Matrice</translation> </message> <message> <source>The Matrix view contains the modulation matrix. Here you can define the modulation relationships between the various operators: Each audible operator (oscillators 1-3) has 3-4 properties that can be modulated by any of the modulators. Using more modulations consumes more CPU power. The view is divided to modulation targets, grouped by the target oscillator. Available targets are volume, pitch, phase, pulse width and sub-osc ratio. Note: some targets are specific to one oscillator only. Each modulation target has 4 knobs, one for each modulator. By default the knobs are at 0, which means no modulation. Turning a knob to 1 causes that modulator to affect the modulation target as much as possible. Turning it to -1 does the same, but the modulation is inversed. </source> <translation>La vista matrice contiene la matrice di modulazione. Qui puoi definire le relazioni di modulazione tra i vari operatori: ogni operatore udibile (gli oscillatori da 1 a 3) ha 3-4 proprietà che possono essere modulate da qualsiasi modulatore. L&apos;utilizzo eccessivo di modulazioni può appesantire la CPU. La vista è divisa in obiettivi di modulazione, raggruppati dagli oscillatori. Possono essere modulati il volume, l&apos;altezza, la fase, la larghezza dell&apos;impulso e il rateo del sottooscillatorie. Nota: alcune proprietà sono esclusive di un solo oscillatore. Ogni proprietà modulabile ha 4 manopole, una per ogni modulatore. Sono tutti a 0 di default, ossia non vi è modulazione. Il massimo della modulazione si ottiene portando una manopola a 1. I valori negativi invertono l&apos;effetto che avrebbero quelli positivi.</translation> </message> <message> <source>Mix Osc2 with Osc3</source> <translation>Mescola l&apos;Osc2 con l&apos;Osc3</translation> </message> <message> <source>Modulate amplitude of Osc3 with Osc2</source> <translation>Modula l&apos;amplificazione dell&apos;Osc3 con l&apos;Osc2</translation> </message> <message> <source>Modulate frequency of Osc3 with Osc2</source> <translation>Modula la frequenza dell&apos;Osc3 con l&apos;Osc2</translation> </message> <message> <source>Modulate phase of Osc3 with Osc2</source> <translation>Modula la fase dell&apos;Osc3 con l&apos;Osc2</translation> </message> <message> <source>The CRS knob changes the tuning of oscillator 1 in semitone steps. </source> <translation>La manopola CRS cambia l&apos;intonazione dell&apos;oscillatore 1 per semitoni.</translation> </message> <message> <source>The CRS knob changes the tuning of oscillator 2 in semitone steps. </source> <translation>La manopola CRS cambia l&apos;intonazione dell&apos;oscillatore 2 per semitoni.</translation> </message> <message> <source>The CRS knob changes the tuning of oscillator 3 in semitone steps. </source> <translation>La manopola CRS cambia l&apos;intonazione dell&apos;oscillatore 3 per semitoni.</translation> </message> <message> <source>FTL and FTR change the finetuning of the oscillator for left and right channels respectively. These can add stereo-detuning to the oscillator which widens the stereo image and causes an illusion of space. </source> <translation>FTL e FTR cambiano l&apos;intonazione precisa dell&apos;oscillatore per i canali sinistro e destro rispettivamente. Possono essere usati per creare un&apos;illusione di spazio.</translation> </message> <message> <source>The SPO knob modifies the difference in phase between left and right channels. Higher difference creates a wider stereo image. </source> <translation>La manopola SPO altera la differenza in fase tra i canali sinistro e destro. Una differenza maggiore crea un&apos;immagine stereo più larga.</translation> </message> <message> <source>The PW knob controls the pulse width, also known as duty cycle, of oscillator 1. Oscillator 1 is a digital pulse wave oscillator, it doesn&apos;t produce bandlimited output, which means that you can use it as an audible oscillator but it will cause aliasing. You can also use it as an inaudible source of a sync signal, which can be used to synchronize oscillators 2 and 3. </source> <translation>La manopola PW controlla la profondità dell&apos;impulso, conosciuta anche come duty cycle, dell&apos;oscillatore 1. L&apos;oscillatore 1 è un oscillatore d&apos;onda a impulso digitale, non produce un output con banda limitata, il che vuol dire che è possibile usarlo come un oscillatore udibile ma ciò creerà aliasing. Puoi anche usarlo come fonte silenziosa di un segnale di sincronizzazione, che sincronizza gli altri due oscillatori.</translation> </message> <message> <source>Send Sync on Rise: When enabled, the Sync signal is sent every time the state of oscillator 1 changes from low to high, ie. when the amplitude changes from -1 to 1. Oscillator 1&apos;s pitch, phase and pulse width may affect the timing of syncs, but its volume has no effect on them. Sync signals are sent independently for both left and right channels. </source> <translation>Manda sync in salita: se abilitato, il segnale di sync viene mandato ogni volta che lo stato dell&apos;oscillatore 1 cambia da basso ad alto, per esempio se l&apos;amplificazione passa da -1 a 1. Sia l&apos;altezza che la fase che i&apos;mpulso possono interessare il tempo dei sync, ma il volume no. I segnali di sync vengono trattati indipendentemente per i canali destro e sinistro.</translation> </message> <message> <source>Send Sync on Fall: When enabled, the Sync signal is sent every time the state of oscillator 1 changes from high to low, ie. when the amplitude changes from 1 to -1. Oscillator 1&apos;s pitch, phase and pulse width may affect the timing of syncs, but its volume has no effect on them. Sync signals are sent independently for both left and right channels. </source> <translation>Manda sync in discesa: se abilitato, il segnale di sync viene mandato ogni volta che lo stato dell&apos;oscillatore 1 cambia da alto a basso, per esempio se l&apos;amplificazione passa da 1 a -1. Sia l&apos;altezza che la fase che i&apos;mpulso possono interessare il tempo dei sync, ma il volume no. I segnali di sync vengono trattati indipendentemente per i canali destro e sinistro.</translation> </message> <message> <source>Hard sync: Every time the oscillator receives a sync signal from oscillator 1, its phase is reset to 0 + whatever its phase offset is. </source> <translation>Sync potente: ogni volta che l&apos;oscillatore siceve un segnale di sync dall&apos;Osc1, la sua fase viene resettata alla sua origine.</translation> </message> <message> <source>Reverse sync: Every time the oscillator receives a sync signal from oscillator 1, the amplitude of the oscillator gets inverted. </source> <translation>Sync di inversione: ogni volta che l&apos;oscillatore riceve un segnale di sync dall&apos;Osc1, l&apos;amplificazione dell&apos;oscillatore viene invertita.</translation> </message> <message> <source>Choose waveform for oscillator 2. </source> <translation>Seleziona la forma d&apos;onda per l&apos;Osc2.</translation> </message> <message> <source>Choose waveform for oscillator 3&apos;s first sub-osc. Oscillator 3 can smoothly interpolate between two different waveforms. </source> <translation>Seleziona la forma d&apos;onda per il primo sub-oscillatore dell&apos;Osc3. L&apos;Osc3 può interpolare morbidamente tra due forme d&apos;onda diverse.</translation> </message> <message> <source>Choose waveform for oscillator 3&apos;s second sub-osc. Oscillator 3 can smoothly interpolate between two different waveforms. </source> <translation>Seleziona la forma d&apos;onda per il secondo sub-oscillatore dell&apos;Osc3. L&apos;Osc3 può interpolare morbidamente tra due forme d&apos;onda diverse.</translation> </message> <message> <source>The SUB knob changes the mixing ratio of the two sub-oscs of oscillator 3. Each sub-osc can be set to produce a different waveform, and oscillator 3 can smoothly interpolate between them. All incoming modulations to oscillator 3 are applied to both sub-oscs/waveforms in the exact same way. </source> <translation>La manopola SUB cambia le qualtità per la miscela tra i due sub-oscillatori.</translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. Mix mode means no modulation: the outputs of the oscillators are simply mixed together. </source> <translation>Oltre ai modulatori dedicati, Monstro permette di modulare l&apos;Osc3 tramite l&apos;output dell&apos;Osc2. La modalità Mix non produce nessuna modulazione: i due oscillatori sono semplicemente miscelati tra di loro.</translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. AM means amplitude modulation: Oscillator 3&apos;s amplitude (volume) is modulated by oscillator 2. </source> <translation>Oltre ai modulatori dedicati, Monstro permette di modulare l&apos;Osc3 tramite l&apos;output dell&apos;Osc2. AM vuol dire modulazione di amplificazione: quella dell&apos;Osc3 (il suo volume) è modulata dall&apos;output dell&apos;Osc2.</translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. FM means frequency modulation: Oscillator 3&apos;s frequency (pitch) is modulated by oscillator 2. The frequency modulation is implemented as phase modulation, which gives a more stable overall pitch than &quot;pure&quot; frequency modulation. </source> <translation>Oltre ai modulatori dedicati, Monstro permette di modulare l&apos;Osc3 tramite l&apos;output dell&apos;Osc2. FM vuol dire modulazione di frequenza: quella dell&apos;Osc3 (la sua altezza) è modulata dall&apos;Osc2. Questa modulazione è implementata come una modulazione di fase, in modo da avere una frequenza risultate più stabile di una FM pura.</translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. PM means phase modulation: Oscillator 3&apos;s phase is modulated by oscillator 2. It differs from frequency modulation in that the phase changes are not cumulative. </source> <translation>Oltre ai modulatori dedicati, Monstro permette di modulare l&apos;Osc3 tramite l&apos;outpit dell&apos;Osc2. PM è la modulazione di fase: quella dell&apos;Osc3 è modulata dall&apos;Osc2. La differenza con la modulazione di frequenza consiste nel fatto che in quella i cambiamenti di fase non sono cumulativi.</translation> </message> <message> <source>Select the waveform for LFO 1. &quot;Random&quot; and &quot;Random smooth&quot; are special waveforms: they produce random output, where the rate of the LFO controls how often the state of the LFO changes. The smooth version interpolates between these states with cosine interpolation. These random modes can be used to give &quot;life&quot; to your presets - add some of that analog unpredictability... </source> <translation>Selezioa la forma d&apos;onda per l&apos;LFO 1. Vi sono due forme speciali: &quot;Random&quot; e &quot;Random morbido&quot; sono onde speciali che producono un aoutup randomico, dove il rate dell&apos;LFO controlla quanto spesso lo stato dell&apos;LFO cambia. La versione morbila interpola tra questi stati con una interpolazione a coseno. Queste modalità possono essere usate per ridare &quot;vita&quot; ai toi preset o aggiungere un po&apos; di quella imprevedibilità degli stumenti analogici...</translation> </message> <message> <source>Select the waveform for LFO 2. &quot;Random&quot; and &quot;Random smooth&quot; are special waveforms: they produce random output, where the rate of the LFO controls how often the state of the LFO changes. The smooth version interpolates between these states with cosine interpolation. These random modes can be used to give &quot;life&quot; to your presets - add some of that analog unpredictability... </source> <translation>Selezioa la forma d&apos;onda per l&apos;LFO 2. Vi sono due forme speciali: &quot;Random&quot; e &quot;Random morbido&quot; sono onde speciali che producono un aoutup randomico, dove il rate dell&apos;LFO controlla quanto spesso lo stato dell&apos;LFO cambia. La versione morbila interpola tra questi stati con una interpolazione a coseno. Queste modalità possono essere usate per ridare &quot;vita&quot; ai toi preset o aggiungere un po&apos; di quella imprevedibilità degli stumenti analogici...</translation> </message> <message> <source>Attack causes the LFO to come on gradually from the start of the note. </source> <translation>L&apos;attacco fa sì che l&apos;LFO arrivi gradualmente al suo stato da quello della nota suonata.</translation> </message> <message> <source>Rate sets the speed of the LFO, measured in milliseconds per cycle. Can be synced to tempo. </source> <translation>Il rate setta la velocità dell&apos;LFO, misurata in millisecondi per ciclo. Può essere sincronizzata al tempo nel suo menù a tendina.</translation> </message> <message> <source>PHS controls the phase offset of the LFO. </source> <translation>PHS controlla lo spostamento di fase dell&apos;LFO.</translation> </message> <message> <source>PRE, or pre-delay, delays the start of the envelope from the start of the note. 0 means no delay. </source> <translation>PRE, o pre-ritardo, ritarda l&apos;inizio dell&apos;inviluppo dal momento in cui la nota viene suonata. 0 vuol dire nessun ritardo.</translation> </message> <message> <source>ATT, or attack, controls how fast the envelope ramps up at start, measured in milliseconds. A value of 0 means instant. </source> <translation>ATT, o attacco, controlla quanto velocemente l&apos;inviluppo arriva al suo masimmo, misurando questo tempo in millisecondi. 0 vuol dire che il valore massimo viene raggiunto istantaneamente.</translation> </message> <message> <source>HOLD controls how long the envelope stays at peak after the attack phase. </source> <translation>HOLD controlla per quanto tempo l&apos;inviluppo rimane al suo massimo dopo l&apos;attacco.</translation> </message> <message> <source>DEC, or decay, controls how fast the envelope falls off from its peak, measured in milliseconds it would take to go from peak to zero. The actual decay may be shorter if sustain is used. </source> <translation>DEC, o decadimento, controlla in quanto tempo l&apos;inviluppo cade dal suo massimo, misurandolo in missilecondi. Il decadimento effettivo potrebbe essere più lento se viene alterato il sostegno.</translation> </message> <message> <source>SUS, or sustain, controls the sustain level of the envelope. The decay phase will not go below this level as long as the note is held. </source> <translation>SUS, o sostegno, controlla il livello di sostegno dell&apos;inviluppo. La fase di decadimento non scenderà oltre questo livello fino a che la nota viene suonata.</translation> </message> <message> <source>REL, or release, controls how long the release is for the note, measured in how long it would take to fall from peak to zero. Actual release may be shorter, depending on at what phase the note is released. </source> <translation>REL, o rilascio, controlla il tempo di rilascio della nota, misurandola in millisecondi. Se l&apos;inviluppo non si trova al suo valore massimo quando la nota è rilasciata, il rilascio potrebbe durare di meno.</translation> </message> <message> <source>The slope knob controls the curve or shape of the envelope. A value of 0 creates straight rises and falls. Negative values create curves that start slowly, peak quickly and fall of slowly again. Positive values create curves that start and end quickly, and stay longer near the peaks. </source> <translation>SLOPE, o inclinazione, controlla la curva (o la forma) dell&apos;inviluppo. Un valore pari a 0 lascia le salite e le discese come linee dritte. Valori negativi creeranno dei movimenti che partono lentamente, arrivano a un picco ripido, e poi terminano di nuovo lentamente. Valori positivi daranno curve che salgono e scendono velocemente, ma si fermano ai picchi.</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Panning</source> <translation>Bilanciamento</translation> </message> <message> <source>Coarse detune</source> <translation>Intonazione grezza</translation> </message> <message> <source> semitones</source> <translation>semitoni</translation> </message> <message> <source>Finetune left</source> <translation>Intonazione precisa sinistra</translation> </message> <message> <source> cents</source> <translation>centesimi</translation> </message> <message> <source>Finetune right</source> <translation>Intonazione precisa destra</translation> </message> <message> <source>Stereo phase offset</source> <translation>Spostamento di fase stereo</translation> </message> <message> <source> deg</source> <translation>gradi</translation> </message> <message> <source>Pulse width</source> <translation>Larghezza impulso</translation> </message> <message> <source>Send sync on pulse rise</source> <translation>Manda sincro alle salite</translation> </message> <message> <source>Send sync on pulse fall</source> <translation>Manda sincro alle discese</translation> </message> <message> <source>Hard sync oscillator 2</source> <translation>Sincro Duro oscillatore 2</translation> </message> <message> <source>Reverse sync oscillator 2</source> <translation>Sincro Inverso oscillatore 2</translation> </message> <message> <source>Sub-osc mix</source> <translation>Missaggio Sub-osc</translation> </message> <message> <source>Hard sync oscillator 3</source> <translation>Sincro Duro oscillatore 3</translation> </message> <message> <source>Reverse sync oscillator 3</source> <translation>Sincro Inverso oscillatore 3</translation> </message> <message> <source>Attack</source> <translation>Attacco</translation> </message> <message> <source>Rate</source> <translation>Periodo</translation> </message> <message> <source>Phase</source> <translation>Fase</translation> </message> <message> <source>Pre-delay</source> <translation>Pre-ritardo</translation> </message> <message> <source>Hold</source> <translation>Mantenimento</translation> </message> <message> <source>Decay</source> <translation>Decadimento</translation> </message> <message> <source>Sustain</source> <translation>Sostegno</translation> </message> <message> <source>Release</source> <translation>Rilascio</translation> </message> <message> <source>Slope</source> <translation>Curvatura</translation> </message> <message> <source>Modulation amount</source> <translation>Quantità di modulazione:</translation> </message> </context> <context> <name>MultitapEchoControlDialog</name> <message> <source>Length</source> <translation>Lunghezza</translation> </message> <message> <source>Step length:</source> <translation>Durata degli step:</translation> </message> <message> <source>Dry</source> <translation>Dry</translation> </message> <message> <source>Dry Gain:</source> <translation>Guadagno senza effetto:</translation> </message> <message> <source>Stages</source> <translation>Fasi</translation> </message> <message> <source>Lowpass stages:</source> <translation>Fasi del Passa Basso:</translation> </message> <message> <source>Swap inputs</source> <translation>Scambia input</translation> </message> <message> <source>Swap left and right input channel for reflections</source> <translation>Scambia i canali destro e sinistro per le ripetizioni</translation> </message> </context> <context> <name>NesInstrument</name> <message> <source>Channel 1 Coarse detune</source> <translation>Intonazione grezza Canale 1</translation> </message> <message> <source>Channel 1 Volume</source> <translation>Volume Canale 1</translation> </message> <message> <source>Channel 1 Envelope length</source> <translation>Lunghezza inviluppo Canale 1</translation> </message> <message> <source>Channel 1 Duty cycle</source> <translation>Duty cycle del Canale 1</translation> </message> <message> <source>Channel 1 Sweep amount</source> <translation>Quantità di sweep Canale 1</translation> </message> <message> <source>Channel 1 Sweep rate</source> <translation>Velocità di sweep Canale 1</translation> </message> <message> <source>Channel 2 Coarse detune</source> <translation>Intonazione grezza Canale 2</translation> </message> <message> <source>Channel 2 Volume</source> <translation>Volume Canale 2</translation> </message> <message> <source>Channel 2 Envelope length</source> <translation>Lunghezza inviluppo Canale 2</translation> </message> <message> <source>Channel 2 Duty cycle</source> <translation>Duty cycle del Canale 2</translation> </message> <message> <source>Channel 2 Sweep amount</source> <translation>Quantità di sweep Canale 2</translation> </message> <message> <source>Channel 2 Sweep rate</source> <translation>Velocità di sweep Canale 2</translation> </message> <message> <source>Channel 3 Coarse detune</source> <translation>Intonazione grezza Canale 3</translation> </message> <message> <source>Channel 3 Volume</source> <translation>Volume Canale 3</translation> </message> <message> <source>Channel 4 Volume</source> <translation>Volume Canale 4</translation> </message> <message> <source>Channel 4 Envelope length</source> <translation>Lunghezza inviluppo Canale 4</translation> </message> <message> <source>Channel 4 Noise frequency</source> <translation>Frequenza rumore Canale 4</translation> </message> <message> <source>Channel 4 Noise frequency sweep</source> <translation>Frequenza rumore di sweep Canale 4</translation> </message> <message> <source>Master volume</source> <translation>Volume principale</translation> </message> <message> <source>Vibrato</source> <translation>Vibrato</translation> </message> </context> <context> <name>NesInstrumentView</name> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Coarse detune</source> <translation>Intonazione grezza</translation> </message> <message> <source>Envelope length</source> <translation>Lunghezza inviluppo</translation> </message> <message> <source>Enable channel 1</source> <translation>Abilita canale 1</translation> </message> <message> <source>Enable envelope 1</source> <translation>Abilita inviluppo 1</translation> </message> <message> <source>Enable envelope 1 loop</source> <translation>Abilita ripetizione inviluppo 1</translation> </message> <message> <source>Enable sweep 1</source> <translation>Abilita glissando 1</translation> </message> <message> <source>Sweep amount</source> <translation>Profondità glissando</translation> </message> <message> <source>Sweep rate</source> <translation>Durata glissando</translation> </message> <message> <source>12.5% Duty cycle</source> <translation>12.5% del periodo</translation> </message> <message> <source>25% Duty cycle</source> <translation>25% del periodo</translation> </message> <message> <source>50% Duty cycle</source> <translation>50% del periodo</translation> </message> <message> <source>75% Duty cycle</source> <translation>75% del periodo</translation> </message> <message> <source>Enable channel 2</source> <translation>Abilita canale 2</translation> </message> <message> <source>Enable envelope 2</source> <translation>Abilita inviluppo 2</translation> </message> <message> <source>Enable envelope 2 loop</source> <translation>Abilita ripetizione inviluppo 2</translation> </message> <message> <source>Enable sweep 2</source> <translation>Abilita glissando 2</translation> </message> <message> <source>Enable channel 3</source> <translation>Abilita canale 3</translation> </message> <message> <source>Noise Frequency</source> <translation>Frequenza rumore</translation> </message> <message> <source>Frequency sweep</source> <translation>Glissando</translation> </message> <message> <source>Enable channel 4</source> <translation>Abilita canale 4</translation> </message> <message> <source>Enable envelope 4</source> <translation>Abilita inviluppo 4</translation> </message> <message> <source>Enable envelope 4 loop</source> <translation>Abilita ripetizione inviluppo 4</translation> </message> <message> <source>Quantize noise frequency when using note frequency</source> <translation>Quantizza la frequenza del rumore, se relativa alla nota</translation> </message> <message> <source>Use note frequency for noise</source> <translation>La frequenza del rumore è relativa alla nota suonata</translation> </message> <message> <source>Noise mode</source> <translation>Modalità rumore</translation> </message> <message> <source>Master Volume</source> <translation>Volume Principale</translation> </message> <message> <source>Vibrato</source> <translation>Vibrato</translation> </message> </context> <context> <name>OscillatorObject</name> <message> <source>Osc %1 volume</source> <translation>Volume osc %1</translation> </message> <message> <source>Osc %1 panning</source> <translation>Panning osc %1</translation> </message> <message> <source>Osc %1 coarse detuning</source> <translation>Intonazione osc %1</translation> </message> <message> <source>Osc %1 fine detuning left</source> <translation>Intonazione precisa osc %1 sinistra</translation> </message> <message> <source>Osc %1 fine detuning right</source> <translation>Intonazione precisa osc %1 destra</translation> </message> <message> <source>Osc %1 phase-offset</source> <translation>Scostamento fase osc %1</translation> </message> <message> <source>Osc %1 stereo phase-detuning</source> <translation>Intonazione fase stereo osc %1</translation> </message> <message> <source>Osc %1 wave shape</source> <translation>Forma d&apos;onda Osc %1</translation> </message> <message> <source>Modulation type %1</source> <translation>Modulazione di tipo %1</translation> </message> <message> <source>Osc %1 waveform</source> <translation>Forma d&apos;onda osc %1</translation> </message> <message> <source>Osc %1 harmonic</source> <translation>Armoniche Osc %1</translation> </message> </context> <context> <name>PatchesDialog</name> <message> <source>Qsynth: Channel Preset</source> <translation>Qsynth: Preset Canale</translation> </message> <message> <source>Bank selector</source> <translation>Selezione banco</translation> </message> <message> <source>Bank</source> <translation>Banco</translation> </message> <message> <source>Program selector</source> <translation>Selezione programma</translation> </message> <message> <source>Patch</source> <translation>Programma</translation> </message> <message> <source>Name</source> <translation>Nome</translation> </message> <message> <source>OK</source> <translation>OK</translation> </message> <message> <source>Cancel</source> <translation>Annulla</translation> </message> </context> <context> <name>PatmanView</name> <message> <source>Open other patch</source> <translation>Apri un&apos;altra patch</translation> </message> <message> <source>Click here to open another patch-file. Loop and Tune settings are not reset.</source> <translation>Clicca qui per aprire un altro file di patch. Le impostazioni di ripetizione e intonazione non vengono reimpostate.</translation> </message> <message> <source>Loop</source> <translation>Ripetizione</translation> </message> <message> <source>Loop mode</source> <translation>Modalità ripetizione</translation> </message> <message> <source>Here you can toggle the Loop mode. If enabled, PatMan will use the loop information available in the file.</source> <translation>Qui puoi scegliere la modalità di ripetizione. Se abilitata, PatMan userà l&apos;informazione sulla ripetizione disponibile nel file.</translation> </message> <message> <source>Tune</source> <translation>Intonazione</translation> </message> <message> <source>Tune mode</source> <translation>Modalità intonazione</translation> </message> <message> <source>Here you can toggle the Tune mode. If enabled, PatMan will tune the sample to match the note&apos;s frequency.</source> <translation>Qui puoi scegliere la modalità di intonazione. Se abilitata, PatMan intonerà il campione alla frequenza della nota.</translation> </message> <message> <source>No file selected</source> <translation>Nessun file selezionato</translation> </message> <message> <source>Open patch file</source> <translation>Apri file di patch</translation> </message> <message> <source>Patch-Files (*.pat)</source> <translation>File di patch (*.pat)</translation> </message> </context> <context> <name>PatternView</name> <message> <source>Open in piano-roll</source> <translation>Apri nel piano-roll</translation> </message> <message> <source>Clear all notes</source> <translation>Cancella tutte le note</translation> </message> <message> <source>Reset name</source> <translation>Reimposta il nome</translation> </message> <message> <source>Change name</source> <translation>Cambia nome</translation> </message> <message> <source>Add steps</source> <translation>Aggiungi note</translation> </message> <message> <source>Remove steps</source> <translation>Elimina note</translation> </message> <message> <source>Clone Steps</source> <translation>Clona gli step</translation> </message> </context> <context> <name>PeakController</name> <message> <source>Peak Controller</source> <translation>Controller dei picchi</translation> </message> <message> <source>Peak Controller Bug</source> <translation>Bug del controller dei picchi</translation> </message> <message> <source>Due to a bug in older version of LMMS, the peak controllers may not be connect properly. Please ensure that peak controllers are connected properly and re-save this file. Sorry for any inconvenience caused.</source> <translation>A causa di un bug nelle versioni precedenti di LMMS, i controller dei picchi potrebbero non essere connessi come dovuto. Assicurati che i controller dei picchi siano connessi e salva questo file di nuovo. Ci scusiamo per gli inconvenienti causati.</translation> </message> </context> <context> <name>PeakControllerDialog</name> <message> <source>PEAK</source> <translation>PICCO</translation> </message> <message> <source>LFO Controller</source> <translation>Controller dell&apos;LFO</translation> </message> </context> <context> <name>PeakControllerEffectControlDialog</name> <message> <source>BASE</source> <translation>BASE</translation> </message> <message> <source>Base amount:</source> <translation>Quantità di base:</translation> </message> <message> <source>Modulation amount:</source> <translation>Quantità di modulazione:</translation> </message> <message> <source>Attack:</source> <translation>Attacco:</translation> </message> <message> <source>Release:</source> <translation>Rilascio:</translation> </message> <message> <source>AMNT</source> <translation>Q.TÀ</translation> </message> <message> <source>MULT</source> <translation>MOLT</translation> </message> <message> <source>Amount Multiplicator:</source> <translation>Moltiplicatore di quantità:</translation> </message> <message> <source>ATCK</source> <translation>ATCC</translation> </message> <message> <source>DCAY</source> <translation>DCAD</translation> </message> <message> <source>Treshold:</source> <translation>Soglia:</translation> </message> <message> <source>TRSH</source> <translation>SCARTA</translation> </message> </context> <context> <name>PeakControllerEffectControls</name> <message> <source>Base value</source> <translation>Valore di base</translation> </message> <message> <source>Modulation amount</source> <translation>Quantità di modulazione</translation> </message> <message> <source>Mute output</source> <translation>Silenzia l&apos;output</translation> </message> <message> <source>Attack</source> <translation>Attacco</translation> </message> <message> <source>Release</source> <translation>Rilascio</translation> </message> <message> <source>Abs Value</source> <translation>Valore Assoluto</translation> </message> <message> <source>Amount Multiplicator</source> <translation>Moltiplicatore della quantità</translation> </message> <message> <source>Treshold</source> <translation>Soglia</translation> </message> </context> <context> <name>PianoRoll</name> <message> <source>Please open a pattern by double-clicking on it!</source> <translation>Aprire un pattern con un doppio-click sul pattern stesso!</translation> </message> <message> <source>Last note</source> <translation>Ultima nota</translation> </message> <message> <source>Note lock</source> <translation>Note lock</translation> </message> <message> <source>Note Velocity</source> <translation>Volume Note</translation> </message> <message> <source>Note Panning</source> <translation>Panning Note</translation> </message> <message> <source>Mark/unmark current semitone</source> <translation>Evidenza (o togli evidenziazione) questo semitono</translation> </message> <message> <source>Mark current scale</source> <translation>Evidenza la scala corrente</translation> </message> <message> <source>Mark current chord</source> <translation>Evidenza l&apos;accordo corrente</translation> </message> <message> <source>Unmark all</source> <translation>Togli tutte le evidenziazioni</translation> </message> <message> <source>No scale</source> <translation>- Scale</translation> </message> <message> <source>No chord</source> <translation>- Accordi</translation> </message> <message> <source>Velocity: %1%</source> <translation>Velocity: %1%</translation> </message> <message> <source>Panning: %1% left</source> <translation>Bilanciamento: %1% a sinistra</translation> </message> <message> <source>Panning: %1% right</source> <translation>Bilanciamento: %1% a destra</translation> </message> <message> <source>Panning: center</source> <translation>Bilanciamento: centrato</translation> </message> <message> <source>Please enter a new value between %1 and %2:</source> <translation>Inserire un valore compreso tra %1 e %2:</translation> </message> <message> <source>Mark/unmark all corresponding octave semitones</source> <translation>Evidenza (o togli evidenziazione) i semitoni alle altre ottave</translation> </message> <message> <source>Select all notes on this key</source> <translation>Seleziona tutte le note in questo tasto</translation> </message> </context> <context> <name>PianoRollWindow</name> <message> <source>Play/pause current pattern (Space)</source> <translation>Riproduci/metti in pausa il beat/bassline selezionato (Spazio)</translation> </message> <message> <source>Record notes from MIDI-device/channel-piano</source> <translation>Registra note da una periferica/canale piano MIDI</translation> </message> <message> <source>Record notes from MIDI-device/channel-piano while playing song or BB track</source> <translation>Registra note da una periferica MIDI/canale piano mentre la traccia o la BB track è in riproduzione</translation> </message> <message> <source>Stop playing of current pattern (Space)</source> <translation>Riproduci/metti in pausa il beat/bassline selezionato (Spazio)</translation> </message> <message> <source>Click here to play the current pattern. This is useful while editing it. The pattern is automatically looped when its end is reached.</source> <translation>Cliccando qui si riproduce il pattern selezionato. Questo è utile mentre lo si modifica. Il pattern viene automaticamente ripetuto quando finisce.</translation> </message> <message> <source>Click here to record notes from a MIDI-device or the virtual test-piano of the according channel-window to the current pattern. When recording all notes you play will be written to this pattern and you can play and edit them afterwards.</source> <translation>Cliccando qui si registrano nel pattern note da una periferica MIDI o dal piano di prova virtuale nella finestra del canale corrispondente. Mentre si registra, tutte le note eseguite vengono scritte in questo pattern e in seguito le si potrà riprodurre e modificare.</translation> </message> <message> <source>Click here to record notes from a MIDI-device or the virtual test-piano of the according channel-window to the current pattern. When recording all notes you play will be written to this pattern and you will hear the song or BB track in the background.</source> <translation>Cliccando qui si registrano nel pattern note da una periferica MIDI o dal piano di prova virtuale nella finestra del canale corrispondente. Mentre si registra, tutte le note eseguite vengono scritte in questo pattern, sentendo contemporaneamente la canzone o la traccia BB in sottofondo.</translation> </message> <message> <source>Click here to stop playback of current pattern.</source> <translation>Cliccando qui si ferma la riproduzione del pattern attivo.</translation> </message> <message> <source>Draw mode (Shift+D)</source> <translation>Modalità disegno (Shift+D)</translation> </message> <message> <source>Erase mode (Shift+E)</source> <translation>Modalità cancella (Shift+E)</translation> </message> <message> <source>Select mode (Shift+S)</source> <translation>Modalità selezione (Shift+S)</translation> </message> <message> <source>Detune mode (Shift+T)</source> <translation>Modalità intonanzione (Shift+T)</translation> </message> <message> <source>Click here and draw mode will be activated. In this mode you can add, resize and move notes. This is the default mode which is used most of the time. You can also press &apos;Shift+D&apos; on your keyboard to activate this mode. In this mode, hold %1 to temporarily go into select mode.</source> <translation>Cliccando qui si attiva la modalità disegno. In questa modalità è possibile aggiungere e spostare singoli valori. Questa è la modalità predefinita, che viene usata la maggior parte del tempo. Questa modalità si attiva anche premendo la combinazione di tasti &apos;Shift+D&apos;. Tieni premuto %1 per andare temporaneamente in modalità selezione.</translation> </message> <message> <source>Click here and erase mode will be activated. In this mode you can erase notes. You can also press &apos;Shift+E&apos; on your keyboard to activate this mode.</source> <translation>Cliccando qui si attiva la modalità cancellazione. In questa modalità è possibile cancellare singoli valori. Questa modalità si attiva anche premendo la combinazione di tasti &apos;Shift+E&apos;.</translation> </message> <message> <source>Click here and select mode will be activated. In this mode you can select notes. Alternatively, you can hold %1 in draw mode to temporarily use select mode.</source> <translation>Cliccando qui viene attivata la modalità selezione. Puoi selezionare le note. Puoi anche tenere premuto %1 durante la modalità disegno per usare la modalità selezione temporaneamente.</translation> </message> <message> <source>Click here and detune mode will be activated. In this mode you can click a note to open its automation detuning. You can utilize this to slide notes from one to another. You can also press &apos;Shift+T&apos; on your keyboard to activate this mode.</source> <translation>Cliccando qui viene attivata la modalità intonazione. Puoi cliccare una nota per aprire la finestra di automazione dell&apos;intonazione. Puoi usare questa modalità per fare uno slide da una nota ad un&apos;altra. Puoi anche premere Shift+T per attivare questa modalità.</translation> </message> <message> <source>Cut selected notes (%1+X)</source> <translation>Taglia le note selezionate (%1+X)</translation> </message> <message> <source>Copy selected notes (%1+C)</source> <translation>Copia le note selezionate (%1+C)</translation> </message> <message> <source>Paste notes from clipboard (%1+V)</source> <translation>Incolla le note selezionate (%1+V)</translation> </message> <message> <source>Click here and the selected notes will be cut into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation>Cliccando qui le note selezionate verranno spostate negli appunti. È possibile incollarle in un punto qualsiasi del pattern cliccando sul tasto incolla.</translation> </message> <message> <source>Click here and the selected notes will be copied into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation>Cliccando qui le note selezionate verranno copiate negli appunti. È possibile incollarle in un punto qualsiasi del pattern cliccando sul tasto incolla.</translation> </message> <message> <source>Click here and the notes from the clipboard will be pasted at the first visible measure.</source> <translation>Cliccando qui i valori nella clipboard vengono incollati alla prima battuta visibile.</translation> </message> <message> <source>This controls the magnification of an axis. It can be helpful to choose magnification for a specific task. For ordinary editing, the magnification should be fitted to your smallest notes. </source> <translation>Controlla l&apos;ingrandimento di un asse. Normalmente, l&apos;ingrandimento dev&apos;essere adatto alle note più piccole che si sta scrivendo.</translation> </message> <message> <source>The &apos;Q&apos; stands for quantization, and controls the grid size notes and control points snap to. With smaller quantization values, you can draw shorter notes in Piano Roll, and more exact control points in the Automation Editor.</source> <translation>la &apos;Q&apos; sta per quantizzazione, e controlla la lunghezza minima di modifica della nota. Con quantità minori, puoi scrivere note più piccole nel Piano Roll, o punti di controllo più precisi nell&apos;Editor di Automazione.</translation> </message> <message> <source>This lets you select the length of new notes. &apos;Last Note&apos; means that LMMS will use the note length of the note you last edited</source> <translation>Puoi selezionare la grandezza delle nuove note. &apos;Ultima nota&apos; significa che LMMS userà la lunghezza dell&apos;ultima nota modificata</translation> </message> <message> <source>The feature is directly connected to the context-menu on the virtual keyboard, to the left in Piano Roll. After you have chosen the scale you want in this drop-down menu, you can right click on a desired key in the virtual keyboard, and then choose &apos;Mark current Scale&apos;. LMMS will highlight all notes that belongs to the chosen scale, and in the key you have selected!</source> <translation>Questa funzionalità è connessa al menù contestuale della tastiera viruale a sinistra. Dopo aver scelto la scala in questo menù a tendina, puoi cliccare con il tasto destro sulla nota desiderata nella tastiera, e selezionare &apos;Evidenza la scala corrente&apos;. LMMS evidenzierà tutte le note che compongono la scala selezionata partendo dalla nota selezionata come tonica!</translation> </message> <message> <source>Let you select a chord which LMMS then can draw or highlight.You can find the most common chords in this drop-down menu. After you have selected a chord, click anywhere to place the chord, and right click on the virtual keyboard to open context menu and highlight the chord. To return to single note placement, you need to choose &apos;No chord&apos; in this drop-down menu.</source> <translation>Ti permette di selezionare un accordo che LMMS può scriviere o evidenziare. Trovi tutti gli accordi più comuni in questo menù a tendina. Dopo averne selezionato uno, clicca dove vuoi per posizionarlo, oppure fai tasto destro sulla tastiera virtuale per evidenziare l&apos;accordo. Per tornare alla scrittura per singola nota, devi selezionare &apos;Nessuno&apos; in questo menù.</translation> </message> <message> <source>Edit actions</source> <translation>Modalità di modifica</translation> </message> <message> <source>Copy paste controls</source> <translation>Controlli di copia-incolla</translation> </message> <message> <source>Timeline controls</source> <translation>Controlla griglia</translation> </message> <message> <source>Zoom and note controls</source> <translation>Controlli di zoom e note</translation> </message> <message> <source>Piano-Roll - %1</source> <translation>Piano-Roll - %1</translation> </message> <message> <source>Piano-Roll - no pattern</source> <translation>Piano-Roll - nessun pattern</translation> </message> <message> <source>Quantize</source> <translation>Quantizza</translation> </message> </context> <context> <name>PianoView</name> <message> <source>Base note</source> <translation>Nota base</translation> </message> </context> <context> <name>Plugin</name> <message> <source>Plugin not found</source> <translation>Plugin non trovato</translation> </message> <message> <source>The plugin &quot;%1&quot; wasn't found or could not be loaded! Reason: &quot;%2&quot;</source> <translation>Il plugin &quot;%1&quot; non è stato trovato o non è stato possibile caricarlo! Motivo: &quot;%2&quot;</translation> </message> <message> <source>Error while loading plugin</source> <translation>Errore nel caricamento del plugin</translation> </message> <message> <source>Failed to load plugin &quot;%1&quot;!</source> <translation>Non è stato possibile caricare il plugin &quot;%1&quot;!</translation> </message> </context> <context> <name>PluginBrowser</name> <message> <source>Instrument browser</source> <translation>Browser strumenti</translation> </message> <message> <source>Drag an instrument into either the Song-Editor, the Beat+Bassline Editor or into an existing instrument track.</source> <translation>È possibile trascinare uno strumento nel Song-Editor, nel Beat+Bassline Editor o direttamente in un canale esistente.</translation> </message> <message> <source>Instrument Plugins</source> <translation>Plugin Strumentali</translation> </message> </context> <context> <name>PluginFactory</name> <message> <source>Plugin not found.</source> <translation>Plugin non trovato.</translation> </message> <message> <source>LMMS plugin %1 does not have a plugin descriptor named %2!</source> <translation>Il plugin LMMS %1 non ha una descrizione chiamata %2!</translation> </message> </context> <context> <name>ProjectNotes</name> <message> <source>Edit Actions</source> <translation>Modifica azioni</translation> </message> <message> <source>&amp;Undo</source> <translation>&amp;Annulla operazione</translation> </message> <message> <source>%1+Z</source> <translation>%1+Z</translation> </message> <message> <source>&amp;Redo</source> <translation>&amp;Ripeti operazione</translation> </message> <message> <source>%1+Y</source> <translation>%1+Y</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copia</translation> </message> <message> <source>%1+C</source> <translation>%1+C</translation> </message> <message> <source>Cu&amp;t</source> <translation>&amp;Taglia</translation> </message> <message> <source>%1+X</source> <translation>%1+X</translation> </message> <message> <source>&amp;Paste</source> <translation>&amp;Incolla</translation> </message> <message> <source>%1+V</source> <translation>%1+V</translation> </message> <message> <source>Format Actions</source> <translation>Opzioni di formattazione</translation> </message> <message> <source>&amp;Bold</source> <translation>&amp;Grassetto</translation> </message> <message> <source>%1+B</source> <translation>%1+B</translation> </message> <message> <source>&amp;Italic</source> <translation>Cors&amp;ivo</translation> </message> <message> <source>%1+I</source> <translation>%1+I</translation> </message> <message> <source>&amp;Underline</source> <translation>&amp;Sottolineato</translation> </message> <message> <source>%1+U</source> <translation>%1+U</translation> </message> <message> <source>&amp;Left</source> <translation>&amp;Sinistra</translation> </message> <message> <source>%1+L</source> <translation>%1+L</translation> </message> <message> <source>C&amp;enter</source> <translation>C&amp;entro</translation> </message> <message> <source>%1+E</source> <translation>%1+E</translation> </message> <message> <source>&amp;Right</source> <translation>Dest&amp;ra</translation> </message> <message> <source>%1+R</source> <translation>%1+R</translation> </message> <message> <source>&amp;Justify</source> <translation>&amp;Giustifica</translation> </message> <message> <source>%1+J</source> <translation>%1+J</translation> </message> <message> <source>&amp;Color...</source> <translation>&amp;Colore...</translation> </message> <message> <source>Project Notes</source> <translation>Mostra/nascondi le note del progetto</translation> </message> <message> <source>Enter project notes here</source> <translation type="unfinished"/> </message> </context> <context> <name>ProjectRenderer</name> <message> <source>WAV-File (*.wav)</source> <translation>File WAV (*.wav)</translation> </message> <message> <source>Compressed OGG-File (*.ogg)</source> <translation>File in formato OGG compresso (*.ogg)</translation> </message> <message> <source>FLAC-File (*.flac)</source> <translation type="unfinished"/> </message> <message> <source>Compressed MP3-File (*.mp3)</source> <translation type="unfinished"/> </message> </context> <context> <name>QWidget</name> <message> <source>Name: </source> <translation>Nome:</translation> </message> <message> <source>Maker: </source> <translation>Autore:</translation> </message> <message> <source>Copyright: </source> <translation>Copyright:</translation> </message> <message> <source>Requires Real Time: </source> <translation>Richiede Real Time:</translation> </message> <message> <source>Yes</source> <translation>Sì</translation> </message> <message> <source>No</source> <translation>No</translation> </message> <message> <source>Real Time Capable: </source> <translation>Abilitato al Real Time:</translation> </message> <message> <source>In Place Broken: </source> <translation>In Place Broken:</translation> </message> <message> <source>Channels In: </source> <translation>Canali in ingresso:</translation> </message> <message> <source>Channels Out: </source> <translation>Canali in uscita:</translation> </message> <message> <source>File: </source> <translation>File:</translation> </message> <message> <source>File: %1</source> <translation>File: %1</translation> </message> </context> <context> <name>RenameDialog</name> <message> <source>Rename...</source> <translation>Rinomina...</translation> </message> </context> <context> <name>ReverbSCControlDialog</name> <message> <source>Input</source> <translation>Ingresso</translation> </message> <message> <source>Input Gain:</source> <translation>Guadagno in Input:</translation> </message> <message> <source>Size</source> <translation>Grandezza</translation> </message> <message> <source>Size:</source> <translation>Grandezza:</translation> </message> <message> <source>Color</source> <translation>Colore</translation> </message> <message> <source>Color:</source> <translation>Colore:</translation> </message> <message> <source>Output</source> <translation>Uscita</translation> </message> <message> <source>Output Gain:</source> <translation>Guadagno in Output:</translation> </message> </context> <context> <name>ReverbSCControls</name> <message> <source>Input Gain</source> <translation>Guadagno input</translation> </message> <message> <source>Size</source> <translation>Grandezza</translation> </message> <message> <source>Color</source> <translation>Colore</translation> </message> <message> <source>Output Gain</source> <translation>Guadagno output</translation> </message> </context> <context> <name>SampleBuffer</name> <message> <source>Open audio file</source> <translation>Apri file audio</translation> </message> <message> <source>Wave-Files (*.wav)</source> <translation>File wave (*.wav)</translation> </message> <message> <source>OGG-Files (*.ogg)</source> <translation>File OGG (*.ogg)</translation> </message> <message> <source>DrumSynth-Files (*.ds)</source> <translation>File DrumSynth (*.ds)</translation> </message> <message> <source>FLAC-Files (*.flac)</source> <translation>File FLAC (*.flac)</translation> </message> <message> <source>SPEEX-Files (*.spx)</source> <translation>File SPEEX (*.spx)</translation> </message> <message> <source>VOC-Files (*.voc)</source> <translation>File VOC (*.voc)</translation> </message> <message> <source>AIFF-Files (*.aif *.aiff)</source> <translation>File AIFF (*.aif *.aiff)</translation> </message> <message> <source>AU-Files (*.au)</source> <translation>File AU (*.au)</translation> </message> <message> <source>RAW-Files (*.raw)</source> <translation>File RAW (*.raw)</translation> </message> <message> <source>All Audio-Files (*.wav *.ogg *.ds *.flac *.spx *.voc *.aif *.aiff *.au *.raw)</source> <translation>Tutti i file audio (*.wav *.ogg *.ds *.flac *.spx *.voc *.aif *.aiff *.au *.raw)</translation> </message> <message> <source>Fail to open file</source> <translation>Impossibile aprire il file</translation> </message> <message> <source>Audio files are limited to %1 MB in size and %2 minutes of playing time</source> <translation>I file audio hanno un limite di %1 MB in grandezza e %2 minuti in durata</translation> </message> </context> <context> <name>SampleTCOView</name> <message> <source>double-click to select sample</source> <translation>Fare doppio click per selezionare il campione</translation> </message> <message> <source>Delete (middle mousebutton)</source> <translation>Elimina (tasto centrale del mouse)</translation> </message> <message> <source>Cut</source> <translation>Taglia</translation> </message> <message> <source>Copy</source> <translation>Copia</translation> </message> <message> <source>Paste</source> <translation>Incolla</translation> </message> <message> <source>Mute/unmute (&lt;%1&gt; + middle click)</source> <translation>Attiva/disattiva la modalità muta (&lt;%1&gt; + tasto centrale)</translation> </message> </context> <context> <name>SampleTrack</name> <message> <source>Sample track</source> <translation>Traccia di campione</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Panning</source> <translation>Bilanciamento</translation> </message> </context> <context> <name>SampleTrackView</name> <message> <source>Track volume</source> <translation>Volume della traccia</translation> </message> <message> <source>Channel volume:</source> <translation>Volume del canale:</translation> </message> <message> <source>VOL</source> <translation>VOL</translation> </message> <message> <source>Panning</source> <translation>Bilanciamento</translation> </message> <message> <source>Panning:</source> <translation>Bilanciamento:</translation> </message> <message> <source>PAN</source> <translation>BIL</translation> </message> </context> <context> <name>SetupDialog</name> <message> <source>Setup LMMS</source> <translation>Cofigura LMMS</translation> </message> <message> <source>General settings</source> <translation>Impostazioni generali</translation> </message> <message> <source>BUFFER SIZE</source> <translation>DIMENSIONE DEL BUFFER</translation> </message> <message> <source>Reset to default-value</source> <translation>Reimposta al valore predefinito</translation> </message> <message> <source>MISC</source> <translation>VARIE</translation> </message> <message> <source>Enable tooltips</source> <translation>Abilita i suggerimenti</translation> </message> <message> <source>Show restart warning after changing settings</source> <translation>Dopo aver modificato le impostazioni, mostra un avviso al riavvio</translation> </message> <message> <source>Compress project files per default</source> <translation>Per impostazione predefinita, comprimi i file di progetto</translation> </message> <message> <source>One instrument track window mode</source> <translation>Mostra un solo strumento per volta</translation> </message> <message> <source>HQ-mode for output audio-device</source> <translation>Modalità alta qualità per l&apos;uscita audio</translation> </message> <message> <source>Compact track buttons</source> <translation>Pulsanti della traccia compatti</translation> </message> <message> <source>Sync VST plugins to host playback</source> <translation>Sincronizza i plugin VST alla riproduzione del programma</translation> </message> <message> <source>Enable note labels in piano roll</source> <translation>Abilita l&apos;etichetta delle note nel piano roll</translation> </message> <message> <source>Enable waveform display by default</source> <translation>Abilità il display della forma d&apos;onda per default</translation> </message> <message> <source>Keep effects running even without input</source> <translation>Lascia gli effetti attivi anche senza input</translation> </message> <message> <source>Create backup file when saving a project</source> <translation>Crea un file di backup quando salva i progetti</translation> </message> <message> <source>LANGUAGE</source> <translation>LINGUA</translation> </message> <message> <source>Paths</source> <translation>Percorsi</translation> </message> <message> <source>LMMS working directory</source> <translation>Directory di lavoro di LMMS</translation> </message> <message> <source>VST-plugin directory</source> <translation>Directory dei plugin VST</translation> </message> <message> <source>Background artwork</source> <translation>Grafica dello sfondo</translation> </message> <message> <source>STK rawwave directory</source> <translation>Directory per i file rawwave STK</translation> </message> <message> <source>Default Soundfont File</source> <translation>File SoundFont predefinito</translation> </message> <message> <source>Performance settings</source> <translation>Impostazioni prestazioni</translation> </message> <message> <source>UI effects vs. performance</source> <translation>Effetti UI (interfaccia grafica) vs. prestazioni</translation> </message> <message> <source>Smooth scroll in Song Editor</source> <translation>Scorrimento morbido nel Song-Editor</translation> </message> <message> <source>Show playback cursor in AudioFileProcessor</source> <translation>Mostra il cursore di riproduzione dentro AudioFileProcessor</translation> </message> <message> <source>Audio settings</source> <translation>Impostazioni audio</translation> </message> <message> <source>AUDIO INTERFACE</source> <translation>INTERFACCIA AUDIO</translation> </message> <message> <source>MIDI settings</source> <translation>Impostazioni MIDI</translation> </message> <message> <source>MIDI INTERFACE</source> <translation>INTERFACCIA MIDI</translation> </message> <message> <source>OK</source> <translation>OK</translation> </message> <message> <source>Cancel</source> <translation>Annulla</translation> </message> <message> <source>Restart LMMS</source> <translation>Riavvia LMMS</translation> </message> <message> <source>Please note that most changes won&apos;t take effect until you restart LMMS!</source> <translation>Si prega di notare che la maggior parte delle modifiche non avrà effetto fino al riavvio di LMMS!</translation> </message> <message> <source>Frames: %1 Latency: %2 ms</source> <translation>Frames: %1 Latenza: %2 ms</translation> </message> <message> <source>Here you can setup the internal buffer-size used by LMMS. Smaller values result in a lower latency but also may cause unusable sound or bad performance, especially on older computers or systems with a non-realtime kernel.</source> <translation>Qui è possibile impostare la dimensione del buffer interno usato da LMMS. Valori più piccoli danno come risultato una latenza più bassa ma possono causare una qualità audio inutilizzabile o cattive prestazioni, specialmente su computer datati o sistemi con kernel non-realtime.</translation> </message> <message> <source>Choose LMMS working directory</source> <translation>Seleziona la directory di lavoro di LMMS</translation> </message> <message> <source>Choose your VST-plugin directory</source> <translation>Seleziona la directory dei plugin VST</translation> </message> <message> <source>Choose artwork-theme directory</source> <translation>Seleziona la directory del tema grafico</translation> </message> <message> <source>Choose LADSPA plugin directory</source> <translation>Seleziona le directory dei plugin LADSPA</translation> </message> <message> <source>Choose STK rawwave directory</source> <translation>Seleziona le directory dei file rawwave STK</translation> </message> <message> <source>Choose default SoundFont</source> <translation>Scegliere il SoundFont predefinito</translation> </message> <message> <source>Choose background artwork</source> <translation>Scegliere la grafica dello sfondo</translation> </message> <message> <source>Here you can select your preferred audio-interface. Depending on the configuration of your system during compilation time you can choose between ALSA, JACK, OSS and more. Below you see a box which offers controls to setup the selected audio-interface.</source> <translation>Qui è possibile selezionare l&apos;interfaccia audio. A seconda della configurazione del tuo sistema in fase di compilazione puoi scegliere tra ALSA, JACK, OSS e altri. Sotto trovi una casella che offre dei controlli per l&apos;interfaccia audio selezionata.</translation> </message> <message> <source>Here you can select your preferred MIDI-interface. Depending on the configuration of your system during compilation time you can choose between ALSA, OSS and more. Below you see a box which offers controls to setup the selected MIDI-interface.</source> <translation>Qui è possibile selezionare l&apos;interfaccia MIDI. A seconda della configurazione del tuo sistema in fase di compilazione puoi scegliere tra ALSA, OSS e altri. Sotto si trova una casella che offre dei controlli per l&apos;interfaccia MIDI selezionata.</translation> </message> <message> <source>Reopen last project on start</source> <translation>Apri l&apos;ultimo progetto all&apos;avvio</translation> </message> <message> <source>Directories</source> <translation>Percorsi cartelle</translation> </message> <message> <source>Themes directory</source> <translation>Directory del tema grafico</translation> </message> <message> <source>GIG directory</source> <translation>Directory di GIG</translation> </message> <message> <source>SF2 directory</source> <translation>Directory dei SoundFont</translation> </message> <message> <source>LADSPA plugin directories</source> <translation>Directory dei plugin VST</translation> </message> <message> <source>Auto save</source> <translation>Salvataggio automatico</translation> </message> <message> <source>Choose your GIG directory</source> <translation>Selezione la directory di GIG</translation> </message> <message> <source>Choose your SF2 directory</source> <translation>Seleziona la directory dei SoundFont</translation> </message> <message> <source>minutes</source> <translation>minuti</translation> </message> <message> <source>minute</source> <translation>minuto</translation> </message> <message> <source>Display volume as dBFS </source> <translation>Mostra il volume in dBFS</translation> </message> <message> <source>Enable auto-save</source> <translation>Abiita funzione di salvataggio automatico</translation> </message> <message> <source>Allow auto-save while playing</source> <translation>Consenti il salvataggio automatico durante la riproduzione</translation> </message> <message> <source>Disabled</source> <translation>Disabilitato</translation> </message> <message> <source>Auto-save interval: %1</source> <translation>Intervallo di salvataggio automatico: %1</translation> </message> <message> <source>Set the time between automatic backup to %1. Remember to also save your project manually. You can choose to disable saving while playing, something some older systems find difficult.</source> <translation>Imposta il tempo tra i salvataggi automatici a %1. Ricorda di salvare i progetti manualmente. Puoi disabilitare il salvataggio automatico durante la riproduzione, in quanto potrebbe pesare troppo su un sistema datato.</translation> </message> </context> <context> <name>Song</name> <message> <source>Tempo</source> <translation>Tempo</translation> </message> <message> <source>Master volume</source> <translation>Volume principale</translation> </message> <message> <source>Master pitch</source> <translation>Altezza principale</translation> </message> <message> <source>Project saved</source> <translation>Progeto salvato</translation> </message> <message> <source>The project %1 is now saved.</source> <translation>Il progetto %1 è stato salvato.</translation> </message> <message> <source>Project NOT saved.</source> <translation>Il progetto NON è stato salvato.</translation> </message> <message> <source>The project %1 was not saved!</source> <translation>Il progetto %1 non è stato salvato!</translation> </message> <message> <source>Import file</source> <translation>Importa file</translation> </message> <message> <source>MIDI sequences</source> <translation>Sequenze MIDI</translation> </message> <message> <source>Hydrogen projects</source> <translation>Progetti Hydrogen</translation> </message> <message> <source>All file types</source> <translation>Tutti i tipi di file</translation> </message> <message> <source>Empty project</source> <translation>Progetto vuoto</translation> </message> <message> <source>This project is empty so exporting makes no sense. Please put some items into Song Editor first!</source> <translation>Questo progetto è vuoto, pertanto non c&apos;è nulla da esportare. Prima, è necessario inserire alcuni elementi nel Song Editor!</translation> </message> <message> <source>Select directory for writing exported tracks...</source> <translation>Seleziona una directory per le tracce esportate...</translation> </message> <message> <source>untitled</source> <translation>senza_nome</translation> </message> <message> <source>Select file for project-export...</source> <translation>Scegliere il file per l&apos;esportazione del progetto...</translation> </message> <message> <source>The following errors occured while loading: </source> <translation>Errori durante il caricamento:</translation> </message> <message> <source>MIDI File (*.mid)</source> <translation>File MIDI (*.mid)</translation> </message> <message> <source>LMMS Error report</source> <translation>Informazioni sull&apos;errore di LMMS</translation> </message> <message> <source>Save project</source> <translation>Salva progetto</translation> </message> </context> <context> <name>SongEditor</name> <message> <source>Could not open file</source> <translation>Non è stato possibile aprire il file</translation> </message> <message> <source>Could not write file</source> <translation>Impossibile scrivere il file</translation> </message> <message> <source>Could not open file %1. You probably have no permissions to read this file. Please make sure to have at least read permissions to the file and try again.</source> <translation>Impossibile aprire il file %1. Probabilmente non disponi dei permessi necessari alla sua lettura. Assicurati di avere almeno i permessi di lettura del file e prova di nuovo.</translation> </message> <message> <source>Error in file</source> <translation>Errore nel file</translation> </message> <message> <source>The file %1 seems to contain errors and therefore can&apos;t be loaded.</source> <translation>Il file %1 sembra contenere errori, quindi non può essere caricato.</translation> </message> <message> <source>Tempo</source> <translation>Tempo</translation> </message> <message> <source>TEMPO/BPM</source> <translation>TEMPO/BPM</translation> </message> <message> <source>tempo of song</source> <translation>tempo della canzone</translation> </message> <message> <source>The tempo of a song is specified in beats per minute (BPM). If you want to change the tempo of your song, change this value. Every measure has four beats, so the tempo in BPM specifies, how many measures / 4 should be played within a minute (or how many measures should be played within four minutes).</source> <translation>Il tempo della canzone è specificato in battiti al minuto (BPM). Per cambiare il tempo della canzone bisogna cambiare questo valore. Ogni marcatore ha 4 battiti, pertanto il tempo in BPM specifica quanti marcatori / 4 verranno riprodotti in un minuto (o quanti marcatori in 4 minuti).</translation> </message> <message> <source>High quality mode</source> <translation>Modalità ad alta qualità</translation> </message> <message> <source>Master volume</source> <translation>Volume principale</translation> </message> <message> <source>master volume</source> <translation>volume principale</translation> </message> <message> <source>Master pitch</source> <translation>Altezza principale</translation> </message> <message> <source>master pitch</source> <translation>altezza principale</translation> </message> <message> <source>Value: %1%</source> <translation>Valore: %1%</translation> </message> <message> <source>Value: %1 semitones</source> <translation>Valore: %1 semitoni</translation> </message> <message> <source>Could not open %1 for writing. You probably are not permitted to write to this file. Please make sure you have write-access to the file and try again.</source> <translation>Impossibile aprire il file %1 per la scrittura. Probabilmente non disponi dei permessi necessari alla scrittura di questo file. Assicurati di avere tali permessi e prova di nuovo.</translation> </message> <message> <source>template</source> <translation>modello</translation> </message> <message> <source>project</source> <translation>progetto</translation> </message> <message> <source>Version difference</source> <translation>Differenza di versione</translation> </message> <message> <source>This %1 was created with LMMS %2.</source> <translation>%1 creato con LMMS %2.</translation> </message> </context> <context> <name>SongEditorWindow</name> <message> <source>Song-Editor</source> <translation>Song-Editor</translation> </message> <message> <source>Play song (Space)</source> <translation>Riproduci il brano (Spazio)</translation> </message> <message> <source>Record samples from Audio-device</source> <translation>Registra campioni da una periferica audio</translation> </message> <message> <source>Record samples from Audio-device while playing song or BB track</source> <translation>Registra campioni da una periferica audio mentre il brano o una traccia BB sono in riproduzione</translation> </message> <message> <source>Stop song (Space)</source> <translation>Ferma la riproduzione del brano (Spazio)</translation> </message> <message> <source>Add beat/bassline</source> <translation>Aggiungi beat/bassline</translation> </message> <message> <source>Add sample-track</source> <translation>Aggiungi traccia di campione</translation> </message> <message> <source>Add automation-track</source> <translation>Aggiungi una traccia di automazione</translation> </message> <message> <source>Draw mode</source> <translation>Modalità disegno</translation> </message> <message> <source>Edit mode (select and move)</source> <translation>Modalità modifica (seleziona e sposta)</translation> </message> <message> <source>Click here, if you want to play your whole song. Playing will be started at the song-position-marker (green). You can also move it while playing.</source> <translation>Cliccando qui si riproduce l&apos;intero brano. La riproduzione inizierà alla posizione attuale del segnaposto (verde). È possibile spostarlo anche durante la riproduzione.</translation> </message> <message> <source>Click here, if you want to stop playing of your song. The song-position-marker will be set to the start of your song.</source> <translation>Cliccando qui si ferma la riproduzione del brano. Il cursore verrà portato all&apos;inizio della canzone.</translation> </message> <message> <source>Track actions</source> <translation>Azioni sulle tracce</translation> </message> <message> <source>Edit actions</source> <translation>Modalità di modifica</translation> </message> <message> <source>Timeline controls</source> <translation>Controlla griglia</translation> </message> <message> <source>Zoom controls</source> <translation>Opzioni di zoom</translation> </message> </context> <context> <name>SpectrumAnalyzerControlDialog</name> <message> <source>Linear spectrum</source> <translation>Spettro lineare</translation> </message> <message> <source>Linear Y axis</source> <translation>Asse Y lineare</translation> </message> </context> <context> <name>SpectrumAnalyzerControls</name> <message> <source>Linear spectrum</source> <translation>Spettro lineare</translation> </message> <message> <source>Linear Y axis</source> <translation>Asse Y lineare</translation> </message> <message> <source>Channel mode</source> <translation>Modalità del canale</translation> </message> </context> <context> <name>SubWindow</name> <message> <source>Close</source> <translation>Chiudi</translation> </message> <message> <source>Maximize</source> <translation>Massimizza</translation> </message> <message> <source>Restore</source> <translation>Apri</translation> </message> </context> <context> <name>TabWidget</name> <message> <source>Settings for %1</source> <translation>Impostazioni per %1</translation> </message> </context> <context> <name>TempoSyncKnob</name> <message> <source>Tempo Sync</source> <translation>Sync del tempo</translation> </message> <message> <source>No Sync</source> <translation>Non in Sync</translation> </message> <message> <source>Eight beats</source> <translation>Otto battiti</translation> </message> <message> <source>Whole note</source> <translation>Un intero</translation> </message> <message> <source>Half note</source> <translation>Una metà</translation> </message> <message> <source>Quarter note</source> <translation>Quarto</translation> </message> <message> <source>8th note</source> <translation>Ottavo</translation> </message> <message> <source>16th note</source> <translation>Sedicesimo</translation> </message> <message> <source>32nd note</source> <translation>Trentaduesimo</translation> </message> <message> <source>Custom...</source> <translation>Personalizzato...</translation> </message> <message> <source>Custom </source> <translation>Personalizzato</translation> </message> <message> <source>Synced to Eight Beats</source> <translation>In sync con otto battiti</translation> </message> <message> <source>Synced to Whole Note</source> <translation>In sync con un intero</translation> </message> <message> <source>Synced to Half Note</source> <translation>In sync con un mezzo</translation> </message> <message> <source>Synced to Quarter Note</source> <translation>In sync con quarti</translation> </message> <message> <source>Synced to 8th Note</source> <translation>In sync con ottavi</translation> </message> <message> <source>Synced to 16th Note</source> <translation>In sync con 16simi</translation> </message> <message> <source>Synced to 32nd Note</source> <translation>In sync con 32simi</translation> </message> </context> <context> <name>TimeDisplayWidget</name> <message> <source>click to change time units</source> <translation>Clicca per cambiare l&apos;unità di tempo visualizzata</translation> </message> <message> <source>MIN</source> <translation>MIN</translation> </message> <message> <source>SEC</source> <translation>SEC</translation> </message> <message> <source>MSEC</source> <translation>MSEC</translation> </message> <message> <source>BAR</source> <translation>BAR</translation> </message> <message> <source>BEAT</source> <translation>BATT</translation> </message> <message> <source>TICK</source> <translation>TICK</translation> </message> </context> <context> <name>TimeLineWidget</name> <message> <source>Enable/disable auto-scrolling</source> <translation>Abilita/disabilita lo scorrimento automatico</translation> </message> <message> <source>Enable/disable loop-points</source> <translation>Abilita/disabilita i punti di ripetizione</translation> </message> <message> <source>After stopping go back to begin</source> <translation>Una volta fermata la riproduzione, torna all&apos;inizio</translation> </message> <message> <source>After stopping go back to position at which playing was started</source> <translation>Una volta fermata la riproduzione, torna alla posizione da cui si è partiti</translation> </message> <message> <source>After stopping keep position</source> <translation>Una volta fermata la riproduzione, mantieni la posizione</translation> </message> <message> <source>Hint</source> <translation>Suggerimento</translation> </message> <message> <source>Press &lt;%1&gt; to disable magnetic loop points.</source> <translation>Premi &lt;%1&gt; per disabilitare i punti di loop magnetici.</translation> </message> <message> <source>Hold &lt;Shift&gt; to move the begin loop point; Press &lt;%1&gt; to disable magnetic loop points.</source> <translation>Tieni premuto &lt;Shift&gt; per spostare l&apos;inizio del punto di loop; premi &lt;%1&gt; per disabilitare i punti di loop magnetici.</translation> </message> </context> <context> <name>Track</name> <message> <source>Mute</source> <translation>Muto</translation> </message> <message> <source>Solo</source> <translation>Solo</translation> </message> </context> <context> <name>TrackContainer</name> <message> <source>Couldn&apos;t import file</source> <translation>Non è stato possibile importare il file</translation> </message> <message> <source>Couldn't find a filter for importing file %1. You should convert this file into a format supported by LMMS using another software.</source> <translation>Non è stato possibile trovare un filtro per importare il file %1. È necessario convertire questo file in un formato supportato da LMMS usando un altro programma.</translation> </message> <message> <source>Couldn&apos;t open file</source> <translation>Non è stato possibile aprire il file</translation> </message> <message> <source>Couldn't open file %1 for reading. Please make sure you have read-permission to the file and the directory containing the file and try again!</source> <translation>Non è stato possibile aprire il file %1 in lettura. Assicurarsi di avere i permessi in lettura per il file e per la directory che lo contiene e riprovare!</translation> </message> <message> <source>Loading project...</source> <translation>Caricamento del progetto...</translation> </message> <message> <source>Cancel</source> <translation>Annulla</translation> </message> <message> <source>Please wait...</source> <translation>Attendere...</translation> </message> <message> <source>Importing MIDI-file...</source> <translation>Importazione del file MIDI...</translation> </message> <message> <source>Loading Track %1 (%2/Total %3)</source> <translation type="unfinished"/> </message> </context> <context> <name>TrackContentObject</name> <message> <source>Mute</source> <translation>Muto</translation> </message> </context> <context> <name>TrackContentObjectView</name> <message> <source>Current position</source> <translation>Posizione attuale</translation> </message> <message> <source>Hint</source> <translation>Suggerimento</translation> </message> <message> <source>Press &lt;%1&gt; and drag to make a copy.</source> <translation>Premere &lt;%1&gt;, cliccare e trascinare per copiare.</translation> </message> <message> <source>Current length</source> <translation>Lunghezza attuale</translation> </message> <message> <source>Press &lt;%1&gt; for free resizing.</source> <translation>Premere &lt;%1&gt; per ridimensionare liberamente.</translation> </message> <message> <source>%1:%2 (%3:%4 to %5:%6)</source> <translation>%1:%2 (da %3:%4 a %5:%6)</translation> </message> <message> <source>Delete (middle mousebutton)</source> <translation>Elimina (tasto centrale del mouse)</translation> </message> <message> <source>Cut</source> <translation>Taglia</translation> </message> <message> <source>Copy</source> <translation>Copia</translation> </message> <message> <source>Paste</source> <translation>Incolla</translation> </message> <message> <source>Mute/unmute (&lt;%1&gt; + middle click)</source> <translation>Attiva/disattiva la modalità muta (&lt;%1&gt; + tasto centrale)</translation> </message> </context> <context> <name>TrackOperationsWidget</name> <message> <source>Press &lt;%1&gt; while clicking on move-grip to begin a new drag&apos;n&apos;drop-action.</source> <translation>Premere &lt;%1&gt; mentre si clicca sulla maniglia per lo spostamento per iniziare una nuova azione di drag&apos;n&apos;drop.</translation> </message> <message> <source>Actions for this track</source> <translation>Azioni per questa traccia</translation> </message> <message> <source>Mute</source> <translation>Muto</translation> </message> <message> <source>Solo</source> <translation>Solo</translation> </message> <message> <source>Mute this track</source> <translation>Silezia questa traccia</translation> </message> <message> <source>Clone this track</source> <translation>Clona questa traccia</translation> </message> <message> <source>Remove this track</source> <translation>Elimina questa traccia</translation> </message> <message> <source>Clear this track</source> <translation>Pulisci questa traccia</translation> </message> <message> <source>FX %1: %2</source> <translation>FX %1: %2</translation> </message> <message> <source>Turn all recording on</source> <translation>Accendi tutti i processi di registrazione</translation> </message> <message> <source>Turn all recording off</source> <translation>Spegni tutti i processi di registrazione</translation> </message> <message> <source>Assign to new FX Channel</source> <translation>Assegna ad un nuovo canale FX</translation> </message> </context> <context> <name>TripleOscillatorView</name> <message> <source>Use phase modulation for modulating oscillator 1 with oscillator 2</source> <translation>Usare la modulazione di fase per modulare l&apos;oscillatore 2 con l&apos;oscillatore 1</translation> </message> <message> <source>Use amplitude modulation for modulating oscillator 1 with oscillator 2</source> <translation>Usare la modulazione di amplificazione per modulare l&apos;oscillatore 2 con l&apos;oscillatore 1</translation> </message> <message> <source>Mix output of oscillator 1 &amp; 2</source> <translation>Miscelare gli oscillatori 1 e 2</translation> </message> <message> <source>Synchronize oscillator 1 with oscillator 2</source> <translation>Sincronizzare l&apos;oscillatore 1 con l&apos;oscillatore 2</translation> </message> <message> <source>Use frequency modulation for modulating oscillator 1 with oscillator 2</source> <translation>Usare la modulazione di frequenza per modulare l&apos;oscillatore 2 con l&apos;oscillatore 1</translation> </message> <message> <source>Use phase modulation for modulating oscillator 2 with oscillator 3</source> <translation>Usare la modulazione di fase per modulare l&apos;oscillatore 3 con l&apos;oscillatore 2</translation> </message> <message> <source>Use amplitude modulation for modulating oscillator 2 with oscillator 3</source> <translation>Usare la modulazione di amplificazione per modulare l&apos;oscillatore 3 con l&apos;oscillatore 2</translation> </message> <message> <source>Mix output of oscillator 2 &amp; 3</source> <translation>Miscelare gli oscillatori 2 e 3</translation> </message> <message> <source>Synchronize oscillator 2 with oscillator 3</source> <translation>Sincronizzare l&apos;oscillatore 2 con l&apos;oscillatore 3</translation> </message> <message> <source>Use frequency modulation for modulating oscillator 2 with oscillator 3</source> <translation>Usare la modulazione di frequenza per modulare l&apos;oscillatore 3 con l&apos;oscillatore 2</translation> </message> <message> <source>Osc %1 volume:</source> <translation>Volume osc %1:</translation> </message> <message> <source>With this knob you can set the volume of oscillator %1. When setting a value of 0 the oscillator is turned off. Otherwise you can hear the oscillator as loud as you set it here.</source> <translation>Questa manopola regola il volume dell&apos;oscillatore %1. Un valore pari a 0 equivale a un oscillatore spento, gli altri valori impostano il volume corrispondente.</translation> </message> <message> <source>Osc %1 panning:</source> <translation>Panning osc %1:</translation> </message> <message> <source>With this knob you can set the panning of the oscillator %1. A value of -100 means 100% left and a value of 100 moves oscillator-output right.</source> <translation>Questa manopola regola il posizionamento nello spettro stereo dell&apos;oscillatore %1. Un valore pari a -100 significa tutto a sinistra mentre un valore pari a 100 significa tutto a destra.</translation> </message> <message> <source>Osc %1 coarse detuning:</source> <translation>Intonazione dell&apos;osc %1:</translation> </message> <message> <source>semitones</source> <translation>semitoni</translation> </message> <message> <source>With this knob you can set the coarse detuning of oscillator %1. You can detune the oscillator 24 semitones (2 octaves) up and down. This is useful for creating sounds with a chord.</source> <translation>Questa manopola regola l&apos;intonazione, con la precisione di 1 semitono, dell&apos;oscillatore %1. L&apos;intonazione può essere variata di 24 semitoni (due ottave) in positivo e in negativo. Può essere usata per creare suoni con un accordo.</translation> </message> <message> <source>Osc %1 fine detuning left:</source> <translation>Intonazione precisa osc %1 sinistra:</translation> </message> <message> <source>cents</source> <translation>centesimi</translation> </message> <message> <source>With this knob you can set the fine detuning of oscillator %1 for the left channel. The fine-detuning is ranged between -100 cents and +100 cents. This is useful for creating &quot;fat&quot; sounds.</source> <translation>Questa manopola regola l&apos;intonazione precisa dell&apos;oscillatore %1 per il canale sinistro. La gamma per l&apos;intonazione di precisione va da -100 a +100 centesimi. Può essere usata per creare suoni &quot;grossi&quot;.</translation> </message> <message> <source>Osc %1 fine detuning right:</source> <translation>Intonazione precisa dell&apos;osc %1 - destra:</translation> </message> <message> <source>With this knob you can set the fine detuning of oscillator %1 for the right channel. The fine-detuning is ranged between -100 cents and +100 cents. This is useful for creating &quot;fat&quot; sounds.</source> <translation>Questa manopola regola l&apos;intonazione precisa dell&apos;oscillatore %1 per il canale destro. La gamma per l&apos;intonazione di precisione va da -100 a +100 centesimi. Può essere usata per creare suoni &quot;grossi&quot;.</translation> </message> <message> <source>Osc %1 phase-offset:</source> <translation>Scostamento fase dell&apos;osc %1:</translation> </message> <message> <source>degrees</source> <translation>gradi</translation> </message> <message> <source>With this knob you can set the phase-offset of oscillator %1. That means you can move the point within an oscillation where the oscillator begins to oscillate. For example if you have a sine-wave and have a phase-offset of 180 degrees the wave will first go down. It&apos;s the same with a square-wave.</source> <translation>Questa manopola regola lo scostamento della fase dell&apos;oscillatore %1. Ciò significa che è possibile spostare il punto in cui inizia l&apos;oscillazione. Per esempio, un&apos;onda sinusoidale e uno scostamento della fase di 180 gradi, fanno iniziare l&apos;onda scendendo. Lo stesso vale per un&apos;onda quadra.</translation> </message> <message> <source>Osc %1 stereo phase-detuning:</source> <translation>Intonazione fase stereo dell&apos;osc %1:</translation> </message> <message> <source>With this knob you can set the stereo phase-detuning of oscillator %1. The stereo phase-detuning specifies the size of the difference between the phase-offset of left and right channel. This is very good for creating wide stereo sounds.</source> <translation>Questa manopola regola l&apos;intonazione stereo della fase dell&apos;oscillatore %1. L&apos;intonazione stereo della fase specifica la differenza tra lo scostamento della fase del canale sinistro e quello destro. Questo è molto utile per creare suoni con grande ampiezza stereo.</translation> </message> <message> <source>Use a sine-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda sinusoidale per questo oscillatore.</translation> </message> <message> <source>Use a triangle-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda triangolare per questo oscillatore.</translation> </message> <message> <source>Use a saw-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda a dente di sega per questo oscillatore.</translation> </message> <message> <source>Use a square-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda quadra per questo oscillatore.</translation> </message> <message> <source>Use a moog-like saw-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda di tipo moog per questo oscillatore.</translation> </message> <message> <source>Use an exponential wave for current oscillator.</source> <translation>Utilizzare un&apos;onda esponenziale per questo oscillatore.</translation> </message> <message> <source>Use white-noise for current oscillator.</source> <translation>Utilizzare rumore bianco per questo oscillatore.</translation> </message> <message> <source>Use a user-defined waveform for current oscillator.</source> <translation>Utilizzare un&apos;onda personalizzata per questo oscillatore.</translation> </message> </context> <context> <name>VersionedSaveDialog</name> <message> <source>Increment version number</source> <translation>Nuova versione</translation> </message> <message> <source>Decrement version number</source> <translation>Riduci numero versione</translation> </message> <message> <source> already exists. Do you want to replace it?</source> <translation>Esiste già. Vuoi sovrascriverlo?</translation> </message> </context> <context> <name>VestigeInstrumentView</name> <message> <source>Open other VST-plugin</source> <translation>Apri un altro plugin VST</translation> </message> <message> <source>Click here, if you want to open another VST-plugin. After clicking on this button, a file-open-dialog appears and you can select your file.</source> <translation>Clicca qui per aprire un altro plugin VST. Una volta cliccato questo pulsante, si aprirà una finestra di dialogo dove potrai selezionare il file.</translation> </message> <message> <source>Show/hide GUI</source> <translation>Mostra/nascondi l&apos;interfaccia</translation> </message> <message> <source>Click here to show or hide the graphical user interface (GUI) of your VST-plugin.</source> <translation>Clicca qui per mostrare o nascondere l&apos;interfaccia grafica (GUI) per i plugin VST.</translation> </message> <message> <source>Turn off all notes</source> <translation>Disabilita tutte le note</translation> </message> <message> <source>Open VST-plugin</source> <translation>Apri plugin VST</translation> </message> <message> <source>DLL-files (*.dll)</source> <translation>File DLL (*.dll)</translation> </message> <message> <source>EXE-files (*.exe)</source> <translation>File EXE (*.exe)</translation> </message> <message> <source>No VST-plugin loaded</source> <translation>Nessun plugin VST caricato</translation> </message> <message> <source>Control VST-plugin from LMMS host</source> <translation>Controlla il plugin VST dal terminale LMMS</translation> </message> <message> <source>Click here, if you want to control VST-plugin from host.</source> <translation>Cliccando qui, si apre una finestra di LMMS dove è possibile modificare le variabili del plugin VST.</translation> </message> <message> <source>Open VST-plugin preset</source> <translation>Apri un preset del plugin VST</translation> </message> <message> <source>Click here, if you want to open another *.fxp, *.fxb VST-plugin preset.</source> <translation>Cliccando qui, è possibile aprire un altro preset del plugin VST (*fxp, *fxb).</translation> </message> <message> <source>Previous (-)</source> <translation>Precedente (-)</translation> </message> <message> <source>Click here, if you want to switch to another VST-plugin preset program.</source> <translation>Cliccando qui, viene cambiato il preset del plugin VST.</translation> </message> <message> <source>Save preset</source> <translation>Salva il preset</translation> </message> <message> <source>Click here, if you want to save current VST-plugin preset program.</source> <translation>Cliccando qui è possibile salvare il preset corrente del plugin VST.</translation> </message> <message> <source>Next (+)</source> <translation>Successivo (+)</translation> </message> <message> <source>Click here to select presets that are currently loaded in VST.</source> <translation>Cliccando qui, è possibile selezionare i preset che sono caricati nel VST al momento.</translation> </message> <message> <source>Preset</source> <translation>Preset</translation> </message> <message> <source>by </source> <translation>da </translation> </message> <message> <source> - VST plugin control</source> <translation> - Controllo del plugin VST</translation> </message> </context> <context> <name>VisualizationWidget</name> <message> <source>click to enable/disable visualization of master-output</source> <translation>cliccando si abilita/disabilita la visualizzazione dell&apos;uscita principale</translation> </message> <message> <source>Click to enable</source> <translation>Clicca per abilitare</translation> </message> </context> <context> <name>VstEffectControlDialog</name> <message> <source>Show/hide</source> <translation>Mostra/nascondi</translation> </message> <message> <source>Control VST-plugin from LMMS host</source> <translation>Controlla il plugin VST dal terminale LMMS</translation> </message> <message> <source>Click here, if you want to control VST-plugin from host.</source> <translation>Cliccando qui, si apre una finestra di LMMS dove è possibile modificare le variabili del plugin VST.</translation> </message> <message> <source>Open VST-plugin preset</source> <translation>Apri un preset del plugin VST</translation> </message> <message> <source>Click here, if you want to open another *.fxp, *.fxb VST-plugin preset.</source> <translation>Cliccando qui, è possibile aprire un altro preset del plugin VST (*fxp, *fxb).</translation> </message> <message> <source>Previous (-)</source> <translation>Precedente (-)</translation> </message> <message> <source>Click here, if you want to switch to another VST-plugin preset program.</source> <translation>Cliccando qui, viene cambiato il preset del plugin VST.</translation> </message> <message> <source>Next (+)</source> <translation>Successivo (+)</translation> </message> <message> <source>Click here to select presets that are currently loaded in VST.</source> <translation>Cliccando qui, è possibile selezionare i preset che sono caricati nel VST al momento.</translation> </message> <message> <source>Save preset</source> <translation>Salva il preset</translation> </message> <message> <source>Click here, if you want to save current VST-plugin preset program.</source> <translation>Cliccando qui è possibile salvare il preset corrente del plugin VST.</translation> </message> <message> <source>Effect by: </source> <translation>Effetto da: </translation> </message> <message> <source>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;br /&gt;</source> <translation>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;br /&gt;</translation> </message> </context> <context> <name>VstPlugin</name> <message> <source>Loading plugin</source> <translation>Caricamento plugin</translation> </message> <message> <source>Open Preset</source> <translation>Apri preset</translation> </message> <message> <source>Vst Plugin Preset (*.fxp *.fxb)</source> <translation>Preset di plugin VST (*.fxp *.fxb)</translation> </message> <message> <source>: default</source> <translation>: default</translation> </message> <message> <source>&quot;</source> <translation>&quot;</translation> </message> <message> <source>&apos;</source> <translation>&apos;</translation> </message> <message> <source>Save Preset</source> <translation>Salva Preset</translation> </message> <message> <source>.fxp</source> <translation>.fxp</translation> </message> <message> <source>.FXP</source> <translation>.FXP</translation> </message> <message> <source>.FXB</source> <translation>.FXB</translation> </message> <message> <source>.fxb</source> <translation>.fxb</translation> </message> <message> <source>Please wait while loading VST plugin...</source> <translation>Sto caricando il plugin VST...</translation> </message> <message> <source>The VST plugin %1 could not be loaded.</source> <translation>Non è stato possibile caricare il plugin VST %1.</translation> </message> </context> <context> <name>WatsynInstrument</name> <message> <source>Volume A1</source> <translation>Volume A1</translation> </message> <message> <source>Volume A2</source> <translation>Volume A2</translation> </message> <message> <source>Volume B1</source> <translation>Volume B1</translation> </message> <message> <source>Volume B2</source> <translation>Volume B2</translation> </message> <message> <source>Panning A1</source> <translation>Bilanciamento A1</translation> </message> <message> <source>Panning A2</source> <translation>Bilanciamento A2</translation> </message> <message> <source>Panning B1</source> <translation>Bilanciamento B1</translation> </message> <message> <source>Panning B2</source> <translation>Bilanciamento B2</translation> </message> <message> <source>Freq. multiplier A1</source> <translation>Moltiplicatore di freq. A1</translation> </message> <message> <source>Freq. multiplier A2</source> <translation>Moltiplicatore di freq. A2</translation> </message> <message> <source>Freq. multiplier B1</source> <translation>Moltiplicatore di freq. B1</translation> </message> <message> <source>Freq. multiplier B2</source> <translation>Moltiplicatore di freq. B2</translation> </message> <message> <source>Left detune A1</source> <translation>Intonazione Sinistra A1</translation> </message> <message> <source>Left detune A2</source> <translation>Intonazione Sinistra A2</translation> </message> <message> <source>Left detune B1</source> <translation>Intonazione Sinistra B1</translation> </message> <message> <source>Left detune B2</source> <translation>Intonazione Sinistra B2</translation> </message> <message> <source>Right detune A1</source> <translation>Intonazione Destra A1</translation> </message> <message> <source>Right detune A2</source> <translation>Intonazione Destra A2</translation> </message> <message> <source>Right detune B1</source> <translation>Intonazione Destra B1</translation> </message> <message> <source>Right detune B2</source> <translation>Intonazione Destra B2</translation> </message> <message> <source>A-B Mix</source> <translation>Mix A-B</translation> </message> <message> <source>A-B Mix envelope amount</source> <translation>Quantità di inviluppo Mix A-B</translation> </message> <message> <source>A-B Mix envelope attack</source> <translation>Attacco inviluppo Mix A-B</translation> </message> <message> <source>A-B Mix envelope hold</source> <translation>Mantenimento inviluppo Mix A-B</translation> </message> <message> <source>A-B Mix envelope decay</source> <translation>Decadimento inviluppo Mix A-B</translation> </message> <message> <source>A1-B2 Crosstalk</source> <translation>Scambio A1-B2</translation> </message> <message> <source>A2-A1 modulation</source> <translation>Modulazione A2-A1</translation> </message> <message> <source>B2-B1 modulation</source> <translation>Modulazione B2-B1</translation> </message> <message> <source>Selected graph</source> <translation>Grafico selezionato</translation> </message> </context> <context> <name>WatsynView</name> <message> <source>Select oscillator A1</source> <translation>Passa all&apos;oscillatore A1</translation> </message> <message> <source>Select oscillator A2</source> <translation>Passa all&apos;oscillatore A2</translation> </message> <message> <source>Select oscillator B1</source> <translation>Passa all&apos;oscillatore B1</translation> </message> <message> <source>Select oscillator B2</source> <translation>Passa all&apos;oscillatore B2</translation> </message> <message> <source>Mix output of A2 to A1</source> <translation>Mescola output di A2 a A1</translation> </message> <message> <source>Modulate amplitude of A1 with output of A2</source> <translation>Modula l&apos;amplificzione di A1 con l&apos;output di A2</translation> </message> <message> <source>Ring-modulate A1 and A2</source> <translation>Modulazione Ring tra A1 e A2</translation> </message> <message> <source>Modulate phase of A1 with output of A2</source> <translation>Modula la fase di A1 con l&apos;output di A2</translation> </message> <message> <source>Mix output of B2 to B1</source> <translation>Mescola output di B2 a B1</translation> </message> <message> <source>Modulate amplitude of B1 with output of B2</source> <translation>Modula l&apos;amplificzione di B1 con l&apos;output di B2</translation> </message> <message> <source>Ring-modulate B1 and B2</source> <translation>Modulazione Ring tra B1 e B2</translation> </message> <message> <source>Modulate phase of B1 with output of B2</source> <translation>Modula la fase di B1 con l&apos;output di B2</translation> </message> <message> <source>Draw your own waveform here by dragging your mouse on this graph.</source> <translation>Cliccando e trascinando il mouse in questo grafico è possibile disegnare una forma d&apos;onda personalizzata.</translation> </message> <message> <source>Load waveform</source> <translation>Carica forma d&apos;onda</translation> </message> <message> <source>Click to load a waveform from a sample file</source> <translation>Clicca per usare la forma d&apos;onda di un file esterno</translation> </message> <message> <source>Phase left</source> <translation>Sposta fase a sinistra</translation> </message> <message> <source>Click to shift phase by -15 degrees</source> <translation>Clicca per spostare la fase di -15°</translation> </message> <message> <source>Phase right</source> <translation>Sposta fase a destra</translation> </message> <message> <source>Click to shift phase by +15 degrees</source> <translation>Clicca per spostare la fase di +15°</translation> </message> <message> <source>Normalize</source> <translation>Normalizza</translation> </message> <message> <source>Click to normalize</source> <translation>Clicca per normalizzare</translation> </message> <message> <source>Invert</source> <translation>Inverti</translation> </message> <message> <source>Click to invert</source> <translation>Clicca per invertire</translation> </message> <message> <source>Smooth</source> <translation>Ammorbidisci</translation> </message> <message> <source>Click to smooth</source> <translation>Clicca per ammorbidire la forma d&apos;onda</translation> </message> <message> <source>Sine wave</source> <translation>Onda sinusoidale</translation> </message> <message> <source>Click for sine wave</source> <translation>Clicca per rimpiazzare il grafico con una forma d&apos;onda sinusoidale</translation> </message> <message> <source>Triangle wave</source> <translation>Onda triangolare</translation> </message> <message> <source>Click for triangle wave</source> <translation>Clicca per rimpiazzare il grafico con una forma d&apos;onda triangolare</translation> </message> <message> <source>Click for saw wave</source> <translation>Clicca per rimpiazzare il grafico con una forma d&apos;onda a dente si sega</translation> </message> <message> <source>Square wave</source> <translation>Onda quadra</translation> </message> <message> <source>Click for square wave</source> <translation>Clicca per rimpiazzare il grafico con una forma d&apos;onda quadra</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Panning</source> <translation>Bilanciamento</translation> </message> <message> <source>Freq. multiplier</source> <translation>Moltiplicatore freq.</translation> </message> <message> <source>Left detune</source> <translation>Intonazione sinistra</translation> </message> <message> <source> cents</source> <translation>centesimi</translation> </message> <message> <source>Right detune</source> <translation>Intonazione destra</translation> </message> <message> <source>A-B Mix</source> <translation>Mix A-B</translation> </message> <message> <source>Mix envelope amount</source> <translation>Quantità di inviluppo sul Mix</translation> </message> <message> <source>Mix envelope attack</source> <translation>Attacco inviluppo sul Mix</translation> </message> <message> <source>Mix envelope hold</source> <translation>Mantenimento inviluppo sul Mix</translation> </message> <message> <source>Mix envelope decay</source> <translation>Decadimento inviluppo sul Mix</translation> </message> <message> <source>Crosstalk</source> <translation>Scambio</translation> </message> </context> <context> <name>ZynAddSubFxInstrument</name> <message> <source>Portamento</source> <translation>Portamento</translation> </message> <message> <source>Filter Frequency</source> <translation>Frequenza del filtro</translation> </message> <message> <source>Filter Resonance</source> <translation>Risonanza del filtro</translation> </message> <message> <source>Bandwidth</source> <translation>Larghezza di Banda</translation> </message> <message> <source>FM Gain</source> <translation>Guadagno FM</translation> </message> <message> <source>Resonance Center Frequency</source> <translation>Frequenza Centrale di Risonanza</translation> </message> <message> <source>Resonance Bandwidth</source> <translation>Bandwidth di Risonanza</translation> </message> <message> <source>Forward MIDI Control Change Events</source> <translation>Inoltra segnali dai controlli MIDI</translation> </message> </context> <context> <name>ZynAddSubFxView</name> <message> <source>Show GUI</source> <translation>Mostra GUI</translation> </message> <message> <source>Click here to show or hide the graphical user interface (GUI) of ZynAddSubFX.</source> <translation>Clicca qui per mostrare o nascondere l&apos;interfaccia grafica (GUI) di ZynAddSubFX.</translation> </message> <message> <source>Portamento:</source> <translation>Portamento:</translation> </message> <message> <source>PORT</source> <translation>PORT</translation> </message> <message> <source>Filter Frequency:</source> <translation>Frequenza del Filtro:</translation> </message> <message> <source>FREQ</source> <translation>FREQ</translation> </message> <message> <source>Filter Resonance:</source> <translation>Risonanza del Filtro:</translation> </message> <message> <source>RES</source> <translation>RIS</translation> </message> <message> <source>Bandwidth:</source> <translation>Larghezza di banda:</translation> </message> <message> <source>BW</source> <translation>Largh:</translation> </message> <message> <source>FM Gain:</source> <translation>Guadagno FM:</translation> </message> <message> <source>FM GAIN</source> <translation>GUAD FM</translation> </message> <message> <source>Resonance center frequency:</source> <translation>Frequenza Centrale di Risonanza:</translation> </message> <message> <source>RES CF</source> <translation>FC RIS</translation> </message> <message> <source>Resonance bandwidth:</source> <translation>Bandwidth della Risonanza:</translation> </message> <message> <source>RES BW</source> <translation>BW RIS</translation> </message> <message> <source>Forward MIDI Control Changes</source> <translation>Inoltra cambiamenti dai controlli MIDI</translation> </message> </context> <context> <name>audioFileProcessor</name> <message> <source>Amplify</source> <translation>Amplificazione</translation> </message> <message> <source>Start of sample</source> <translation>Inizio del campione</translation> </message> <message> <source>End of sample</source> <translation>Fine del campione</translation> </message> <message> <source>Reverse sample</source> <translation>Inverti il campione</translation> </message> <message> <source>Stutter</source> <translation>Passaggio</translation> </message> <message> <source>Loopback point</source> <translation>Punto di LoopBack</translation> </message> <message> <source>Loop mode</source> <translation>Modalità ripetizione</translation> </message> <message> <source>Interpolation mode</source> <translation>Modalità Interpolazione</translation> </message> <message> <source>None</source> <translation>Nessuna</translation> </message> <message> <source>Linear</source> <translation>Lineare</translation> </message> <message> <source>Sinc</source> <translation>Sincronizzata</translation> </message> <message> <source>Sample not found: %1</source> <translation>Campione non trovato: %1</translation> </message> </context> <context> <name>bitInvader</name> <message> <source>Samplelength</source> <translation>LunghezzaCampione</translation> </message> </context> <context> <name>bitInvaderView</name> <message> <source>Sample Length</source> <translation>Lunghezza del campione</translation> </message> <message> <source>Sine wave</source> <translation>Onda sinusoidale</translation> </message> <message> <source>Triangle wave</source> <translation>Onda triangolare</translation> </message> <message> <source>Saw wave</source> <translation>Onda a dente di sega</translation> </message> <message> <source>Square wave</source> <translation>Onda quadra</translation> </message> <message> <source>White noise wave</source> <translation>Rumore bianco</translation> </message> <message> <source>User defined wave</source> <translation>Forma d&apos;onda personalizzata</translation> </message> <message> <source>Smooth</source> <translation>Ammorbidisci</translation> </message> <message> <source>Click here to smooth waveform.</source> <translation>Cliccando qui la forma d&apos;onda viene ammorbidita.</translation> </message> <message> <source>Interpolation</source> <translation>Interpolazione</translation> </message> <message> <source>Normalize</source> <translation>Normalizza</translation> </message> <message> <source>Draw your own waveform here by dragging your mouse on this graph.</source> <translation>Cliccando e trascinando il mouse in questo grafico è possibile disegnare una forma d&apos;onda personalizzata.</translation> </message> <message> <source>Click for a sine-wave.</source> <translation>Cliccando qui si ottiene una forma d&apos;onda sinusoidale.</translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda triangolare.</translation> </message> <message> <source>Click here for a saw-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda a dente di sega.</translation> </message> <message> <source>Click here for a square-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda quadra.</translation> </message> <message> <source>Click here for white-noise.</source> <translation>Cliccando qui si ottiene rumore bianco.</translation> </message> <message> <source>Click here for a user-defined shape.</source> <translation>Cliccando qui è possibile definire una forma d&apos;onda personalizzata.</translation> </message> </context> <context> <name>dynProcControlDialog</name> <message> <source>INPUT</source> <translation>INPUT</translation> </message> <message> <source>Input gain:</source> <translation>Guadagno in Input:</translation> </message> <message> <source>OUTPUT</source> <translation>OUTPUT</translation> </message> <message> <source>Output gain:</source> <translation>Guadagno in Output:</translation> </message> <message> <source>ATTACK</source> <translation>ATTACCO</translation> </message> <message> <source>Peak attack time:</source> <translation>Attacco del picco:</translation> </message> <message> <source>RELEASE</source> <translation>RILASCIO</translation> </message> <message> <source>Peak release time:</source> <translation>Rilascio del picco:</translation> </message> <message> <source>Reset waveform</source> <translation>Resetta forma d&apos;onda</translation> </message> <message> <source>Click here to reset the wavegraph back to default</source> <translation>Clicca per riportare la forma d&apos;onda allo stato originale</translation> </message> <message> <source>Smooth waveform</source> <translation>Ammorbidisci forma d&apos;onda</translation> </message> <message> <source>Click here to apply smoothing to wavegraph</source> <translation>Clicca per ammorbidire la forma d&apos;onda</translation> </message> <message> <source>Increase wavegraph amplitude by 1dB</source> <translation>Aumenta l&apos;amplificazione di 1dB</translation> </message> <message> <source>Click here to increase wavegraph amplitude by 1dB</source> <translation>Clicca per aumentare l&apos;amplificazione del grafico d&apos;onda di 1dB</translation> </message> <message> <source>Decrease wavegraph amplitude by 1dB</source> <translation>Diminuisci l&apos;amplificazione di 1dB</translation> </message> <message> <source>Click here to decrease wavegraph amplitude by 1dB</source> <translation>Clicca qui per diminuire l&apos;amplificazione del grafico d&apos;onda di 1dB</translation> </message> <message> <source>Stereomode Maximum</source> <translation>Modalità stereo: Massimo</translation> </message> <message> <source>Process based on the maximum of both stereo channels</source> <translation>L&apos;effetto si basa sul valore massimo tra i due canali stereo</translation> </message> <message> <source>Stereomode Average</source> <translation>Modalità stereo: Media</translation> </message> <message> <source>Process based on the average of both stereo channels</source> <translation>L&apos;effetto si basa sul valore medio tra i due canali stereo</translation> </message> <message> <source>Stereomode Unlinked</source> <translation>Modalità stereo: Indipendenti</translation> </message> <message> <source>Process each stereo channel independently</source> <translation>L&apos;effetto tratta i due canali stereo indipendentemente</translation> </message> </context> <context> <name>dynProcControls</name> <message> <source>Input gain</source> <translation>Guadagno in input</translation> </message> <message> <source>Output gain</source> <translation>Guadagno in output</translation> </message> <message> <source>Attack time</source> <translation>Tempo di Attacco</translation> </message> <message> <source>Release time</source> <translation>Tempo di Rilascio</translation> </message> <message> <source>Stereo mode</source> <translation>Modalità stereo</translation> </message> </context> <context> <name>expressiveView</name> <message> <source>Select oscillator W1</source> <translation type="unfinished"/> </message> <message> <source>Select oscillator W2</source> <translation type="unfinished"/> </message> <message> <source>Select oscillator W3</source> <translation type="unfinished"/> </message> <message> <source>Select OUTPUT 1</source> <translation type="unfinished"/> </message> <message> <source>Select OUTPUT 2</source> <translation type="unfinished"/> </message> <message> <source>Open help window</source> <translation type="unfinished"/> </message> <message> <source>Sine wave</source> <translation>Onda sinusoidale</translation> </message> <message> <source>Click for a sine-wave.</source> <translation>Cliccando qui si ottiene una forma d&apos;onda sinusoidale.</translation> </message> <message> <source>Moog-Saw wave</source> <translation type="unfinished"/> </message> <message> <source>Click for a Moog-Saw-wave.</source> <translation type="unfinished"/> </message> <message> <source>Exponential wave</source> <translation>Onda esponenziale</translation> </message> <message> <source>Click for an exponential wave.</source> <translation type="unfinished"/> </message> <message> <source>Saw wave</source> <translation>Onda a dente di sega</translation> </message> <message> <source>Click here for a saw-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda a dente di sega.</translation> </message> <message> <source>User defined wave</source> <translation>Forma d&apos;onda personalizzata</translation> </message> <message> <source>Click here for a user-defined shape.</source> <translation>Cliccando qui è possibile definire una forma d&apos;onda personalizzata.</translation> </message> <message> <source>Triangle wave</source> <translation>Onda triangolare</translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda triangolare.</translation> </message> <message> <source>Square wave</source> <translation>Onda quadra</translation> </message> <message> <source>Click here for a square-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda quadra.</translation> </message> <message> <source>White noise wave</source> <translation>Rumore bianco</translation> </message> <message> <source>Click here for white-noise.</source> <translation>Cliccando qui si ottiene rumore bianco.</translation> </message> <message> <source>WaveInterpolate</source> <translation type="unfinished"/> </message> <message> <source>ExpressionValid</source> <translation type="unfinished"/> </message> <message> <source>General purpose 1:</source> <translation type="unfinished"/> </message> <message> <source>General purpose 2:</source> <translation type="unfinished"/> </message> <message> <source>General purpose 3:</source> <translation type="unfinished"/> </message> <message> <source>O1 panning:</source> <translation type="unfinished"/> </message> <message> <source>O2 panning:</source> <translation type="unfinished"/> </message> <message> <source>Release transition:</source> <translation type="unfinished"/> </message> <message> <source>Smoothness</source> <translation type="unfinished"/> </message> </context> <context> <name>fxLineLcdSpinBox</name> <message> <source>Assign to:</source> <translation>Assegna a:</translation> </message> <message> <source>New FX Channel</source> <translation>Nuovo canale FX</translation> </message> </context> <context> <name>graphModel</name> <message> <source>Graph</source> <translation>Grafico</translation> </message> </context> <context> <name>kickerInstrument</name> <message> <source>Start frequency</source> <translation>Frequenza iniziale</translation> </message> <message> <source>End frequency</source> <translation>Frequenza finale</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>Length</source> <translation>Lunghezza</translation> </message> <message> <source>Distortion Start</source> <translation>Distorsione iniziale</translation> </message> <message> <source>Distortion End</source> <translation>Distorsione finale</translation> </message> <message> <source>Envelope Slope</source> <translation>Inclinazione Inviluppo</translation> </message> <message> <source>Noise</source> <translation>Rumore</translation> </message> <message> <source>Click</source> <translation>Click</translation> </message> <message> <source>Frequency Slope</source> <translation>Inclinazione Frequenza</translation> </message> <message> <source>Start from note</source> <translation>Inizia dalla nota</translation> </message> <message> <source>End to note</source> <translation>Finisci sulla nota</translation> </message> </context> <context> <name>kickerInstrumentView</name> <message> <source>Start frequency:</source> <translation>Frequenza iniziale:</translation> </message> <message> <source>End frequency:</source> <translation>Frequenza finale:</translation> </message> <message> <source>Gain:</source> <translation>Guadagno:</translation> </message> <message> <source>Frequency Slope:</source> <translation>Inclinazione Frequenza:</translation> </message> <message> <source>Envelope Length:</source> <translation>Lunghezza Inviluppo:</translation> </message> <message> <source>Envelope Slope:</source> <translation>Inclinazione Inviluppo:</translation> </message> <message> <source>Click:</source> <translation>Click:</translation> </message> <message> <source>Noise:</source> <translation>Rumore:</translation> </message> <message> <source>Distortion Start:</source> <translation>Distorsione iniziale:</translation> </message> <message> <source>Distortion End:</source> <translation>Distorsione finale:</translation> </message> </context> <context> <name>ladspaBrowserView</name> <message> <source>Available Effects</source> <translation>Effetti disponibili</translation> </message> <message> <source>Unavailable Effects</source> <translation>Effetti non disponibili</translation> </message> <message> <source>Instruments</source> <translation>Strumenti</translation> </message> <message> <source>Analysis Tools</source> <translation>Strumenti di analisi</translation> </message> <message> <source>Don&apos;t know</source> <translation>Sconosciuto</translation> </message> <message> <source>This dialog displays information on all of the LADSPA plugins LMMS was able to locate. The plugins are divided into five categories based upon an interpretation of the port types and names. Available Effects are those that can be used by LMMS. In order for LMMS to be able to use an effect, it must, first and foremost, be an effect, which is to say, it has to have both input channels and output channels. LMMS identifies an input channel as an audio rate port containing 'in' in the name. Output channels are identified by the letters 'out'. Furthermore, the effect must have the same number of inputs and outputs and be real time capable. Unavailable Effects are those that were identified as effects, but either didn't have the same number of input and output channels or weren't real time capable. Instruments are plugins for which only output channels were identified. Analysis Tools are plugins for which only input channels were identified. Don't Knows are plugins for which no input or output channels were identified. Double clicking any of the plugins will bring up information on the ports.</source> <translation>Questa finestra mostra le informazioni relative ai plugin LADSPA che LMMS è stato in grado di localizzare. I plugin sono divisi in cinque categorie, in base all&apos;interpretazione dei tipi di porta e ai nomi. Gli Effetti Disponibili sono quelli che possono essere usati con LMMS. Perché LMMS possa usare un effetto deve, prima di tutto, essere un effetto, cioè deve avere sia ingressi che uscite. LMMS identifica un ingresso come una porta con una frequenza audio associata e che contiene &apos;in&apos; nel nome. Le uscite sono identificate dalle lettere &apos;out&apos;. Inoltre, l&apos;effetto deve avere lo stesso numero di ingressi e di uscite e deve poter funzionare in real time. Gli Effetti non Disponibili sono quelli che sono stati identificati come effetti ma che non hanno lo stesso numero di ingressi e uscite oppure non supportano il real time. Gli Strumenti sono plugin che hanno solo uscite. Gli Strumenti di Analisi sono plugin che hanno solo ingressi. Quelli Sconosciuti sono plugin che non hanno né ingressi né uscite. Facendo doppio click sui plugin verranno fornite informazioni sulle relative porte.</translation> </message> <message> <source>Type:</source> <translation>Tipo:</translation> </message> </context> <context> <name>ladspaDescription</name> <message> <source>Plugins</source> <translation>Plugin</translation> </message> <message> <source>Description</source> <translation>Descrizione</translation> </message> </context> <context> <name>ladspaPortDialog</name> <message> <source>Ports</source> <translation>Porte</translation> </message> <message> <source>Name</source> <translation>Nome</translation> </message> <message> <source>Rate</source> <translation>Frequenza</translation> </message> <message> <source>Direction</source> <translation>Direzione</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Min &lt; Default &lt; Max</source> <translation>Minimo &lt; Predefinito &lt; Massimo</translation> </message> <message> <source>Logarithmic</source> <translation>Logaritmico</translation> </message> <message> <source>SR Dependent</source> <translation>Dipendente da SR</translation> </message> <message> <source>Audio</source> <translation>Audio</translation> </message> <message> <source>Control</source> <translation>Controllo</translation> </message> <message> <source>Input</source> <translation>Ingresso</translation> </message> <message> <source>Output</source> <translation>Uscita</translation> </message> <message> <source>Toggled</source> <translation>Abilitato</translation> </message> <message> <source>Integer</source> <translation>Intero</translation> </message> <message> <source>Float</source> <translation>Virgola mobile</translation> </message> <message> <source>Yes</source> <translation>Sì</translation> </message> </context> <context> <name>lb302Synth</name> <message> <source>VCF Cutoff Frequency</source> <translation>VCF - frequenza di taglio</translation> </message> <message> <source>VCF Resonance</source> <translation>VCF - Risonanza</translation> </message> <message> <source>VCF Envelope Mod</source> <translation>VCF - modulazione dell&apos;envelope</translation> </message> <message> <source>VCF Envelope Decay</source> <translation>VCF - decadimento dell&apos;envelope</translation> </message> <message> <source>Distortion</source> <translation>Distorsione</translation> </message> <message> <source>Waveform</source> <translation>Forma d&apos;onda</translation> </message> <message> <source>Slide Decay</source> <translation>Decadimento slide</translation> </message> <message> <source>Slide</source> <translation>Slide</translation> </message> <message> <source>Accent</source> <translation>Accento</translation> </message> <message> <source>Dead</source> <translation>Dead</translation> </message> <message> <source>24dB/oct Filter</source> <translation>Filtro 24dB/ottava</translation> </message> </context> <context> <name>lb302SynthView</name> <message> <source>Cutoff Freq:</source> <translation>Freq. di taglio:</translation> </message> <message> <source>Resonance:</source> <translation>Risonanza:</translation> </message> <message> <source>Env Mod:</source> <translation>Env Mod:</translation> </message> <message> <source>Decay:</source> <translation>Decadimento:</translation> </message> <message> <source>303-es-que, 24dB/octave, 3 pole filter</source> <translation>filtro tripolare &quot;tipo 303&quot;, 24dB/ottava</translation> </message> <message> <source>Slide Decay:</source> <translation>Decadimento slide:</translation> </message> <message> <source>DIST:</source> <translation>DIST:</translation> </message> <message> <source>Saw wave</source> <translation>Onda a dente di sega</translation> </message> <message> <source>Click here for a saw-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda a dente di sega.</translation> </message> <message> <source>Triangle wave</source> <translation>Onda triangolare</translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda triangolare.</translation> </message> <message> <source>Square wave</source> <translation>Onda quadra</translation> </message> <message> <source>Click here for a square-wave.</source> <translation>Cliccando qui si ottiene un&apos;onda quadra.</translation> </message> <message> <source>Rounded square wave</source> <translation>Onda quadra arrotondata</translation> </message> <message> <source>Click here for a square-wave with a rounded end.</source> <translation>Cliccando qui si ottiene un&apos;onda quadra arrotondata.</translation> </message> <message> <source>Moog wave</source> <translation>Onda moog</translation> </message> <message> <source>Click here for a moog-like wave.</source> <translation>Cliccando qui si ottieme un&apos;onda moog.</translation> </message> <message> <source>Sine wave</source> <translation>Onda sinusoidale</translation> </message> <message> <source>Click for a sine-wave.</source> <translation>Cliccando qui si ottiene una forma d&apos;onda sinusoidale.</translation> </message> <message> <source>White noise wave</source> <translation>Rumore bianco</translation> </message> <message> <source>Click here for an exponential wave.</source> <translation>Cliccando qui si ha un&apos;onda esponenziale.</translation> </message> <message> <source>Click here for white-noise.</source> <translation>Cliccando qui si ottiene rumore bianco.</translation> </message> <message> <source>Bandlimited saw wave</source> <translation>Onda a dente di sega limitata</translation> </message> <message> <source>Click here for bandlimited saw wave.</source> <translation>Clicca per usare un&apos;onda a dente di sega a banda limitata.</translation> </message> <message> <source>Bandlimited square wave</source> <translation>Onda quadra limitata</translation> </message> <message> <source>Click here for bandlimited square wave.</source> <translation>Clicca per usare un&apos;onda quadra a banda limitata.</translation> </message> <message> <source>Bandlimited triangle wave</source> <translation>Onda triangolare limitata</translation> </message> <message> <source>Click here for bandlimited triangle wave.</source> <translation>Clicca per usare un&apos;onda triangolare a banda limitata.</translation> </message> <message> <source>Bandlimited moog saw wave</source> <translation>Onda Moog limitata</translation> </message> <message> <source>Click here for bandlimited moog saw wave.</source> <translation>Clicca per usare un&apos;onda Moog a banda limitata.</translation> </message> </context> <context> <name>malletsInstrument</name> <message> <source>Hardness</source> <translation>Durezza</translation> </message> <message> <source>Position</source> <translation>Posizione</translation> </message> <message> <source>Vibrato Gain</source> <translation>Guadagno del vibrato</translation> </message> <message> <source>Vibrato Freq</source> <translation>Fequenza del vibrato</translation> </message> <message> <source>Stick Mix</source> <translation>Stick Mix</translation> </message> <message> <source>Modulator</source> <translation>Modulatore</translation> </message> <message> <source>Crossfade</source> <translation>Crossfade</translation> </message> <message> <source>LFO Speed</source> <translation>Velocità dell&apos;LFO</translation> </message> <message> <source>LFO Depth</source> <translation>Profondità dell&apos;LFO</translation> </message> <message> <source>ADSR</source> <translation>ADSR</translation> </message> <message> <source>Pressure</source> <translation>Pressione</translation> </message> <message> <source>Motion</source> <translation>Moto</translation> </message> <message> <source>Speed</source> <translation>Velocità</translation> </message> <message> <source>Bowed</source> <translation>Bowed</translation> </message> <message> <source>Spread</source> <translation>Apertura</translation> </message> <message> <source>Marimba</source> <translation>Marimba</translation> </message> <message> <source>Vibraphone</source> <translation>Vibraphone</translation> </message> <message> <source>Agogo</source> <translation>Agogo</translation> </message> <message> <source>Wood1</source> <translation>Legno1</translation> </message> <message> <source>Reso</source> <translation>Reso</translation> </message> <message> <source>Wood2</source> <translation>Legno2</translation> </message> <message> <source>Beats</source> <translation>Beats</translation> </message> <message> <source>Two Fixed</source> <translation>Two Fixed</translation> </message> <message> <source>Clump</source> <translation>Clump</translation> </message> <message> <source>Tubular Bells</source> <translation>Tubular Bells</translation> </message> <message> <source>Uniform Bar</source> <translation>Uniform Bar</translation> </message> <message> <source>Tuned Bar</source> <translation>Tuned Bar</translation> </message> <message> <source>Glass</source> <translation>Glass</translation> </message> <message> <source>Tibetan Bowl</source> <translation>Tibetan Bowl</translation> </message> </context> <context> <name>malletsInstrumentView</name> <message> <source>Instrument</source> <translation>Strumento</translation> </message> <message> <source>Spread</source> <translation>Apertura</translation> </message> <message> <source>Spread:</source> <translation>Apertura:</translation> </message> <message> <source>Hardness</source> <translation>Durezza</translation> </message> <message> <source>Hardness:</source> <translation>Durezza:</translation> </message> <message> <source>Position</source> <translation>Posizione</translation> </message> <message> <source>Position:</source> <translation>Posizione:</translation> </message> <message> <source>Vib Gain</source> <translation>Guad Vib</translation> </message> <message> <source>Vib Gain:</source> <translation>Guad Vib:</translation> </message> <message> <source>Vib Freq</source> <translation>Freq Vib</translation> </message> <message> <source>Vib Freq:</source> <translation>Freq Vib:</translation> </message> <message> <source>Stick Mix</source> <translation>Stick Mix</translation> </message> <message> <source>Stick Mix:</source> <translation>Stick Mix:</translation> </message> <message> <source>Modulator</source> <translation>Modulatore</translation> </message> <message> <source>Modulator:</source> <translation>Modulatore:</translation> </message> <message> <source>Crossfade</source> <translation>Crossfade</translation> </message> <message> <source>Crossfade:</source> <translation>Crossfade:</translation> </message> <message> <source>LFO Speed</source> <translation>Velocità LFO</translation> </message> <message> <source>LFO Speed:</source> <translation>Velocità LFO:</translation> </message> <message> <source>LFO Depth</source> <translation>Profondità LFO</translation> </message> <message> <source>LFO Depth:</source> <translation>Profondità LFO:</translation> </message> <message> <source>ADSR</source> <translation>ADSR</translation> </message> <message> <source>ADSR:</source> <translation>ADSR:</translation> </message> <message> <source>Pressure</source> <translation>Pressione</translation> </message> <message> <source>Pressure:</source> <translation>Pressione:</translation> </message> <message> <source>Speed</source> <translation>Velocità</translation> </message> <message> <source>Speed:</source> <translation>Velocità:</translation> </message> <message> <source>Missing files</source> <translation>File mancanti</translation> </message> <message> <source>Your Stk-installation seems to be incomplete. Please make sure the full Stk-package is installed!</source> <translation>L&apos;installazione di Stk sembra incompleta. Assicurarsi che sia installato il pacchetto Stk completo!</translation> </message> </context> <context> <name>manageVSTEffectView</name> <message> <source> - VST parameter control</source> <translation> - Controllo parametri VST</translation> </message> <message> <source>VST Sync</source> <translation>Sync VST</translation> </message> <message> <source>Click here if you want to synchronize all parameters with VST plugin.</source> <translation>Clicca qui se vuoi sincronizzare tutti i parametri con il plugin VST.</translation> </message> <message> <source>Automated</source> <translation>Automatizzati</translation> </message> <message> <source>Click here if you want to display automated parameters only.</source> <translation>Clicca qui se vuoi visualizzare solo i parametri automatizzati.</translation> </message> <message> <source> Close </source> <translation> Chiudi </translation> </message> <message> <source>Close VST effect knob-controller window.</source> <translation>Chiudi la finestra delle manopole dell&apos;effetto VST.</translation> </message> </context> <context> <name>manageVestigeInstrumentView</name> <message> <source> - VST plugin control</source> <translation> - Controllo del plugin VST</translation> </message> <message> <source>VST Sync</source> <translation>Sync VST</translation> </message> <message> <source>Click here if you want to synchronize all parameters with VST plugin.</source> <translation>Clicca qui se vuoi sincronizzare tutti i parametri con il plugin VST.</translation> </message> <message> <source>Automated</source> <translation>Automatizzati</translation> </message> <message> <source>Click here if you want to display automated parameters only.</source> <translation>Clicca qui se vuoi visualizzare solo i parametri automatizzati.</translation> </message> <message> <source> Close </source> <translation> Chiudi </translation> </message> <message> <source>Close VST plugin knob-controller window.</source> <translation>Chiudi la finestra delle manopole del plugin VST.</translation> </message> </context> <context> <name>opl2instrument</name> <message> <source>Patch</source> <translation>Patch</translation> </message> <message> <source>Op 1 Attack</source> <translation>Attacco Op 1</translation> </message> <message> <source>Op 1 Decay</source> <translation>Decadimento Op 1</translation> </message> <message> <source>Op 1 Sustain</source> <translation>Sostegno Op 1</translation> </message> <message> <source>Op 1 Release</source> <translation>Rilascio Op 1</translation> </message> <message> <source>Op 1 Level</source> <translation>Livello Op 1</translation> </message> <message> <source>Op 1 Level Scaling</source> <translation>Scala di livello Op 1</translation> </message> <message> <source>Op 1 Frequency Multiple</source> <translation>Moltiplicatore di frequenza Op 1</translation> </message> <message> <source>Op 1 Feedback</source> <translation>Feedback Op 1</translation> </message> <message> <source>Op 1 Key Scaling Rate</source> <translation>Rateo del Key Scaling Op 1</translation> </message> <message> <source>Op 1 Percussive Envelope</source> <translation>Envelope a percussione Op 1</translation> </message> <message> <source>Op 1 Tremolo</source> <translation>Tremolo Op 1</translation> </message> <message> <source>Op 1 Vibrato</source> <translation>Vibrato Op 1</translation> </message> <message> <source>Op 1 Waveform</source> <translation>Forma d&apos;onda Op 1</translation> </message> <message> <source>Op 2 Attack</source> <translation>Attacco Op 2</translation> </message> <message> <source>Op 2 Decay</source> <translation>Decadimento Op 2</translation> </message> <message> <source>Op 2 Sustain</source> <translation>Sostegno Op 2</translation> </message> <message> <source>Op 2 Release</source> <translation>Rilascio Op 2</translation> </message> <message> <source>Op 2 Level</source> <translation>Livello Op 2</translation> </message> <message> <source>Op 2 Level Scaling</source> <translation>Scala di livello Op 2</translation> </message> <message> <source>Op 2 Frequency Multiple</source> <translation>Moltiplicatore di frequenza Op 2</translation> </message> <message> <source>Op 2 Key Scaling Rate</source> <translation>Rateo del Key Scaling Op 2</translation> </message> <message> <source>Op 2 Percussive Envelope</source> <translation>Envelope a percussione Op 2</translation> </message> <message> <source>Op 2 Tremolo</source> <translation>Tremolo Op 2</translation> </message> <message> <source>Op 2 Vibrato</source> <translation>Vibrato Op 2</translation> </message> <message> <source>Op 2 Waveform</source> <translation>Forma d&apos;onda Op 2</translation> </message> <message> <source>FM</source> <translation>FM</translation> </message> <message> <source>Vibrato Depth</source> <translation>Profondità del Vibrato</translation> </message> <message> <source>Tremolo Depth</source> <translation>Profondità del Tremolo</translation> </message> </context> <context> <name>opl2instrumentView</name> <message> <source>Attack</source> <translation>Attacco</translation> </message> <message> <source>Decay</source> <translation>Decadimento</translation> </message> <message> <source>Release</source> <translation>Rilascio</translation> </message> <message> <source>Frequency multiplier</source> <translation>Moltiplicatore della frequenza</translation> </message> </context> <context> <name>organicInstrument</name> <message> <source>Distortion</source> <translation>Distorsione</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> </context> <context> <name>organicInstrumentView</name> <message> <source>Distortion:</source> <translation>Distorsione:</translation> </message> <message> <source>Volume:</source> <translation>Volume:</translation> </message> <message> <source>Randomise</source> <translation>Rendi casuale</translation> </message> <message> <source>Osc %1 waveform:</source> <translation>Onda osc %1:</translation> </message> <message> <source>Osc %1 volume:</source> <translation>Volume osc %1:</translation> </message> <message> <source>Osc %1 panning:</source> <translation>Panning osc %1:</translation> </message> <message> <source>cents</source> <translation>centesimi</translation> </message> <message> <source>The distortion knob adds distortion to the output of the instrument. </source> <translation>La manopola di distorsione aggiunge distorsione all&apos;ouyput dello strumento.</translation> </message> <message> <source>The volume knob controls the volume of the output of the instrument. It is cumulative with the instrument window&apos;s volume control. </source> <translation>La manopola di volume cntrolla il volume di output dello strumento. Si rapporta al volume della finestra del plugin in modo cumulativo.</translation> </message> <message> <source>The randomize button randomizes all knobs except the harmonics,main volume and distortion knobs. </source> <translation>Il pulsante randomize genera un nuovo suono randomizzando tutte le manopole tranne le Armoniche, il volume principale e la distorsione.</translation> </message> <message> <source>Osc %1 stereo detuning</source> <translation>Osc %1 intonazione stereo</translation> </message> <message> <source>Osc %1 harmonic:</source> <translation>Osc %1 armoniche:</translation> </message> </context> <context> <name>papuInstrument</name> <message> <source>Sweep time</source> <translation>Tempo di sweep</translation> </message> <message> <source>Sweep direction</source> <translation>Direzione sweep</translation> </message> <message> <source>Sweep RtShift amount</source> <translation>Quantità RtShift per lo sweep</translation> </message> <message> <source>Wave Pattern Duty</source> <translation>Wave Pattern Duty</translation> </message> <message> <source>Channel 1 volume</source> <translation>Volume del canale 1</translation> </message> <message> <source>Volume sweep direction</source> <translation>Direzione sweep del volume</translation> </message> <message> <source>Length of each step in sweep</source> <translation>Lunghezza di ogni passo nello sweep</translation> </message> <message> <source>Channel 2 volume</source> <translation>Volume del canale 2</translation> </message> <message> <source>Channel 3 volume</source> <translation>Volume del canale 3</translation> </message> <message> <source>Channel 4 volume</source> <translation>Volume del canale 4</translation> </message> <message> <source>Right Output level</source> <translation>Volume uscita destra</translation> </message> <message> <source>Left Output level</source> <translation>Volume uscita sinistra</translation> </message> <message> <source>Channel 1 to SO2 (Left)</source> <translation>Canale 1 a SO2 (sinistra)</translation> </message> <message> <source>Channel 2 to SO2 (Left)</source> <translation>Canale 2 a SO2 (sinistra)</translation> </message> <message> <source>Channel 3 to SO2 (Left)</source> <translation>Canale 3 a SO2 (sinistra)</translation> </message> <message> <source>Channel 4 to SO2 (Left)</source> <translation>Canale 4 a SO2 (sinistra)</translation> </message> <message> <source>Channel 1 to SO1 (Right)</source> <translation>Canale 1 a SO1 (destra)</translation> </message> <message> <source>Channel 2 to SO1 (Right)</source> <translation>Canale 2 a SO1 (destra)</translation> </message> <message> <source>Channel 3 to SO1 (Right)</source> <translation>Canale 3 a SO1 (destra)</translation> </message> <message> <source>Channel 4 to SO1 (Right)</source> <translation>Canale 4 a SO1 (destra)</translation> </message> <message> <source>Treble</source> <translation>Alti</translation> </message> <message> <source>Bass</source> <translation>Bassi</translation> </message> <message> <source>Shift Register width</source> <translation>Ampiezza spostamento del registro</translation> </message> </context> <context> <name>papuInstrumentView</name> <message> <source>Sweep Time:</source> <translation>Tempo di sweep:</translation> </message> <message> <source>Sweep Time</source> <translation>Tempo di sweep</translation> </message> <message> <source>Sweep RtShift amount:</source> <translation>Quantità RtShift per lo sweep:</translation> </message> <message> <source>Sweep RtShift amount</source> <translation>Quantità RtShift per lo sweep</translation> </message> <message> <source>Wave pattern duty:</source> <translation>Wave Pattern Duty:</translation> </message> <message> <source>Wave Pattern Duty</source> <translation>Wave Pattern Duty</translation> </message> <message> <source>Square Channel 1 Volume:</source> <translation>Volume del canale 1 square:</translation> </message> <message> <source>Length of each step in sweep:</source> <translation>Lunghezza di ogni passo nello sweep:</translation> </message> <message> <source>Length of each step in sweep</source> <translation>Lunghezza di ogni passo nello sweep</translation> </message> <message> <source>Wave pattern duty</source> <translation>Wave Pattern Duty</translation> </message> <message> <source>Square Channel 2 Volume:</source> <translation>Volume square del canale 2:</translation> </message> <message> <source>Square Channel 2 Volume</source> <translation>Volume square del canale 2</translation> </message> <message> <source>Wave Channel Volume:</source> <translation>Volume wave del canale:</translation> </message> <message> <source>Wave Channel Volume</source> <translation>Volume wave del canale</translation> </message> <message> <source>Noise Channel Volume:</source> <translation>Volume rumore del canale:</translation> </message> <message> <source>Noise Channel Volume</source> <translation>Volume rumore del canale</translation> </message> <message> <source>SO1 Volume (Right):</source> <translation>Volume SO1 (destra):</translation> </message> <message> <source>SO1 Volume (Right)</source> <translation>Volume SO1 (destra)</translation> </message> <message> <source>SO2 Volume (Left):</source> <translation>Volume SO2 (sinistra):</translation> </message> <message> <source>SO2 Volume (Left)</source> <translation>Volume SO2 (sinistra)</translation> </message> <message> <source>Treble:</source> <translation>Alti:</translation> </message> <message> <source>Treble</source> <translation>Alti</translation> </message> <message> <source>Bass:</source> <translation>Bassi:</translation> </message> <message> <source>Bass</source> <translation>Bassi</translation> </message> <message> <source>Sweep Direction</source> <translation>Direzione sweep</translation> </message> <message> <source>Volume Sweep Direction</source> <translation>Direzione sweep del volume</translation> </message> <message> <source>Shift Register Width</source> <translation>Ampiezza spostamento del registro</translation> </message> <message> <source>Channel1 to SO1 (Right)</source> <translation>Canale 1 a SO1 (destra)</translation> </message> <message> <source>Channel2 to SO1 (Right)</source> <translation>Canale 2 a SO1 (destra)</translation> </message> <message> <source>Channel3 to SO1 (Right)</source> <translation>Canale 3 a SO1 (destra)</translation> </message> <message> <source>Channel4 to SO1 (Right)</source> <translation>Canale 4 a SO1 (destra)</translation> </message> <message> <source>Channel1 to SO2 (Left)</source> <translation>Canale 1 a SO2 (sinistra)</translation> </message> <message> <source>Channel2 to SO2 (Left)</source> <translation>Canale 1 a SO2 (sinistra)</translation> </message> <message> <source>Channel3 to SO2 (Left)</source> <translation>Canale 3 a SO2 (sinistra)</translation> </message> <message> <source>Channel4 to SO2 (Left)</source> <translation>Canale 4 a SO2 (sinistra)</translation> </message> <message> <source>Wave Pattern</source> <translation>Wave Pattern</translation> </message> <message> <source>The amount of increase or decrease in frequency</source> <translation>La quantità di aumento o diminuzione di frequenza</translation> </message> <message> <source>The rate at which increase or decrease in frequency occurs</source> <translation>La velocità a cui l&apos;aumento o la diminuzione di frequenza avvengono</translation> </message> <message> <source>The duty cycle is the ratio of the duration (time) that a signal is ON versus the total period of the signal.</source> <translation>Il duty cycle è il rapporto tra il tempo in cui il segnale è ON e il periodo completo del segnale.</translation> </message> <message> <source>Square Channel 1 Volume</source> <translation>Volume square del canale 1</translation> </message> <message> <source>The delay between step change</source> <translation>Ritardo tra i cambi di step</translation> </message> <message> <source>Draw the wave here</source> <translation>Disegnare l&apos;onda qui</translation> </message> </context> <context> <name>patchesDialog</name> <message> <source>Qsynth: Channel Preset</source> <translation>Qsynth: Preset Canale</translation> </message> <message> <source>Bank selector</source> <translation>Selezione banca</translation> </message> <message> <source>Bank</source> <translation>Banco</translation> </message> <message> <source>Program selector</source> <translation>Selezione programma</translation> </message> <message> <source>Patch</source> <translation>Programma</translation> </message> <message> <source>Name</source> <translation>Nome</translation> </message> <message> <source>OK</source> <translation>OK</translation> </message> <message> <source>Cancel</source> <translation>Annulla</translation> </message> </context> <context> <name>pluginBrowser</name> <message> <source>no description</source> <translation>nessuna descrizione</translation> </message> <message> <source>Incomplete monophonic imitation tb303</source> <translation>Imitazione monofonica del tb303 incompleta</translation> </message> <message> <source>Plugin for freely manipulating stereo output</source> <translation>Plugin per manipolare liberamente un&apos;uscita stereo</translation> </message> <message> <source>Plugin for controlling knobs with sound peaks</source> <translation>Plugin per controllare le manopole con picchi di suono</translation> </message> <message> <source>Plugin for enhancing stereo separation of a stereo input file</source> <translation>Plugin per migliorare la separazione stereo di un file</translation> </message> <message> <source>List installed LADSPA plugins</source> <translation>Elenca i plugin LADSPA installati</translation> </message> <message> <source>GUS-compatible patch instrument</source> <translation>strumento compatibile con GUS</translation> </message> <message> <source>Additive Synthesizer for organ-like sounds</source> <translation>Sintetizzatore additivo per suoni tipo organo</translation> </message> <message> <source>Tuneful things to bang on</source> <translation>Oggetti dotati di intonazione su cui picchiare</translation> </message> <message> <source>VST-host for using VST(i)-plugins within LMMS</source> <translation>Host VST per usare i plugin VST con LMMS</translation> </message> <message> <source>Vibrating string modeler</source> <translation>Modulatore di corde vibranti</translation> </message> <message> <source>plugin for using arbitrary LADSPA-effects inside LMMS.</source> <translation>Plugin per usare qualsiasi effetto LADSPA in LMMS.</translation> </message> <message> <source>Filter for importing MIDI-files into LMMS</source> <translation>Filtro per importare file MIDI in LMMS</translation> </message> <message> <source>Emulation of the MOS6581 and MOS8580 SID. This chip was used in the Commodore 64 computer.</source> <translation>Emulazione di MOS6581 and MOS8580 SID. Questo chip era utilizzato nel Commode 64.</translation> </message> <message> <source>Player for SoundFont files</source> <translation>Riproduttore di file SounFont</translation> </message> <message> <source>Emulation of GameBoy (TM) APU</source> <translation>Emulatore di GameBoy™ APU</translation> </message> <message> <source>Customizable wavetable synthesizer</source> <translation>Sintetizzatore wavetable configurabile</translation> </message> <message> <source>Embedded ZynAddSubFX</source> <translation>ZynAddSubFX incorporato</translation> </message> <message> <source>2-operator FM Synth</source> <translation>Sintetizzatore FM a 2 operatori</translation> </message> <message> <source>Filter for importing Hydrogen files into LMMS</source> <translation>Strumento per l&apos;importazione di file Hydrogen dentro LMMS</translation> </message> <message> <source>LMMS port of sfxr</source> <translation>Port di sfxr su LMMS</translation> </message> <message> <source>Monstrous 3-oscillator synth with modulation matrix</source> <translation>Sintetizzatore mostruoso con 3 oscillatori e matrice di modulazione</translation> </message> <message> <source>Three powerful oscillators you can modulate in several ways</source> <translation>Tre potenti oscillatori modulabili in vari modi</translation> </message> <message> <source>A native amplifier plugin</source> <translation>Un plugin di amplificazione nativo</translation> </message> <message> <source>Carla Rack Instrument</source> <translation>Strutmento Rack Carla</translation> </message> <message> <source>4-oscillator modulatable wavetable synth</source> <translation>Sintetizzatore wavetable con 4 oscillatori modulabili</translation> </message> <message> <source>plugin for waveshaping</source> <translation>Plugin per la modifica della forma d&apos;onda</translation> </message> <message> <source>Boost your bass the fast and simple way</source> <translation>Potenzia il tuo basso in modo veloce e semplice</translation> </message> <message> <source>Versatile drum synthesizer</source> <translation>Sintetizzatore di percussioni versatile</translation> </message> <message> <source>Simple sampler with various settings for using samples (e.g. drums) in an instrument-track</source> <translation>Semplice sampler con varie impostazioni, per usare suoni (come percussioni) in una traccia strumentale</translation> </message> <message> <source>plugin for processing dynamics in a flexible way</source> <translation>Un versatile processore di dynamic</translation> </message> <message> <source>Carla Patchbay Instrument</source> <translation>Strumento Patchbay Carla</translation> </message> <message> <source>plugin for using arbitrary VST effects inside LMMS.</source> <translation>Plugin per usare effetti VST arbitrari dentro LMMS.</translation> </message> <message> <source>Graphical spectrum analyzer plugin</source> <translation>Analizzatore di spettro grafico</translation> </message> <message> <source>A NES-like synthesizer</source> <translation>Un sintetizzatore che imita i suoni del Nintendo Entertainment System</translation> </message> <message> <source>A native delay plugin</source> <translation>Un plugin di ritardi eco nativo</translation> </message> <message> <source>Player for GIG files</source> <translation>Riproduttore di file GIG</translation> </message> <message> <source>A multitap echo delay plugin</source> <translation>Un plugin di ritardo eco multitap</translation> </message> <message> <source>A native flanger plugin</source> <translation>Un plugin di flager nativo</translation> </message> <message> <source>An oversampling bitcrusher</source> <translation>Un riduttore di bit con oversampling</translation> </message> <message> <source>A native eq plugin</source> <translation>Un plugin di equalizzazione nativo</translation> </message> <message> <source>A 4-band Crossover Equalizer</source> <translation>Un equalizzatore Crossover a 4 bande</translation> </message> <message> <source>A Dual filter plugin</source> <translation>Un plugin di duplice filtraggio</translation> </message> <message> <source>Filter for exporting MIDI-files from LMMS</source> <translation>Filtro per esportare file MIDI da LMMS</translation> </message> <message> <source>Reverb algorithm by Sean Costello</source> <translation>Algoritmo di Riverbero di Sean Costello</translation> </message> <message> <source>Mathematical expression parser</source> <translation type="unfinished"/> </message> </context> <context> <name>sf2Instrument</name> <message> <source>Bank</source> <translation>Banco</translation> </message> <message> <source>Patch</source> <translation>Patch</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>Reverb</source> <translation>Riverbero</translation> </message> <message> <source>Reverb Roomsize</source> <translation>Riverbero - dimensione stanza</translation> </message> <message> <source>Reverb Damping</source> <translation>Riverbero - attenuazione</translation> </message> <message> <source>Reverb Width</source> <translation>Riverbero - ampiezza</translation> </message> <message> <source>Reverb Level</source> <translation>Riverbero - livello</translation> </message> <message> <source>Chorus</source> <translation>Chorus</translation> </message> <message> <source>Chorus Lines</source> <translation>Chorus - voci</translation> </message> <message> <source>Chorus Level</source> <translation>Chorus - livello</translation> </message> <message> <source>Chorus Speed</source> <translation>Chorus - velocità</translation> </message> <message> <source>Chorus Depth</source> <translation>Chorus - profondità</translation> </message> <message> <source>A soundfont %1 could not be loaded.</source> <translation>Non è stato possibile caricare un soundfont %1.</translation> </message> </context> <context> <name>sf2InstrumentView</name> <message> <source>Open other SoundFont file</source> <translation>Apri un altro file SoundFont</translation> </message> <message> <source>Click here to open another SF2 file</source> <translation>Clicca qui per aprire un altro file SF2</translation> </message> <message> <source>Choose the patch</source> <translation>Seleziona il patch</translation> </message> <message> <source>Gain</source> <translation>Guadagno</translation> </message> <message> <source>Apply reverb (if supported)</source> <translation>Applica il riverbero (se supportato)</translation> </message> <message> <source>This button enables the reverb effect. This is useful for cool effects, but only works on files that support it.</source> <translation>Questo pulsante abilita l&apos;effetto riverbero, che è utile per effetti particolari ma funziona solo su file che lo supportano.</translation> </message> <message> <source>Reverb Roomsize:</source> <translation>Riverbero - dimensione stanza:</translation> </message> <message> <source>Reverb Damping:</source> <translation>Riverbero - attenuazione:</translation> </message> <message> <source>Reverb Width:</source> <translation>Riverbero - ampiezza:</translation> </message> <message> <source>Reverb Level:</source> <translation>Riverbero - livello:</translation> </message> <message> <source>Apply chorus (if supported)</source> <translation>Applica il chorus (se supportato)</translation> </message> <message> <source>This button enables the chorus effect. This is useful for cool echo effects, but only works on files that support it.</source> <translation>Questo pulsante abilita l&apos;effetto chorus, che è utile per effetti di eco particolari ma funziona solo su file che lo supportano.</translation> </message> <message> <source>Chorus Lines:</source> <translation>Chorus - voci:</translation> </message> <message> <source>Chorus Level:</source> <translation>Chorus - livello:</translation> </message> <message> <source>Chorus Speed:</source> <translation>Chorus - velocità:</translation> </message> <message> <source>Chorus Depth:</source> <translation>Chorus - profondità:</translation> </message> <message> <source>Open SoundFont file</source> <translation>Apri un file SoundFont</translation> </message> <message> <source>SoundFont2 Files (*.sf2)</source> <translation>File SoundFont2 (*.sf2)</translation> </message> </context> <context> <name>sfxrInstrument</name> <message> <source>Wave Form</source> <translation>Forma d&apos;onda</translation> </message> </context> <context> <name>sidInstrument</name> <message> <source>Cutoff</source> <translation>Taglio</translation> </message> <message> <source>Resonance</source> <translation>Risonanza</translation> </message> <message> <source>Filter type</source> <translation>Tipo di filtro</translation> </message> <message> <source>Voice 3 off</source> <translation>Voce 3 spenta</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Chip model</source> <translation>Modello di chip</translation> </message> </context> <context> <name>sidInstrumentView</name> <message> <source>Volume:</source> <translation>Volume:</translation> </message> <message> <source>Resonance:</source> <translation>Risonanza:</translation> </message> <message> <source>Cutoff frequency:</source> <translation>Frequenza di taglio:</translation> </message> <message> <source>High-Pass filter </source> <translation>Filtro passa-alto</translation> </message> <message> <source>Band-Pass filter </source> <translation>Filtro passa-banda</translation> </message> <message> <source>Low-Pass filter </source> <translation>Filtro passa-basso</translation> </message> <message> <source>Voice3 Off </source> <translation>Voce 3 spenta</translation> </message> <message> <source>MOS6581 SID </source> <translation>MOS6581 SID</translation> </message> <message> <source>MOS8580 SID </source> <translation>MOS8580 SID</translation> </message> <message> <source>Attack:</source> <translation>Attacco:</translation> </message> <message> <source>Attack rate determines how rapidly the output of Voice %1 rises from zero to peak amplitude.</source> <translation>Il livello di attacco determina quanto rapidamente l&apos;uscita della voce %1 sale da zero al picco di amplificazione.</translation> </message> <message> <source>Decay:</source> <translation>Decadimento:</translation> </message> <message> <source>Decay rate determines how rapidly the output falls from the peak amplitude to the selected Sustain level.</source> <translation>Il livello di decadimento determina quanto rapidamente l&apos;uscita ricade dal picco di amplificazione al livello di sostegno impostato.</translation> </message> <message> <source>Sustain:</source> <translation>Sostegno:</translation> </message> <message> <source>Output of Voice %1 will remain at the selected Sustain amplitude as long as the note is held.</source> <translation>L&apos;uscita della voce %1 rimarrà al livello di sostegno impostato per tutta la durata della nota.</translation> </message> <message> <source>Release:</source> <translation>Rilascio:</translation> </message> <message> <source>The output of of Voice %1 will fall from Sustain amplitude to zero amplitude at the selected Release rate.</source> <translation>L&apos;uscita della voce %1 ricadrà dal livello di sostegno verso il silenzio con la velocità di rilascio impostata.</translation> </message> <message> <source>Pulse Width:</source> <translation>Ampiezza pulse:</translation> </message> <message> <source>The Pulse Width resolution allows the width to be smoothly swept with no discernable stepping. The Pulse waveform on Oscillator %1 must be selected to have any audible effect.</source> <translation>La risoluzione dell&apos;ampiezza del Pulse permette di impostare che l&apos;ampiezza venga variata in modo continuo senza salti udibili. Sull&apos;oscillatore %1 deve essere selezionata la forma d&apos;onda Pulse perché si abbia un effetto udibile.</translation> </message> <message> <source>Coarse:</source> <translation>Approssimativo:</translation> </message> <message> <source>The Coarse detuning allows to detune Voice %1 one octave up or down.</source> <translation>L&apos;intonazione permette di &quot;stonare&quot; la voce %1 verso l&apos;alto o verso il basso di un&apos;ottava.</translation> </message> <message> <source>Pulse Wave</source> <translation>Onda pulse</translation> </message> <message> <source>Triangle Wave</source> <translation>Onda triangolare</translation> </message> <message> <source>SawTooth</source> <translation>Dente di sega</translation> </message> <message> <source>Noise</source> <translation>Rumore</translation> </message> <message> <source>Sync</source> <translation>Sincronizzato</translation> </message> <message> <source>Sync synchronizes the fundamental frequency of Oscillator %1 with the fundamental frequency of Oscillator %2 producing &quot;Hard Sync&quot; effects.</source> <translation>Il Sync sincronizza la frequenza fondamentale dell&apos;oscillatore %1 con quella dell&apos;oscillatore %2 producendo effetti di &quot;Hard Sync&quot;.</translation> </message> <message> <source>Ring-Mod</source> <translation>Modulazione ring</translation> </message> <message> <source>Ring-mod replaces the Triangle Waveform output of Oscillator %1 with a &quot;Ring Modulated&quot; combination of Oscillators %1 and %2.</source> <translation>Ring-mod rimpiazza l&apos;uscita della forma d&apos;onda triangolare dell&apos;oscillatore %1 con la combinazione &quot;Ring Modulated&quot; degli oscillatori %1 e %2.</translation> </message> <message> <source>Filtered</source> <translation>Filtrato</translation> </message> <message> <source>When Filtered is on, Voice %1 will be processed through the Filter. When Filtered is off, Voice %1 appears directly at the output, and the Filter has no effect on it.</source> <translation>Quando il filtraggio è attivo, la voce %1 verrà processata dal filtro. Quando il filtraggio è spento, la voce %1 arriva direttamente all&apos;uscita e il filtro non ha effetto su di essa.</translation> </message> <message> <source>Test</source> <translation>Test</translation> </message> <message> <source>Test, when set, resets and locks Oscillator %1 at zero until Test is turned off.</source> <translation>Quando Test è attivo, e finché non viene spento, reimposta e blocca l&apos;oscillatore %1 a zero.</translation> </message> </context> <context> <name>stereoEnhancerControlDialog</name> <message> <source>WIDE</source> <translation>AMPIO</translation> </message> <message> <source>Width:</source> <translation>Ampiezza:</translation> </message> </context> <context> <name>stereoEnhancerControls</name> <message> <source>Width</source> <translation>Ampiezza</translation> </message> </context> <context> <name>stereoMatrixControlDialog</name> <message> <source>Left to Left Vol:</source> <translation>Volume da Sinistra a Sinistra:</translation> </message> <message> <source>Left to Right Vol:</source> <translation>Volume da Sinistra a Destra:</translation> </message> <message> <source>Right to Left Vol:</source> <translation>Volume da Destra a Sinistra:</translation> </message> <message> <source>Right to Right Vol:</source> <translation>Volume da Destra a Destra:</translation> </message> </context> <context> <name>stereoMatrixControls</name> <message> <source>Left to Left</source> <translation>Da Sinistra a Sinistra</translation> </message> <message> <source>Left to Right</source> <translation>Da Sinistra a Destra</translation> </message> <message> <source>Right to Left</source> <translation>Da Destra a Sinistra</translation> </message> <message> <source>Right to Right</source> <translation>Da Destra a Destra</translation> </message> </context> <context> <name>vestigeInstrument</name> <message> <source>Loading plugin</source> <translation>Caricamento plugin</translation> </message> <message> <source>Please wait while loading VST-plugin...</source> <translation>Prego attendere, caricamento del plugin VST...</translation> </message> </context> <context> <name>vibed</name> <message> <source>String %1 volume</source> <translation>Volume della corda %1</translation> </message> <message> <source>String %1 stiffness</source> <translation>Durezza della corda %1</translation> </message> <message> <source>Pick %1 position</source> <translation>Posizione del plettro %1</translation> </message> <message> <source>Pickup %1 position</source> <translation>Posizione del pickup %1</translation> </message> <message> <source>Pan %1</source> <translation>Pan %1</translation> </message> <message> <source>Detune %1</source> <translation>Intonazione %1</translation> </message> <message> <source>Fuzziness %1 </source> <translation>Fuzziness %1</translation> </message> <message> <source>Length %1</source> <translation>Lunghezza %1</translation> </message> <message> <source>Impulse %1</source> <translation>Impulso %1</translation> </message> <message> <source>Octave %1</source> <translation>Ottava %1</translation> </message> </context> <context> <name>vibedView</name> <message> <source>Volume:</source> <translation>Volume:</translation> </message> <message> <source>The &apos;V&apos; knob sets the volume of the selected string.</source> <translation>La manopola &apos;V&apos; regola il volume della corda selezionata.</translation> </message> <message> <source>String stiffness:</source> <translation>Durezza della corda:</translation> </message> <message> <source>The &apos;S&apos; knob sets the stiffness of the selected string. The stiffness of the string affects how long the string will ring out. The lower the setting, the longer the string will ring.</source> <translation>La manopola &apos;S&apos; regola la durezza della corda selezionata. La durezza della corda influenza la durata della vibrazione. Più basso sarà il valore, più a lungo suonerà la corda.</translation> </message> <message> <source>Pick position:</source> <translation>Posizione del plettro:</translation> </message> <message> <source>The &apos;P&apos; knob sets the position where the selected string will be &apos;picked&apos;. The lower the setting the closer the pick is to the bridge.</source> <translation>La manopola &apos;P&apos; regola il punto in cui verrà &apos;pizzicata&apos; la corda. Più basso sarà il valore, più vicino al ponte sarà il plettro.</translation> </message> <message> <source>Pickup position:</source> <translation>Posizione del pickup:</translation> </message> <message> <source>The &apos;PU&apos; knob sets the position where the vibrations will be monitored for the selected string. The lower the setting, the closer the pickup is to the bridge.</source> <translation>La manopola &apos;PU&apos; regola la posizione in cui verranno rilevate le vibrazioni della corda selezionata. Più basso sarà il valore, più vicino al ponte sarà il pickup.</translation> </message> <message> <source>Pan:</source> <translation>Pan:</translation> </message> <message> <source>The Pan knob determines the location of the selected string in the stereo field.</source> <translation>La manopola Pan determina la posizione della corda selezionata nello spettro stereo.</translation> </message> <message> <source>Detune:</source> <translation>Intonazione:</translation> </message> <message> <source>The Detune knob modifies the pitch of the selected string. Settings less than zero will cause the string to sound flat. Settings greater than zero will cause the string to sound sharp.</source> <translation>La manopola Intonazione regola l&apos;altezza del suono della corda selezionata. Valori sotto lo zero sposteranno l&apos;intonazione della corda verso il bemolle. Valori sopra lo zero spostarenno l&apos;intonazione della corda verso il diesis.</translation> </message> <message> <source>Fuzziness:</source> <translation>Fuzziness:</translation> </message> <message> <source>The Slap knob adds a bit of fuzz to the selected string which is most apparent during the attack, though it can also be used to make the string sound more &apos;metallic&apos;.</source> <translation>La manopola Slap aggiungeun po&apos; di &quot;sporco&quot; al suono della corda selezionata, sensibile soprattutto nell&apos;attacco, anche se può essere usato per rendere il suono più &quot;metallico&quot;.</translation> </message> <message> <source>Length:</source> <translation>Lunghezza:</translation> </message> <message> <source>The Length knob sets the length of the selected string. Longer strings will both ring longer and sound brighter, however, they will also eat up more CPU cycles.</source> <translation>La manopola Lunghezza regola la lunghezza della corda selezionata. Corde più lunghe suonano più a lungo e hanno un suono più brillante. Tuttavia richiedono anche più tempo del processore.</translation> </message> <message> <source>Impulse or initial state</source> <translation>Impulso o stato iniziale</translation> </message> <message> <source>The &apos;Imp&apos; selector determines whether the waveform in the graph is to be treated as an impulse imparted to the string by the pick or the initial state of the string.</source> <translation>Il selettore &apos;Imp&apos; determina se la forma d&apos;onda nel grafico deve essere trattata come l&apos;impulso del plettro sulla corda o come lo stato iniziale della corda.</translation> </message> <message> <source>Octave</source> <translation>Ottava</translation> </message> <message> <source>The Octave selector is used to choose which harmonic of the note the string will ring at. For example, &apos;-2&apos; means the string will ring two octaves below the fundamental, &apos;F&apos; means the string will ring at the fundamental, and &apos;6&apos; means the string will ring six octaves above the fundamental.</source> <translation>Il seletore Ottava serve per scegliere a quale armonico della nota risuona la corda. Per esempio, &apos;-2&apos; significa che la corda risuona due ottave sotto la fondamentale, &apos;F&apos; significa che la corda risuona alla fondamentale e &apos;6&apos; significa che la corda risuona sei ottave sopra la fondamentale.</translation> </message> <message> <source>Impulse Editor</source> <translation>Editor dell&apos;impulso</translation> </message> <message> <source>The waveform editor provides control over the initial state or impulse that is used to start the string vibrating. The buttons to the right of the graph will initialize the waveform to the selected type. The '?' button will load a waveform from a file--only the first 128 samples will be loaded. The waveform can also be drawn in the graph. The 'S' button will smooth the waveform. The &apos;N&apos; button will normalize the waveform.</source> <translation>L&apos;editor della forma d&apos;onda fornisce il controllo sull&apos;impulso iniziale usato per far vibrare la corda. I pulsanti a destra del grafico predispongono una forma d&apos;onda del tipo selezionato. Il pulsante &apos;?&apos; carica la forma d&apos;onda da un file--verranno caricati solo i primi 128 campioni. La forma d&apos;onda può anche essere disegnata direttamente sul grafico. Il pulsante &apos;S&apos; ammorbisce la forma d&apos;onda. Il pulsante &apos;N&apos; normalizza la forma d&apos;onda.</translation> </message> <message> <source>Vibed models up to nine independently vibrating strings. The 'String' selector allows you to choose which string is being edited. The 'Imp' selector chooses whether the graph represents an impulse or the initial state of the string. The 'Octave' selector chooses which harmonic the string should vibrate at. The graph allows you to control the initial state or impulse used to set the string in motion. The 'V' knob controls the volume. The 'S' knob controls the string's stiffness. The 'P' knob controls the pick position. The 'PU' knob controls the pickup position. 'Pan' and 'Detune' hopefully don't need explanation. The 'Slap' knob adds a bit of fuzz to the sound of the string. The 'Length' knob controls the length of the string. The LED in the lower right corner of the waveform editor determines whether the string is active in the current instrument.</source> <translation>Vibed modella fino a nove corde che vibrano indipendentemente. Il selettore &apos;Corda&apos; permettedi scegliere quale corda modificare. Il selettore &apos;Imp&apos; sceglie se il grafico sarà l&apos;impulso dato o lo stato iniziale della corda. Il selettore &apos;Ottava&apos; imposta l&apos;armonico a cui risuonerà la corda. Il grafico permette di controllare l&apos;impulso (o lo stato iniziale) per far vibrare la corda. La manopola &apos;V&apos; reogla il volume. La manopola &apos;S&apos; regola la durezza della corda. La manopola &apos;P&apos; regola la posiziona del plettro. La manopola &apos;PU&apos; regola la posizione del pickup. &apos;Pan&apos; e &apos;Detune&apos; non dovrebbero aver bisogno di spiegazioni. La manopola &apos;Slap&apos; aggiunge un po&apos; di &quot;sporco&quot; al suono della corda. La manopola &apos;Lunghezza&apos; regola la lunghezza della corda. Il LED nell&apos;angolo in basso a destra sull&apos;editor della forma d&apos;onda determina se la corda è attiva nello strumento selezionato.</translation> </message> <message> <source>Enable waveform</source> <translation>Abilita forma d&apos;onda</translation> </message> <message> <source>Click here to enable/disable waveform.</source> <translation>Cliccando qui si abilita/disabilita la forma d&apos;onda.</translation> </message> <message> <source>String</source> <translation>Corda</translation> </message> <message> <source>The String selector is used to choose which string the controls are editing. A Vibed instrument can contain up to nine independently vibrating strings. The LED in the lower right corner of the waveform editor indicates whether the selected string is active.</source> <translation>Il selettore della Corda serve per scegliere su quale corda hanno effetto i controlli. Uno strumento Vibed può contenere fino a nove corde che indipendenti. Il LED nell&apos;angolo in basso a destra dell&apos;editor della forma d&apos;onda indica se la corda è attiva.</translation> </message> <message> <source>Sine wave</source> <translation>Onda sinusoidale</translation> </message> <message> <source>Triangle wave</source> <translation>Onda triangolare</translation> </message> <message> <source>Saw wave</source> <translation>Onda a dente di sega</translation> </message> <message> <source>Square wave</source> <translation>Onda quadra</translation> </message> <message> <source>White noise wave</source> <translation>Rumore bianco</translation> </message> <message> <source>User defined wave</source> <translation>Forma d&apos;onda personalizzata</translation> </message> <message> <source>Smooth</source> <translation>Ammorbidisci</translation> </message> <message> <source>Click here to smooth waveform.</source> <translation>Cliccando qui la forma d&apos;onda viene ammorbidita.</translation> </message> <message> <source>Normalize</source> <translation>Normalizza</translation> </message> <message> <source>Click here to normalize waveform.</source> <translation>Cliccando qui la forma d&apos;onda viene normalizzata.</translation> </message> <message> <source>Use a sine-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda sinusoidale per questo oscillatore.</translation> </message> <message> <source>Use a triangle-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda triangolare per questo oscillatore.</translation> </message> <message> <source>Use a saw-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda a dente di sega per questo oscillatore.</translation> </message> <message> <source>Use a square-wave for current oscillator.</source> <translation>Utilizzare un&apos;onda quadra per questo oscillatore.</translation> </message> <message> <source>Use white-noise for current oscillator.</source> <translation>Utilizzare rumore bianco per questo oscillatore.</translation> </message> <message> <source>Use a user-defined waveform for current oscillator.</source> <translation>Utilizzare un&apos;onda personalizzata per questo oscillatore.</translation> </message> </context> <context> <name>voiceObject</name> <message> <source>Voice %1 pulse width</source> <translation>Ampiezza pulse voce %1</translation> </message> <message> <source>Voice %1 attack</source> <translation>Attacco voce %1</translation> </message> <message> <source>Voice %1 decay</source> <translation>Decadimento voce %1</translation> </message> <message> <source>Voice %1 sustain</source> <translation>Sostegno voce %1</translation> </message> <message> <source>Voice %1 release</source> <translation>Rilascio voce %1</translation> </message> <message> <source>Voice %1 coarse detuning</source> <translation>Intonazione voce %1</translation> </message> <message> <source>Voice %1 wave shape</source> <translation>Forma d&apos;onda voce %1</translation> </message> <message> <source>Voice %1 sync</source> <translation>Sincronizzazione voce %1</translation> </message> <message> <source>Voice %1 ring modulate</source> <translation>Modulazione ring voce %1</translation> </message> <message> <source>Voice %1 filtered</source> <translation>Filtraggio voce %1</translation> </message> <message> <source>Voice %1 test</source> <translation>Test voce %1</translation> </message> </context> <context> <name>waveShaperControlDialog</name> <message> <source>INPUT</source> <translation>INPUT</translation> </message> <message> <source>Input gain:</source> <translation>Guadagno in Input:</translation> </message> <message> <source>OUTPUT</source> <translation>OUTPUT</translation> </message> <message> <source>Output gain:</source> <translation>Guadagno in output:</translation> </message> <message> <source>Reset waveform</source> <translation>Resetta forma d&apos;onda</translation> </message> <message> <source>Click here to reset the wavegraph back to default</source> <translation>Clicca qui per resettare il grafico d&apos;onda alla condizione originale</translation> </message> <message> <source>Smooth waveform</source> <translation>Spiana forma d&apos;onda</translation> </message> <message> <source>Click here to apply smoothing to wavegraph</source> <translation>Clicca qui per addolcire il grafico d&apos;onda</translation> </message> <message> <source>Increase graph amplitude by 1dB</source> <translation>Aumenta l&apos;amplificazione di 1dB</translation> </message> <message> <source>Click here to increase wavegraph amplitude by 1dB</source> <translation>Clicca qui per aumentare l&apos;amplificazione del grafico d&apos;onda di 1dB</translation> </message> <message> <source>Decrease graph amplitude by 1dB</source> <translation>Diminuisi l&apos;amplificatore di 1dB</translation> </message> <message> <source>Click here to decrease wavegraph amplitude by 1dB</source> <translation>Clicca qui per diminuire l&apos;amplificazione del grafico d&apos;onda di 1dB</translation> </message> <message> <source>Clip input</source> <translation>Taglia input</translation> </message> <message> <source>Clip input signal to 0dB</source> <translation>Taglia in segnale di input a 0dB</translation> </message> </context> <context> <name>waveShaperControls</name> <message> <source>Input gain</source> <translation>Guadagno in input</translation> </message> <message> <source>Output gain</source> <translation>Guadagno in output</translation> </message> </context> </TS><|fim▁end|>
<source>Record while playing</source> <translation>Registra in play</translation>
<|file_name|>LibraryLoader.java<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved. package com.blinkboxbooks.android.list; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.database.MergeCursor; import android.support.v4.content.AsyncTaskLoader; import android.util.SparseArray; import com.blinkboxbooks.android.model.Book; import com.blinkboxbooks.android.model.BookItem; import com.blinkboxbooks.android.model.Bookmark; import com.blinkboxbooks.android.model.Query; import com.blinkboxbooks.android.model.helper.BookHelper; import com.blinkboxbooks.android.model.helper.BookmarkHelper; import com.blinkboxbooks.android.util.LogUtils; import com.crashlytics.android.Crashlytics; import java.util.ArrayList; import java.util.List;<|fim▁hole|> /* * A loader that queries the {@link ContentResolver} and returns a {@link Cursor}. * This class implements the {@link Loader} protocol in a standard way for * querying cursors, building on {@link AsyncTaskLoader} to perform the cursor * query on a background thread so that it does not block the application's UI. * * <p>A LibraryLoader must be built with the full information for the query to * perform. */ public class LibraryLoader extends AsyncTaskLoader<List<BookItem>> { final ForceLoadContentObserver mObserver; List<BookItem> mBookItems; private List<Query> mQueryList; /** * Creates an empty unspecified CursorLoader. You must follow this with * calls to {@link #setQueryList(List<Query>)} to specify the query to * perform. */ public LibraryLoader(Context context) { super(context); mObserver = new ForceLoadContentObserver(); } /** * Creates a fully-specified LibraryLoader. */ public LibraryLoader(Context context, List<Query> queryList) { super(context); mObserver = new ForceLoadContentObserver(); mQueryList = queryList; } public void setQueryList(List<Query> queryList) { mQueryList = queryList; } /* Runs on a worker thread */ @Override public List<BookItem> loadInBackground() { Cursor cursor = null; List<Cursor> cursorList = new ArrayList<Cursor>(); for (Query query : mQueryList) { cursor = getContext().getContentResolver().query(query.uri, query.projection, query.selection, query.selectionArgs, query.sortOrder); if (cursor != null) { // Ensure the cursor window is filled cursor.getCount(); // registerContentObserver(cursor, mObserver); cursorList.add(cursor); } } Cursor[] cursorArray = new Cursor[cursorList.size()]; List<BookItem> bookItemList; if (cursorList.size() > 0) { bookItemList = createBookItems(new MergeCursor(cursorList.toArray(cursorArray))); for (Cursor c : cursorList) { c.close(); } } else { // Return an empty book list bookItemList = new ArrayList<BookItem>(); } return bookItemList; } /** * Registers an observer to get notifications from the content provider * when the cursor needs to be refreshed. */ void registerContentObserver(Cursor cursor, ContentObserver observer) { cursor.registerContentObserver(mObserver); } /* Runs on the UI thread */ @Override public void deliverResult(List<BookItem> bookItems) { if (isReset()) { // An async query came in while the loader is stopped return; } mBookItems = bookItems; if (isStarted()) { super.deliverResult(bookItems); } } /** * Starts an asynchronous load of the book list data. When the result is ready the callbacks * will be called on the UI thread. If a previous load has been completed and is still valid * the result may be passed to the callbacks immediately. * <p/> * Must be called from the UI thread */ @Override protected void onStartLoading() { if (mBookItems != null) { deliverResult(mBookItems); } if (takeContentChanged() || mBookItems == null) { forceLoad(); } } /** * Must be called from the UI thread */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); } /** * Takes a list of books from the Cursor and arranges them into a list of BookItem objects */ private List<BookItem> createBookItems(Cursor cursor) { // Check for error cases if (cursor == null || cursor.isClosed()) { String error = String.format("Trying to create a new library item list with %s cursor.", cursor == null ? "null" : "closed"); Crashlytics.logException(new Exception(error)); LogUtils.stack(); List<BookItem> bookItems = new ArrayList<BookItem>(); return bookItems; } cursor.moveToFirst(); Book book; Bookmark bookmark; BookItem bookItem; List<BookItem> booksList = new ArrayList<BookItem>(); while (!cursor.isAfterLast()) { book = BookHelper.createBook(cursor); bookmark = BookmarkHelper.createBookmark(cursor); bookItem = new BookItem(book, bookmark, "", "", null); booksList.add(bookItem); cursor.moveToNext(); } return booksList; } }<|fim▁end|>
<|file_name|>test-request.ts<|end_file_name|><|fim▁begin|>import {request} from 'mithril/request' interface Result { id: number } request<Result>({method: "GET", url: "/item"}).then(result => { console.log(result.id) }) request<{a: string}>("/item", {method: "POST"}).then(result => { console.log(result.a) }) request<any>({ method: "GET", url: "/item",<|fim▁hole|> console.log(result) }) request<Result>({ method: "GET", url: "/item", data: 5, serialize: (data: number) => "id=" + data.toString() }).then(result => { console.log(result) }) request<Result>('/item', { method: "GET", deserialize: str => JSON.parse(str) as Result }).then(result => { console.log(result.id) }) request<Result>('/id', { method: "GET", extract: xhr => ({id: Number(xhr.responseText)}) }).then(result => { console.log(result.id) }) request<Result>('/item', { config: xhr => { xhr.setRequestHeader('accept', '*') }, headers: {"Content-Type": "application/json"}, background: true, }).then(result => { console.log(result.id) }) class Item { identifier: number constructor(result: Result) { this.identifier = result.id } } request<Item>('/item', { method: 'GET', async: true, user: "Me", password: "qwerty", withCredentials: true, type: Item, useBody: false }).then(item => { console.log(item.identifier) })<|fim▁end|>
data: {x: "y"} }).then(result => {
<|file_name|>database.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # Database Module # -------------------- from __future__ import unicode_literals import warnings import datetime import frappe import frappe.defaults import frappe.async import re import frappe.model.meta from frappe.utils import now, get_datetime, cstr, cast_fieldtype from frappe import _ from frappe.model.utils.link_count import flush_local_link_count from frappe.model.utils import STANDARD_FIELD_CONVERSION_MAP from frappe.utils.background_jobs import execute_job, get_queue from frappe import as_unicode import six # imports - compatibility imports from six import ( integer_types, string_types, binary_type, text_type, iteritems ) # imports - third-party imports from markdown2 import UnicodeWithAttrs from pymysql.times import TimeDelta from pymysql.constants import ER, FIELD_TYPE from pymysql.converters import conversions import pymysql # Helpers def _cast_result(doctype, result): batch = [ ] try: for field, value in result: df = frappe.get_meta(doctype).get_field(field) if df: value = cast_fieldtype(df.fieldtype, value) batch.append(tuple([field, value])) except frappe.exceptions.DoesNotExistError: return result return tuple(batch) class Database: """ Open a database connection with the given parmeters, if use_default is True, use the login details from `conf.py`. This is called by the request handler and is accessible using the `db` global variable. the `sql` method is also global to run queries """ def __init__(self, host=None, user=None, password=None, ac_name=None, use_default = 0, local_infile = 0): self.host = host or frappe.conf.db_host or 'localhost' self.user = user or frappe.conf.db_name self._conn = None if ac_name: self.user = self.get_db_login(ac_name) or frappe.conf.db_name if use_default: self.user = frappe.conf.db_name self.transaction_writes = 0 self.auto_commit_on_many_writes = 0 self.password = password or frappe.conf.db_password self.value_cache = {} # this param is to load CSV's with LOCAL keyword. # it can be set in site_config as > bench set-config local_infile 1 # once the local-infile is set on MySql Server, the client needs to connect with this option # Connections without this option leads to: 'The used command is not allowed with this MariaDB version' error self.local_infile = local_infile or frappe.conf.local_infile def get_db_login(self, ac_name): return ac_name def connect(self): """Connects to a database as set in `site_config.json`.""" warnings.filterwarnings('ignore', category=pymysql.Warning) usessl = 0 if frappe.conf.db_ssl_ca and frappe.conf.db_ssl_cert and frappe.conf.db_ssl_key: usessl = 1 self.ssl = { 'ca':frappe.conf.db_ssl_ca, 'cert':frappe.conf.db_ssl_cert, 'key':frappe.conf.db_ssl_key } conversions.update({ FIELD_TYPE.NEWDECIMAL: float, FIELD_TYPE.DATETIME: get_datetime, UnicodeWithAttrs: conversions[text_type] }) if six.PY2: conversions.update({ TimeDelta: conversions[binary_type] }) if usessl: self._conn = pymysql.connect(self.host, self.user or '', self.password or '', charset='utf8mb4', use_unicode = True, ssl=self.ssl, conv = conversions, local_infile = self.local_infile) else: self._conn = pymysql.connect(self.host, self.user or '', self.password or '', charset='utf8mb4', use_unicode = True, conv = conversions, local_infile = self.local_infile) # MYSQL_OPTION_MULTI_STATEMENTS_OFF = 1 # # self._conn.set_server_option(MYSQL_OPTION_MULTI_STATEMENTS_OFF) self._cursor = self._conn.cursor() if self.user != 'root': self.use(self.user) frappe.local.rollback_observers = [] def use(self, db_name): """`USE` db_name.""" self._conn.select_db(db_name) self.cur_db_name = db_name def validate_query(self, q): """Throw exception for dangerous queries: `ALTER`, `DROP`, `TRUNCATE` if not `Administrator`.""" cmd = q.strip().lower().split()[0] if cmd in ['alter', 'drop', 'truncate'] and frappe.session.user != 'Administrator': frappe.throw(_("Not permitted"), frappe.PermissionError) def sql(self, query, values=(), as_dict = 0, as_list = 0, formatted = 0, debug=0, ignore_ddl=0, as_utf8=0, auto_commit=0, update=None): """Execute a SQL query and fetch all rows. :param query: SQL query. :param values: List / dict of values to be escaped and substituted in the query. :param as_dict: Return as a dictionary. :param as_list: Always return as a list. :param formatted: Format values like date etc. :param debug: Print query and `EXPLAIN` in debug log. :param ignore_ddl: Catch exception if table, column missing. :param as_utf8: Encode values as UTF 8. :param auto_commit: Commit after executing the query. :param update: Update this dict to all rows (if returned `as_dict`). Examples: # return customer names as dicts frappe.db.sql("select name from tabCustomer", as_dict=True) # return names beginning with a frappe.db.sql("select name from tabCustomer where name like %s", "a%") # values as dict frappe.db.sql("select name from tabCustomer where name like %(name)s and owner=%(owner)s", {"name": "a%", "owner":"[email protected]"}) """ if not self._conn: self.connect() # in transaction validations self.check_transaction_status(query) # autocommit if auto_commit: self.commit() # execute try: if values!=(): if isinstance(values, dict): values = dict(values) # MySQL-python==1.2.5 hack! if not isinstance(values, (dict, tuple, list)): values = (values,) if debug: try: self.explain_query(query, values) frappe.errprint(query % values) except TypeError: frappe.errprint([query, values]) if (frappe.conf.get("logging") or False)==2: frappe.log("<<<< query") frappe.log(query) frappe.log("with values:") frappe.log(values) frappe.log(">>>>") self._cursor.execute(query, values) else: if debug: self.explain_query(query) frappe.errprint(query) if (frappe.conf.get("logging") or False)==2: frappe.log("<<<< query") frappe.log(query) frappe.log(">>>>") self._cursor.execute(query) except Exception as e: if ignore_ddl and e.args[0] in (ER.BAD_FIELD_ERROR, ER.NO_SUCH_TABLE, ER.CANT_DROP_FIELD_OR_KEY): pass # NOTE: causes deadlock # elif e.args[0]==2006: # # mysql has gone away # self.connect() # return self.sql(query=query, values=values, # as_dict=as_dict, as_list=as_list, formatted=formatted, # debug=debug, ignore_ddl=ignore_ddl, as_utf8=as_utf8, # auto_commit=auto_commit, update=update) else: raise if auto_commit: self.commit() # scrub output if required if as_dict: ret = self.fetch_as_dict(formatted, as_utf8) if update: for r in ret: r.update(update) return ret elif as_list: return self.convert_to_lists(self._cursor.fetchall(), formatted, as_utf8) elif as_utf8: return self.convert_to_lists(self._cursor.fetchall(), formatted, as_utf8) else: return self._cursor.fetchall() def explain_query(self, query, values=None): """Print `EXPLAIN` in error log.""" try: frappe.errprint("--- query explain ---") if values is None: self._cursor.execute("explain " + query) else: self._cursor.execute("explain " + query, values) import json frappe.errprint(json.dumps(self.fetch_as_dict(), indent=1)) frappe.errprint("--- query explain end ---") except: frappe.errprint("error in query explain") def sql_list(self, query, values=(), debug=False): """Return data as list of single elements (first column). Example: # doctypes = ["DocType", "DocField", "User", ...] doctypes = frappe.db.sql_list("select name from DocType") """ return [r[0] for r in self.sql(query, values, debug=debug)] def sql_ddl(self, query, values=(), debug=False): """Commit and execute a query. DDL (Data Definition Language) queries that alter schema autocommit in MariaDB.""" self.commit() self.sql(query, debug=debug) def check_transaction_status(self, query): """Raises exception if more than 20,000 `INSERT`, `UPDATE` queries are executed in one transaction. This is to ensure that writes are always flushed otherwise this could cause the system to hang.""" if self.transaction_writes and \ query and query.strip().split()[0].lower() in ['start', 'alter', 'drop', 'create', "begin", "truncate"]: raise Exception('This statement can cause implicit commit') if query and query.strip().lower() in ('commit', 'rollback'): self.transaction_writes = 0 if query[:6].lower() in ('update', 'insert', 'delete'): self.transaction_writes += 1 if self.transaction_writes > 200000: if self.auto_commit_on_many_writes: frappe.db.commit() else: frappe.throw(_("Too many writes in one request. Please send smaller requests"), frappe.ValidationError) def fetch_as_dict(self, formatted=0, as_utf8=0): """Internal. Converts results to dict.""" result = self._cursor.fetchall() ret = [] needs_formatting = self.needs_formatting(result, formatted) for r in result: row_dict = frappe._dict({}) for i in range(len(r)): if needs_formatting: val = self.convert_to_simple_type(r[i], formatted) else: val = r[i] if as_utf8 and type(val) is text_type: val = val.encode('utf-8') row_dict[self._cursor.description[i][0]] = val ret.append(row_dict) return ret def needs_formatting(self, result, formatted): """Returns true if the first row in the result has a Date, Datetime, Long Int.""" if result and result[0]: for v in result[0]: if isinstance(v, (datetime.date, datetime.timedelta, datetime.datetime, integer_types)): return True if formatted and isinstance(v, (int, float)): return True return False def get_description(self): """Returns result metadata.""" return self._cursor.description def convert_to_simple_type(self, v, formatted=0): """Format date, time, longint values.""" return v from frappe.utils import formatdate, fmt_money if isinstance(v, (datetime.date, datetime.timedelta, datetime.datetime, integer_types)): if isinstance(v, datetime.date): v = text_type(v) if formatted: v = formatdate(v) # time elif isinstance(v, (datetime.timedelta, datetime.datetime)): v = text_type(v) # long elif isinstance(v, integer_types): v=int(v) # convert to strings... (if formatted) if formatted: if isinstance(v, float): v=fmt_money(v) elif isinstance(v, int): v = text_type(v) return v def convert_to_lists(self, res, formatted=0, as_utf8=0): """Convert tuple output to lists (internal).""" nres = [] needs_formatting = self.needs_formatting(res, formatted) for r in res: nr = [] for c in r: if needs_formatting: val = self.convert_to_simple_type(c, formatted) else: val = c if as_utf8 and type(val) is text_type: val = val.encode('utf-8') nr.append(val) nres.append(nr) return nres def convert_to_utf8(self, res, formatted=0): """Encode result as UTF-8.""" nres = [] for r in res: nr = [] for c in r: if type(c) is text_type: c = c.encode('utf-8') nr.append(self.convert_to_simple_type(c, formatted)) nres.append(nr) return nres def build_conditions(self, filters): """Convert filters sent as dict, lists to SQL conditions. filter's key is passed by map function, build conditions like: * ifnull(`fieldname`, default_value) = %(fieldname)s * `fieldname` [=, !=, >, >=, <, <=] %(fieldname)s """ conditions = [] values = {} def _build_condition(key): """ filter's key is passed by map function build conditions like: * ifnull(`fieldname`, default_value) = %(fieldname)s * `fieldname` [=, !=, >, >=, <, <=] %(fieldname)s """ _operator = "=" _rhs = " %(" + key + ")s" value = filters.get(key) values[key] = value if isinstance(value, (list, tuple)): # value is a tuble like ("!=", 0) _operator = value[0] values[key] = value[1] if isinstance(value[1], (tuple, list)): # value is a list in tuple ("in", ("A", "B")) inner_list = [] for i, v in enumerate(value[1]): inner_key = "{0}_{1}".format(key, i) values[inner_key] = v inner_list.append("%({0})s".format(inner_key)) _rhs = " ({0})".format(", ".join(inner_list)) del values[key] if _operator not in ["=", "!=", ">", ">=", "<", "<=", "like", "in", "not in", "not like"]: _operator = "=" if "[" in key: split_key = key.split("[") condition = "ifnull(`" + split_key[0] + "`, " + split_key[1][:-1] + ") " \ + _operator + _rhs else: condition = "`" + key + "` " + _operator + _rhs conditions.append(condition) if isinstance(filters, int): # docname is a number, convert to string filters = str(filters) if isinstance(filters, string_types): filters = { "name": filters } for f in filters: _build_condition(f) return " and ".join(conditions), values def get(self, doctype, filters=None, as_dict=True, cache=False): """Returns `get_value` with fieldname='*'""" return self.get_value(doctype, filters, "*", as_dict=as_dict, cache=cache) def get_value(self, doctype, filters=None, fieldname="name", ignore=None, as_dict=False, debug=False, order_by=None, cache=False): """Returns a document property or list of properties. :param doctype: DocType name. :param filters: Filters like `{"x":"y"}` or name of the document. `None` if Single DocType. :param fieldname: Column name. :param ignore: Don't raise exception if table, column is missing. :param as_dict: Return values as dict. :param debug: Print query in error log. :param order_by: Column to order by Example: # return first customer starting with a frappe.db.get_value("Customer", {"name": ("like a%")}) # return last login of **User** `[email protected]` frappe.db.get_value("User", "[email protected]", "last_login") last_login, last_ip = frappe.db.get_value("User", "[email protected]", ["last_login", "last_ip"]) # returns default date_format frappe.db.get_value("System Settings", None, "date_format") """ ret = self.get_values(doctype, filters, fieldname, ignore, as_dict, debug, order_by, cache=cache) return ((len(ret[0]) > 1 or as_dict) and ret[0] or ret[0][0]) if ret else None def get_values(self, doctype, filters=None, fieldname="name", ignore=None, as_dict=False, debug=False, order_by=None, update=None, cache=False): """Returns multiple document properties. :param doctype: DocType name. :param filters: Filters like `{"x":"y"}` or name of the document. :param fieldname: Column name. :param ignore: Don't raise exception if table, column is missing. :param as_dict: Return values as dict. :param debug: Print query in error log. :param order_by: Column to order by Example: # return first customer starting with a customers = frappe.db.get_values("Customer", {"name": ("like a%")}) # return last login of **User** `[email protected]` user = frappe.db.get_values("User", "[email protected]", "*")[0] """ out = None if cache and isinstance(filters, string_types) and \ (doctype, filters, fieldname) in self.value_cache: return self.value_cache[(doctype, filters, fieldname)] if not order_by: order_by = 'modified desc' if isinstance(filters, list): out = self._get_value_for_many_names(doctype, filters, fieldname, debug=debug) else: fields = fieldname if fieldname!="*": if isinstance(fieldname, string_types): fields = [fieldname] else: fields = fieldname if (filters is not None) and (filters!=doctype or doctype=="DocType"): try: out = self._get_values_from_table(fields, filters, doctype, as_dict, debug, order_by, update) except Exception as e: if ignore and e.args[0] in (1146, 1054): # table or column not found, return None out = None elif (not ignore) and e.args[0]==1146: # table not found, look in singles out = self.get_values_from_single(fields, filters, doctype, as_dict, debug, update) else: raise else: out = self.get_values_from_single(fields, filters, doctype, as_dict, debug, update) if cache and isinstance(filters, string_types): self.value_cache[(doctype, filters, fieldname)] = out return out def get_values_from_single(self, fields, filters, doctype, as_dict=False, debug=False, update=None): """Get values from `tabSingles` (Single DocTypes) (internal). :param fields: List of fields, :param filters: Filters (dict). :param doctype: DocType name. """ # TODO # if not frappe.model.meta.is_single(doctype): # raise frappe.DoesNotExistError("DocType", doctype) if fields=="*" or isinstance(filters, dict): # check if single doc matches with filters values = self.get_singles_dict(doctype) if isinstance(filters, dict): for key, value in filters.items(): if values.get(key) != value: return [] if as_dict: return values and [values] or [] if isinstance(fields, list): return [map(lambda d: values.get(d), fields)] else: r = self.sql("""select field, value from tabSingles where field in (%s) and doctype=%s""" \ % (', '.join(['%s'] * len(fields)), '%s'), tuple(fields) + (doctype,), as_dict=False, debug=debug) # r = _cast_result(doctype, r) if as_dict: if r: r = frappe._dict(r) if update: r.update(update) return [r] else: return [] else: return r and [[i[1] for i in r]] or [] def get_singles_dict(self, doctype, debug = False): """Get Single DocType as dict. :param doctype: DocType of the single object whose value is requested Example: # Get coulmn and value of the single doctype Accounts Settings account_settings = frappe.db.get_singles_dict("Accounts Settings") """ result = self.sql(""" SELECT field, value FROM `tabSingles` WHERE doctype = %s """, doctype) # result = _cast_result(doctype, result) dict_ = frappe._dict(result) return dict_ def get_all(self, *args, **kwargs): return frappe.get_all(*args, **kwargs) def get_list(self, *args, **kwargs): return frappe.get_list(*args, **kwargs) def get_single_value(self, doctype, fieldname, cache=False): """Get property of Single DocType. Cache locally by default :param doctype: DocType of the single object whose value is requested :param fieldname: `fieldname` of the property whose value is requested Example: # Get the default value of the company from the Global Defaults doctype. company = frappe.db.get_single_value('Global Defaults', 'default_company') """ value = self.value_cache.setdefault(doctype, {}).get(fieldname) if value is not None: return value val = self.sql("""select value from tabSingles where doctype=%s and field=%s""", (doctype, fieldname)) val = val[0][0] if val else None if val=="0" or val=="1": # check type val = int(val) self.value_cache[doctype][fieldname] = val return val def get_singles_value(self, *args, **kwargs): """Alias for get_single_value""" return self.get_single_value(*args, **kwargs) def _get_values_from_table(self, fields, filters, doctype, as_dict, debug, order_by=None, update=None): fl = [] if isinstance(fields, (list, tuple)): for f in fields: if "(" in f or " as " in f: # function fl.append(f) else: fl.append("`" + f + "`") fl = ", ".join(fl) else: fl = fields if fields=="*": as_dict = True conditions, values = self.build_conditions(filters) order_by = ("order by " + order_by) if order_by else "" r = self.sql("select {0} from `tab{1}` {2} {3} {4}" .format(fl, doctype, "where" if conditions else "", conditions, order_by), values, as_dict=as_dict, debug=debug, update=update) return r def _get_value_for_many_names(self, doctype, names, field, debug=False): names = list(filter(None, names)) if names: return dict(self.sql("select name, `%s` from `tab%s` where name in (%s)" \ % (field, doctype, ", ".join(["%s"]*len(names))), names, debug=debug)) else: return {} def update(self, *args, **kwargs): """Update multiple values. Alias for `set_value`."""<|fim▁hole|> def set_value(self, dt, dn, field, val, modified=None, modified_by=None, update_modified=True, debug=False): """Set a single value in the database, do not call the ORM triggers but update the modified timestamp (unless specified not to). **Warning:** this function will not call Document events and should be avoided in normal cases. :param dt: DocType name. :param dn: Document name. :param field: Property / field name or dictionary of values to be updated :param value: Value to be updated. :param modified: Use this as the `modified` timestamp. :param modified_by: Set this user as `modified_by`. :param update_modified: default True. Set as false, if you don't want to update the timestamp. :param debug: Print the query in the developer / js console. """ if not modified: modified = now() if not modified_by: modified_by = frappe.session.user to_update = {} if update_modified: to_update = {"modified": modified, "modified_by": modified_by} if isinstance(field, dict): to_update.update(field) else: to_update.update({field: val}) if dn and dt!=dn: # with table conditions, values = self.build_conditions(dn) values.update(to_update) set_values = [] for key in to_update: set_values.append('`{0}`=%({0})s'.format(key)) self.sql("""update `tab{0}` set {1} where {2}""".format(dt, ', '.join(set_values), conditions), values, debug=debug) else: # for singles keys = list(to_update) self.sql(''' delete from tabSingles where field in ({0}) and doctype=%s'''.format(', '.join(['%s']*len(keys))), list(keys) + [dt], debug=debug) for key, value in iteritems(to_update): self.sql('''insert into tabSingles(doctype, field, value) values (%s, %s, %s)''', (dt, key, value), debug=debug) if dt in self.value_cache: del self.value_cache[dt] def set(self, doc, field, val): """Set value in document. **Avoid**""" doc.db_set(field, val) def touch(self, doctype, docname): """Update the modified timestamp of this document.""" from frappe.utils import now modified = now() frappe.db.sql("""update `tab{doctype}` set `modified`=%s where name=%s""".format(doctype=doctype), (modified, docname)) return modified def set_temp(self, value): """Set a temperory value and return a key.""" key = frappe.generate_hash() frappe.cache().hset("temp", key, value) return key def get_temp(self, key): """Return the temperory value and delete it.""" return frappe.cache().hget("temp", key) def set_global(self, key, val, user='__global'): """Save a global key value. Global values will be automatically set if they match fieldname.""" self.set_default(key, val, user) def get_global(self, key, user='__global'): """Returns a global key value.""" return self.get_default(key, user) def set_default(self, key, val, parent="__default", parenttype=None): """Sets a global / user default value.""" frappe.defaults.set_default(key, val, parent, parenttype) def add_default(self, key, val, parent="__default", parenttype=None): """Append a default value for a key, there can be multiple default values for a particular key.""" frappe.defaults.add_default(key, val, parent, parenttype) def get_default(self, key, parent="__default"): """Returns default value as a list if multiple or single""" d = self.get_defaults(key, parent) return isinstance(d, list) and d[0] or d def get_defaults(self, key=None, parent="__default"): """Get all defaults""" if key: defaults = frappe.defaults.get_defaults(parent) d = defaults.get(key, None) if(not d and key != frappe.scrub(key)): d = defaults.get(frappe.scrub(key), None) return d else: return frappe.defaults.get_defaults(parent) def begin(self): self.sql("start transaction") def commit(self): """Commit current transaction. Calls SQL `COMMIT`.""" self.sql("commit") frappe.local.rollback_observers = [] self.flush_realtime_log() enqueue_jobs_after_commit() flush_local_link_count() def flush_realtime_log(self): for args in frappe.local.realtime_log: frappe.async.emit_via_redis(*args) frappe.local.realtime_log = [] def rollback(self): """`ROLLBACK` current transaction.""" self.sql("rollback") self.begin() for obj in frappe.local.rollback_observers: if hasattr(obj, "on_rollback"): obj.on_rollback() frappe.local.rollback_observers = [] def field_exists(self, dt, fn): """Return true of field exists.""" return self.sql("select name from tabDocField where fieldname=%s and parent=%s", (dt, fn)) def table_exists(self, doctype): """Returns True if table for given doctype exists.""" return ("tab" + doctype) in self.get_tables() def get_tables(self): return [d[0] for d in self.sql("show tables")] def a_row_exists(self, doctype): """Returns True if atleast one row exists.""" return self.sql("select name from `tab{doctype}` limit 1".format(doctype=doctype)) def exists(self, dt, dn=None): """Returns true if document exists. :param dt: DocType name. :param dn: Document name or filter dict.""" if isinstance(dt, string_types): if dt!="DocType" and dt==dn: return True # single always exists (!) try: return self.get_value(dt, dn, "name") except: return None elif isinstance(dt, dict) and dt.get('doctype'): try: conditions = [] for d in dt: if d == 'doctype': continue conditions.append('`%s` = "%s"' % (d, cstr(dt[d]).replace('"', '\"'))) return self.sql('select name from `tab%s` where %s' % \ (dt['doctype'], " and ".join(conditions))) except: return None def count(self, dt, filters=None, debug=False, cache=False): """Returns `COUNT(*)` for given DocType and filters.""" if cache and not filters: cache_count = frappe.cache().get_value('doctype:count:{}'.format(dt)) if cache_count is not None: return cache_count if filters: conditions, filters = self.build_conditions(filters) count = frappe.db.sql("""select count(*) from `tab%s` where %s""" % (dt, conditions), filters, debug=debug)[0][0] return count else: count = frappe.db.sql("""select count(*) from `tab%s`""" % (dt,))[0][0] if cache: frappe.cache().set_value('doctype:count:{}'.format(dt), count, expires_in_sec = 86400) return count def get_creation_count(self, doctype, minutes): """Get count of records created in the last x minutes""" from frappe.utils import now_datetime from dateutil.relativedelta import relativedelta return frappe.db.sql("""select count(name) from `tab{doctype}` where creation >= %s""".format(doctype=doctype), now_datetime() - relativedelta(minutes=minutes))[0][0] def get_db_table_columns(self, table): """Returns list of column names from given table.""" return [r[0] for r in self.sql("DESC `%s`" % table)] def get_table_columns(self, doctype): """Returns list of column names from given doctype.""" return self.get_db_table_columns('tab' + doctype) def has_column(self, doctype, column): """Returns True if column exists in database.""" return column in self.get_table_columns(doctype) def get_column_type(self, doctype, column): return frappe.db.sql('''SELECT column_type FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'tab{0}' AND COLUMN_NAME = "{1}"'''.format(doctype, column))[0][0] def add_index(self, doctype, fields, index_name=None): """Creates an index with given fields if not already created. Index name will be `fieldname1_fieldname2_index`""" if not index_name: index_name = "_".join(fields) + "_index" # remove index length if present e.g. (10) from index name index_name = re.sub(r"\s*\([^)]+\)\s*", r"", index_name) if not frappe.db.sql("""show index from `tab%s` where Key_name="%s" """ % (doctype, index_name)): frappe.db.commit() frappe.db.sql("""alter table `tab%s` add index `%s`(%s)""" % (doctype, index_name, ", ".join(fields))) def add_unique(self, doctype, fields, constraint_name=None): if isinstance(fields, string_types): fields = [fields] if not constraint_name: constraint_name = "unique_" + "_".join(fields) if not frappe.db.sql("""select CONSTRAINT_NAME from information_schema.TABLE_CONSTRAINTS where table_name=%s and constraint_type='UNIQUE' and CONSTRAINT_NAME=%s""", ('tab' + doctype, constraint_name)): frappe.db.commit() frappe.db.sql("""alter table `tab%s` add unique `%s`(%s)""" % (doctype, constraint_name, ", ".join(fields))) def get_system_setting(self, key): def _load_system_settings(): return self.get_singles_dict("System Settings") return frappe.cache().get_value("system_settings", _load_system_settings).get(key) def close(self): """Close database connection.""" if self._conn: # self._cursor.close() self._conn.close() self._cursor = None self._conn = None def escape(self, s, percent=True): """Excape quotes and percent in given string.""" # pymysql expects unicode argument to escape_string with Python 3 s = as_unicode(pymysql.escape_string(as_unicode(s)), "utf-8").replace("`", "\\`") # NOTE separating % escape, because % escape should only be done when using LIKE operator # or when you use python format string to generate query that already has a %s # for example: sql("select name from `tabUser` where name=%s and {0}".format(conditions), something) # defaulting it to True, as this is the most frequent use case # ideally we shouldn't have to use ESCAPE and strive to pass values via the values argument of sql if percent: s = s.replace("%", "%%") return s def get_descendants(self, doctype, name): '''Return descendants of the current record''' lft, rgt = self.get_value(doctype, name, ('lft', 'rgt')) return self.sql_list('''select name from `tab{doctype}` where lft > {lft} and rgt < {rgt}'''.format(doctype=doctype, lft=lft, rgt=rgt)) def enqueue_jobs_after_commit(): if frappe.flags.enqueue_after_commit and len(frappe.flags.enqueue_after_commit) > 0: for job in frappe.flags.enqueue_after_commit: q = get_queue(job.get("queue"), async=job.get("async")) q.enqueue_call(execute_job, timeout=job.get("timeout"), kwargs=job.get("queue_args")) frappe.flags.enqueue_after_commit = []<|fim▁end|>
return self.set_value(*args, **kwargs)
<|file_name|>command_manager.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding=UTF-8 __author__ = "Pierre-Yves Langlois" __copyright__ = "https://github.com/pylanglois/uwsa/blob/master/LICENCE" __credits__ = ["Pierre-Yves Langlois"] __license__ = "BSD" __maintainer__ = "Pierre-Yves Langlois" from uwsas.common import * from uwsas.commands.abstract_command import AbstractCommand class CommandManager(AbstractCommand): NAME = 'CommandManager' def __init__(self): AbstractCommand.__init__(self) self.help = t(""" Usage: uwsa cmd param<|fim▁hole|> def get_log_name(self): return 'uwsas' cmanager = CommandManager()<|fim▁end|>
where cmd in %s """)
<|file_name|>newmessage.py<|end_file_name|><|fim▁begin|>'''u413 - an open-source BBS/transmit/PI-themed forum Copyright (C) 2012 PiMaster Copyright (C) 2012 EnKrypt<|fim▁hole|> (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.''' import command import user import database as db import util import bbcode def user_id(uname): user=db.query("SELECT username,id FROM users WHERE LCASE(username)='%s';"%db.escape(uname.lower())) if len(user)==0: return None return int(user[0]["id"]) def user_exists(uname): user=user_id(uname) if user==None: return False return True def nmsg_func(args,u413): if "step" in u413.cmddata: if u413.cmddata["step"]==1: u413.cmddata["step"]=2 args=args.strip().split()[0] to=user_id(args) if to==None: u413.type('"%s" is not a u413 user.'%args) return u413.cmddata["to"]=to u413.type("Enter the topic:") u413.set_context("TOPIC") u413.continue_cmd() elif u413.cmddata["step"]==2: u413.cmddata["step"]=3 u413.cmddata["topic"]=args u413.type("Enter your message:") u413.set_context("MESSAGE") u413.continue_cmd() elif u413.cmddata["step"]==3: db.query("INSERT INTO messages(sender,receiver,topic,msg,sent,seen) VALUES(%i,%i,'%s','%s',NOW(),FALSE);"%(u413.user.userid,u413.cmddata["to"],db.escape(u413.cmddata["topic"]),db.escape(args))) u413.type("Message sent.") u413.set_context('') else: params=args.split(' ',1) if len(args)==0: u413.cmddata["step"]=1 u413.type("Enter the receiver:") u413.set_context("USER") u413.continue_cmd() elif len(params)==1: u413.cmddata["step"]=2 args=params[0].strip().split()[0] to=user_id(args) if to==None: u413.type('"%s" is not a u413 user.'%args) return u413.cmddata["to"]=to u413.type("Enter the topic:") u413.set_context("TOPIC") u413.continue_cmd() else: u413.cmddata["step"]=3 args=params[0].strip().split()[0] to=user_id(args) if to==None: u413.type('"%s" is not a u413 user.'%args) return u413.cmddata["to"]=to u413.cmddata["topic"]=params[1] u413.type("Enter your message:") u413.set_context("MESSAGE") u413.continue_cmd() command.Command("NEWMESSAGE","[user [topic]]",{"id":"The ID of the PM"},"Sends a private message to another user.",nmsg_func,user.User.member)<|fim▁end|>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or
<|file_name|>fract.rs<|end_file_name|><|fim▁begin|>#![feature(core, core_float)] extern crate core; #[cfg(test)] mod tests { use core::num::Float; // impl Float for f32 { // #[inline] // fn nan() -> f32 { NAN } // // #[inline] // fn infinity() -> f32 { INFINITY } // // #[inline] // fn neg_infinity() -> f32 { NEG_INFINITY } // // #[inline] // fn zero() -> f32 { 0.0 } // // #[inline] // fn neg_zero() -> f32 { -0.0 } // // #[inline] // fn one() -> f32 { 1.0 } // // from_str_radix_float_impl! { f32 } // // /// Returns `true` if the number is NaN. // #[inline] // fn is_nan(self) -> bool { self != self } // // /// Returns `true` if the number is infinite. // #[inline] // fn is_infinite(self) -> bool { // self == Float::infinity() || self == Float::neg_infinity() // } // // /// Returns `true` if the number is neither infinite or NaN. // #[inline] // fn is_finite(self) -> bool { // !(self.is_nan() || self.is_infinite()) // } // // /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. // #[inline] // fn is_normal(self) -> bool { // self.classify() == Fp::Normal // } // // /// Returns the floating point category of the number. If only one property // /// is going to be tested, it is generally faster to use the specific // /// predicate instead. // fn classify(self) -> Fp { // const EXP_MASK: u32 = 0x7f800000; // const MAN_MASK: u32 = 0x007fffff; // // let bits: u32 = unsafe { mem::transmute(self) }; // match (bits & MAN_MASK, bits & EXP_MASK) { // (0, 0) => Fp::Zero, // (_, 0) => Fp::Subnormal, // (0, EXP_MASK) => Fp::Infinite, // (_, EXP_MASK) => Fp::Nan, // _ => Fp::Normal, // } // } // // /// Returns the mantissa, exponent and sign as integers. // fn integer_decode(self) -> (u64, i16, i8) { // let bits: u32 = unsafe { mem::transmute(self) }; // let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 }; // let mut exponent: i16 = ((bits >> 23) & 0xff) as i16; // let mantissa = if exponent == 0 { // (bits & 0x7fffff) << 1 // } else { // (bits & 0x7fffff) | 0x800000 // }; // // Exponent bias + mantissa shift // exponent -= 127 + 23; // (mantissa as u64, exponent, sign) // } // // /// Rounds towards minus infinity. // #[inline] // fn floor(self) -> f32 { // unsafe { intrinsics::floorf32(self) } // } // // /// Rounds towards plus infinity. // #[inline] // fn ceil(self) -> f32 { // unsafe { intrinsics::ceilf32(self) } // } // // /// Rounds to nearest integer. Rounds half-way cases away from zero. // #[inline] // fn round(self) -> f32 { // unsafe { intrinsics::roundf32(self) } // } // // /// Returns the integer part of the number (rounds towards zero). // #[inline] // fn trunc(self) -> f32 { // unsafe { intrinsics::truncf32(self) } // } // // /// The fractional part of the number, satisfying: // /// // /// ``` // /// let x = 1.65f32; // /// assert!(x == x.trunc() + x.fract()) // /// ``` // #[inline] // fn fract(self) -> f32 { self - self.trunc() } // // /// Computes the absolute value of `self`. Returns `Float::nan()` if the<|fim▁hole|> // /// number is `Float::nan()`. // #[inline] // fn abs(self) -> f32 { // unsafe { intrinsics::fabsf32(self) } // } // // /// Returns a number that represents the sign of `self`. // /// // /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` // /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` // /// - `Float::nan()` if the number is `Float::nan()` // #[inline] // fn signum(self) -> f32 { // if self.is_nan() { // Float::nan() // } else { // unsafe { intrinsics::copysignf32(1.0, self) } // } // } // // /// Returns `true` if `self` is positive, including `+0.0` and // /// `Float::infinity()`. // #[inline] // fn is_positive(self) -> bool { // self > 0.0 || (1.0 / self) == Float::infinity() // } // // /// Returns `true` if `self` is negative, including `-0.0` and // /// `Float::neg_infinity()`. // #[inline] // fn is_negative(self) -> bool { // self < 0.0 || (1.0 / self) == Float::neg_infinity() // } // // /// Fused multiply-add. Computes `(self * a) + b` with only one rounding // /// error. This produces a more accurate result with better performance than // /// a separate multiplication operation followed by an add. // #[inline] // fn mul_add(self, a: f32, b: f32) -> f32 { // unsafe { intrinsics::fmaf32(self, a, b) } // } // // /// Returns the reciprocal (multiplicative inverse) of the number. // #[inline] // fn recip(self) -> f32 { 1.0 / self } // // #[inline] // fn powi(self, n: i32) -> f32 { // unsafe { intrinsics::powif32(self, n) } // } // // #[inline] // fn powf(self, n: f32) -> f32 { // unsafe { intrinsics::powf32(self, n) } // } // // #[inline] // fn sqrt(self) -> f32 { // if self < 0.0 { // NAN // } else { // unsafe { intrinsics::sqrtf32(self) } // } // } // // #[inline] // fn rsqrt(self) -> f32 { self.sqrt().recip() } // // /// Returns the exponential of the number. // #[inline] // fn exp(self) -> f32 { // unsafe { intrinsics::expf32(self) } // } // // /// Returns 2 raised to the power of the number. // #[inline] // fn exp2(self) -> f32 { // unsafe { intrinsics::exp2f32(self) } // } // // /// Returns the natural logarithm of the number. // #[inline] // fn ln(self) -> f32 { // unsafe { intrinsics::logf32(self) } // } // // /// Returns the logarithm of the number with respect to an arbitrary base. // #[inline] // fn log(self, base: f32) -> f32 { self.ln() / base.ln() } // // /// Returns the base 2 logarithm of the number. // #[inline] // fn log2(self) -> f32 { // unsafe { intrinsics::log2f32(self) } // } // // /// Returns the base 10 logarithm of the number. // #[inline] // fn log10(self) -> f32 { // unsafe { intrinsics::log10f32(self) } // } // // /// Converts to degrees, assuming the number is in radians. // #[inline] // fn to_degrees(self) -> f32 { self * (180.0f32 / consts::PI) } // // /// Converts to radians, assuming the number is in degrees. // #[inline] // fn to_radians(self) -> f32 { // let value: f32 = consts::PI; // self * (value / 180.0f32) // } // } #[test] fn fract_test1() { let value: f32 = 1.01; let result: f32 = value.fract(); assert_eq!(result, 0.00999999); } #[test] fn fract_test2() { let value: f32 = 1.49; let result: f32 = value.fract(); assert_eq!(result, 0.49); } #[test] fn fract_test3() { let value: f32 = 1.50; let result: f32 = value.fract(); assert_eq!(result, 0.50); } #[test] fn fract_test4() { let value: f32 = 1.99; let result: f32 = value.fract(); assert_eq!(result, 0.99); } #[test] fn fract_test5() { let value: f32 = -1.01; let result: f32 = value.fract(); assert_eq!(result, -0.00999999); } #[test] fn fract_test6() { let value: f32 = -1.49; let result: f32 = value.fract(); assert_eq!(result, -0.49); } #[test] fn fract_test7() { let value: f32 = -1.50; let result: f32 = value.fract(); assert_eq!(result, -0.5); } #[test] fn fract_test8() { let value: f32 = -1.99; let result: f32 = value.fract(); assert_eq!(result, -0.99); } }<|fim▁end|>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Defines the Weld abstract syntax tree. //! //! Most of Weld's optimizations occur over the AST, which doubles as a "High-Level IR." The AST //! captures the expressions in Weld using a tree data structure. pub use self::ast::*; // Various convinience methods on the AST. pub use self::builder::NewExpr; pub use self::cmp::CompareIgnoringSymbols; pub use self::hash::HashIgnoringSymbols; pub use self::pretty_print::{PrettyPrint, PrettyPrintConfig}; pub use self::type_inference::InferTypes; pub use self::uniquify::Uniquify; pub mod constructors; pub mod prelude; mod ast; mod builder; mod cmp;<|fim▁hole|>mod hash; mod pretty_print; mod type_inference; mod uniquify;<|fim▁end|>
<|file_name|>0005_auto__add_macadjanuserprofile.py<|end_file_name|><|fim▁begin|># -*- coding: 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 'MacadjanUserProfile' db.create_table(u'macadjan_macadjanuserprofile', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='macadjan_profile', unique=True, to=orm['auth.User'])), ('map_source', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='user_profiles', null=True, on_delete=models.SET_NULL, to=orm['macadjan.MapSource'])), )) db.send_create_signal(u'macadjan', ['MacadjanUserProfile']) def backwards(self, orm): # Deleting model 'MacadjanUserProfile' db.delete_table(u'macadjan_macadjanuserprofile') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'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': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), '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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'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'}) }, u'macadjan.category': { 'Meta': {'ordering': "['name']", 'object_name': 'Category'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'marker_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'macadjan.entitytag': { 'Meta': {'ordering': "['collection', 'name']", 'object_name': 'EntityTag'}, 'collection': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tags'", 'to': u"orm['macadjan.TagCollection']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'macadjan.entitytype': { 'Meta': {'ordering': "['name']", 'object_name': 'EntityType'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'macadjan.macadjanuserprofile': { 'Meta': {'object_name': 'MacadjanUserProfile'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'map_source': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_profiles'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['macadjan.MapSource']"}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'macadjan_profile'", 'unique': 'True', 'to': u"orm['auth.User']"}) }, u'macadjan.mapsource': { 'Meta': {'ordering': "['name']", 'object_name': 'MapSource'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'blank': 'True'}), 'web': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}) }, u'macadjan.siteinfo': { 'Meta': {'ordering': "['website_name']", 'object_name': 'SiteInfo'}, 'additional_info_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'additional_info_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'address_1_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'address_2_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'alias_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'change_proposal_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'change_proposal_title': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'city_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'contact_person_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'contact_phone_1_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'contact_phone_2_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'country_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'creation_year_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'description_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'description_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'email_2_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'email_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'entity_change_proposal_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'fax_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'finances_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'finances_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'footer_line': ('django.db.models.fields.TextField', [], {}), 'goals_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'goals_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'how_to_access_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'how_to_access_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitude_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'legal_form_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'longitude_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'map_bounds_bottom': ('django.db.models.fields.FloatField', [], {'default': '-20037508.34'}), 'map_bounds_left': ('django.db.models.fields.FloatField', [], {'default': '-20037508.34'}), 'map_bounds_right': ('django.db.models.fields.FloatField', [], {'default': '20037508.34'}),<|fim▁hole|> 'map_initial_lat': ('django.db.models.fields.FloatField', [], {}), 'map_initial_lon': ('django.db.models.fields.FloatField', [], {}), 'map_initial_zoom': ('django.db.models.fields.IntegerField', [], {}), 'map_max_resolution': ('django.db.models.fields.IntegerField', [], {'default': '156543'}), 'map_units': ('django.db.models.fields.CharField', [], {'default': "'meters'", 'max_length': '50'}), 'map_zoom_levels': ('django.db.models.fields.IntegerField', [], {'default': '18'}), 'needs_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'needs_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'networks_member_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'networks_member_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'networks_works_with_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'networks_works_with_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'new_entity_proposal_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'new_entity_proposal_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'new_entity_proposal_title': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'offerings_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'offerings_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'ongoing_projects_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'ongoing_projects_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'proponent_comment_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'proponent_email_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'proposal_bottom_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'province_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'site': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'site_info'", 'unique': 'True', 'to': u"orm['sites.Site']"}), 'social_values_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'social_values_hints': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'subcategories_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'summary_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'web_2_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'web_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'website_description': ('django.db.models.fields.TextField', [], {}), 'website_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'website_subtitle': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100', 'blank': 'True'}), 'zipcode_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'zone_field_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) }, u'macadjan.subcategory': { 'Meta': {'ordering': "['category', 'name']", 'object_name': 'SubCategory'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'subcategories'", 'to': u"orm['macadjan.Category']"}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'marker_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'macadjan.tagcollection': { 'Meta': {'ordering': "['name']", 'object_name': 'TagCollection'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['macadjan']<|fim▁end|>
'map_bounds_top': ('django.db.models.fields.FloatField', [], {'default': '20037508.34'}),
<|file_name|>StarTreeIndexContainer.java<|end_file_name|><|fim▁begin|>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/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 org.apache.pinot.core.startree.v2.store; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.nio.ByteOrder; import java.util.List; import java.util.Map; import org.apache.commons.configuration.ConfigurationException; import org.apache.pinot.common.segment.ReadMode; import org.apache.pinot.core.segment.index.column.ColumnIndexContainer; import org.apache.pinot.core.segment.index.metadata.SegmentMetadataImpl; import org.apache.pinot.core.segment.memory.PinotDataBuffer; import org.apache.pinot.core.startree.v2.StarTreeV2; import org.apache.pinot.core.startree.v2.StarTreeV2Constants; import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexKey; import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexValue; /** * The {@code StarTreeIndexContainer} class contains the indexes for multiple star-trees. */<|fim▁hole|>public class StarTreeIndexContainer implements Closeable { private final PinotDataBuffer _dataBuffer; private final List<StarTreeV2> _starTrees; public StarTreeIndexContainer(File segmentDirectory, SegmentMetadataImpl segmentMetadata, Map<String, ColumnIndexContainer> indexContainerMap, ReadMode readMode) throws ConfigurationException, IOException { File indexFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_FILE_NAME); if (readMode == ReadMode.heap) { _dataBuffer = PinotDataBuffer .loadFile(indexFile, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer"); } else { _dataBuffer = PinotDataBuffer .mapFile(indexFile, true, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer"); } File indexMapFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_MAP_FILE_NAME); List<Map<IndexKey, IndexValue>> indexMapList = StarTreeIndexMapUtils.loadFromFile(indexMapFile, segmentMetadata.getStarTreeV2MetadataList().size()); _starTrees = StarTreeLoaderUtils.loadStarTreeV2(_dataBuffer, indexMapList, segmentMetadata, indexContainerMap); } public List<StarTreeV2> getStarTrees() { return _starTrees; } @Override public void close() throws IOException { _dataBuffer.close(); } }<|fim▁end|>
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>/* Copyright 2013 Jesse 'Jeaye' Wilkerson See licensing in LICENSE file, or at: http://www.opensource.org/licenses/BSD-3-Clause File: server/main.rs Author: Jesse 'Jeaye' Wilkerson Description: Main engine controller and entry point for the server. */ #[feature(globs)]; #[feature(macro_rules)]; #[feature(managed_boxes)]; extern mod log; extern mod console; extern mod ui; use std::os; use log::Log; #[macro_escape] #[path = "../shared/log/macros.rs"] mod macros; struct Server { ui_driver: Option<~ui::Driver>, } impl Server { pub fn new() -> Server { let server = Server { ui_driver: None, }; server } pub fn initialize(&mut self) { /* Create the console. */ let _console = console::Console::new(); self.parse_cmd_line(); } fn parse_cmd_line(&mut self) { let args = os::args(); if args.contains(&~"--help") { Server::show_help(); } if args.contains(&~"--version") { Server::show_version(); } /* Determine the UI driver. */ let driver = if args.contains(&~"--gui") { log_fail!("GUI mode is not yet implemented"); } else<|fim▁hole|> self.ui_driver = driver; } fn show_version() { println!("Q³ Server {}.{}", env!("VERSION"), env!("COMMIT")); fail!("Exiting"); } fn show_help() { let args = os::args(); println!("Q³ Server {}.{}", env!("VERSION"), env!("COMMIT")); println!("Usage:"); println!("\t{} [options...]", args[0]); println!(""); println!("Options:"); println!("\t--help\tShows this help menu and exits"); println!("\t--tui\tEnable textual user interface mode (default)"); println!("\t--gui\tEnable graphical user interface mode"); println!(""); fail!("Exiting"); } } fn main() { log::Log::initialize(); let mut server = Server::new(); server.initialize(); }<|fim▁end|>
{ ui::term::initialize() }; log_assert!(driver.is_some(), "Unable to initialize UI");
<|file_name|>blocks.py<|end_file_name|><|fim▁begin|>import time import rlp import trie import db import utils import processblock import transactions import logging import copy import sys from repoze.lru import lru_cache # logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() INITIAL_DIFFICULTY = 2 ** 17 GENESIS_PREVHASH = '\00' * 32 GENESIS_COINBASE = "0" * 40 GENESIS_NONCE = utils.sha3(chr(42)) GENESIS_GAS_LIMIT = 10 ** 6 MIN_GAS_LIMIT = 125000 GASLIMIT_EMA_FACTOR = 1024 BLOCK_REWARD = 1500 * utils.denoms.finney UNCLE_REWARD = 15 * BLOCK_REWARD / 16 NEPHEW_REWARD = BLOCK_REWARD / 32 BLOCK_DIFF_FACTOR = 1024 GENESIS_MIN_GAS_PRICE = 0 BLKLIM_FACTOR_NOM = 6 BLKLIM_FACTOR_DEN = 5 DIFF_ADJUSTMENT_CUTOFF = 5 RECORDING = 1 NONE = 0 VERIFYING = -1 GENESIS_INITIAL_ALLOC = \ {"51ba59315b3a95761d0863b05ccc7a7f54703d99": 2 ** 200, # (G) "e6716f9544a56c530d868e4bfbacb172315bdead": 2 ** 200, # (J) "b9c015918bdaba24b4ff057a92a3873d6eb201be": 2 ** 200, # (V) "1a26338f0d905e295fccb71fa9ea849ffa12aaf4": 2 ** 200, # (A) "2ef47100e0787b915105fd5e3f4ff6752079d5cb": 2 ** 200, # (M) "cd2a3d9f938e13cd947ec05abc7fe734df8dd826": 2 ** 200, # (R) "6c386a4b26f73c802f34673f7248bb118f97424a": 2 ** 200, # (HH) "e4157b34ea9615cfbde6b4fda419828124b70c78": 2 ** 200, # (CH) } block_structure = [ ["prevhash", "bin", "\00" * 32], ["uncles_hash", "bin", utils.sha3(rlp.encode([]))], ["coinbase", "addr", GENESIS_COINBASE], ["state_root", "trie_root", trie.BLANK_ROOT], ["tx_list_root", "trie_root", trie.BLANK_ROOT], ["difficulty", "int", INITIAL_DIFFICULTY], ["number", "int", 0], ["min_gas_price", "int", GENESIS_MIN_GAS_PRICE], ["gas_limit", "int", GENESIS_GAS_LIMIT], ["gas_used", "int", 0], ["timestamp", "int", 0], ["extra_data", "bin", ""], ["nonce", "bin", ""], ] block_structure_rev = {} for i, (name, typ, default) in enumerate(block_structure): block_structure_rev[name] = [i, typ, default] acct_structure = [ ["nonce", "int", 0], ["balance", "int", 0], ["storage", "trie_root", trie.BLANK_ROOT], ["code", "hash", ""], ] acct_structure_rev = {} for i, (name, typ, default) in enumerate(acct_structure): acct_structure_rev[name] = [i, typ, default] def calc_difficulty(parent, timestamp): offset = parent.difficulty / BLOCK_DIFF_FACTOR sign = 1 if timestamp - parent.timestamp < DIFF_ADJUSTMENT_CUTOFF else -1 return parent.difficulty + offset * sign def calc_gaslimit(parent): prior_contribution = parent.gas_limit * (GASLIMIT_EMA_FACTOR - 1) new_contribution = parent.gas_used * BLKLIM_FACTOR_NOM / BLKLIM_FACTOR_DEN gl = (prior_contribution + new_contribution) / GASLIMIT_EMA_FACTOR return max(gl, MIN_GAS_LIMIT) class UnknownParentException(Exception): pass class TransientBlock(object): """ Read only, non persisted, not validated representation of a block """ def __init__(self, rlpdata): self.rlpdata = rlpdata self.header_args, transaction_list, uncles = rlp.decode(rlpdata) self.hash = utils.sha3(rlp.encode(self.header_args)) self.transaction_list = transaction_list # rlp encoded transactions self.uncles = uncles for i, (name, typ, default) in enumerate(block_structure): setattr(self, name, utils.decoders[typ](self.header_args[i])) def __repr__(self): return '<TransientBlock(#%d %s %s)>' %\ (self.number, self.hash.encode('hex')[ :4], self.prevhash.encode('hex')[:4]) def check_header_pow(header): assert len(header[-1]) == 32 rlp_Hn = rlp.encode(header[:-1]) nonce = header[-1] diff = utils.decoders['int'](header[block_structure_rev['difficulty'][0]]) h = utils.sha3(utils.sha3(rlp_Hn) + nonce) return utils.big_endian_to_int(h) < 2 ** 256 / diff class Block(object): def __init__(self, prevhash='\00' * 32, uncles_hash=block_structure_rev['uncles_hash'][2], coinbase=block_structure_rev['coinbase'][2], state_root=trie.BLANK_ROOT, tx_list_root=trie.BLANK_ROOT, difficulty=block_structure_rev['difficulty'][2], number=0, min_gas_price=block_structure_rev['min_gas_price'][2], gas_limit=block_structure_rev['gas_limit'][2], gas_used=0, timestamp=0, extra_data='', nonce='', transaction_list=[], uncles=[], header=None): self.prevhash = prevhash self.uncles_hash = uncles_hash self.coinbase = coinbase self.difficulty = difficulty self.number = number self.min_gas_price = min_gas_price self.gas_limit = gas_limit self.gas_used = gas_used self.timestamp = timestamp self.extra_data = extra_data self.nonce = nonce self.uncles = uncles self.suicides = [] self.postqueue = [] self.caches = { 'balance': {}, 'nonce': {}, 'code': {}, 'all': {} } self.journal = [] self.transactions = trie.Trie(utils.get_db_path(), tx_list_root) self.transaction_count = 0 self.state = trie.Trie(utils.get_db_path(), state_root) self.proof_mode = None self.proof_nodes = [] # If transaction_list is None, then it's a block header imported for # SPV purposes if transaction_list is not None: # support init with transactions only if state is known assert self.state.root_hash_valid() for tx_lst_serialized, state_root, gas_used_encoded \ in transaction_list: self._add_transaction_to_list( tx_lst_serialized, state_root, gas_used_encoded) if tx_list_root != self.transactions.root_hash: raise Exception("Transaction list root hash does not match!") if not self.is_genesis() and self.nonce and\ not check_header_pow(header or self.list_header()): raise Exception("PoW check failed") # make sure we are all on the same db assert self.state.db.db == self.transactions.db.db # use de/encoders to check type and validity for name, typ, d in block_structure: v = getattr(self, name) assert utils.decoders[typ](utils.encoders[typ](v)) == v # Basic consistency verifications if not self.state.root_hash_valid(): raise Exception( "State Merkle root not found in database! %r" % self) if not self.transactions.root_hash_valid(): raise Exception( "Transactions root not found in database! %r" % self) if len(self.extra_data) > 1024: raise Exception("Extra data cannot exceed 1024 bytes") if self.coinbase == '': raise Exception("Coinbase cannot be empty address") def validate_uncles(self): if utils.sha3(rlp.encode(self.uncles)) != self.uncles_hash: return False # Check uncle validity ancestor_chain = [self] # Uncle can have a block from 2-7 blocks ago as its parent for i in [1, 2, 3, 4, 5, 6, 7]: if ancestor_chain[-1].number > 0: ancestor_chain.append(ancestor_chain[-1].get_parent()) ineligible = [] # Uncles of this block cannot be direct ancestors and cannot also # be uncles included 1-6 blocks ago for ancestor in ancestor_chain[1:]: ineligible.extend(ancestor.uncles) ineligible.extend([b.list_header() for b in ancestor_chain]) eligible_ancestor_hashes = [x.hash for x in ancestor_chain[2:]] for uncle in self.uncles: if not check_header_pow(uncle): sys.stderr.write('1\n\n') return False # uncle's parent cannot be the block's own parent prevhash = uncle[block_structure_rev['prevhash'][0]] if prevhash not in eligible_ancestor_hashes: logger.debug("%r: Uncle does not have a valid ancestor", self) sys.stderr.write('2 ' + prevhash.encode('hex') + ' ' + str(map(lambda x: x.encode('hex'), eligible_ancestor_hashes)) + '\n\n') return False if uncle in ineligible: sys.stderr.write('3\n\n') logger.debug("%r: Duplicate uncle %r", self, utils.sha3(rlp.encode(uncle)).encode('hex')) return False ineligible.append(uncle) return True def is_genesis(self): return self.prevhash == GENESIS_PREVHASH and \ self.nonce == GENESIS_NONCE def check_proof_of_work(self, nonce): H = self.list_header() H[-1] = nonce return check_header_pow(H) @classmethod def deserialize_header(cls, header_data): if isinstance(header_data, (str, unicode)): header_data = rlp.decode(header_data) assert len(header_data) == len(block_structure) kargs = {} # Deserialize all properties for i, (name, typ, default) in enumerate(block_structure): kargs[name] = utils.decoders[typ](header_data[i]) return kargs @classmethod def deserialize(cls, rlpdata): header_args, transaction_list, uncles = rlp.decode(rlpdata) kargs = cls.deserialize_header(header_args) kargs['header'] = header_args kargs['transaction_list'] = transaction_list kargs['uncles'] = uncles # if we don't have the state we need to replay transactions _db = db.DB(utils.get_db_path()) if len(kargs['state_root']) == 32 and kargs['state_root'] in _db: return Block(**kargs) elif kargs['prevhash'] == GENESIS_PREVHASH: return Block(**kargs) else: # no state, need to replay try: parent = get_block(kargs['prevhash']) except KeyError: raise UnknownParentException(kargs['prevhash'].encode('hex')) return parent.deserialize_child(rlpdata) @classmethod def init_from_header(cls, rlpdata): kargs = cls.deserialize_header(rlpdata) kargs['transaction_list'] = None kargs['uncles'] = None return Block(**kargs) def deserialize_child(self, rlpdata): """ deserialization w/ replaying transactions """ header_args, transaction_list, uncles = rlp.decode(rlpdata) assert len(header_args) == len(block_structure) kargs = dict(transaction_list=transaction_list, uncles=uncles) # Deserialize all properties for i, (name, typ, default) in enumerate(block_structure): kargs[name] = utils.decoders[typ](header_args[i]) block = Block.init_from_parent(self, kargs['coinbase'], extra_data=kargs['extra_data'], timestamp=kargs['timestamp'], uncles=uncles) # replay transactions for tx_lst_serialized, _state_root, _gas_used_encoded in \ transaction_list: tx = transactions.Transaction.create(tx_lst_serialized) # logger.debug('state:\n%s', utils.dump_state(block.state)) # logger.debug('applying %r', tx) success, output = processblock.apply_transaction(block, tx) #block.add_transaction_to_list(tx) # < this is done by processblock # logger.debug('state:\n%s', utils.dump_state(block.state)) logger.debug('d %s %s', _gas_used_encoded, block.gas_used) assert utils.decode_int(_gas_used_encoded) == block.gas_used, \ "Gas mismatch (ours %d, theirs %d) on block: %r" % \ (block.gas_used, _gas_used_encoded, block.to_dict(False, True, True)) assert _state_root == block.state.root_hash, \ "State root mismatch (ours %r theirs %r) on block: %r" % \ (block.state.root_hash.encode('hex'), _state_root.encode('hex'), block.to_dict(False, True, True)) block.finalize() block.uncles_hash = kargs['uncles_hash'] block.nonce = kargs['nonce'] block.min_gas_price = kargs['min_gas_price'] # checks assert block.prevhash == self.hash assert block.gas_used == kargs['gas_used'] assert block.gas_limit == kargs['gas_limit'] assert block.timestamp == kargs['timestamp'] assert block.difficulty == kargs['difficulty'] assert block.number == kargs['number'] assert block.extra_data == kargs['extra_data'] assert utils.sha3(rlp.encode(block.uncles)) == kargs['uncles_hash'] assert block.tx_list_root == kargs['tx_list_root'] assert block.state.root_hash == kargs['state_root'], (block.state.root_hash, kargs['state_root']) return block @classmethod def hex_deserialize(cls, hexrlpdata): return cls.deserialize(hexrlpdata.decode('hex')) def mk_blank_acct(self): if not hasattr(self, '_blank_acct'): codehash = '' self.state.db.put(codehash, '') self._blank_acct = [utils.encode_int(0), utils.encode_int(0), trie.BLANK_ROOT, codehash] return self._blank_acct[:] def get_acct(self, address): if len(address) == 40: address = address.decode('hex') acct = rlp.decode(self.state.get(address)) or self.mk_blank_acct() return tuple(utils.decoders[t](acct[i]) for i, (n, t, d) in enumerate(acct_structure)) # _get_acct_item(bin or hex, int) -> bin def _get_acct_item(self, address, param): ''' get account item :param address: account address, can be binary or hex string :param param: parameter to get ''' if param != 'storage' and address in self.caches[param]: return self.caches[param][address] return self.get_acct(address)[acct_structure_rev[param][0]] # _set_acct_item(bin or hex, int, bin) def _set_acct_item(self, address, param, value): ''' set account item :param address: account address, can be binary or hex string :param param: parameter to set :param value: new value ''' # logger.debug('set acct %r %r %d', address, param, value) self.set_and_journal(param, address, value) self.set_and_journal('all', address, True) def set_and_journal(self, cache, index, value): prev = self.caches[cache].get(index, None) if prev != value: self.journal.append([cache, index, prev, value]) self.caches[cache][index] = value # _delta_item(bin or hex, int, int) -> success/fail def _delta_item(self, address, param, value): ''' add value to account item :param address: account address, can be binary or hex string :param param: parameter to increase/decrease :param value: can be positive or negative ''' value = self._get_acct_item(address, param) + value if value < 0: return False self._set_acct_item(address, param, value) return True def _add_transaction_to_list(self, tx_lst_serialized, state_root, gas_used_encoded): # adds encoded data # FIXME: the constructor should get objects assert isinstance(tx_lst_serialized, list) data = [tx_lst_serialized, state_root, gas_used_encoded] self.transactions.update( rlp.encode(utils.encode_int(self.transaction_count)), rlp.encode(data)) self.transaction_count += 1 def add_transaction_to_list(self, tx): tx_lst_serialized = rlp.decode(tx.serialize()) self._add_transaction_to_list(tx_lst_serialized, self.state_root, utils.encode_int(self.gas_used)) def _list_transactions(self): # returns [[tx_lst_serialized, state_root, gas_used_encoded],...] txlist = [] for i in range(self.transaction_count): txlist.append(self.get_transaction(i)) return txlist def get_transaction(self, num): # returns [tx_lst_serialized, state_root, gas_used_encoded] return rlp.decode(self.transactions.get(rlp.encode(utils.encode_int(num)))) def get_transactions(self): return [transactions.Transaction.create(tx) for tx, s, g in self._list_transactions()] def get_nonce(self, address): return self._get_acct_item(address, 'nonce') def set_nonce(self, address, value): return self._set_acct_item(address, 'nonce', value) def increment_nonce(self, address): return self._delta_item(address, 'nonce', 1) def decrement_nonce(self, address): return self._delta_item(address, 'nonce', -1) def get_balance(self, address): return self._get_acct_item(address, 'balance') def set_balance(self, address, value): self._set_acct_item(address, 'balance', value) def delta_balance(self, address, value): return self._delta_item(address, 'balance', value) def transfer_value(self, from_addr, to_addr, value): assert value >= 0 if self.delta_balance(from_addr, -value): return self.delta_balance(to_addr, value) return False def get_code(self, address): return self._get_acct_item(address, 'code') def set_code(self, address, value): self._set_acct_item(address, 'code', value) def get_storage(self, address): storage_root = self._get_acct_item(address, 'storage') return trie.Trie(utils.get_db_path(), storage_root) def get_storage_data(self, address, index): if 'storage:'+address in self.caches: if index in self.caches['storage:'+address]: return self.caches['storage:'+address][index] t = self.get_storage(address) t.proof_mode = self.proof_mode t.proof_nodes = self.proof_nodes key = utils.zpad(utils.coerce_to_bytes(index), 32) val = rlp.decode(t.get(key)) if self.proof_mode == RECORDING: self.proof_nodes.extend(t.proof_nodes) return utils.big_endian_to_int(val) if val else 0 def set_storage_data(self, address, index, val): if 'storage:'+address not in self.caches: self.caches['storage:'+address] = {} self.set_and_journal('all', address, True) self.set_and_journal('storage:'+address, index, val) def commit_state(self): changes = [] if not len(self.journal): processblock.pblogger.log('delta', changes=[]) return for address in self.caches['all']: acct = rlp.decode(self.state.get(address.decode('hex'))) \ or self.mk_blank_acct() for i, (key, typ, default) in enumerate(acct_structure): if key == 'storage': t = trie.Trie(utils.get_db_path(), acct[i]) t.proof_mode = self.proof_mode t.proof_nodes = self.proof_nodes for k, v in self.caches.get('storage:'+address, {}).iteritems(): enckey = utils.zpad(utils.coerce_to_bytes(k), 32) val = rlp.encode(utils.int_to_big_endian(v)) changes.append(['storage', address, k, v]) if v: t.update(enckey, val) else: t.delete(enckey) acct[i] = t.root_hash if self.proof_mode == RECORDING: self.proof_nodes.extend(t.proof_nodes) else: if address in self.caches[key]: v = self.caches[key].get(address, default) changes.append([key, address, v]) acct[i] = utils.encoders[acct_structure[i][1]](v) self.state.update(address.decode('hex'), rlp.encode(acct)) if self.proof_mode == RECORDING: self.proof_nodes.extend(self.state.proof_nodes) self.state.proof_nodes = [] if processblock.pblogger.log_state_delta: processblock.pblogger.log('delta', changes=changes) self.reset_cache() def del_account(self, address): self.commit_state() if len(address) == 40: address = address.decode('hex') self.state.delete(address) def account_to_dict(self, address, with_storage_root=False, with_storage=True, for_vmtest=False): if with_storage_root: assert len(self.journal) == 0 med_dict = {} for i, val in enumerate(self.get_acct(address)): name, typ, default = acct_structure[i] key = acct_structure[i][0] if name == 'storage': strie = trie.Trie(utils.get_db_path(), val) if with_storage_root: med_dict['storage_root'] = strie.get_root_hash().encode('hex') else: med_dict[key] = self.caches[key].get(address, utils.printers[typ](val)) if with_storage: med_dict['storage'] = {} d = strie.to_dict() subcache = self.caches.get('storage:'+address, {}) subkeys = [utils.zpad(utils.coerce_to_bytes(kk), 32) for kk in subcache.keys()] for k in d.keys() + subkeys: v = d.get(k, None) v2 = subcache.get(utils.big_endian_to_int(k), None) hexkey = '0x'+utils.zunpad(k).encode('hex') if v2 is not None: if v2 != 0: med_dict['storage'][hexkey] = \ '0x'+utils.int_to_big_endian(v2).encode('hex') elif v is not None: med_dict['storage'][hexkey] = '0x'+rlp.decode(v).encode('hex') return med_dict def reset_cache(self): self.caches = { 'all': {}, 'balance': {}, 'nonce': {}, 'code': {}, } self.journal = [] # Revert computation def snapshot(self): return { 'state': self.state.root_hash, 'gas': self.gas_used, 'txs': self.transactions, 'txcount': self.transaction_count, 'postqueue': copy.copy(self.postqueue), 'suicides': self.suicides, 'suicides_size': len(self.suicides), 'journal': self.journal, # pointer to reference, so is not static 'journal_size': len(self.journal) } def revert(self, mysnapshot): self.journal = mysnapshot['journal'] logger.debug('reverting') while len(self.journal) > mysnapshot['journal_size']: cache, index, prev, post = self.journal.pop() logger.debug('%r %r %r %r', cache, index, prev, post) if prev is not None: self.caches[cache][index] = prev else: del self.caches[cache][index] self.suicides = mysnapshot['suicides'] while len(self.suicides) > mysnapshot['suicides_size']: self.suicides.pop() self.state.root_hash = mysnapshot['state'] self.gas_used = mysnapshot['gas'] self.transactions = mysnapshot['txs'] self.transaction_count = mysnapshot['txcount'] self.postqueue = mysnapshot['postqueue'] def finalize(self): """ Apply rewards We raise the block's coinbase account by Rb, the block reward, and the coinbase of each uncle by 7 of 8 that. Rb = 1500 finney """ self.delta_balance(self.coinbase, BLOCK_REWARD + NEPHEW_REWARD * len(self.uncles)) for uncle_rlp in self.uncles: uncle_data = Block.deserialize_header(uncle_rlp) self.delta_balance(uncle_data['coinbase'], UNCLE_REWARD) self.commit_state() def serialize_header_without_nonce(self): return rlp.encode(self.list_header(exclude=['nonce'])) def get_state_root(self): self.commit_state() return self.state.root_hash def set_state_root(self, state_root_hash): self.state = trie.Trie(utils.get_db_path(), state_root_hash) self.reset_cache() state_root = property(get_state_root, set_state_root) def get_tx_list_root(self): return self.transactions.root_hash tx_list_root = property(get_tx_list_root) def list_header(self, exclude=[]): header = [] for name, typ, default in block_structure: # print name, typ, default , getattr(self, name) if name not in exclude: header.append(utils.encoders[typ](getattr(self, name))) return header def serialize(self): # Serialization method; should act as perfect inverse function of the # constructor assuming no verification failures return rlp.encode([self.list_header(), self._list_transactions(), self.uncles]) def hex_serialize(self): return self.serialize().encode('hex') def serialize_header(self): return rlp.encode(self.list_header()) def hex_serialize_header(self): return rlp.encode(self.list_header()).encode('hex') def to_dict(self, with_state=False, full_transactions=False, with_storage_roots=False, with_uncles=False): """ serializes the block with_state: include state for all accounts full_transactions: include serialized tx (hashes otherwise) with_uncles: include uncle hashes """ b = {} for name, typ, default in block_structure: b[name] = utils.printers[typ](getattr(self, name)) txlist = []<|fim▁hole|> if full_transactions: txjson = transactions.Transaction.create(tx).to_dict() else: txjson = utils.sha3(rlp.descend(tx_rlp, 0)).encode('hex') # tx hash txlist.append({ "tx": txjson, "medstate": msr.encode('hex'), "gas": str(utils.decode_int(gas)) }) b["transactions"] = txlist if with_state: state_dump = {} for address, v in self.state.to_dict().iteritems(): state_dump[address.encode('hex')] = \ self.account_to_dict(address, with_storage_roots) b['state'] = state_dump if with_uncles: b['uncles'] = [utils.sha3(rlp.encode(u)).encode('hex') for u in self.uncles] return b def _hash(self): return utils.sha3(self.serialize_header()) @property def hash(self): return self._hash() def hex_hash(self): return self.hash.encode('hex') def get_parent(self): if self.number == 0: raise UnknownParentException('Genesis block has no parent') try: parent = get_block(self.prevhash) except KeyError: raise UnknownParentException(self.prevhash.encode('hex')) #assert parent.state.db.db == self.state.db.db return parent def has_parent(self): try: self.get_parent() return True except UnknownParentException: return False def chain_difficulty(self): # calculate the summarized_difficulty if self.is_genesis(): return self.difficulty elif 'difficulty:'+self.hex_hash() in self.state.db: return utils.decode_int( self.state.db.get('difficulty:'+self.hex_hash())) else: _idx, _typ, _ = block_structure_rev['difficulty'] o = self.difficulty + self.get_parent().chain_difficulty() o += sum([utils.decoders[_typ](u[_idx]) for u in self.uncles]) self.state.db.put('difficulty:'+self.hex_hash(), utils.encode_int(o)) return o def __eq__(self, other): return isinstance(other, (Block, CachedBlock)) and self.hash == other.hash def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): return self.number > other.number def __lt__(self, other): return self.number < other.number def __repr__(self): return '<Block(#%d %s %s)>' % (self.number, self.hex_hash()[:4], self.prevhash.encode('hex')[:4]) @classmethod def init_from_parent(cls, parent, coinbase, extra_data='', timestamp=int(time.time()), uncles=[]): return Block( prevhash=parent.hash, uncles_hash=utils.sha3(rlp.encode(uncles)), coinbase=coinbase, state_root=parent.state.root_hash, tx_list_root=trie.BLANK_ROOT, difficulty=calc_difficulty(parent, timestamp), number=parent.number + 1, min_gas_price=0, gas_limit=calc_gaslimit(parent), gas_used=0, timestamp=timestamp, extra_data=extra_data, nonce='', transaction_list=[], uncles=uncles) def set_proof_mode(self, pm, pmnodes=None): self.proof_mode = pm self.state.proof_mode = pm self.proof_nodes = pmnodes or [] self.state.proof_nodes = pmnodes or [] class CachedBlock(Block): # note: immutable refers to: do not manipulate! _hash_cached = None def _set_acct_item(self): raise NotImplementedError def _add_transaction_to_list(self): raise NotImplementedError def set_state_root(self): raise NotImplementedError def revert(self): raise NotImplementedError def commit_state(self): pass def _hash(self): if not self._hash_cached: self._hash_cached = Block._hash(self) return self._hash_cached @classmethod def create_cached(cls, blk): blk.__class__ = CachedBlock return blk @lru_cache(500) def get_block(blockhash): """ Assumtion: blocks loaded from the db are not manipulated -> can be cached including hash """ return CachedBlock.create_cached(Block.deserialize(db.DB(utils.get_db_path()).get(blockhash))) def has_block(blockhash): return blockhash in db.DB(utils.get_db_path()) def genesis(start_alloc=GENESIS_INITIAL_ALLOC, difficulty=INITIAL_DIFFICULTY): # https://ethereum.etherpad.mozilla.org/11 block = Block(prevhash=GENESIS_PREVHASH, coinbase=GENESIS_COINBASE, tx_list_root=trie.BLANK_ROOT, difficulty=difficulty, nonce=GENESIS_NONCE, gas_limit=GENESIS_GAS_LIMIT) for addr, balance in start_alloc.iteritems(): block.set_balance(addr, balance) block.state.db.commit() return block def dump_genesis_block_tests_data(): import json g = genesis() data = dict( genesis_state_root=g.state_root.encode('hex'), genesis_hash=g.hex_hash(), genesis_rlp_hex=g.serialize().encode('hex'), initial_alloc=dict() ) for addr, balance in GENESIS_INITIAL_ALLOC.iteritems(): data['initial_alloc'][addr] = str(balance) print json.dumps(data, indent=1)<|fim▁end|>
for i in range(self.transaction_count): tx_rlp = self.transactions.get(rlp.encode(utils.encode_int(i))) tx, msr, gas = rlp.decode(tx_rlp)
<|file_name|>go_import_meta_tag_reader.py<|end_file_name|><|fim▁begin|># Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import re import requests from pants.subsystem.subsystem import Subsystem from pants.util.memo import memoized_method from pants.contrib.go.subsystems.imported_repo import ImportedRepo class GoImportMetaTagReader(Subsystem): """Implements a reader for the <meta name="go-import"> protocol.<|fim▁hole|> See https://golang.org/cmd/go/#hdr-Remote_import_paths . """ options_scope = "go-import-metatag-reader" @classmethod def register_options(cls, register): super().register_options(register) register( "--retries", type=int, default=1, advanced=True, help="How many times to retry when fetching meta tags.", ) _META_IMPORT_REGEX = re.compile( r""" <meta \s+ name=['"]go-import['"] \s+ content=['"](?P<root>[^\s]+)\s+(?P<vcs>[^\s]+)\s+(?P<url>[^\s]+)['"] \s* /?>""", flags=re.VERBOSE, ) @classmethod def find_meta_tags(cls, page_html): """Returns the content of the meta tag if found inside of the provided HTML.""" return cls._META_IMPORT_REGEX.findall(page_html) @memoized_method def get_imported_repo(self, import_path): """Looks for a go-import meta tag for the provided import_path. Returns an ImportedRepo instance with the information in the meta tag, or None if no go- import meta tag is found. """ try: session = requests.session() # TODO: Support https with (optional) fallback to http, as Go does. # See https://github.com/pantsbuild/pants/issues/3503. session.mount( "http://", requests.adapters.HTTPAdapter(max_retries=self.get_options().retries) ) page_data = session.get(f"http://{import_path}?go-get=1") except requests.ConnectionError: return None if not page_data: return None # Return the first match, rather than doing some kind of longest prefix search. # Hopefully no one returns multiple valid go-import meta tags. for (root, vcs, url) in self.find_meta_tags(page_data.text): if root and vcs and url: # Check to make sure returned root is an exact match to the provided import path. If it is # not then run a recursive check on the returned and return the values provided by that call. if root == import_path: return ImportedRepo(root, vcs, url) elif import_path.startswith(root): return self.get_imported_repo(root) return None<|fim▁end|>
<|file_name|>MainController.java<|end_file_name|><|fim▁begin|>package finalWeb.controller; import org.springframework.stereotype.Controller; <|fim▁hole|> }<|fim▁end|>
@Controller public class MainController {
<|file_name|>union_find.py<|end_file_name|><|fim▁begin|>""" Union-find data structure. """ from networkx.utils import groups class UnionFind: """Union-find data structure. Each unionFind instance X maintains a family of disjoint sets of hashable objects, supporting the following two methods: - X[item] returns a name for the set containing the given item. Each set is named by an arbitrarily-chosen one of its members; as long as the set remains unchanged it will keep the same name. If the item is not yet part of a set in X, a new singleton set is created for it. - X.union(item1, item2, ...) merges the sets containing each item into a single larger set. If any item is not yet part of a set in X, it is added to X as one of the members of the merged set. Union-find data structure. Based on Josiah Carlson's code, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215912<|fim▁hole|> http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py """ def __init__(self, elements=None): """Create a new empty union-find structure. If *elements* is an iterable, this structure will be initialized with the discrete partition on the given set of elements. """ if elements is None: elements = () self.parents = {} self.weights = {} for x in elements: self.weights[x] = 1 self.parents[x] = x def __getitem__(self, object): """Find and return the name of the set containing the object.""" # check for previously unknown object if object not in self.parents: self.parents[object] = object self.weights[object] = 1 return object # find path of objects leading to the root path = [object] root = self.parents[object] while root != path[-1]: path.append(root) root = self.parents[root] # compress the path and return for ancestor in path: self.parents[ancestor] = root return root def __iter__(self): """Iterate through all items ever found or unioned by this structure. """ return iter(self.parents) def to_sets(self): """Iterates over the sets stored in this structure. For example:: >>> partition = UnionFind('xyz') >>> sorted(map(sorted, partition.to_sets())) [['x'], ['y'], ['z']] >>> partition.union('x', 'y') >>> sorted(map(sorted, partition.to_sets())) [['x', 'y'], ['z']] """ # Ensure fully pruned paths for x in self.parents.keys(): _ = self[x] # Evaluated for side-effect only yield from groups(self.parents).values() def union(self, *objects): """Find the sets containing the objects and merge them all.""" # Find the heaviest root according to its weight. roots = iter(sorted({self[x] for x in objects}, key=lambda r: self.weights[r])) try: root = next(roots) except StopIteration: return for r in roots: self.weights[root] += self.weights[r] self.parents[r] = root<|fim▁end|>
with significant additional changes by D. Eppstein.
<|file_name|>test_client.py<|end_file_name|><|fim▁begin|># Copyright 2014 Google 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. import unittest import mock def _make_credentials(): import google.auth.credentials return mock.Mock(spec=google.auth.credentials.Credentials) def _make_entity_pb(project, kind, integer_id, name=None, str_val=None): from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.datastore.helpers import _new_value_pb entity_pb = entity_pb2.Entity() entity_pb.key.partition_id.project_id = project path_element = entity_pb.key.path.add() path_element.kind = kind path_element.id = integer_id if name is not None and str_val is not None: value_pb = _new_value_pb(entity_pb, name) value_pb.string_value = str_val return entity_pb class Test__get_gcd_project(unittest.TestCase): def _call_fut(self): from google.cloud.datastore.client import _get_gcd_project return _get_gcd_project() def test_no_value(self): environ = {} with mock.patch("os.getenv", new=environ.get): project = self._call_fut() self.assertIsNone(project) def test_value_set(self): from google.cloud.datastore.client import GCD_DATASET MOCK_PROJECT = object() environ = {GCD_DATASET: MOCK_PROJECT} with mock.patch("os.getenv", new=environ.get): project = self._call_fut() self.assertEqual(project, MOCK_PROJECT) class Test__determine_default_project(unittest.TestCase): def _call_fut(self, project=None): from google.cloud.datastore.client import _determine_default_project return _determine_default_project(project=project) def _determine_default_helper(self, gcd=None, fallback=None, project_called=None): _callers = [] def gcd_mock(): _callers.append("gcd_mock") return gcd def fallback_mock(project=None): _callers.append(("fallback_mock", project)) return fallback patch = mock.patch.multiple( "google.cloud.datastore.client", _get_gcd_project=gcd_mock, _base_default_project=fallback_mock, ) with patch: returned_project = self._call_fut(project_called) return returned_project, _callers def test_no_value(self): project, callers = self._determine_default_helper() self.assertIsNone(project) self.assertEqual(callers, ["gcd_mock", ("fallback_mock", None)]) def test_explicit(self): PROJECT = object() project, callers = self._determine_default_helper(project_called=PROJECT) self.assertEqual(project, PROJECT) self.assertEqual(callers, []) def test_gcd(self): PROJECT = object() project, callers = self._determine_default_helper(gcd=PROJECT) self.assertEqual(project, PROJECT) self.assertEqual(callers, ["gcd_mock"]) def test_fallback(self): PROJECT = object() project, callers = self._determine_default_helper(fallback=PROJECT) self.assertEqual(project, PROJECT) self.assertEqual(callers, ["gcd_mock", ("fallback_mock", None)]) class TestClient(unittest.TestCase): PROJECT = "PROJECT" @staticmethod def _get_target_class(): from google.cloud.datastore.client import Client return Client def _make_one( self, project=PROJECT, namespace=None, credentials=None, client_info=None, client_options=None, _http=None, _use_grpc=None, ): return self._get_target_class()( project=project, namespace=namespace, credentials=credentials, client_info=client_info, client_options=client_options, _http=_http, _use_grpc=_use_grpc, ) def test_constructor_w_project_no_environ(self): # Some environments (e.g. AppVeyor CI) run in GCE, so # this test would fail artificially. patch = mock.patch( "google.cloud.datastore.client._base_default_project", return_value=None ) with patch: self.assertRaises(EnvironmentError, self._make_one, None) def test_constructor_w_implicit_inputs(self): from google.cloud.datastore.client import _CLIENT_INFO from google.cloud.datastore.client import _DATASTORE_BASE_URL other = "other" creds = _make_credentials() klass = self._get_target_class() patch1 = mock.patch( "google.cloud.datastore.client._determine_default_project", return_value=other, ) patch2 = mock.patch("google.auth.default", return_value=(creds, None)) with patch1 as _determine_default_project: with patch2 as default: client = klass() self.assertEqual(client.project, other) self.assertIsNone(client.namespace) self.assertIs(client._credentials, creds) self.assertIs(client._client_info, _CLIENT_INFO) self.assertIsNone(client._http_internal) self.assertIsNone(client._client_options) self.assertEqual(client.base_url, _DATASTORE_BASE_URL) self.assertIsNone(client.current_batch) self.assertIsNone(client.current_transaction) default.assert_called_once_with() _determine_default_project.assert_called_once_with(None) def test_constructor_w_explicit_inputs(self): from google.api_core.client_options import ClientOptions other = "other" namespace = "namespace" creds = _make_credentials() client_info = mock.Mock() client_options = ClientOptions("endpoint") http = object() client = self._make_one( project=other, namespace=namespace, credentials=creds, client_info=client_info, client_options=client_options, _http=http, ) self.assertEqual(client.project, other) self.assertEqual(client.namespace, namespace) self.assertIs(client._credentials, creds) self.assertIs(client._client_info, client_info) self.assertIs(client._http_internal, http) self.assertIsNone(client.current_batch) self.assertIs(client._base_url, "endpoint") self.assertEqual(list(client._batch_stack), []) def test_constructor_use_grpc_default(self): import google.cloud.datastore.client as MUT project = "PROJECT" creds = _make_credentials() http = object() with mock.patch.object(MUT, "_USE_GRPC", new=True): client1 = self._make_one(project=project, credentials=creds, _http=http) self.assertTrue(client1._use_grpc) # Explicitly over-ride the environment. client2 = self._make_one( project=project, credentials=creds, _http=http, _use_grpc=False ) self.assertFalse(client2._use_grpc) with mock.patch.object(MUT, "_USE_GRPC", new=False): client3 = self._make_one(project=project, credentials=creds, _http=http) self.assertFalse(client3._use_grpc) # Explicitly over-ride the environment. client4 = self._make_one( project=project, credentials=creds, _http=http, _use_grpc=True ) self.assertTrue(client4._use_grpc) def test_constructor_gcd_host(self): from google.cloud.environment_vars import GCD_HOST host = "localhost:1234" fake_environ = {GCD_HOST: host} project = "PROJECT" creds = _make_credentials() http = object() with mock.patch("os.environ", new=fake_environ): client = self._make_one(project=project, credentials=creds, _http=http) self.assertEqual(client.base_url, "http://" + host) def test_base_url_property(self): from google.cloud.datastore.client import _DATASTORE_BASE_URL from google.api_core.client_options import ClientOptions alternate_url = "https://alias.example.com/" project = "PROJECT" creds = _make_credentials() http = object() client_options = ClientOptions() client = self._make_one( project=project, credentials=creds, _http=http, client_options=client_options, ) self.assertEqual(client.base_url, _DATASTORE_BASE_URL) client.base_url = alternate_url self.assertEqual(client.base_url, alternate_url) def test_base_url_property_w_client_options(self): alternate_url = "https://alias.example.com/" project = "PROJECT" creds = _make_credentials() http = object() client_options = {"api_endpoint": "endpoint"} client = self._make_one( project=project, credentials=creds, _http=http, client_options=client_options, ) self.assertEqual(client.base_url, "endpoint") client.base_url = alternate_url self.assertEqual(client.base_url, alternate_url) def test__datastore_api_property_already_set(self): client = self._make_one( project="prahj-ekt", credentials=_make_credentials(), _use_grpc=True ) already = client._datastore_api_internal = object() self.assertIs(client._datastore_api, already) def test__datastore_api_property_gapic(self): client_info = mock.Mock() client = self._make_one( project="prahj-ekt", credentials=_make_credentials(), client_info=client_info, _http=object(), _use_grpc=True, ) self.assertIsNone(client._datastore_api_internal) patch = mock.patch( "google.cloud.datastore.client.make_datastore_api", return_value=mock.sentinel.ds_api, ) with patch as make_api: ds_api = client._datastore_api self.assertIs(ds_api, mock.sentinel.ds_api) self.assertIs(client._datastore_api_internal, mock.sentinel.ds_api) make_api.assert_called_once_with(client) def test__datastore_api_property_http(self): client_info = mock.Mock() client = self._make_one( project="prahj-ekt", credentials=_make_credentials(), client_info=client_info, _http=object(), _use_grpc=False, ) self.assertIsNone(client._datastore_api_internal) patch = mock.patch( "google.cloud.datastore.client.HTTPDatastoreAPI", return_value=mock.sentinel.ds_api, ) with patch as make_api: ds_api = client._datastore_api self.assertIs(ds_api, mock.sentinel.ds_api) self.assertIs(client._datastore_api_internal, mock.sentinel.ds_api) make_api.assert_called_once_with(client) def test__push_batch_and__pop_batch(self): creds = _make_credentials() client = self._make_one(credentials=creds) batch = client.batch() xact = client.transaction() client._push_batch(batch) self.assertEqual(list(client._batch_stack), [batch]) self.assertIs(client.current_batch, batch) self.assertIsNone(client.current_transaction) client._push_batch(xact) self.assertIs(client.current_batch, xact) self.assertIs(client.current_transaction, xact) # list(_LocalStack) returns in reverse order. self.assertEqual(list(client._batch_stack), [xact, batch]) self.assertIs(client._pop_batch(), xact) self.assertEqual(list(client._batch_stack), [batch]) self.assertIs(client._pop_batch(), batch) self.assertEqual(list(client._batch_stack), []) def test_get_miss(self): _called_with = [] def _get_multi(*args, **kw): _called_with.append((args, kw)) return [] creds = _make_credentials() client = self._make_one(credentials=creds) client.get_multi = _get_multi key = object() self.assertIsNone(client.get(key)) self.assertEqual(_called_with[0][0], ()) self.assertEqual(_called_with[0][1]["keys"], [key]) self.assertIsNone(_called_with[0][1]["missing"]) self.assertIsNone(_called_with[0][1]["deferred"]) self.assertIsNone(_called_with[0][1]["transaction"]) def test_get_hit(self): TXN_ID = "123" _called_with = [] _entity = object() def _get_multi(*args, **kw): _called_with.append((args, kw)) return [_entity] creds = _make_credentials() client = self._make_one(credentials=creds) client.get_multi = _get_multi key, missing, deferred = object(), [], [] self.assertIs(client.get(key, missing, deferred, TXN_ID), _entity) self.assertEqual(_called_with[0][0], ()) self.assertEqual(_called_with[0][1]["keys"], [key]) self.assertIs(_called_with[0][1]["missing"], missing) self.assertIs(_called_with[0][1]["deferred"], deferred) self.assertEqual(_called_with[0][1]["transaction"], TXN_ID) def test_get_multi_no_keys(self): creds = _make_credentials() client = self._make_one(credentials=creds) results = client.get_multi([]) self.assertEqual(results, []) def test_get_multi_miss(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.key import Key creds = _make_credentials() client = self._make_one(credentials=creds) ds_api = _make_datastore_api() client._datastore_api_internal = ds_api key = Key("Kind", 1234, project=self.PROJECT) results = client.get_multi([key]) self.assertEqual(results, []) read_options = datastore_pb2.ReadOptions() ds_api.lookup.assert_called_once_with( self.PROJECT, [key.to_protobuf()], read_options=read_options ) def test_get_multi_miss_w_missing(self): from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.key import Key KIND = "Kind" ID = 1234 # Make a missing entity pb to be returned from mock backend. missed = entity_pb2.Entity() missed.key.partition_id.project_id = self.PROJECT path_element = missed.key.path.add() path_element.kind = KIND path_element.id = ID creds = _make_credentials() client = self._make_one(credentials=creds) # Set missing entity on mock connection. lookup_response = _make_lookup_response(missing=[missed]) ds_api = _make_datastore_api(lookup_response=lookup_response) client._datastore_api_internal = ds_api key = Key(KIND, ID, project=self.PROJECT) missing = [] entities = client.get_multi([key], missing=missing) self.assertEqual(entities, []) key_pb = key.to_protobuf() self.assertEqual([missed.key.to_protobuf() for missed in missing], [key_pb]) read_options = datastore_pb2.ReadOptions() ds_api.lookup.assert_called_once_with( self.PROJECT, [key_pb], read_options=read_options ) def test_get_multi_w_missing_non_empty(self): from google.cloud.datastore.key import Key creds = _make_credentials() client = self._make_one(credentials=creds) key = Key("Kind", 1234, project=self.PROJECT) missing = ["this", "list", "is", "not", "empty"] self.assertRaises(ValueError, client.get_multi, [key], missing=missing) def test_get_multi_w_deferred_non_empty(self): from google.cloud.datastore.key import Key creds = _make_credentials() client = self._make_one(credentials=creds) key = Key("Kind", 1234, project=self.PROJECT) deferred = ["this", "list", "is", "not", "empty"] self.assertRaises(ValueError, client.get_multi, [key], deferred=deferred) def test_get_multi_miss_w_deferred(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.key import Key key = Key("Kind", 1234, project=self.PROJECT) key_pb = key.to_protobuf() # Set deferred entity on mock connection. creds = _make_credentials() client = self._make_one(credentials=creds) lookup_response = _make_lookup_response(deferred=[key_pb]) ds_api = _make_datastore_api(lookup_response=lookup_response) client._datastore_api_internal = ds_api deferred = [] entities = client.get_multi([key], deferred=deferred) self.assertEqual(entities, []) self.assertEqual([def_key.to_protobuf() for def_key in deferred], [key_pb]) read_options = datastore_pb2.ReadOptions() ds_api.lookup.assert_called_once_with( self.PROJECT, [key_pb], read_options=read_options ) def test_get_multi_w_deferred_from_backend_but_not_passed(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.datastore.entity import Entity from google.cloud.datastore.key import Key key1 = Key("Kind", project=self.PROJECT) key1_pb = key1.to_protobuf() key2 = Key("Kind", 2345, project=self.PROJECT) key2_pb = key2.to_protobuf() entity1_pb = entity_pb2.Entity() entity1_pb.key.CopyFrom(key1_pb) entity2_pb = entity_pb2.Entity() entity2_pb.key.CopyFrom(key2_pb) creds = _make_credentials() client = self._make_one(credentials=creds) # Mock up two separate requests. Using an iterable as side_effect # allows multiple return values. lookup_response1 = _make_lookup_response( results=[entity1_pb], deferred=[key2_pb] ) lookup_response2 = _make_lookup_response(results=[entity2_pb]) ds_api = _make_datastore_api() ds_api.lookup = mock.Mock( side_effect=[lookup_response1, lookup_response2], spec=[] ) client._datastore_api_internal = ds_api missing = [] found = client.get_multi([key1, key2], missing=missing) self.assertEqual(len(found), 2) self.assertEqual(len(missing), 0) # Check the actual contents on the response. self.assertIsInstance(found[0], Entity) self.assertEqual(found[0].key.path, key1.path) self.assertEqual(found[0].key.project, key1.project) self.assertIsInstance(found[1], Entity) self.assertEqual(found[1].key.path, key2.path) self.assertEqual(found[1].key.project, key2.project) self.assertEqual(ds_api.lookup.call_count, 2) read_options = datastore_pb2.ReadOptions() ds_api.lookup.assert_any_call( self.PROJECT, [key2_pb], read_options=read_options ) ds_api.lookup.assert_any_call( self.PROJECT, [key1_pb, key2_pb], read_options=read_options ) def test_get_multi_hit(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.key import Key kind = "Kind" id_ = 1234 path = [{"kind": kind, "id": id_}] # Make a found entity pb to be returned from mock backend. entity_pb = _make_entity_pb(self.PROJECT, kind, id_, "foo", "Foo") # Make a connection to return the entity pb. creds = _make_credentials() client = self._make_one(credentials=creds) lookup_response = _make_lookup_response(results=[entity_pb]) ds_api = _make_datastore_api(lookup_response=lookup_response) client._datastore_api_internal = ds_api key = Key(kind, id_, project=self.PROJECT) result, = client.get_multi([key]) new_key = result.key # Check the returned value is as expected. self.assertIsNot(new_key, key) self.assertEqual(new_key.project, self.PROJECT) self.assertEqual(new_key.path, path) self.assertEqual(list(result), ["foo"]) self.assertEqual(result["foo"], "Foo") read_options = datastore_pb2.ReadOptions() ds_api.lookup.assert_called_once_with( self.PROJECT, [key.to_protobuf()], read_options=read_options ) def test_get_multi_hit_w_transaction(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.key import Key txn_id = b"123" kind = "Kind" id_ = 1234 path = [{"kind": kind, "id": id_}] # Make a found entity pb to be returned from mock backend. entity_pb = _make_entity_pb(self.PROJECT, kind, id_, "foo", "Foo") # Make a connection to return the entity pb. creds = _make_credentials() client = self._make_one(credentials=creds) lookup_response = _make_lookup_response(results=[entity_pb]) ds_api = _make_datastore_api(lookup_response=lookup_response) client._datastore_api_internal = ds_api key = Key(kind, id_, project=self.PROJECT) txn = client.transaction() txn._id = txn_id result, = client.get_multi([key], transaction=txn) new_key = result.key # Check the returned value is as expected. self.assertIsNot(new_key, key) self.assertEqual(new_key.project, self.PROJECT) self.assertEqual(new_key.path, path) self.assertEqual(list(result), ["foo"]) self.assertEqual(result["foo"], "Foo") read_options = datastore_pb2.ReadOptions(transaction=txn_id) ds_api.lookup.assert_called_once_with( self.PROJECT, [key.to_protobuf()], read_options=read_options ) def test_get_multi_hit_multiple_keys_same_project(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.key import Key kind = "Kind" id1 = 1234 id2 = 2345 # Make a found entity pb to be returned from mock backend. entity_pb1 = _make_entity_pb(self.PROJECT, kind, id1) entity_pb2 = _make_entity_pb(self.PROJECT, kind, id2) # Make a connection to return the entity pbs. creds = _make_credentials() client = self._make_one(credentials=creds) lookup_response = _make_lookup_response(results=[entity_pb1, entity_pb2]) ds_api = _make_datastore_api(lookup_response=lookup_response) client._datastore_api_internal = ds_api key1 = Key(kind, id1, project=self.PROJECT) key2 = Key(kind, id2, project=self.PROJECT) retrieved1, retrieved2 = client.get_multi([key1, key2]) # Check values match. self.assertEqual(retrieved1.key.path, key1.path) self.assertEqual(dict(retrieved1), {}) self.assertEqual(retrieved2.key.path, key2.path) self.assertEqual(dict(retrieved2), {}) read_options = datastore_pb2.ReadOptions() ds_api.lookup.assert_called_once_with( self.PROJECT, [key1.to_protobuf(), key2.to_protobuf()], read_options=read_options, ) def test_get_multi_hit_multiple_keys_different_project(self): from google.cloud.datastore.key import Key PROJECT1 = "PROJECT" PROJECT2 = "PROJECT-ALT" # Make sure our IDs are actually different. self.assertNotEqual(PROJECT1, PROJECT2) key1 = Key("KIND", 1234, project=PROJECT1) key2 = Key("KIND", 1234, project=PROJECT2) creds = _make_credentials() client = self._make_one(credentials=creds) with self.assertRaises(ValueError): client.get_multi([key1, key2]) def test_get_multi_max_loops(self): from google.cloud.datastore.key import Key kind = "Kind" id_ = 1234 # Make a found entity pb to be returned from mock backend. entity_pb = _make_entity_pb(self.PROJECT, kind, id_, "foo", "Foo") # Make a connection to return the entity pb. creds = _make_credentials() client = self._make_one(credentials=creds) lookup_response = _make_lookup_response(results=[entity_pb]) ds_api = _make_datastore_api(lookup_response=lookup_response) client._datastore_api_internal = ds_api key = Key(kind, id_, project=self.PROJECT) deferred = [] missing = [] patch = mock.patch("google.cloud.datastore.client._MAX_LOOPS", new=-1) with patch: result = client.get_multi([key], missing=missing, deferred=deferred) # Make sure we have no results, even though the connection has been # set up as in `test_hit` to return a single result. self.assertEqual(result, []) self.assertEqual(missing, []) self.assertEqual(deferred, []) ds_api.lookup.assert_not_called() def test_put(self): _called_with = [] def _put_multi(*args, **kw): _called_with.append((args, kw)) creds = _make_credentials() client = self._make_one(credentials=creds) client.put_multi = _put_multi entity = object() client.put(entity) self.assertEqual(_called_with[0][0], ()) self.assertEqual(_called_with[0][1]["entities"], [entity]) def test_put_multi_no_entities(self): creds = _make_credentials() client = self._make_one(credentials=creds) self.assertIsNone(client.put_multi([])) def test_put_multi_w_single_empty_entity(self): # https://github.com/GoogleCloudPlatform/google-cloud-python/issues/649 from google.cloud.datastore.entity import Entity creds = _make_credentials() client = self._make_one(credentials=creds) self.assertRaises(ValueError, client.put_multi, Entity()) def test_put_multi_no_batch_w_partial_key(self): from google.cloud.datastore_v1.proto import datastore_pb2 from google.cloud.datastore.helpers import _property_tuples entity = _Entity(foo=u"bar") key = entity.key = _Key(self.PROJECT) key._id = None creds = _make_credentials() client = self._make_one(credentials=creds) key_pb = _make_key(234) ds_api = _make_datastore_api(key_pb) client._datastore_api_internal = ds_api result = client.put_multi([entity]) self.assertIsNone(result) self.assertEqual(ds_api.commit.call_count, 1) _, positional, keyword = ds_api.commit.mock_calls[0] self.assertEqual(keyword, {"transaction": None}) self.assertEqual(len(positional), 3) self.assertEqual(positional[0], self.PROJECT) self.assertEqual(positional[1], datastore_pb2.CommitRequest.NON_TRANSACTIONAL) mutations = positional[2] mutated_entity = _mutated_pb(self, mutations, "insert") self.assertEqual(mutated_entity.key, key.to_protobuf()) prop_list = list(_property_tuples(mutated_entity)) self.assertTrue(len(prop_list), 1) name, value_pb = prop_list[0] self.assertEqual(name, "foo") self.assertEqual(value_pb.string_value, u"bar") def test_put_multi_existing_batch_w_completed_key(self): from google.cloud.datastore.helpers import _property_tuples creds = _make_credentials() client = self._make_one(credentials=creds) entity = _Entity(foo=u"bar") key = entity.key = _Key(self.PROJECT) with _NoCommitBatch(client) as CURR_BATCH: result = client.put_multi([entity]) self.assertIsNone(result) mutated_entity = _mutated_pb(self, CURR_BATCH.mutations, "upsert") self.assertEqual(mutated_entity.key, key.to_protobuf()) prop_list = list(_property_tuples(mutated_entity)) self.assertTrue(len(prop_list), 1) name, value_pb = prop_list[0] self.assertEqual(name, "foo") self.assertEqual(value_pb.string_value, u"bar") def test_delete(self): _called_with = [] def _delete_multi(*args, **kw): _called_with.append((args, kw)) creds = _make_credentials() client = self._make_one(credentials=creds) client.delete_multi = _delete_multi key = object() client.delete(key) self.assertEqual(_called_with[0][0], ()) self.assertEqual(_called_with[0][1]["keys"], [key]) def test_delete_multi_no_keys(self): creds = _make_credentials() client = self._make_one(credentials=creds) client._datastore_api_internal = _make_datastore_api() result = client.delete_multi([]) self.assertIsNone(result) client._datastore_api_internal.commit.assert_not_called() def test_delete_multi_no_batch(self): from google.cloud.datastore_v1.proto import datastore_pb2 key = _Key(self.PROJECT) creds = _make_credentials() client = self._make_one(credentials=creds) ds_api = _make_datastore_api() client._datastore_api_internal = ds_api result = client.delete_multi([key]) self.assertIsNone(result) self.assertEqual(ds_api.commit.call_count, 1) _, positional, keyword = ds_api.commit.mock_calls[0] self.assertEqual(keyword, {"transaction": None}) self.assertEqual(len(positional), 3) self.assertEqual(positional[0], self.PROJECT) self.assertEqual(positional[1], datastore_pb2.CommitRequest.NON_TRANSACTIONAL) mutations = positional[2] mutated_key = _mutated_pb(self, mutations, "delete") self.assertEqual(mutated_key, key.to_protobuf()) def test_delete_multi_w_existing_batch(self): creds = _make_credentials() client = self._make_one(credentials=creds) client._datastore_api_internal = _make_datastore_api() key = _Key(self.PROJECT) with _NoCommitBatch(client) as CURR_BATCH: result = client.delete_multi([key]) self.assertIsNone(result) mutated_key = _mutated_pb(self, CURR_BATCH.mutations, "delete") self.assertEqual(mutated_key, key._key) client._datastore_api_internal.commit.assert_not_called() def test_delete_multi_w_existing_transaction(self): creds = _make_credentials() client = self._make_one(credentials=creds) client._datastore_api_internal = _make_datastore_api() key = _Key(self.PROJECT) with _NoCommitTransaction(client) as CURR_XACT: result = client.delete_multi([key]) self.assertIsNone(result) mutated_key = _mutated_pb(self, CURR_XACT.mutations, "delete") self.assertEqual(mutated_key, key._key) client._datastore_api_internal.commit.assert_not_called() def test_allocate_ids_w_partial_key(self): num_ids = 2 incomplete_key = _Key(self.PROJECT) incomplete_key._id = None creds = _make_credentials() client = self._make_one(credentials=creds, _use_grpc=False) allocated = mock.Mock(keys=[_KeyPB(i) for i in range(num_ids)], spec=["keys"]) alloc_ids = mock.Mock(return_value=allocated, spec=[]) ds_api = mock.Mock(allocate_ids=alloc_ids, spec=["allocate_ids"]) client._datastore_api_internal = ds_api result = client.allocate_ids(incomplete_key, num_ids) # Check the IDs returned. self.assertEqual([key._id for key in result], list(range(num_ids))) def test_allocate_ids_w_completed_key(self): creds = _make_credentials() client = self._make_one(credentials=creds) complete_key = _Key(self.PROJECT) self.assertRaises(ValueError, client.allocate_ids, complete_key, 2) def test_reserve_ids_w_completed_key(self): num_ids = 2 creds = _make_credentials() client = self._make_one(credentials=creds, _use_grpc=False) complete_key = _Key(self.PROJECT) reserve_ids = mock.Mock() ds_api = mock.Mock(reserve_ids=reserve_ids, spec=["reserve_ids"]) client._datastore_api_internal = ds_api self.assertTrue(not complete_key.is_partial) client.reserve_ids(complete_key, num_ids) expected_keys = [complete_key.to_protobuf()] * num_ids reserve_ids.assert_called_once_with(self.PROJECT, expected_keys) def test_reserve_ids_w_partial_key(self): num_ids = 2 incomplete_key = _Key(self.PROJECT) incomplete_key._id = None creds = _make_credentials() client = self._make_one(credentials=creds) with self.assertRaises(ValueError): client.reserve_ids(incomplete_key, num_ids) def test_reserve_ids_w_wrong_num_ids(self): num_ids = "2" complete_key = _Key(self.PROJECT) creds = _make_credentials() client = self._make_one(credentials=creds) with self.assertRaises(ValueError): client.reserve_ids(complete_key, num_ids) def test_key_w_project(self): KIND = "KIND" ID = 1234 creds = _make_credentials() client = self._make_one(credentials=creds) self.assertRaises(TypeError, client.key, KIND, ID, project=self.PROJECT) def test_key_wo_project(self): kind = "KIND" id_ = 1234 creds = _make_credentials() client = self._make_one(credentials=creds) patch = mock.patch("google.cloud.datastore.client.Key", spec=["__call__"]) with patch as mock_klass: key = client.key(kind, id_) self.assertIs(key, mock_klass.return_value) mock_klass.assert_called_once_with( kind, id_, project=self.PROJECT, namespace=None ) def test_key_w_namespace(self): kind = "KIND" id_ = 1234 namespace = object() creds = _make_credentials() client = self._make_one(namespace=namespace, credentials=creds) patch = mock.patch("google.cloud.datastore.client.Key", spec=["__call__"]) with patch as mock_klass: key = client.key(kind, id_) self.assertIs(key, mock_klass.return_value) mock_klass.assert_called_once_with( kind, id_, project=self.PROJECT, namespace=namespace ) def test_key_w_namespace_collision(self): kind = "KIND" id_ = 1234 namespace1 = object() namespace2 = object() creds = _make_credentials() client = self._make_one(namespace=namespace1, credentials=creds) patch = mock.patch("google.cloud.datastore.client.Key", spec=["__call__"]) with patch as mock_klass: key = client.key(kind, id_, namespace=namespace2) self.assertIs(key, mock_klass.return_value) mock_klass.assert_called_once_with( kind, id_, project=self.PROJECT, namespace=namespace2 ) def test_batch(self): creds = _make_credentials() client = self._make_one(credentials=creds) patch = mock.patch("google.cloud.datastore.client.Batch", spec=["__call__"]) with patch as mock_klass: batch = client.batch() self.assertIs(batch, mock_klass.return_value) mock_klass.assert_called_once_with(client) def test_transaction_defaults(self): creds = _make_credentials() client = self._make_one(credentials=creds) patch = mock.patch( "google.cloud.datastore.client.Transaction", spec=["__call__"] ) with patch as mock_klass: xact = client.transaction() self.assertIs(xact, mock_klass.return_value) mock_klass.assert_called_once_with(client) def test_read_only_transaction_defaults(self): from google.cloud.datastore_v1.types import TransactionOptions creds = _make_credentials() client = self._make_one(credentials=creds) xact = client.transaction(read_only=True) self.assertEqual( xact._options, TransactionOptions(read_only=TransactionOptions.ReadOnly()) ) self.assertFalse(xact._options.HasField("read_write")) self.assertTrue(xact._options.HasField("read_only")) self.assertEqual(xact._options.read_only, TransactionOptions.ReadOnly()) def test_query_w_client(self): KIND = "KIND" creds = _make_credentials() client = self._make_one(credentials=creds) other = self._make_one(credentials=_make_credentials()) self.assertRaises(TypeError, client.query, kind=KIND, client=other) def test_query_w_project(self): KIND = "KIND" creds = _make_credentials() client = self._make_one(credentials=creds) self.assertRaises(TypeError, client.query, kind=KIND, project=self.PROJECT) def test_query_w_defaults(self): creds = _make_credentials() client = self._make_one(credentials=creds) patch = mock.patch("google.cloud.datastore.client.Query", spec=["__call__"]) with patch as mock_klass: query = client.query() self.assertIs(query, mock_klass.return_value) mock_klass.assert_called_once_with( client, project=self.PROJECT, namespace=None ) def test_query_explicit(self): kind = "KIND" namespace = "NAMESPACE" ancestor = object() filters = [("PROPERTY", "==", "VALUE")] projection = ["__key__"] order = ["PROPERTY"] distinct_on = ["DISTINCT_ON"] creds = _make_credentials() client = self._make_one(credentials=creds) patch = mock.patch("google.cloud.datastore.client.Query", spec=["__call__"]) with patch as mock_klass: query = client.query( kind=kind, namespace=namespace, ancestor=ancestor, filters=filters, projection=projection, order=order, distinct_on=distinct_on, ) self.assertIs(query, mock_klass.return_value) mock_klass.assert_called_once_with( client, project=self.PROJECT, kind=kind, namespace=namespace, ancestor=ancestor, filters=filters, projection=projection, order=order, distinct_on=distinct_on, ) def test_query_w_namespace(self): kind = "KIND" namespace = object() creds = _make_credentials() client = self._make_one(namespace=namespace, credentials=creds) patch = mock.patch("google.cloud.datastore.client.Query", spec=["__call__"]) with patch as mock_klass: query = client.query(kind=kind) self.assertIs(query, mock_klass.return_value) mock_klass.assert_called_once_with( client, project=self.PROJECT, namespace=namespace, kind=kind ) def test_query_w_namespace_collision(self): kind = "KIND" namespace1 = object() namespace2 = object() creds = _make_credentials() client = self._make_one(namespace=namespace1, credentials=creds) patch = mock.patch("google.cloud.datastore.client.Query", spec=["__call__"]) with patch as mock_klass: query = client.query(kind=kind, namespace=namespace2) self.assertIs(query, mock_klass.return_value) mock_klass.assert_called_once_with( client, project=self.PROJECT, namespace=namespace2, kind=kind ) class _NoCommitBatch(object):<|fim▁hole|> from google.cloud.datastore.batch import Batch self._client = client self._batch = Batch(client) self._batch.begin() def __enter__(self): self._client._push_batch(self._batch) return self._batch def __exit__(self, *args): self._client._pop_batch() class _NoCommitTransaction(object): def __init__(self, client, transaction_id="TRANSACTION"): from google.cloud.datastore.batch import Batch from google.cloud.datastore.transaction import Transaction self._client = client xact = self._transaction = Transaction(client) xact._id = transaction_id Batch.begin(xact) def __enter__(self): self._client._push_batch(self._transaction) return self._transaction def __exit__(self, *args): self._client._pop_batch() class _Entity(dict): key = None exclude_from_indexes = () _meanings = {} class _Key(object): _MARKER = object() _kind = "KIND" _key = "KEY" _path = None _id = 1234 _stored = None def __init__(self, project): self.project = project @property def is_partial(self): return self._id is None def to_protobuf(self): from google.cloud.datastore_v1.proto import entity_pb2 key = self._key = entity_pb2.Key() # Don't assign it, because it will just get ripped out # key.partition_id.project_id = self.project element = key.path.add() element.kind = self._kind if self._id is not None: element.id = self._id return key def completed_key(self, new_id): assert self.is_partial new_key = self.__class__(self.project) new_key._id = new_id return new_key class _PathElementPB(object): def __init__(self, id_): self.id = id_ class _KeyPB(object): def __init__(self, id_): self.path = [_PathElementPB(id_)] def _assert_num_mutations(test_case, mutation_pb_list, num_mutations): test_case.assertEqual(len(mutation_pb_list), num_mutations) def _mutated_pb(test_case, mutation_pb_list, mutation_type): # Make sure there is only one mutation. _assert_num_mutations(test_case, mutation_pb_list, 1) # We grab the only mutation. mutated_pb = mutation_pb_list[0] # Then check if it is the correct type. test_case.assertEqual(mutated_pb.WhichOneof("operation"), mutation_type) return getattr(mutated_pb, mutation_type) def _make_key(id_): from google.cloud.datastore_v1.proto import entity_pb2 key = entity_pb2.Key() elem = key.path.add() elem.id = id_ return key def _make_commit_response(*keys): from google.cloud.datastore_v1.proto import datastore_pb2 mutation_results = [datastore_pb2.MutationResult(key=key) for key in keys] return datastore_pb2.CommitResponse(mutation_results=mutation_results) def _make_lookup_response(results=(), missing=(), deferred=()): entity_results_found = [ mock.Mock(entity=result, spec=["entity"]) for result in results ] entity_results_missing = [ mock.Mock(entity=missing_entity, spec=["entity"]) for missing_entity in missing ] return mock.Mock( found=entity_results_found, missing=entity_results_missing, deferred=deferred, spec=["found", "missing", "deferred"], ) def _make_datastore_api(*keys, **kwargs): commit_method = mock.Mock(return_value=_make_commit_response(*keys), spec=[]) lookup_response = kwargs.pop("lookup_response", _make_lookup_response()) lookup_method = mock.Mock(return_value=lookup_response, spec=[]) return mock.Mock( commit=commit_method, lookup=lookup_method, spec=["commit", "lookup"] )<|fim▁end|>
def __init__(self, client):
<|file_name|>function_ptr.hpp<|end_file_name|><|fim▁begin|>/*============================================================================= <|fim▁hole|> file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_PHOENIX_PREPROCESSED_BIND_DETAIL_FUNCTION_PTR_HPP) #define BOOST_PHOENIX_PREPROCESSED_BIND_DETAIL_FUNCTION_PTR_HPP #if BOOST_PHOENIX_LIMIT <= 10 #include <boost/phoenix/bind/detail/preprocessed/function_ptr_10.hpp> #elif BOOST_PHOENIX_LIMIT <= 20 #include <boost/phoenix/bind/detail/preprocessed/function_ptr_20.hpp> #elif BOOST_PHOENIX_LIMIT <= 30 #include <boost/phoenix/bind/detail/preprocessed/function_ptr_30.hpp> #elif BOOST_PHOENIX_LIMIT <= 40 #include <boost/phoenix/bind/detail/preprocessed/function_ptr_40.hpp> #elif BOOST_PHOENIX_LIMIT <= 50 #include <boost/phoenix/bind/detail/preprocessed/function_ptr_50.hpp> #else #error "BOOST_PHOENIX_LIMIT out of bounds for preprocessed headers" #endif #endif<|fim▁end|>
Copyright (c) 2011 Hartmut Kaiser Distributed under the Boost Software License, Version 1.0. (See accompanying
<|file_name|>test_carepoint_import_mapper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2015-2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.addons.connector_carepoint.unit import mapper from .common import SetUpCarepointBase class TestCarepointImporterMapper(SetUpCarepointBase): def setUp(self): super(TestCarepointImporterMapper, self).setUp() self.Importer = mapper.CarepointImportMapper self.model = 'carepoint.carepoint.store' self.mock_env = self.get_carepoint_helper( self.model ) self.importer = self.Importer(self.mock_env) <|fim▁hole|> self.assertDictEqual(expect, res) def test_company_id(self): """ It should map company_id correctly """ res = self.importer.company_id(True) expect = {'company_id': self.importer.backend_record.company_id.id} self.assertDictEqual(expect, res)<|fim▁end|>
def test_backend_id(self): """ It should map backend_id correctly """ res = self.importer.backend_id(True) expect = {'backend_id': self.importer.backend_record.id}
<|file_name|>rtconfig.py<|end_file_name|><|fim▁begin|>import os # toolchains options ARCH = 'arm' CPU = 'cortex-m3' CROSS_TOOL = 'gcc' if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if CROSS_TOOL == 'gcc': PLATFORM = 'gcc' EXEC_PATH = 'C:\Program Files (x86)\CodeSourcery\Sourcery G++ Lite\bin' #EXEC_PATH = 'C:\Program Files (x86)\yagarto\bin' elif CROSS_TOOL == 'keil': print '================ERROR============================' print 'Not support keil yet!' print '=================================================' exit(0) elif CROSS_TOOL == 'iar': print '================ERROR============================' print 'Not support iar yet!' print '=================================================' exit(0) if os.getenv('RTT_EXEC_PATH'): EXEC_PATH = os.getenv('RTT_EXEC_PATH') BUILD = 'debug' # EFM32_BOARD = 'EFM32_G8XX_STK' # EFM32_BOARD = 'EFM32_GXXX_DK' EFM32_BOARD = 'EFM32GG_DK3750' if EFM32_BOARD == 'EFM32_G8XX_STK': EFM32_FAMILY = 'Gecko' EFM32_TYPE = 'EFM32G890F128' EFM32_LCD = 'none' elif EFM32_BOARD == 'EFM32_GXXX_DK': EFM32_FAMILY = 'Gecko' EFM32_TYPE = 'EFM32G290F128' EFM32_LCD = 'none' elif EFM32_BOARD == 'EFM32GG_DK3750': EFM32_FAMILY = 'Giant Gecko' EFM32_TYPE = 'EFM32GG990F1024' # EFM32_LCD = 'LCD_MAPPED' EFM32_LCD = 'LCD_DIRECT' if PLATFORM == 'gcc': # toolchains PREFIX = 'arm-none-eabi-' CC = PREFIX + 'gcc' AS = PREFIX + 'gcc' AR = PREFIX + 'ar' LINK = PREFIX + 'gcc' TARGET_EXT = 'axf' SIZE = PREFIX + 'size' OBJDUMP = PREFIX + 'objdump' OBJCPY = PREFIX + 'objcopy' DEVICE = ' -mcpu=cortex-m3 -mthumb -ffunction-sections -fdata-sections' CFLAGS = DEVICE AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp' LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-efm32.map,-cref,-u,__cs3_reset -T' if EFM32_BOARD == 'EFM32_G8XX_STK' or EFM32_BOARD == 'EFM32_GXXX_DK': LFLAGS += ' efm32g_rom.ld' elif EFM32_BOARD == 'EFM32GG_DK3750': LFLAGS += ' efm32gg_rom.ld' CPATH = '' LPATH = '' if BUILD == 'debug': CFLAGS += ' -O0 -gdwarf-2' AFLAGS += ' -gdwarf-2' else: CFLAGS += ' -O2' <|fim▁hole|><|fim▁end|>
POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread.bin\n' + SIZE + ' $TARGET \n'
<|file_name|>shakeout_menu.spec.js<|end_file_name|><|fim▁begin|><|fim▁hole|> describe("Shakeout Menu", () => { // Before running tests - we have to make sure the admin user is logged in before(() => { cy.login('team_leader','Test1234$'); cy.getCookie("sessionid").should("exist"); cy.getCookie("csrftoken").should("exist"); }); //Making sure we still have the sessionid and csrftoken beforeEach(() => { Cypress.Cookies.preserveOnce("sessionid", "csrftoken"); }); //Make sure the administration menu does not exist it("Check no admin menu", () => { //Go to dashboard cy.visit('http://localhost:8000/'); //Make sure the administration drop down does not exist cy.get('#administrationDropdown') .should('not.exist'); }) })<|fim▁end|>
// The following will make sure the team_leader does not have access to certain menu items // All menu items have been tested at the administration level
<|file_name|>plot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ femagtools.plot ~~~~~~~~~~~~~~~ Creating plots """ import numpy as np import scipy.interpolate as ip import logging try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from mpl_toolkits.mplot3d import Axes3D matplotlibversion = matplotlib.__version__ except ImportError: # ModuleNotFoundError: matplotlibversion = 0 logger = logging.getLogger("femagtools.plot") def _create_3d_axis(): """creates a subplot with 3d projection if one does not already exist""" from matplotlib.projections import get_projection_class from matplotlib import _pylab_helpers create_axis = True if _pylab_helpers.Gcf.get_active() is not None: if isinstance(plt.gca(), get_projection_class('3d')): create_axis = False if create_axis: plt.figure() plt.subplot(111, projection='3d') def _plot_surface(ax, x, y, z, labels, azim=None): """helper function for surface plots""" # ax.tick_params(axis='both', which='major', pad=-3) assert np.size(x) > 1 and np.size(y) > 1 and np.size(z) > 1 if azim is not None: ax.azim = azim X, Y = np.meshgrid(x, y) Z = np.ma.masked_invalid(z) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis, alpha=0.85, vmin=np.nanmin(z), vmax=np.nanmax(z), linewidth=0, antialiased=True) # edgecolor=(0, 0, 0, 0)) # ax.set_xticks(xticks) # ax.set_yticks(yticks) # ax.set_zticks(zticks) ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) ax.set_title(labels[2]) # plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) def __phasor_plot(ax, up, idq, uxdq): uref = max(up, uxdq[0]) uxd = uxdq[0]/uref uxq = uxdq[1]/uref u1d, u1q = (uxd, 1+uxq) u1 = np.sqrt(u1d**2 + u1q**2)*uref i1 = np.linalg.norm(idq) i1d, i1q = (idq[0]/i1, idq[1]/i1) qhw = 6 # width arrow head qhl = 15 # length arrow head qlw = 2 # line width qts = 10 # textsize # Length of the Current adjust to Ud: Initally 0.9, Maier(Oswald) = 0.5 curfac = max(0.9, 1.5*i1q/up) def label_line(ax, X, Y, U, V, label, color='k', size=8): """Add a label to a line, at the proper angle. Arguments --------- line : matplotlib.lines.Line2D object, label : str x : float x-position to place center of text (in data coordinated y : float y-position to place center of text (in data coordinates) color : str size : float """ x1, x2 = X, X + U y1, y2 = Y, Y + V if y2 == 0: y2 = y1 if x2 == 0: x2 = x1 x = (x1 + x2) / 2 y = (y1 + y2) / 2 slope_degrees = np.rad2deg(np.angle(U + V * 1j)) if slope_degrees < 0: slope_degrees += 180 if 90 < slope_degrees <= 270: slope_degrees += 180 x_offset = np.sin(np.deg2rad(slope_degrees)) y_offset = np.cos(np.deg2rad(slope_degrees)) bbox_props = dict(boxstyle="Round4, pad=0.1", fc="white", lw=0) text = ax.annotate(label, xy=(x, y), xytext=(x_offset * 10, y_offset * 8), textcoords='offset points', size=size, color=color, horizontalalignment='center', verticalalignment='center', fontfamily='monospace', fontweight='bold', bbox=bbox_props) text.set_rotation(slope_degrees) return text if ax == 0: ax = plt.gca() ax.axes.xaxis.set_ticklabels([]) ax.axes.yaxis.set_ticklabels([]) # ax.set_aspect('equal') ax.set_title( r'$U_1$={0} V, $I_1$={1} A, $U_p$={2} V'.format( round(u1, 1), round(i1, 1), round(up, 1)), fontsize=14) up /= uref ax.quiver(0, 0, 0, up, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw/2, headlength=qhl/2, headaxislength=qhl/2, width=qlw*2, color='k') label_line(ax, 0, 0, 0, up, '$U_p$', 'k', qts) ax.quiver(0, 0, u1d, u1q, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='r') label_line(ax, 0, 0, u1d, u1q, '$U_1$', 'r', qts) ax.quiver(0, 1, uxd, 0, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g') label_line(ax, 0, 1, uxd, 0, '$U_d$', 'g', qts) ax.quiver(uxd, 1, 0, uxq, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g') label_line(ax, uxd, 1, 0, uxq, '$U_q$', 'g', qts) ax.quiver(0, 0, curfac*i1d, curfac*i1q, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='b') label_line(ax, 0, 0, curfac*i1d, curfac*i1q, '$I_1$', 'b', qts) xmin, xmax = (min(0, uxd, i1d), max(0, i1d, uxd)) ymin, ymax = (min(0, i1q, 1-uxq), max(1, i1q, 1+uxq)) ax.set_xlim([xmin-0.1, xmax+0.1]) ax.set_ylim([ymin-0.1, ymax+0.1]) ax.grid(True) def i1beta_phasor(up, i1, beta, r1, xd, xq, ax=0): """creates a phasor plot up: internal voltage i1: current beta: angle i1 vs up [deg] r1: resistance xd: reactance in direct axis xq: reactance in quadrature axis""" i1d, i1q = (i1*np.sin(beta/180*np.pi), i1*np.cos(beta/180*np.pi)) uxdq = ((r1*i1d - xq*i1q), (r1*i1q + xd*i1d)) __phasor_plot(ax, up, (i1d, i1q), uxdq) def iqd_phasor(up, iqd, uqd, ax=0): """creates a phasor plot up: internal voltage iqd: current uqd: terminal voltage""" uxdq = (uqd[1]/np.sqrt(2), (uqd[0]/np.sqrt(2)-up)) __phasor_plot(ax, up, (iqd[1]/np.sqrt(2), iqd[0]/np.sqrt(2)), uxdq) def phasor(bch, ax=0): """create phasor plot from bch""" f1 = bch.machine['p']*bch.dqPar['speed'] w1 = 2*np.pi*f1 xd = w1*bch.dqPar['ld'][-1] xq = w1*bch.dqPar['lq'][-1] r1 = bch.machine['r1'] i1beta_phasor(bch.dqPar['up'][-1], bch.dqPar['i1'][-1], bch.dqPar['beta'][-1], r1, xd, xq, ax) def airgap(airgap, ax=0): """creates plot of flux density in airgap""" if ax == 0: ax = plt.gca() ax.set_title('Airgap Flux Density [T]') ax.plot(airgap['pos'], airgap['B'], label='Max {:4.2f} T'.format(max(airgap['B']))) ax.plot(airgap['pos'], airgap['B_fft'], label='Base Ampl {:4.2f} T'.format(airgap['Bamp'])) ax.set_xlabel('Position/°') ax.legend() ax.grid(True) def airgap_fft(airgap, bmin=1e-2, ax=0): """plot airgap harmonics""" unit = 'T' if ax == 0: ax = plt.gca() ax.set_title('Airgap Flux Density Harmonics / {}'.format(unit)) ax.grid(True) order, fluxdens = np.array([(n, b) for n, b in zip(airgap['nue'], airgap['B_nue']) if b > bmin]).T try: markerline1, stemlines1, _ = ax.stem(order, fluxdens, '-.', basefmt=" ", use_line_collection=True) ax.set_xticks(order) except ValueError: # empty sequence pass def torque(pos, torque, ax=0): """creates plot from torque vs position""" k = 20 alpha = np.linspace(pos[0], pos[-1], k*len(torque)) f = ip.interp1d(pos, torque, kind='quadratic') unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if ax == 0: ax = plt.gca() ax.set_title('Torque / {}'.format(unit)) ax.grid(True) ax.plot(pos, [scale*t for t in torque], 'go') ax.plot(alpha, scale*f(alpha)) if np.min(torque) > 0 and np.max(torque) > 0: ax.set_ylim(bottom=0) elif np.min(torque) < 0 and np.max(torque) < 0: ax.set_ylim(top=0) def torque_fft(order, torque, ax=0): """plot torque harmonics""" unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if ax == 0: ax = plt.gca() ax.set_title('Torque Harmonics / {}'.format(unit)) ax.grid(True) try: bw = 2.5E-2*max(order) ax.bar(order, [scale*t for t in torque], width=bw, align='center') ax.set_xlim(left=-bw/2) except ValueError: # empty sequence pass def force(title, pos, force, xlabel='', ax=0): """plot force vs position""" unit = 'N' scale = 1 if min(force) < -9.9e3 or max(force) > 9.9e3: scale = 1e-3 unit = 'kN' if ax == 0: ax = plt.gca() ax.set_title('{} / {}'.format(title, unit)) ax.grid(True) ax.plot(pos, [scale*f for f in force]) if xlabel: ax.set_xlabel(xlabel) if min(force) > 0: ax.set_ylim(bottom=0) def force_fft(order, force, ax=0): """plot force harmonics""" unit = 'N' scale = 1 if min(force) < -9.9e3 or max(force) > 9.9e3: scale = 1e-3 unit = 'kN' if ax == 0: ax = plt.gca() ax.set_title('Force Harmonics / {}'.format(unit)) ax.grid(True) try: bw = 2.5E-2*max(order) ax.bar(order, [scale*t for t in force], width=bw, align='center') ax.set_xlim(left=-bw/2) except ValueError: # empty sequence pass def forcedens(title, pos, fdens, ax=0): """plot force densities""" if ax == 0: ax = plt.gca() ax.set_title(title) ax.grid(True) ax.plot(pos, [1e-3*ft for ft in fdens[0]], label='F tang') ax.plot(pos, [1e-3*fn for fn in fdens[1]], label='F norm') ax.legend() ax.set_xlabel('Pos / deg') ax.set_ylabel('Force Density / kN/m²') def forcedens_surface(fdens, ax=0): if ax == 0: _create_3d_axis() ax = plt.gca() xpos = [p for p in fdens.positions[0]['X']] ypos = [p['position'] for p in fdens.positions] z = 1e-3*np.array([p['FN'] for p in fdens.positions]) _plot_surface(ax, xpos, ypos, z, (u'Rotor pos/°', u'Pos/°', u'F N / kN/m²')) def forcedens_fft(title, fdens, ax=0): """plot force densities FFT Args: title: plot title fdens: force density object """ if ax == 0: ax = plt.axes(projection="3d") F = 1e-3*fdens.fft() fmin = 0.2 num_bars = F.shape[0] + 1 _xx, _yy = np.meshgrid(np.arange(1, num_bars), np.arange(1, num_bars)) z_size = F[F > fmin] x_pos, y_pos = _xx[F > fmin], _yy[F > fmin] z_pos = np.zeros_like(z_size) x_size = 2 y_size = 2 ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size) ax.view_init(azim=120) ax.set_xlim(0, num_bars+1) ax.set_ylim(0, num_bars+1) ax.set_title(title) ax.set_xlabel('M') ax.set_ylabel('N') ax.set_zlabel('kN/m²') def winding_flux(pos, flux, ax=0): """plot flux vs position""" if ax == 0: ax = plt.gca() ax.set_title('Winding Flux / Vs') ax.grid(True) for p, f in zip(pos, flux): ax.plot(p, f) def winding_current(pos, current, ax=0): """plot winding currents""" if ax == 0: ax = plt.gca() ax.set_title('Winding Currents / A') ax.grid(True) for p, i in zip(pos, current): ax.plot(p, i) def voltage(title, pos, voltage, ax=0): """plot voltage vs. position""" if ax == 0: ax = plt.gca() ax.set_title('{} / V'.format(title)) ax.grid(True) ax.plot(pos, voltage) def voltage_fft(title, order, voltage, ax=0): """plot FFT harmonics of voltage""" if ax == 0: ax = plt.gca() ax.set_title('{} / V'.format(title)) ax.grid(True) if max(order) < 5: order += [5] voltage += [0] try: bw = 2.5E-2*max(order) ax.bar(order, voltage, width=bw, align='center') except ValueError: # empty sequence pass def mcv_hbj(mcv, log=True, ax=0): """plot H, B, J of mcv dict""" import femagtools.mcv MUE0 = 4e-7*np.pi ji = [] csiz = len(mcv['curve']) if ax == 0: ax = plt.gca() ax.set_title(mcv['name']) for k, c in enumerate(mcv['curve']): bh = [(bi, hi*1e-3) for bi, hi in zip(c['bi'], c['hi'])] try: if csiz == 1 and mcv['ctype'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV): ji = [b-MUE0*h*1e3 for b, h in bh] except Exception: pass bi, hi = zip(*bh) label = 'Flux Density' if csiz > 1: label = 'Flux Density ({0}°)'.format(mcv.mc1_angle[k]) if log: ax.semilogx(hi, bi, label=label) if ji: ax.semilogx(hi, ji, label='Polarisation') else: ax.plot(hi, bi, label=label) if ji: ax.plot(hi, ji, label='Polarisation') ax.set_xlabel('H / kA/m') ax.set_ylabel('T') if ji or csiz > 1: ax.legend(loc='lower right') ax.grid() def mcv_muer(mcv, ax=0): """plot rel. permeability vs. B of mcv dict""" MUE0 = 4e-7*np.pi bi, ur = zip(*[(bx, bx/hx/MUE0) for bx, hx in zip(mcv['curve'][0]['bi'], mcv['curve'][0]['hi']) if not hx == 0]) if ax == 0: ax = plt.gca() ax.plot(bi, ur) ax.set_xlabel('B / T') ax.set_title('rel. Permeability') ax.grid() def mtpa(pmrel, i1max, title='', projection='', ax=0): """create a line or surface plot with torque and mtpa curve""" nsamples = 10 i1 = np.linspace(0, i1max, nsamples) iopt = np.array([pmrel.mtpa(x) for x in i1]).T iqmax, idmax = pmrel.iqdmax(i1max) iqmin, idmin = pmrel.iqdmin(i1max) if projection == '3d': nsamples = 50 else: if iqmin == 0: iqmin = 0.1*iqmax id = np.linspace(idmin, idmax, nsamples) iq = np.linspace(iqmin, iqmax, nsamples) torque_iqd = np.array( [[pmrel.torque_iqd(x, y) for y in id] for x in iq]) if projection == '3d': ax = idq_torque(id, iq, torque_iqd, ax) ax.plot(iopt[1], iopt[0], iopt[2], color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format( np.max(iopt[2][-1]))) else: if ax == 0: ax = plt.gca() ax.set_aspect('equal') x, y = np.meshgrid(id, iq) CS = ax.contour(x, y, torque_iqd, 6, colors='k') ax.clabel(CS, fmt='%d', inline=1) ax.set_xlabel('Id/A') ax.set_ylabel('Iq/A') ax.plot(iopt[1], iopt[0], color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format( np.max(iopt[2][-1]))) ax.grid() if title: ax.set_title(title) ax.legend() def mtpv(pmrel, u1max, i1max, title='', projection='', ax=0): """create a line or surface plot with voltage and mtpv curve""" w1 = pmrel.w2_imax_umax(i1max, u1max) nsamples = 20 if projection == '3d': nsamples = 50 iqmax, idmax = pmrel.iqdmax(i1max) iqmin, idmin = pmrel.iqdmin(i1max) id = np.linspace(idmin, idmax, nsamples) iq = np.linspace(iqmin, iqmax, nsamples) u1_iqd = np.array( [[np.linalg.norm(pmrel.uqd(w1, iqx, idx))/np.sqrt(2) for idx in id] for iqx in iq]) u1 = np.mean(u1_iqd) imtpv = np.array([pmrel.mtpv(wx, u1, i1max) for wx in np.linspace(w1, 20*w1, nsamples)]).T if projection == '3d': torque_iqd = np.array( [[pmrel.torque_iqd(x, y) for y in id] for x in iq]) ax = idq_torque(id, iq, torque_iqd, ax) ax.plot(imtpv[1], imtpv[0], imtpv[2], color='red', linewidth=2) else: if ax == 0: ax = plt.gca() ax.set_aspect('equal') x, y = np.meshgrid(id, iq) CS = ax.contour(x, y, u1_iqd, 4, colors='b') # linestyles='dashed') ax.clabel(CS, fmt='%d', inline=1) ax.plot(imtpv[1], imtpv[0], color='red', linewidth=2, label='MTPV: {0:5.0f} Nm'.format(np.max(imtpv[2]))) # beta = np.arctan2(imtpv[1][0], imtpv[0][0]) # b = np.linspace(beta, 0) # ax.plot(np.sqrt(2)*i1max*np.sin(b), np.sqrt(2)*i1max*np.cos(b), 'r-') ax.grid() ax.legend() ax.set_xlabel('Id/A') ax.set_ylabel('Iq/A') if title: ax.set_title(title) def __get_linearForce_title_keys(lf): if 'force_r' in lf: return ['Force r', 'Force z'], ['force_r', 'force_z'] return ['Force x', 'Force y'], ['force_x', 'force_y'] def pmrelsim(bch, title=''): """creates a plot of a PM/Rel motor simulation""" cols = 2 rows = 4 if len(bch.flux['1']) > 1: rows += 1 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) tq = list(bch.torque_fft[-1]['torque']) order = list(bch.torque_fft[-1]['order']) if order and max(order) < 5: order += [15] tq += [0] torque_fft(order, tq) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) <|fim▁hole|> """creates a plot of a MULT CAL simulation""" cols = 2 rows = 4 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) tq = list(bch.torque_fft[-1]['torque']) order = list(bch.torque_fft[-1]['order']) if order and max(order) < 5: order += [15] tq += [0] torque_fft(order, tq) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def fasttorque(bch, title=''): """creates a plot of a Fast Torque simulation""" cols = 2 rows = 4 if len(bch.flux['1']) > 1: rows += 1 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) torque_fft(bch.torque_fft[-1]['order'], bch.torque_fft[-1]['torque']) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def cogging(bch, title=''): """creates a cogging plot""" cols = 2 rows = 3 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[0]['angle'], bch.torque[0]['torque']) plt.subplot(rows, cols, row+1) if bch.torque_fft: torque_fft(bch.torque_fft[0]['order'], bch.torque_fft[0]['torque']) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[0]['angle'], bch.torque[0]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[0]['angle'], bch.torque[0]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) voltage('Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+2) voltage_fft('Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) fig.tight_layout(h_pad=2) if title: fig.subplots_adjust(top=0.92) def transientsc(bch, title=''): """creates a transient short circuit plot""" cols = 1 rows = 2 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) ax = plt.gca() ax.set_title('Currents / A') ax.grid(True) for i in ('ia', 'ib', 'ic'): ax.plot(bch.scData['time'], bch.scData[i], label=i) ax.set_xlabel('Time / s') ax.legend() row = 2 plt.subplot(rows, cols, row) ax = plt.gca() ax.set_title('Torque / Nm') ax.grid(True) ax.plot(bch.scData['time'], bch.scData['torque']) ax.set_xlabel('Time / s') fig.tight_layout(h_pad=2) if title: fig.subplots_adjust(top=0.92) def i1beta_torque(i1, beta, torque, title='', ax=0): """creates a surface plot of torque vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 210 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -60 unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if title: _plot_surface(ax, i1, beta, scale*np.asarray(torque), (u'I1/A', u'Beta/°', title), azim=azim) else: _plot_surface(ax, i1, beta, scale*np.asarray(torque), (u'I1/A', u'Beta/°', u'Torque/{}'.format(unit)), azim=azim) def i1beta_ld(i1, beta, ld, ax=0): """creates a surface plot of ld vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, np.asarray(ld)*1e3, (u'I1/A', u'Beta/°', u'Ld/mH'), azim=60) def i1beta_lq(i1, beta, lq, ax=0): """creates a surface plot of ld vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 60 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -120 _plot_surface(ax, i1, beta, np.asarray(lq)*1e3, (u'I1/A', u'Beta/°', u'Lq/mH'), azim=azim) def i1beta_psim(i1, beta, psim, ax=0): """creates a surface plot of psim vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, psim, (u'I1/A', u'Beta/°', u'Psi m/Vs'), azim=60) def i1beta_up(i1, beta, up, ax=0): """creates a surface plot of up vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, up, (u'I1/A', u'Beta/°', u'Up/V'), azim=60) def i1beta_psid(i1, beta, psid, ax=0): """creates a surface plot of psid vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = -60 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = 60 _plot_surface(ax, i1, beta, psid, (u'I1/A', u'Beta/°', u'Psi d/Vs'), azim=azim) def i1beta_psiq(i1, beta, psiq, ax=0): """creates a surface plot of psiq vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 210 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -60 _plot_surface(ax, i1, beta, psiq, (u'I1/A', u'Beta/°', u'Psi q/Vs'), azim=azim) def idq_torque(id, iq, torque, ax=0): """creates a surface plot of torque vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' _plot_surface(ax, id, iq, scale*np.asarray(torque), (u'Id/A', u'Iq/A', u'Torque/{}'.format(unit)), azim=-60) return ax def idq_psid(id, iq, psid, ax=0): """creates a surface plot of psid vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psid, (u'Id/A', u'Iq/A', u'Psi d/Vs'), azim=210) def idq_psiq(id, iq, psiq, ax=0): """creates a surface plot of psiq vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psiq, (u'Id/A', u'Iq/A', u'Psi q/Vs'), azim=210) def idq_psim(id, iq, psim, ax=0): """creates a surface plot of psim vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psim, (u'Id/A', u'Iq/A', u'Psi m [Vs]'), azim=120) def idq_ld(id, iq, ld, ax=0): """creates a surface plot of ld vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, np.asarray(ld)*1e3, (u'Id/A', u'Iq/A', u'L d/mH'), azim=120) def idq_lq(id, iq, lq, ax=0): """creates a surface plot of lq vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, np.asarray(lq)*1e3, (u'Id/A', u'Iq/A', u'L q/mH'), azim=120) def ldlq(bch): """creates the surface plots of a BCH reader object with a ld-lq identification""" beta = bch.ldq['beta'] i1 = bch.ldq['i1'] torque = bch.ldq['torque'] ld = np.array(bch.ldq['ld']) lq = np.array(bch.ldq['lq']) psid = bch.ldq['psid'] psiq = bch.ldq['psiq'] rows = 3 fig = plt.figure(figsize=(10, 4*rows)) fig.suptitle('Ld-Lq Identification {}'.format(bch.filename), fontsize=16) fig.add_subplot(rows, 2, 1, projection='3d') i1beta_torque(i1, beta, torque) fig.add_subplot(rows, 2, 2, projection='3d') i1beta_psid(i1, beta, psid) fig.add_subplot(rows, 2, 3, projection='3d') i1beta_psiq(i1, beta, psiq) fig.add_subplot(rows, 2, 4, projection='3d') try: i1beta_psim(i1, beta, bch.ldq['psim']) except: i1beta_up(i1, beta, bch.ldq['up']) fig.add_subplot(rows, 2, 5, projection='3d') i1beta_ld(i1, beta, ld) fig.add_subplot(rows, 2, 6, projection='3d') i1beta_lq(i1, beta, lq) def psidq(bch): """creates the surface plots of a BCH reader object with a psid-psiq identification""" id = bch.psidq['id'] iq = bch.psidq['iq'] torque = bch.psidq['torque'] ld = np.array(bch.psidq_ldq['ld']) lq = np.array(bch.psidq_ldq['lq']) psim = bch.psidq_ldq['psim'] psid = bch.psidq['psid'] psiq = bch.psidq['psiq'] rows = 3 fig = plt.figure(figsize=(10, 4*rows)) fig.suptitle('Psid-Psiq Identification {}'.format( bch.filename), fontsize=16) fig.add_subplot(rows, 2, 1, projection='3d') idq_torque(id, iq, torque) fig.add_subplot(rows, 2, 2, projection='3d') idq_psid(id, iq, psid) fig.add_subplot(rows, 2, 3, projection='3d') idq_psiq(id, iq, psiq) fig.add_subplot(rows, 2, 4, projection='3d') idq_psim(id, iq, psim) fig.add_subplot(rows, 2, 5, projection='3d') idq_ld(id, iq, ld) fig.add_subplot(rows, 2, 6, projection='3d') idq_lq(id, iq, lq) def felosses(losses, coeffs, title='', log=True, ax=0): """plot iron losses with steinmetz or jordan approximation Args: losses: dict with f, B, pfe values coeffs: list with steinmetz (cw, alpha, beta) or jordan (cw, alpha, ch, beta, gamma) coeffs title: title string log: log scale for x and y axes if True """ import femagtools.losscoeffs as lc if ax == 0: ax = plt.gca() fo = losses['fo'] Bo = losses['Bo'] B = plt.np.linspace(0.9*np.min(losses['B']), 1.1*0.9*np.max(losses['B'])) for i, f in enumerate(losses['f']): pfe = [p for p in np.array(losses['pfe'])[i] if p] if f > 0: if len(coeffs) == 5: ax.plot(B, lc.pfe_jordan(f, B, *coeffs, fo=fo, Bo=Bo)) elif len(coeffs) == 3: ax.plot(B, lc.pfe_steinmetz(f, B, *coeffs, fo=fo, Bo=Bo)) plt.plot(losses['B'][:len(pfe)], pfe, marker='o', label="{} Hz".format(f)) ax.set_title("Fe Losses/(W/kg) " + title) if log: ax.set_yscale('log') ax.set_xscale('log') ax.set_xlabel("Flux Density [T]") # plt.ylabel("Pfe [W/kg]") ax.legend() ax.grid(True) def spel(isa, with_axis=False, ax=0): """plot super elements of I7/ISA7 model Args: isa: Isa7 object """ from matplotlib.patches import Polygon if ax == 0: ax = plt.gca() ax.set_aspect('equal') for se in isa.superelements: ax.add_patch(Polygon([n.xy for nc in se.nodechains for n in nc.nodes], color=isa.color[se.color], lw=0)) ax.autoscale(enable=True) if not with_axis: ax.axis('off') def mesh(isa, with_axis=False, ax=0): """plot mesh of I7/ISA7 model Args: isa: Isa7 object """ from matplotlib.lines import Line2D if ax == 0: ax = plt.gca() ax.set_aspect('equal') for el in isa.elements: pts = [list(i) for i in zip(*[v.xy for v in el.vertices])] ax.add_line(Line2D(pts[0], pts[1], color='b', ls='-', lw=0.25)) # for nc in isa.nodechains: # pts = [list(i) for i in zip(*[(n.x, n.y) for n in nc.nodes])] # ax.add_line(Line2D(pts[0], pts[1], color="b", ls="-", lw=0.25, # marker=".", ms="2", mec="None")) # for nc in isa.nodechains: # if nc.nodemid is not None: # plt.plot(*nc.nodemid.xy, "rx") ax.autoscale(enable=True) if not with_axis: ax.axis('off') def _contour(ax, title, elements, values, label='', isa=None): from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection if ax == 0: ax = plt.gca() ax.set_aspect('equal') ax.set_title(title, fontsize=18) if isa: for se in isa.superelements: ax.add_patch(Polygon([n.xy for nc in se.nodechains for n in nc.nodes], color='gray', alpha=0.1, lw=0)) valid_values = np.logical_not(np.isnan(values)) patches = np.array([Polygon([v.xy for v in e.vertices]) for e in elements])[valid_values] # , cmap=matplotlib.cm.jet, alpha=0.4) p = PatchCollection(patches, alpha=1.0, match_original=False) p.set_array(np.asarray(values)[valid_values]) ax.add_collection(p) cb = plt.colorbar(p) for patch in np.array([Polygon([v.xy for v in e.vertices], fc='white', alpha=1.0) for e in elements])[np.isnan(values)]: ax.add_patch(patch) if label: cb.set_label(label=label, fontsize=18) ax.autoscale(enable=True) ax.axis('off') def demag(isa, ax=0): """plot demag of NC/I7/ISA7 model Args: isa: Isa7/NC object """ emag = [e for e in isa.elements if e.is_magnet()] demag = np.array([e.demagnetization(isa.MAGN_TEMPERATURE) for e in emag]) _contour(ax, f'Demagnetization at {isa.MAGN_TEMPERATURE} °C', emag, demag, '-H / kA/m', isa) logger.info("Max demagnetization %f", np.max(demag)) def demag_pos(isa, pos, icur=-1, ibeta=-1, ax=0): """plot demag of NC/I7/ISA7 model at rotor position Args: isa: Isa7/NC object pos: rotor position in degree icur: cur amplitude index or last index if -1 ibeta: beta angle index or last index if -1 """ emag = [e for e in isa.elements if e.is_magnet()] demag = np.array([isa.demagnetization(e, icur, ibeta)[1] for e in emag]) for i, x in enumerate(isa.pos_el_fe_induction): if x >= pos/180*np.pi: break hpol = demag[:, i] hpol[hpol == 0] = np.nan _contour(ax, f'Demagnetization at Pos. {round(x/np.pi*180)}° ({isa.MAGN_TEMPERATURE} °C)', emag, hpol, '-H / kA/m', isa) logger.info("Max demagnetization %f kA/m", np.nanmax(hpol)) def flux_density(isa, subreg=[], ax=0): """plot flux density of NC/I7/ISA7 model Args: isa: Isa7/NC object """ if subreg: if isinstance(subreg, list): sr = subreg else: sr = [subreg] elements = [e for s in sr for se in isa.get_subregion(s).elements() for e in se] else: elements = [e for e in isa.elements] fluxd = np.array([np.linalg.norm(e.flux_density()) for e in elements]) _contour(ax, f'Flux Density T', elements, fluxd) logger.info("Max flux dens %f", np.max(fluxd)) def loss_density(isa, subreg=[], ax=0): """plot loss density of NC/I7/ISA7 model Args: isa: Isa7/NC object """ if subreg: if isinstance(subreg, list): sr = subreg else: sr = [subreg] elements = [e for s in sr for sre in isa.get_subregion(s).elements() for e in sre] else: elements = [e for e in isa.elements] lossd = np.array([e.loss_density*1e-3 for e in elements]) _contour(ax, 'Loss Density kW/m³', elements, lossd) def mmf(f, title='', ax=0): """plot magnetomotive force (mmf) of winding""" if ax == 0: ax = plt.gca() if title: ax.set_title(title) ax.plot(np.array(f['pos'])/np.pi*180, f['mmf']) ax.plot(np.array(f['pos_fft'])/np.pi*180, f['mmf_fft']) ax.set_xlabel('Position / Deg') phi = [f['alfa0']/np.pi*180, f['alfa0']/np.pi*180] y = [min(f['mmf_fft']), 1.1*max(f['mmf_fft'])] ax.plot(phi, y, '--') alfa0 = round(f['alfa0']/np.pi*180, 3) ax.text(phi[0]/2, y[0]+0.05, f"{alfa0}°", ha="center", va="bottom") ax.annotate(f"", xy=(phi[0], y[0]), xytext=(0, y[0]), arrowprops=dict(arrowstyle="->")) ax.grid() def mmf_fft(f, title='', mmfmin=1e-2, ax=0): """plot winding mmf harmonics""" if ax == 0: ax = plt.gca() if title: ax.set_title(title) else: ax.set_title('MMF Harmonics') ax.grid(True) order, mmf = np.array([(n, m) for n, m in zip(f['nue'], f['mmf_nue']) if m > mmfmin]).T try: markerline1, stemlines1, _ = ax.stem(order, mmf, '-.', basefmt=" ", use_line_collection=True) ax.set_xticks(order) except ValueError: # empty sequence pass def zoneplan(wdg, ax=0): """plot zone plan of winding wdg""" from matplotlib.patches import Rectangle upper, lower = wdg.zoneplan() Qb = len([n for l in upper for n in l]) from femagtools.windings import coil_color rh = 0.5 if lower: yl = rh ymax = 2*rh + 0.2 else: yl = 0 ymax = rh + 0.2 if ax == 0: ax = plt.gca() ax.axis('off') ax.set_xlim([-0.5, Qb-0.5]) ax.set_ylim([0, ymax]) ax.set_aspect(Qb/6+0.3) for i, p in enumerate(upper): for x in p: ax.add_patch(Rectangle((abs(x)-1.5, yl), 1, rh, facecolor=coil_color[i], edgecolor='white', fill=True)) s = f'+{i+1}' if x > 0 else f'-{i+1}' ax.text(abs(x)-1, yl+rh/2, s, color='black', ha="center", va="center") for i, p in enumerate(lower): for x in p: ax.add_patch(Rectangle((abs(x)-1.5, yl-rh), 1, rh, facecolor=coil_color[i], edgecolor='white', fill=True)) s = f'+{i+1}' if x > 0 else f'-{i+1}' ax.text(abs(x)-1, yl-rh/2, s, color='black', ha="center", va="center") yu = yl+rh step = 1 if Qb < 25 else 2 if lower: yl -= rh margin = 0.05 ax.text(-0.5, yu+margin, f'Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}', ha='left', va='bottom', size=15) for i in range(0, Qb, step): ax.text(i, yl-margin, f'{i+1}', ha="center", va="top") def winding_factors(wdg, n=8, ax=0): """plot winding factors""" ax = plt.gca() ax.set_title(f'Winding factors Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}') ax.grid(True) order, kwp, kwd, kw = np.array([(n, k1, k2, k3) for n, k1, k2, k3 in zip(wdg.kw_order(n), wdg.kwp(n), wdg.kwd(n), wdg.kw(n))]).T try: markerline1, stemlines1, _ = ax.stem(order-1, kwp, 'C1:', basefmt=" ", markerfmt='C1.', use_line_collection=True, label='Pitch') markerline2, stemlines2, _ = ax.stem(order+1, kwd, 'C2:', basefmt=" ", markerfmt='C2.', use_line_collection=True, label='Distribution') markerline3, stemlines3, _ = ax.stem(order, kw, 'C0-', basefmt=" ", markerfmt='C0o', use_line_collection=True, label='Total') ax.set_xticks(order) ax.legend() except ValueError: # empty sequence pass def winding(wdg, ax=0): """plot coils of windings wdg""" from matplotlib.patches import Rectangle from matplotlib.lines import Line2D from femagtools.windings import coil_color coil_len = 25 coil_height = 4 dslot = 8 arrow_head_length = 2 arrow_head_width = 2 if ax == 0: ax = plt.gca() z = wdg.zoneplan() xoff = 0 if z[-1]: xoff = 0.75 yd = dslot*wdg.yd mh = 2*coil_height/yd slots = sorted([abs(n) for m in z[0] for n in m]) smax = slots[-1]*dslot for n in slots: x = n*dslot ax.add_patch(Rectangle((x + dslot/4, 1), dslot / 2, coil_len - 2, fc="lightblue")) ax.text(x, coil_len / 2, str(n), horizontalalignment="center", verticalalignment="center", backgroundcolor="white", bbox=dict(boxstyle='circle,pad=0', fc="white", lw=0)) line_thickness = [0.6, 1.2] for i, layer in enumerate(z): b = -xoff if i else xoff lw = line_thickness[i] for m, mslots in enumerate(layer): for k in mslots: x = abs(k) * dslot + b xpoints = [] ypoints = [] if (i == 0 and (k > 0 or (k < 0 and wdg.l > 1))): # first layer, positive dir or neg. dir and 2-layers: # from right bottom if x + yd > smax+b: dx = dslot if yd > dslot else yd/4 xpoints = [x + yd//2 + dx - xoff] ypoints = [-coil_height + mh*dx] xpoints += [x + yd//2 - xoff, x, x, x + yd//2-xoff] ypoints += [-coil_height, 0, coil_len, coil_len+coil_height] if x + yd > smax+b: xpoints += [x + yd//2 + dx - xoff] ypoints += [coil_len+coil_height - mh*dx] else: # from left bottom if x - yd < 0: # and x - yd/2 > -3*dslot: dx = dslot if yd > dslot else yd/4 xpoints = [x - yd//2 - dx + xoff] ypoints = [- coil_height + mh*dx] xpoints += [x - yd//2+xoff, x, x, x - yd/2+xoff] ypoints += [-coil_height, 0, coil_len, coil_len+coil_height] if x - yd < 0: # and x - yd > -3*dslot: xpoints += [x - yd//2 - dx + xoff] ypoints += [coil_len + coil_height - mh*dx] ax.add_line(Line2D(xpoints, ypoints, color=coil_color[m], lw=lw)) if k > 0: h = arrow_head_length y = coil_len * 0.8 else: h = -arrow_head_length y = coil_len * 0.2 ax.arrow(x, y, 0, h, length_includes_head=True, head_starts_at_zero=False, head_length=arrow_head_length, head_width=arrow_head_width, fc=coil_color[m], lw=0) if False: # TODO show winding connections m = 0 for k in [n*wdg.Q/wdg.p/wdg.m + 1 for n in range(wdg.m)]: if k < len(slots): x = k * dslot + b + yd/2 - xoff ax.add_line(Line2D([x, x], [-2*coil_height, -coil_height], color=coil_color[m], lw=lw)) ax.text(x, -2*coil_height+0.5, str(m+1), color=coil_color[m]) m += 1 ax.autoscale(enable=True) ax.set_axis_off() def main(): import io import sys import argparse from .__init__ import __version__ from femagtools.bch import Reader argparser = argparse.ArgumentParser( description='Read BCH/BATCH/PLT file and create a plot') argparser.add_argument('filename', help='name of BCH/BATCH/PLT file') argparser.add_argument( "--version", "-v", action="version", version="%(prog)s {}, Python {}".format(__version__, sys.version), help="display version information", ) args = argparser.parse_args() if not matplotlibversion: sys.exit(0) if not args.filename: sys.exit(0) ext = args.filename.split('.')[-1].upper() if ext.startswith('MC'): import femagtools.mcv mcv = femagtools.mcv.read(sys.argv[1]) if mcv['mc1_type'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV): ncols = 2 else: # Permanent Magnet ncols = 1 fig, ax = plt.subplots(nrows=1, ncols=ncols, figsize=(10, 6)) if ncols > 1: plt.subplot(1, 2, 1) mcv_hbj(mcv) plt.subplot(1, 2, 2) mcv_muer(mcv) else: mcv_hbj(mcv, log=False) fig.tight_layout() fig.subplots_adjust(top=0.94) plt.show() return if ext.startswith('PLT'): import femagtools.forcedens fdens = femagtools.forcedens.read(args.filename) cols = 1 rows = 2 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 10*rows)) title = '{}, Rotor position {}'.format( fdens.title, fdens.positions[0]['position']) pos = fdens.positions[0]['X'] FT_FN = (fdens.positions[0]['FT'], fdens.positions[0]['FN']) plt.subplot(rows, cols, 1) forcedens(title, pos, FT_FN) title = 'Force Density Harmonics' plt.subplot(rows, cols, 2) forcedens_fft(title, fdens) # fig.tight_layout(h_pad=3.5) # if title: # fig.subplots_adjust(top=0.92) plt.show() return bchresults = Reader() with io.open(args.filename, encoding='latin1', errors='ignore') as f: bchresults.read(f.readlines()) if (bchresults.type.lower().find( 'pm-synchronous-motor simulation') >= 0 or bchresults.type.lower().find( 'permanet-magnet-synchronous-motor') >= 0 or bchresults.type.lower().find( 'simulation pm/universal-motor') >= 0): pmrelsim(bchresults, bchresults.filename) elif bchresults.type.lower().find( 'multiple calculation of forces and flux') >= 0: multcal(bchresults, bchresults.filename) elif bchresults.type.lower().find('cogging calculation') >= 0: cogging(bchresults, bchresults.filename) elif bchresults.type.lower().find('ld-lq-identification') >= 0: ldlq(bchresults) elif bchresults.type.lower().find('psid-psiq-identification') >= 0: psidq(bchresults) elif bchresults.type.lower().find('fast_torque calculation') >= 0: fasttorque(bchresults) elif bchresults.type.lower().find('transient sc') >= 0: transientsc(bchresults, bchresults.filename) else: raise ValueError("BCH type {} not yet supported".format( bchresults.type)) plt.show() def characteristics(char, title=''): fig, axs = plt.subplots(2, 2, figsize=(10, 8), sharex=True) if title: fig.suptitle(title) n = np.array(char['n'])*60 pmech = np.array(char['pmech'])*1e-3 axs[0, 0].plot(n, np.array(char['T']), 'C0-', label='Torque') axs[0, 0].set_ylabel("Torque / Nm") axs[0, 0].grid() axs[0, 0].legend(loc='center left') ax1 = axs[0, 0].twinx() ax1.plot(n, pmech, 'C1-', label='P mech') ax1.set_ylabel("Power / kW") ax1.legend(loc='lower center') axs[0, 1].plot(n[1:], np.array(char['u1'][1:]), 'C0-', label='Voltage') axs[0, 1].set_ylabel("Voltage / V",) axs[0, 1].grid() axs[0, 1].legend(loc='center left') ax2 = axs[0, 1].twinx() ax2.plot(n[1:], char['cosphi'][1:], 'C1-', label='Cos Phi') ax2.set_ylabel("Cos Phi") ax2.legend(loc='lower right') if 'id' in char: axs[1, 0].plot(n, np.array(char['id']), label='Id') if 'iq' in char: axs[1, 0].plot(n, np.array(char['iq']), label='Iq') axs[1, 0].plot(n, np.array(char['i1']), label='I1') axs[1, 0].set_xlabel("Speed / rpm") axs[1, 0].set_ylabel("Current / A") axs[1, 0].legend(loc='center left') if 'beta' in char: ax3 = axs[1, 0].twinx() ax3.plot(n, char['beta'], 'C3-', label='Beta') ax3.set_ylabel("Beta / °") ax3.legend(loc='center right') axs[1, 0].grid() plfe = np.array(char['plfe'])*1e-3 plcu = np.array(char['plcu'])*1e-3 pl = np.array(char['losses'])*1e-3 axs[1, 1].plot(n, plcu, 'C0-', label='Cu Losses') axs[1, 1].plot(n, plfe, 'C1-', label='Fe Losses') axs[1, 1].set_ylabel("Losses / kW") axs[1, 1].legend(loc='center left') axs[1, 1].grid() axs[1, 1].set_xlabel("Speed / rpm") ax4 = axs[1, 1].twinx() ax4.plot(n[1:-1], char['eta'][1:-1], 'C3-', label="Eta") ax4.legend(loc='upper center') ax4.set_ylabel("Efficiency") fig.tight_layout() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') main()<|fim▁end|>
def multcal(bch, title=''):
<|file_name|>webpack-helpers.js<|end_file_name|><|fim▁begin|>const path = require(`path`) exports.chunkNamer = chunk => {<|fim▁hole|> chunk.forEachModule(m => { n.push(path.relative(m.context, m.userRequest)) }) return n.join(`_`) }<|fim▁end|>
if (chunk.name) return chunk.name let n = []
<|file_name|>Type.java<|end_file_name|><|fim▁begin|>package sbahjsic.runtime; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import sbahjsic.core.Warnings; import sbahjsic.core.Warnings.Level; import sbahjsic.runtime.Operator.BiOperator; import sbahjsic.runtime.Operator.UnOperator; import sbahjsic.runtime.Operator.VarargOperator; import sbahjsic.runtime.type.AnyType; import sbahjsic.runtime.type.SVoid; /** Describes a Sbahjsic type. * * <p>For all subclasses, there must only exist one instance. To enforce * this, this class implements final {@code equals()} and {@code hashCode()} * methods as they are defined in {@code Object}.*/ public abstract class Type { private final Map<String, Operator> operators = new HashMap<>(); private final Set<Type> supertypes = new HashSet<>(); private final Set<String> fields = new HashSet<>(); private final Map<String, Method> methods = new HashMap<>(); private int priority = 0; protected Type() { // Fixes a bug where AnyType tried to add AnyType.INSTANCE, which // was null at that point, to its own supertypes if(!getClass().equals(AnyType.class)) { addSupertype(AnyType.INSTANCE); } } /** Registers a new supertype for this type. * @param supertype the new supertype*/ public final void addSupertype(Type supertype) { if(getSupertypes().contains(supertype) || supertype.getSupertypes().contains(this)) { throw new RecursiveTypedefException(this.toString()); } if(this != supertype) { supertypes.add(supertype); } } /** Removes a supertype from this type if it exists. * @param supertype the supertype to remove*/ public final void removeSupertype(Type supertype) { supertypes.remove(supertype); } /** Registers an unary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addUnOperator(String op, UnOperator func) { operators.put(op, Operator.unaryOperator(func)); } /** Registers a binary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addBiOperator(String op, BiOperator func) { operators.put(op, Operator.binaryOperator(func)); } /** Adds an operator that can accept one or two arguments. * @param op the operator * @param unary the unary operator * @param binary the binary operator*/ protected final void addDoubleOperator(String op, UnOperator unary, BiOperator binary) { operators.put(op, (con, args) -> { if(args.length == 1) return unary.apply(con, args[0]); else if(args.length == 2) return binary.apply(con, args[0], args[1]); throw new OperatorCallException("Called with " + args.length + " arguments, expected 1 or 2"); }); } /** Registers a vararg operator for this type.*/ public void addVarargOperator(String op, VarargOperator func) { operators.put(op, Operator.varargOperator(func)); } /** Adds a field to this type. * @param field the field to add*/ protected final void addField(String field) { fields.add(field); } /** Returns a specific operator of this type. * @param op the operator to search * @return the operator matching {@code op} * @throws OperatorCallException if {@code op} isn't defined*/ public final Operator getOperator(String op) { if(operators.containsKey(op)) { return operators.get(op); } Operator operator = operatorLookup(op); if(operator == null) { throw new OperatorCallException("Operator " + op + " not defined on type " + getName()); } return operator; } <|fim▁hole|> for(Type supertype : supertypes) { if(supertype.operators.containsKey(op)) { return supertype.operators.get(op); } } for(Type supertype : supertypes) { Operator operator = supertype.operatorLookup(op); if(operator != null) { return operator; } } return null; } /** Returns a set of all defined operators of this type. * @return a set of the defined operators of this type*/ public final Set<String> getDefinedOperators() { Set<String> ops = new HashSet<>(); ops.addAll(operators.keySet()); for(Type supertype : getSupertypes()) { ops.addAll(supertype.getDefinedOperators()); } return ops; } /** Returns a set of the supertypes of this type. * @return a set of the supertypes of this type*/ public final Set<Type> getSupertypes() { Set<Type> types = new HashSet<>(); types.addAll(supertypes); for(Type supertype : supertypes) { types.addAll(supertype.getSupertypes()); } return types; } /** Returns the fields declared for this type. * @return a set of fields declared for this type*/ public final Set<String> getFields() { Set<String> allFields = new HashSet<>(); allFields.addAll(fields); for(Type supertype : getSupertypes()) { allFields.addAll(supertype.getFields()); } return allFields; } /** Adds a method to this type. * @param name the name of the method * @param method the method*/ public final void addMethod(String name, Method method) { methods.put(name, method); } /** Returns all methods defined for this type. * @return all methods defined for this type*/ public final Set<String> getMethods() { Map<String, Method> allMethods = new HashMap<>(); allMethods.putAll(methods); for(Type supertype : getSupertypes()) { allMethods.putAll(supertype.methods); } return allMethods.keySet(); } /** Returns a method of this type. * @param name the name of the method * @return the method * @throws MethodCallException if the method isn't defined for this type*/ public final Method getMethod(String name) { if(methods.containsKey(name)) { return methods.get(name); } Method method = methodLookup(name); if(method == null) { throw new MethodCallException("Method " + name + " not defined for type " + getName()); } return method; } private final Method methodLookup(String name) { for(Type supertype : supertypes) { if(supertype.methods.containsKey(name)) { return supertype.methods.get(name); } } for(Type supertype : supertypes) { Method method = supertype.methodLookup(name); if(method != null) { return method; } } return null; } /** Returns the name of this type. * @return the name of this type*/ public abstract String getName(); /** Casts a value to this type. * @param object the value to cast * @return the casted value*/ public SValue cast(SValue object) { Warnings.warn(Level.ADVICE, "Undefined cast from " + object.getType() + " to " + this); return object; } /** Returns whether this type is the subtype of some other type. That is * true if this type or any if its supertypes is the other type. * @param other the other type * @return whether this type is the subtype of the other type */ public boolean isSubtype(Type other) { return this.equals(other) || getSupertypes().contains(other); } /** Constructs an instance of this type * @param context the RuntimeContext * @param args the arguments passed to the constructor*/ public SValue construct(RuntimeContext context, SValue...args) { Warnings.warn(Level.NOTIFICATION, "Cannot instantiate " + getName()); return SVoid.VOID; } /** Returns the priority of this type, used to determine which operand * should choose the implementation of a binary operator. Defaults to zero.*/ public int priority() { return priority; } /** Sets the priority for this type.*/ public void setPriority(int p) { priority = p; } @Override public final boolean equals(Object o) { return super.equals(o); } @Override public final int hashCode() { return super.hashCode(); } @Override public final String toString() { return getName(); } }<|fim▁end|>
private final Operator operatorLookup(String op) {
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![allow(unknown_lints)] #![allow(clippy::identity_op)] // used for vertical alignment use std::collections::BTreeMap; use std::fs::File; use std::io::prelude::*; use std::io::Cursor; use std::time::Instant; use anyhow::{bail, Result}; use curl::easy::{Easy, List}; use percent_encoding::{percent_encode, NON_ALPHANUMERIC}; use serde::{Deserialize, Serialize}; use url::Url; pub struct Registry { /// The base URL for issuing API requests. host: String, /// Optional authorization token. /// If None, commands requiring authorization will fail. token: Option<String>, /// Curl handle for issuing requests. handle: Easy, } #[derive(PartialEq, Clone, Copy)] pub enum Auth { Authorized, Unauthorized, } #[derive(Deserialize)] pub struct Crate { pub name: String, pub description: Option<String>, pub max_version: String, } #[derive(Serialize)] pub struct NewCrate { pub name: String, pub vers: String, pub deps: Vec<NewCrateDependency>, pub features: BTreeMap<String, Vec<String>>, pub authors: Vec<String>, pub description: Option<String>, pub documentation: Option<String>, pub homepage: Option<String>, pub readme: Option<String>, pub readme_file: Option<String>, pub keywords: Vec<String>, pub categories: Vec<String>, pub license: Option<String>, pub license_file: Option<String>, pub repository: Option<String>, pub badges: BTreeMap<String, BTreeMap<String, String>>, pub links: Option<String>, } #[derive(Serialize)] pub struct NewCrateDependency { pub optional: bool, pub default_features: bool, pub name: String, pub features: Vec<String>, pub version_req: String, pub target: Option<String>, pub kind: String, #[serde(skip_serializing_if = "Option::is_none")] pub registry: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub explicit_name_in_toml: Option<String>, } #[derive(Deserialize)] pub struct User { pub id: u32, pub login: String, pub avatar: Option<String>, pub email: Option<String>, pub name: Option<String>, } pub struct Warnings { pub invalid_categories: Vec<String>, pub invalid_badges: Vec<String>, pub other: Vec<String>, } #[derive(Deserialize)] struct R { ok: bool, } #[derive(Deserialize)] struct OwnerResponse { ok: bool, msg: String, } #[derive(Deserialize)] struct ApiErrorList { errors: Vec<ApiError>, } #[derive(Deserialize)] struct ApiError { detail: String, } #[derive(Serialize)] struct OwnersReq<'a> { users: &'a [&'a str], } #[derive(Deserialize)] struct Users { users: Vec<User>, } #[derive(Deserialize)] struct TotalCrates { total: u32, } #[derive(Deserialize)] struct Crates { crates: Vec<Crate>, meta: TotalCrates, } impl Registry { pub fn new(host: String, token: Option<String>) -> Registry { Registry::new_handle(host, token, Easy::new()) } pub fn new_handle(host: String, token: Option<String>, handle: Easy) -> Registry { Registry { host, token, handle, } } pub fn host(&self) -> &str { &self.host } pub fn host_is_crates_io(&self) -> bool { Url::parse(self.host()) .map(|u| u.host_str() == Some("crates.io")) .unwrap_or(false) } pub fn add_owners(&mut self, krate: &str, owners: &[&str]) -> Result<String> { let body = serde_json::to_string(&OwnersReq { users: owners })?; let body = self.put(&format!("/crates/{}/owners", krate), body.as_bytes())?; assert!(serde_json::from_str::<OwnerResponse>(&body)?.ok); Ok(serde_json::from_str::<OwnerResponse>(&body)?.msg) } pub fn remove_owners(&mut self, krate: &str, owners: &[&str]) -> Result<()> { let body = serde_json::to_string(&OwnersReq { users: owners })?; let body = self.delete(&format!("/crates/{}/owners", krate), Some(body.as_bytes()))?; assert!(serde_json::from_str::<OwnerResponse>(&body)?.ok); Ok(()) } pub fn list_owners(&mut self, krate: &str) -> Result<Vec<User>> { let body = self.get(&format!("/crates/{}/owners", krate))?; Ok(serde_json::from_str::<Users>(&body)?.users) } pub fn publish(&mut self, krate: &NewCrate, tarball: &File) -> Result<Warnings> { let json = serde_json::to_string(krate)?; // Prepare the body. The format of the upload request is: // // <le u32 of json> // <json request> (metadata for the package) // <le u32 of tarball> // <source tarball> let stat = tarball.metadata()?; let header = { let mut w = Vec::new(); w.extend( [ (json.len() >> 0) as u8, (json.len() >> 8) as u8, (json.len() >> 16) as u8, (json.len() >> 24) as u8, ] .iter() .cloned(), ); w.extend(json.as_bytes().iter().cloned()); w.extend( [ (stat.len() >> 0) as u8, (stat.len() >> 8) as u8, (stat.len() >> 16) as u8, (stat.len() >> 24) as u8, ] .iter() .cloned(), ); w }; let size = stat.len() as usize + header.len(); let mut body = Cursor::new(header).chain(tarball); let url = format!("{}/api/v1/crates/new", self.host); let token = match self.token.as_ref() { Some(s) => s, None => bail!("no upload token found, please run `cargo login`"), }; self.handle.put(true)?; self.handle.url(&url)?; self.handle.in_filesize(size as u64)?; let mut headers = List::new(); headers.append("Accept: application/json")?; headers.append(&format!("Authorization: {}", token))?; self.handle.http_headers(headers)?; let body = self.handle(&mut |buf| body.read(buf).unwrap_or(0))?; let response = if body.is_empty() { "{}".parse()? } else { body.parse::<serde_json::Value>()? }; let invalid_categories: Vec<String> = response .get("warnings") .and_then(|j| j.get("invalid_categories")) .and_then(|j| j.as_array()) .map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect()) .unwrap_or_else(Vec::new); let invalid_badges: Vec<String> = response .get("warnings") .and_then(|j| j.get("invalid_badges")) .and_then(|j| j.as_array()) .map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect()) .unwrap_or_else(Vec::new); let other: Vec<String> = response .get("warnings") .and_then(|j| j.get("other")) .and_then(|j| j.as_array()) .map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect()) .unwrap_or_else(Vec::new); Ok(Warnings { invalid_categories, invalid_badges, other, }) } pub fn search(&mut self, query: &str, limit: u32) -> Result<(Vec<Crate>, u32)> { let formatted_query = percent_encode(query.as_bytes(), NON_ALPHANUMERIC); let body = self.req( &format!("/crates?q={}&per_page={}", formatted_query, limit), None, Auth::Unauthorized, )?; let crates = serde_json::from_str::<Crates>(&body)?; Ok((crates.crates, crates.meta.total)) } pub fn yank(&mut self, krate: &str, version: &str) -> Result<()> { let body = self.delete(&format!("/crates/{}/{}/yank", krate, version), None)?; assert!(serde_json::from_str::<R>(&body)?.ok); Ok(()) } pub fn unyank(&mut self, krate: &str, version: &str) -> Result<()> { let body = self.put(&format!("/crates/{}/{}/unyank", krate, version), &[])?; assert!(serde_json::from_str::<R>(&body)?.ok); Ok(()) } fn put(&mut self, path: &str, b: &[u8]) -> Result<String> { self.handle.put(true)?; self.req(path, Some(b), Auth::Authorized) } fn get(&mut self, path: &str) -> Result<String> { self.handle.get(true)?; self.req(path, None, Auth::Authorized) } fn delete(&mut self, path: &str, b: Option<&[u8]>) -> Result<String> { self.handle.custom_request("DELETE")?; self.req(path, b, Auth::Authorized) } fn req(&mut self, path: &str, body: Option<&[u8]>, authorized: Auth) -> Result<String> { self.handle.url(&format!("{}/api/v1{}", self.host, path))?; let mut headers = List::new(); headers.append("Accept: application/json")?; headers.append("Content-Type: application/json")?; if authorized == Auth::Authorized { let token = match self.token.as_ref() { Some(s) => s, None => bail!("no upload token found, please run `cargo login`"), }; headers.append(&format!("Authorization: {}", token))?; } self.handle.http_headers(headers)?; match body { Some(mut body) => { self.handle.upload(true)?; self.handle.in_filesize(body.len() as u64)?; self.handle(&mut |buf| body.read(buf).unwrap_or(0)) } None => self.handle(&mut |_| 0), } } fn handle(&mut self, read: &mut dyn FnMut(&mut [u8]) -> usize) -> Result<String> { let mut headers = Vec::new(); let mut body = Vec::new(); let started; { let mut handle = self.handle.transfer(); handle.read_function(|buf| Ok(read(buf)))?; handle.write_function(|data| { body.extend_from_slice(data); Ok(data.len()) })?; handle.header_function(|data| { headers.push(String::from_utf8_lossy(data).into_owned()); true })?; started = Instant::now(); handle.perform()?; } let body = match String::from_utf8(body) { Ok(body) => body, Err(..) => bail!("response body was not valid utf-8"), }; let errors = serde_json::from_str::<ApiErrorList>(&body) .ok() .map(|s| s.errors.into_iter().map(|s| s.detail).collect::<Vec<_>>()); match (self.handle.response_code()?, errors) { (0, None) | (200, None) => {} (503, None) if started.elapsed().as_secs() >= 29 && self.host_is_crates_io() => bail!( "Request timed out after 30 seconds. If you're trying to \ upload a crate it may be too large. If the crate is under \ 10MB in size, you can email [email protected] for assistance." ), (code, Some(errors)) => { let reason = reason(code); bail!( "api errors (status {} {}): {}", code, reason, errors.join(", ") ) } (code, None) => bail!( "failed to get a 200 OK response, got {}\n\ headers:\n\ \t{}\n\ body:\n\ {}", code, headers.join("\n\t"), body, ), } Ok(body) } } fn reason(code: u32) -> &'static str { // Taken from https://developer.mozilla.org/en-US/docs/Web/HTTP/Status match code { 100 => "Continue", 101 => "Switching Protocol", 103 => "Early Hints", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 300 => "Multiple Choice",<|fim▁hole|> 304 => "Not Modified", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Payload Too Large", 414 => "URI Too Long", 415 => "Unsupported Media Type", 416 => "Request Range Not Satisfiable", 417 => "Expectation Failed", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", _ => "<unknown>", } }<|fim▁end|>
301 => "Moved Permanently", 302 => "Found", 303 => "See Other",
<|file_name|>test_parser.py<|end_file_name|><|fim▁begin|># Copyright 2016 Matthias Gazzari # # 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 unittest from .util import GrobidServer from instmatcher import parser import xml.etree.ElementTree as et class test_parser(unittest.TestCase):<|fim▁hole|> def setUp(self): host = 'localhost' port = 8081 self.url = 'http://' + host + ':' + str(port) self.server = GrobidServer(host, port) self.server.start() def tearDown(self): self.server.stop() def test_parse_None(self): actual = list(parser.parseAll(None, self.url)) expected = [] self.assertEqual(actual, expected) def test_parse_empty(self): self.server.setResponse(__name__, '') actual = list(parser.parseAll(__name__, self.url)) expected = [] self.assertEqual(actual, expected) def test_parse_no_institution(self): self.server.setResponse( __name__, '''<affiliation> <address> <country key="AQ">Irrelevant</country> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [] self.assertEqual(actual, expected) def test_parse_no_alpha2(self): self.server.setResponse( __name__, '''<affiliation> <orgName type="institution">institA</orgName> <address> <country>country</country> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [{ 'institution': 'institA', 'institutionSource': 'grobid', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_no_country(self): self.server.setResponse( __name__, '''<affiliation> <orgName type="institution">institB</orgName> <address> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [{ 'institution': 'institB', 'institutionSource': 'grobid', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_no_settlement(self): self.server.setResponse( __name__, '''<affiliation> <orgName type="institution">institC</orgName> <address> <country key="AQ">Irrelevant</country> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [{ 'institution': 'institC', 'institutionSource': 'grobid', 'alpha2': 'AQ', 'country': 'Antarctica', 'countrySource': 'grobid', 'settlement':[], },] self.assertEqual(actual, expected) def test_parse_not_regocnised_country(self): affiliation = 'institA, settlement, INDIA' self.server.setResponse( affiliation, '''<affiliation> <orgName type="institution">institA</orgName> <address> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'institA', 'institutionSource': 'regexReplace', 'alpha2': 'IN', 'country': 'India', 'countrySource': 'regex', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_not_regocnised_bad_country(self): affiliation = 'institA, settlement, Fantasia' self.server.setResponse( affiliation, '''<affiliation> <orgName type="institution">institA</orgName> <address> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'institA', 'institutionSource': 'regexReplace', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_not_recognised_country_no_comma_in_affiliation_string(self): affiliation = 'institA settlement Algeria' self.server.setResponse( affiliation, '''<affiliation> <orgName type="institution">institA</orgName> <address> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'institA', 'institutionSource': 'grobid', 'alpha2': 'DZ', 'country': 'Algeria', 'countrySource': 'regex', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_multiple_not_recognised_countries(self): affiliation = 'institA settlement Algeria India' self.server.setResponse( affiliation, '''<affiliation> <orgName type="institution">institA</orgName> <address> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'institA', 'institutionSource': 'grobid', 'alpha2': 'IN', 'country': 'India', 'countrySource': 'regex', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_releveant_tags(self): self.server.setResponse( __name__, '''<affiliation> <orgName type="institution">institD</orgName> <address> <country key="AQ">Irrelevant</country> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [{ 'institution': 'institD', 'institutionSource': 'grobid', 'alpha2': 'AQ', 'country': 'Antarctica', 'countrySource': 'grobid', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_every_tags(self): self.server.setResponse( __name__, '''<affiliation> <orgName type="laboratory">lab</orgName> <orgName type="department">dep</orgName> <orgName type="institution">institE</orgName> <address> <addrLine>addrLine</addrLine> <country key="AQ">Irrelevant</country> <postCode>postCode</postCode> <region>region</region> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [{ 'institution': 'institE', 'institutionSource': 'grobid', 'department': 'dep', 'laboratory': 'lab', 'alpha2': 'AQ', 'country': 'Antarctica', 'countrySource': 'grobid', 'settlement': ['settlement',], 'region': 'region', 'postCode': 'postCode', },] self.assertEqual(actual, expected) def test_parse_multiple_institutions(self): self.server.setResponse( __name__, '''<affiliation> <orgName type="laboratory" key="lab1">lab1</orgName> <orgName type="laboratory" key="lab2">lab2</orgName> <orgName type="laboratory" key="lab3">lab3</orgName> <orgName type="department" key="dep1">dep1</orgName> <orgName type="department" key="dep2">dep2</orgName> <orgName type="department" key="dep3">dep3</orgName> <orgName type="institution" key="instit1">instit1</orgName> <orgName type="institution" key="instit2">instit2</orgName> <orgName type="institution" key="instit3">instit3</orgName> <address> <addrLine>addrLine1</addrLine> <addrLine>addrLine2</addrLine> <addrLine>addrLine3</addrLine> <country key="AQ">Irrelevant</country> <postCode>postCode</postCode> <region>region</region> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [{ 'institution': 'instit1', 'institutionSource': 'grobid', 'department': 'dep1', 'laboratory': 'lab1', 'alpha2': 'AQ', 'country': 'Antarctica', 'countrySource': 'grobid', 'settlement': ['settlement',], 'region': 'region', 'postCode': 'postCode', },{ 'institution': 'instit2', 'institutionSource': 'grobid', 'department': 'dep2', 'laboratory': 'lab2', 'alpha2': 'AQ', 'country': 'Antarctica', 'countrySource': 'grobid', 'settlement': ['settlement',], 'region': 'region', 'postCode': 'postCode', },{ 'institution': 'instit3', 'institutionSource': 'grobid', 'department': 'dep3', 'laboratory': 'lab3', 'alpha2': 'AQ', 'country': 'Antarctica', 'countrySource': 'grobid', 'settlement': ['settlement',], 'region': 'region', 'postCode': 'postCode', },] self.assertEqual(actual, expected) def test_parse_multiple_institutions_first_missing(self): affiliation = 'first instit,' self.server.setResponse( affiliation, '''<affiliation> <orgName type="laboratory" key="lab1">lab1</orgName> <orgName type="laboratory" key="lab2">lab2</orgName> <orgName type="department" key="dep1">dep1</orgName> <orgName type="department" key="dep2">dep2</orgName> <orgName type="institution" key="instit2">instit2</orgName> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'first instit', 'institutionSource': 'regexInsert', 'settlement': ['first instit'], },{ 'institutionSource': 'grobid', 'department': 'dep1', 'laboratory': 'lab1', 'settlement': ['first instit'], },{ 'institution': 'instit2', 'institutionSource': 'grobid', 'department': 'dep2', 'laboratory': 'lab2', 'settlement': ['first instit'], },] self.assertEqual(actual, expected) def test_parse_institution_partially_recognised(self): affiliation = 'first instit,' self.server.setResponse( affiliation, '''<affiliation> <orgName type="laboratory" key="lab1">lab1</orgName> <orgName type="department" key="dep1">dep1</orgName> <orgName type="institution" key="instit1">first</orgName> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'first instit', 'institutionSource': 'regexReplace', 'department': 'dep1', 'laboratory': 'lab1', 'settlement': ['first instit'], },] self.assertEqual(actual, expected) def test_parse_no_grobid_result(self): affiliation = 'first instit,' self.server.setResponse(affiliation, '') actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'first instit', 'institutionSource': 'regexInsert', 'settlement': ['first instit'], },] self.assertEqual(actual, expected) def test_parse_institution_not_recognised(self): affiliation = 'first instit,' self.server.setResponse( affiliation, '''<affiliation> <orgName type="laboratory" key="lab1">lab1</orgName> <orgName type="department" key="dep1">dep1</orgName> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'first instit', 'institutionSource': 'regexInsert', 'settlement': ['first instit'], },{ 'institutionSource': 'grobid', 'department': 'dep1', 'laboratory': 'lab1', 'settlement': ['first instit'], },] self.assertEqual(actual, expected) def test_parse_institution_name_with_comma(self): affiliation = 'comma, inst' self.server.setResponse( affiliation, '''<affiliation> <orgName type="laboratory" key="lab1">lab1</orgName> <orgName type="department" key="dep1">dep1</orgName> <orgName type="institution" key="instit1">comma, inst</orgName> </affiliation>''' ) actual = list(parser.parseAll(affiliation, self.url)) expected = [{ 'institution': 'comma, inst', 'institutionSource': 'grobid', 'department': 'dep1', 'laboratory': 'lab1', 'settlement': ['comma'], },{ 'institution': 'comma', 'institutionSource': 'regexInsertAfter', 'settlement': ['comma'], },] self.assertEqual(actual, expected) def test_parse_invalid_xml(self): self.server.setResponse(__name__, '<broken tag>') actual = list(parser.parseAll(__name__, self.url)) expected = [] self.assertEqual(actual, expected) def test_parseAddress_Guinea(self): actual = parser.parseAddress('guinea', et.Element(None)) expected = { 'alpha2': 'GN', 'country': 'Guinea', 'countrySource': 'regex', } self.assertEqual(actual, expected) def test_parseAddress_Papua_New_Guinea(self): actual = parser.parseAddress('papua new guinea', et.Element(None)) expected = { 'alpha2': 'PG', 'country': 'Papua New Guinea', 'countrySource': 'regex', } self.assertEqual(actual, expected) def test_parseAddress_None(self): actual = parser.parseAddress('there is no country in this string', et.Element(None)) expected = {} self.assertEqual(actual, expected) def test_parseAddress_empty(self): actual = parser.parseAddress('', et.Element(None)) expected = {} self.assertEqual(actual, expected) def test_parseAddress_multiple_countries(self): actual = parser.parseAddress('Serbia Montenegro', et.Element(None)) expected = { 'alpha2': 'ME', 'country': 'Montenegro', 'countrySource': 'regex', } self.assertEqual(actual, expected) def test_parseAddress_Hong_Kong_in_China(self): actual = parser.parseAddress('Hong Kong, China', et.Element(None)) expected = { 'alpha2': 'HK', 'country': 'Hong Kong', 'countrySource': 'regex', } self.assertEqual(actual, expected) def test_parseAddress_Macao_in_China(self): actual = parser.parseAddress('Macao, PR China', et.Element(None)) expected = { 'alpha2': 'MO', 'country': 'Macao', 'countrySource': 'regex', } self.assertEqual(actual, expected) def test_countryList_successors_name_are_not_part_of_predecessors(self): length = len(parser.countryList) for i in range(length): for j in range(i + 1, length): predeccesor = parser.countryList[i][1] successor = parser.countryList[j][1] self.assertNotIn(predeccesor, successor) def test_parseOrganisations_regex_None_Element_args(self): actual = parser.parseOrganisations(None, et.Element(None)) expected = [] self.assertEqual(actual, expected) def test_parseOrganisations_regex_empty_list(self): affiliation = 'first words, second part, third word list' root = et.Element(None) actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words', 'institutionSource': 'regexInsert', },] self.assertEqual(actual, expected) def test_parseOrganisations_regex_comma_before_words(self): affiliation = ',comma before any words' root = et.Element(None) actual = parser.parseOrganisations(affiliation, root) expected = [] self.assertEqual(actual, expected) def test_parseOrganisations_regex_identical(self): affiliation = 'first words, second part, third word list' root = et.fromstring(''' <results> <affiliation> <orgName type="institution">first words</orgName> </affiliation> </results> ''') actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words', 'institutionSource': 'regexReplace', },] self.assertEqual(actual, expected) def test_parseOrganisations_regex_left_part(self): affiliation = 'first words, second part, third word list' root = et.fromstring(''' <results> <affiliation> <orgName type="institution">fir</orgName> </affiliation> </results> ''') actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words', 'institutionSource': 'regexReplace', },] self.assertEqual(actual, expected) def test_parseOrganisations_regex_middle_part(self): affiliation = 'first words, second part, third word list' root = et.fromstring(''' <results> <affiliation> <orgName type="institution">st word</orgName> </affiliation> </results> ''') actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words', 'institutionSource': 'regexReplace', },] self.assertEqual(actual, expected) def test_parseOrganisations_regex_right_part(self): affiliation = 'first words, second part, third word list' root = et.fromstring(''' <results> <affiliation> <orgName type="institution">words</orgName> </affiliation> </results> ''') actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words', 'institutionSource': 'regexReplace', },] self.assertEqual(actual, expected) def test_parseOrganisations_regex_more_on_the_right(self): affiliation = 'first words, second part, ...' root = et.fromstring(''' <results> <affiliation> <orgName type="institution">first words, seco</orgName> </affiliation> </results> ''') actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words, seco', 'institutionSource': 'grobid', },{ 'institution': 'first words', 'institutionSource': 'regexInsertAfter', },] self.assertEqual(actual, expected) def test_parseOrganisations_regex_overlap_on_the_right(self): affiliation = 'first words, second part, third word list' root = et.fromstring(''' <results> <affiliation> <orgName type="institution">words, second</orgName> </affiliation> </results> ''') actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words', 'institutionSource': 'regexInsertBefore', },{ 'institution': 'words, second', 'institutionSource': 'grobid', },] self.assertEqual(actual, expected) def test_parseOrganisations_regex_no_overlap(self): affiliation = 'first words, second part, third word list' root = et.fromstring(''' <results> <affiliation> <orgName type="institution">third word</orgName> </affiliation> </results> ''') actual = parser.parseOrganisations(affiliation, root) expected = [{ 'institution': 'first words', 'institutionSource': 'regexInsertBefore', },{ 'institution': 'third word', 'institutionSource': 'grobid', },] self.assertEqual(actual, expected) def test_queryGrobid_None(self): actual = parser.queryGrobid(None, self.url) expected = '<results></results>' self.assertEqual(actual, expected) def test_queryGrobid_invalid_type(self): actual = parser.queryGrobid([1,2,3,], self.url) expected = '<results></results>' self.assertEqual(actual, expected) def test_queryGrobid_empty_string(self): actual = parser.queryGrobid('', self.url) expected = '<results></results>' self.assertEqual(actual, expected) def test_queryGrobid_valid_xml(self): self.server.setResponse('valid_output', '<affiliation/>') actual = parser.queryGrobid('valid_output', self.url) expected = '<results><affiliation/></results>' self.assertEqual(actual, expected) def test_queryGrobid_invalid_xml(self): self.server.setResponse('invalid_output', '>invalid<') actual = parser.queryGrobid('invalid_output', self.url) expected = '<results>>invalid<</results>' self.assertEqual(actual, expected) def test_parseSettlement_None(self): actual = parser.parseSettlement(None, et.Element(None)) expected = {'settlement':[],} self.assertEqual(actual, expected) def test_parseSettlement_empty(self): actual = parser.parseSettlement('', et.Element(None)) expected = {'settlement':[],} self.assertEqual(actual, expected) def test_parseSettlement_empty_but_node(self): actual = parser.parseSettlement('', et.fromstring(''' <results> <affiliation> <address> <settlement>settlement</settlement> </address> </affiliation> </results> ''') ) expected = {'settlement':['settlement',],} self.assertEqual(actual, expected) def test_parseSettlement_no_comma(self): actual = parser.parseSettlement('teststring', et.Element(None)) expected = {'settlement':[],} self.assertEqual(actual, expected) def test_parseSettlement_one_comma(self): actual = parser.parseSettlement('before comma, after comma', et.Element(None)) expected = {'settlement':['before comma',],} self.assertEqual(actual, expected) def test_parseSettlement_two_comma(self): actual = parser.parseSettlement('one, two, three', et.Element(None)) expected = {'settlement':['one','two',],} self.assertEqual(actual, expected) def test_parseSettlement_contain_number(self): actual = parser.parseSettlement( '3 A-2 one 1 , 343-C two 4 , three', et.Element(None) ) expected = {'settlement':['one','two',],} self.assertEqual(actual, expected) def test_parseSettlement_capitals(self): actual = parser.parseSettlement( 'A BB CCC dD Dd test b Test worD WOrd woRd, Country', et.Element(None) ) expected = {'settlement':['A Dd test b Test',],} self.assertEqual(actual, expected) def test_parseSettlement_contain_number_and_node(self): actual = parser.parseSettlement( '3 A-2 one 1 , 343-C two 4 , three', et.fromstring(''' <results> <affiliation> <address> <settlement>settlement</settlement> </address> </affiliation> </results> ''') ) expected = {'settlement':['one','two','settlement'],} self.assertEqual(actual, expected)<|fim▁end|>
<|file_name|>insertsort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # Copyright (C) 2014-2016 Miquel Sabaté Solà <[email protected]> # This file is licensed under the MIT license. # See the LICENSE file. def insertsort(lst): for i in range(1, len(lst)): value = lst[i] j = i while j > 0 and value < lst[j - 1]:<|fim▁hole|> ary = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] print(ary) insertsort(ary) print(ary)<|fim▁end|>
lst[j] = lst[j - 1] j -= 1 lst[j] = value
<|file_name|>0007_auto_20160221_1533.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-21 15:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):<|fim▁hole|> ('pages', '0006_auto_20160221_1241'), ] operations = [ migrations.AlterField( model_name='page', name='image', field=models.ImageField(default='none.jpg', upload_to='uploads/'), ), ]<|fim▁end|>
dependencies = [
<|file_name|>types.py<|end_file_name|><|fim▁begin|>import logging import re import socket from mopidy.config import validators from mopidy.internal import log, path def decode(value): if isinstance(value, bytes): value = value.decode(errors="surrogateescape") for char in ("\\", "\n", "\t"): value = value.replace( char.encode(encoding="unicode-escape").decode(), char ) return value def encode(value): if isinstance(value, bytes): value = value.decode(errors="surrogateescape") for char in ("\\", "\n", "\t"): value = value.replace( char, char.encode(encoding="unicode-escape").decode() ) return value class DeprecatedValue: pass class ConfigValue: """Represents a config key's value and how to handle it. Normally you will only be interacting with sub-classes for config values that encode either deserialization behavior and/or validation. Each config value should be used for the following actions: 1. Deserializing from a raw string and validating, raising ValueError on failure. 2. Serializing a value back to a string that can be stored in a config. 3. Formatting a value to a printable form (useful for masking secrets). :class:`None` values should not be deserialized, serialized or formatted, the code interacting with the config should simply skip None config values. """ def deserialize(self, value): """Cast raw string to appropriate type.""" return decode(value) def serialize(self, value, display=False): """Convert value back to string for saving.""" if value is None: return "" return str(value) class Deprecated(ConfigValue): """Deprecated value. Used for ignoring old config values that are no longer in use, but should not cause the config parser to crash. """ def deserialize(self, value): return DeprecatedValue() def serialize(self, value, display=False): return DeprecatedValue() class String(ConfigValue): """String value. Is decoded as utf-8 and \\n \\t escapes should work and be preserved. """ def __init__(self, optional=False, choices=None): self._required = not optional self._choices = choices def deserialize(self, value): value = decode(value).strip() validators.validate_required(value, self._required) if not value: return None validators.validate_choice(value, self._choices) return value def serialize(self, value, display=False): if value is None: return "" return encode(value) class Secret(String): """Secret string value. Is decoded as utf-8 and \\n \\t escapes should work and be preserved. Should be used for passwords, auth tokens etc. Will mask value when being displayed. """ def __init__(self, optional=False, choices=None): self._required = not optional self._choices = None # Choices doesn't make sense for secrets def serialize(self, value, display=False): if value is not None and display: return "********" return super().serialize(value, display) class Integer(ConfigValue): """Integer value.""" def __init__( self, minimum=None, maximum=None, choices=None, optional=False ): self._required = not optional self._minimum = minimum self._maximum = maximum self._choices = choices def deserialize(self, value): value = decode(value) validators.validate_required(value, self._required) if not value: return None value = int(value) validators.validate_choice(value, self._choices) validators.validate_minimum(value, self._minimum) validators.validate_maximum(value, self._maximum) return value class Boolean(ConfigValue): """Boolean value. Accepts ``1``, ``yes``, ``true``, and ``on`` with any casing as :class:`True`. Accepts ``0``, ``no``, ``false``, and ``off`` with any casing as :class:`False`. """ true_values = ("1", "yes", "true", "on") false_values = ("0", "no", "false", "off") def __init__(self, optional=False): self._required = not optional def deserialize(self, value): value = decode(value) validators.validate_required(value, self._required) if not value: return None if value.lower() in self.true_values: return True elif value.lower() in self.false_values: return False raise ValueError(f"invalid value for boolean: {value!r}") def serialize(self, value, display=False): if value is True: return "true" elif value in (False, None): return "false" else: raise ValueError(f"{value!r} is not a boolean") class List(ConfigValue): """List value. Supports elements split by commas or newlines. Newlines take presedence and empty list items will be filtered out. """ def __init__(self, optional=False): self._required = not optional def deserialize(self, value): value = decode(value) if "\n" in value: values = re.split(r"\s*\n\s*", value) else: values = re.split(r"\s*,\s*", value) values = tuple(v.strip() for v in values if v.strip()) validators.validate_required(values, self._required) return tuple(values) def serialize(self, value, display=False): if not value: return "" return "\n " + "\n ".join(encode(v) for v in value if v) class LogColor(ConfigValue): def deserialize(self, value): value = decode(value) validators.validate_choice(value.lower(), log.COLORS) return value.lower() def serialize(self, value, display=False): if value.lower() in log.COLORS: return encode(value.lower()) return "" class LogLevel(ConfigValue): """Log level value. Expects one of ``critical``, ``error``, ``warning``, ``info``, ``debug``, ``trace``, or ``all``, with any casing. """ levels = { "critical": logging.CRITICAL, "error": logging.ERROR, "warning": logging.WARNING, "info": logging.INFO, "debug": logging.DEBUG, "trace": log.TRACE_LOG_LEVEL, "all": logging.NOTSET, } def deserialize(self, value): value = decode(value) validators.validate_choice(value.lower(), self.levels.keys()) return self.levels.get(value.lower()) def serialize(self, value, display=False): lookup = {v: k for k, v in self.levels.items()} if value in lookup: return encode(lookup[value]) return "" class Hostname(ConfigValue): """Network hostname value.""" def __init__(self, optional=False): self._required = not optional def deserialize(self, value, display=False): value = decode(value).strip() validators.validate_required(value, self._required) if not value: return None socket_path = path.get_unix_socket_path(value) if socket_path is not None: path_str = Path(not self._required).deserialize(socket_path) return f"unix:{path_str}" try: socket.getaddrinfo(value, None) except OSError: raise ValueError("must be a resolveable hostname or valid IP") return value class Port(Integer): """Network port value. Expects integer in the range 0-65535, zero tells the kernel to simply allocate a port for us. """ def __init__(self, choices=None, optional=False): super().__init__( minimum=0, maximum=2 ** 16 - 1, choices=choices, optional=optional ) <|fim▁hole|> def __new__(cls, original, expanded): return super().__new__(cls, expanded) def __init__(self, original, expanded): self.original = original class Path(ConfigValue): """File system path. The following expansions of the path will be done: - ``~`` to the current user's home directory - ``$XDG_CACHE_DIR`` according to the XDG spec - ``$XDG_CONFIG_DIR`` according to the XDG spec - ``$XDG_DATA_DIR`` according to the XDG spec - ``$XDG_MUSIC_DIR`` according to the XDG spec """ def __init__(self, optional=False): self._required = not optional def deserialize(self, value): value = decode(value).strip() expanded = path.expand_path(value) validators.validate_required(value, self._required) validators.validate_required(expanded, self._required) if not value or expanded is None: return None return _ExpandedPath(value, expanded) def serialize(self, value, display=False): if isinstance(value, _ExpandedPath): value = value.original if isinstance(value, bytes): value = value.decode(errors="surrogateescape") return value<|fim▁end|>
class _ExpandedPath(str):
<|file_name|>setup.py<|end_file_name|><|fim▁begin|><|fim▁hole|> with open('README.md') as fp: long_description = fp.read() setup( name='typeform', version='1.1.0', description='Python Client wrapper for Typeform API', long_description=long_description, long_description_content_type='text/markdown', keywords=[ 'type', 'form', 'typeform', 'api', ], author='Typeform', author_email='[email protected]', url='https://github.com/MichaelSolati/typeform-python-sdk', packages=find_packages(), install_requires=['requests'], test_suite='typeform.test.suite.test_suite', license='MIT', # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python', ] )<|fim▁end|>
from setuptools import setup, find_packages
<|file_name|>bitcoin_en.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="en"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About SLIMCoin</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;SLIMCoin&lt;/b&gt; version</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="91"/> <source>Copyright © 2011-2013 SLIMCoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt 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 type="unfinished"></translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your SLIMCoin 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 type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="33"/> <source>Double-click to edit address or label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="57"/> <source>Create a new address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="60"/> <source>&amp;New Address...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="71"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="74"/> <source>&amp;Copy to Clipboard</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="85"/> <source>Show &amp;QR Code</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="96"/> <source>Sign a message to prove you own this address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="99"/> <source>&amp;Sign Message</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="110"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="113"/> <source>&amp;Delete</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="65"/> <source>Copy address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="66"/> <source>Copy label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="67"/> <source>Edit</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="68"/> <source>Delete</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="288"/> <source>Export Address Book Data</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="289"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="302"/> <source>Error exporting</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addressbookpage.cpp" line="302"/> <source>Could not write to file %1.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../addresstablemodel.cpp" line="113"/> <source>(no label)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Dialog</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="32"/> <location filename="../forms/askpassphrasedialog.ui" line="97"/> <source>TextLabel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="50"/> <source>Enter passphrase</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="64"/> <source>New passphrase</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="78"/> <source>Repeat new passphrase</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <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 type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="35"/> <source>Encrypt wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="38"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="43"/> <source>Unlock wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="46"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="51"/> <source>Decrypt wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Change passphrase</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="55"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>Confirm wallet encryption</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="102"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR SLIMCoinS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet encrypted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="112"/> <source>SLIMCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your SLIMCoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="208"/> <location filename="../askpassphrasedialog.cpp" line="232"/> <source>Warning: The Caps Lock key is on.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>Wallet encryption failed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="118"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="125"/> <location filename="../askpassphrasedialog.cpp" line="173"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <source>Wallet unlock failed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="137"/> <location filename="../askpassphrasedialog.cpp" line="148"/> <location filename="../askpassphrasedialog.cpp" line="167"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="147"/> <source>Wallet decryption failed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="161"/> <source>Wallet passphrase was succesfully changed.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SLIMCoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="70"/> <source>SLIMCoin Wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>Show/Hide &amp;SLIMCoin</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="499"/> <source>Synchronizing with network...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="180"/> <source>&amp;Overview</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="181"/> <source>Show general overview of wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="186"/> <source>&amp;Transactions</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="187"/> <source>Browse transaction history</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="192"/> <source>&amp;Address Book</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="193"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="198"/> <source>&amp;Receive coins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="199"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="204"/> <source>&amp;Send coins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="205"/> <source>Send coins to a SLIMCoin address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="210"/> <source>Sign &amp;message</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="211"/> <source>Prove you control an address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="230"/> <source>E&amp;xit</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="231"/> <source>Quit application</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="234"/> <source>&amp;About %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="235"/> <source>Show information about SLIMCoin</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="237"/> <source>About &amp;Qt</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="238"/> <source>Show information about Qt</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>&amp;Options...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="241"/> <source>Modify configuration options for SLIMCoin</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="501"/> <source>~%n block(s) remaining</source> <translation> <numerusform>~%n block remaining</numerusform> <numerusform>~%n blocks remaining</numerusform> </translation> </message> <message> <location filename="../bitcoingui.cpp" line="512"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="245"/> <source>&amp;Export...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="244"/> <source>Show or hide the SLIMCoin window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="247"/> <source>&amp;Encrypt Wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="248"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="250"/> <source>&amp;Backup Wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="251"/> <source>Backup wallet to another location</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="252"/> <source>&amp;Change Passphrase</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="253"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="276"/> <source>&amp;File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="285"/> <source>&amp;Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="291"/> <source>&amp;Help</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="298"/> <source>Tabs toolbar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="309"/> <source>Actions toolbar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="321"/> <source>[testnet]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="383"/> <source>SLIMCoin client</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="411"/> <source>SLIMCoin-qt</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="475"/> <source>%n active connection(s) to SLIMCoin network</source> <translation> <numerusform>%n active connection to SLIMCoin network</numerusform> <numerusform>%n active connections to SLIMCoin network</numerusform> </translation> </message> <message> <location filename="../bitcoingui.cpp" line="524"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="539"/> <source>%n second(s) ago</source> <translation> <numerusform>%n second ago</numerusform> <numerusform>%n seconds ago</numerusform> </translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="543"/> <source>%n minute(s) ago</source> <translation> <numerusform>%n minute ago</numerusform> <numerusform>%n minutes ago</numerusform> </translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="547"/> <source>%n hour(s) ago</source> <translation> <numerusform>%n hour ago</numerusform> <numerusform>%n hours ago</numerusform> </translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="551"/> <source>%n day(s) ago</source> <translation> <numerusform>%n day ago</numerusform> <numerusform>%n days ago</numerusform> </translation> </message> <message> <location filename="../bitcoingui.cpp" line="557"/> <source>Up to date</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="562"/> <source>Catching up...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="570"/> <source>Last received block was generated %1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="626"/> <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"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="631"/> <source>Sending...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="658"/> <source>Sent transaction</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="659"/> <source>Incoming transaction</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="660"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="785"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="793"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="816"/> <source>Backup Wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="816"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="819"/> <source>Backup Failed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoingui.cpp" line="819"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="268"/> <source>&amp;Unit to show amounts in: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="272"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="279"/> <source>Display addresses in transaction list</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid SLIMCoin address.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainOptionsPage</name><|fim▁hole|> <location filename="../optionsdialog.cpp" line="170"/> <source>&amp;Start SLIMCoin on window system startup</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="171"/> <source>Automatically start SLIMCoin after the computer is turned on</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="175"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="176"/> <source>Show only a tray icon after minimizing the window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="184"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="185"/> <source>Automatically open the SLIMCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="179"/> <source>M&amp;inimize on close</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="180"/> <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 type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="188"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="189"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="194"/> <source>Proxy &amp;IP: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="200"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="203"/> <source>&amp;Port: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="209"/> <source>Port of the proxy (e.g. 1234)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="215"/> <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 type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="221"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="224"/> <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 type="unfinished"></translation> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Message</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <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 type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="105"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>Sign a message to prove you own this address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="120"/> <source>&amp;Sign Message</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/messagepage.ui" line="134"/> <source>&amp;Copy to Clipboard</source> <translation type="unfinished"></translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <location filename="../messagepage.cpp" line="89"/> <location filename="../messagepage.cpp" line="101"/> <source>Error signing</source> <translation type="unfinished"></translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <source>%1 is not a valid address.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../messagepage.cpp" line="89"/> <source>Private key for %1 is not available.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../messagepage.cpp" line="101"/> <source>Sign failed</source> <translation type="unfinished"></translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="79"/> <source>Main</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="84"/> <source>Display</source> <translation type="unfinished"></translation> </message> <message> <location filename="../optionsdialog.cpp" line="104"/> <source>Options</source> <translation type="unfinished"></translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Balance:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <source>123.456 BTC</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="54"/> <source>Number of transactions:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="61"/> <source>0</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="68"/> <source>Unconfirmed:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="75"/> <source>0 BTC</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="82"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Ubuntu&apos;; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Wallet&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/overviewpage.ui" line="122"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../overviewpage.cpp" line="103"/> <source>Your current balance</source> <translation type="unfinished"></translation> </message> <message> <location filename="../overviewpage.cpp" line="108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"></translation> </message> <message> <location filename="../overviewpage.cpp" line="111"/> <source>Total number of transactions in wallet</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>Dialog</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="55"/> <source>Request Payment</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="70"/> <source>Amount:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="105"/> <source>BTC</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="121"/> <source>Label:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="144"/> <source>Message:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="186"/> <source>&amp;Save As...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qrcodedialog.cpp" line="59"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qrcodedialog.cpp" line="116"/> <source>Save Image...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qrcodedialog.cpp" line="116"/> <source>PNG Images (*.png)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add recipient...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear all</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>Amount exceeds your balance</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>Total exceeds your balance when the %1 transaction fee is included</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once in one send operation</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <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"></translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation type="unfinished"></translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a SLIMCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="18"/> <source>Open for %1 blocks</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="20"/> <source>Open until %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="26"/> <source>%1/offline?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="28"/> <source>%1/unconfirmed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="30"/> <source>%1 confirmations</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="48"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="53"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="55"/> <source>, broadcast through %1 node</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="57"/> <source>, broadcast through %1 nodes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="61"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="68"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="74"/> <location filename="../transactiondesc.cpp" line="91"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="91"/> <source>unknown</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="92"/> <location filename="../transactiondesc.cpp" line="115"/> <location filename="../transactiondesc.cpp" line="174"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="95"/> <source> (yours, label: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="97"/> <source> (yours)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="132"/> <location filename="../transactiondesc.cpp" line="146"/> <location filename="../transactiondesc.cpp" line="191"/> <location filename="../transactiondesc.cpp" line="208"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="134"/> <source>(%1 matures in %2 more blocks)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="138"/> <source>(not accepted)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="182"/> <location filename="../transactiondesc.cpp" line="190"/> <location filename="../transactiondesc.cpp" line="205"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="196"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="212"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="218"/> <source>Message:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="220"/> <source>Comment:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="222"/> <source>Transaction ID:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiondesc.cpp" line="225"/> <source>Generated coins must wait 120 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, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation type="unfinished"></translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Date</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Type</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Amount</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="274"/> <source>Open for %n block(s)</source> <translation> <numerusform>Open for %n block</numerusform> <numerusform>Open for %n blocks</numerusform> </translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="277"/> <source>Open until %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="280"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="283"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="286"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="294"/> <source>Mined balance will be available in %n more blocks</source> <translation> <numerusform>Mined balance will be available in %n more block</numerusform> <numerusform>Mined balance will be available in %n more blocks</numerusform> </translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="300"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="303"/> <source>Generated but not accepted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="346"/> <source>Received with</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="348"/> <source>Received from</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="351"/> <source>Sent to</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="353"/> <source>Payment to yourself</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="355"/> <source>Mined</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="393"/> <source>(n/a)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="592"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="594"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="596"/> <source>Type of transaction.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="598"/> <source>Destination address of transaction.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="600"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="84"/> <source>Enter address or label to search</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="90"/> <source>Min amount</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="124"/> <source>Copy address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="125"/> <source>Copy label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy amount</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Edit label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Show details...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="268"/> <source>Export Transaction Data</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="269"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="277"/> <source>Confirmed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="278"/> <source>Date</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Type</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Amount</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>ID</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Error exporting</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Could not write to file %1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="382"/> <source>Range:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../transactionview.cpp" line="390"/> <source>to</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="143"/> <source>Sending...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SLIMCoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="7"/> <source>SLIMCoin version</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="8"/> <source>Usage:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="9"/> <source>Send command to -server or slimcoind</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="10"/> <source>List commands</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="11"/> <source>Get help for a command</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="12"/> <source>Options:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="13"/> <source>Specify configuration file (default: SLIMCoin.conf)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="14"/> <source>Specify pid file (default: slimcoind.pid)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="15"/> <source>Generate coins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="16"/> <source>Don&apos;t generate coins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="17"/> <source>Start minimized</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="18"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="19"/> <source>Specify data directory</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="20"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="21"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="22"/> <source>Specify connection timeout (in milliseconds)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="23"/> <source>Connect through socks4 proxy</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="24"/> <source>Allow DNS lookups for addnode and connect</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="25"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="26"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="28"/> <source>Connect only to the specified node</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="33"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="34"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="37"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="38"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="42"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Use the test network</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Output extra debugging information</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="48"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="49"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="52"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="54"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="57"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="58"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="59"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="60"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="61"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="62"/> <source> SSL options: (see the SLIMCoin Wiki for SSL setup instructions)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="65"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="67"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="68"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="71"/> <source>This help message</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="72"/> <source>Usage</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="73"/> <source>Cannot obtain a lock on data directory %s. SLIMCoin is probably already running.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>SLIMCoin</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="77"/> <source>Loading addresses...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="78"/> <source>Error loading addr.dat</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="80"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="82"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="83"/> <source>Error loading wallet.dat: Wallet requires newer version of SLIMCoin</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="84"/> <source>Wallet needed to be rewritten: restart SLIMCoin to complete</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="85"/> <source>Error loading wallet.dat</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="117"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="118"/> <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"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="121"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="122"/> <source>Sending...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="123"/> <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"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="127"/> <source>Invalid amount</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="128"/> <source>Insufficient funds</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="79"/> <source>Loading block index...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="27"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="29"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="30"/> <source>Accept connections from outside (default: 1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="31"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="32"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="39"/> <source>Use Universal Plug and Play to map the listening port (default: 1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="40"/> <source>Use Universal Plug and Play to map the listening port (default: 0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="41"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="81"/> <source>Loading wallet...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="86"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="87"/> <source>Cannot initialize keypool</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="88"/> <source>Cannot write default address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="89"/> <source>Rescanning...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="90"/> <source>Done loading</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="91"/> <source>Invalid -proxy address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="92"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="93"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="96"/> <source>Error: CreateThread(StartNode) failed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="6"/> <source>Warning: Disk space is low </source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="3"/> <source>Unable to bind to port %d on this computer. SLIMCoin is probably already running.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="97"/> <source>To use the %s option</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="98"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=SLIMCoinrpc rpcpassword=%s (you do not need to remember this password) If the file does not exist, create it with owner-readable-only file permissions. </source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="107"/> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="108"/> <source>An error occured while setting up the RPC port %i for listening: %s</source> <translation type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="109"/> <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 type="unfinished"></translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="114"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong SLIMCoin will not work properly.</source> <translation type="unfinished"></translation> </message> </context> </TS><|fim▁end|>
<message>
<|file_name|>issue-6318.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub enum Thing { A(~Foo)<|fim▁hole|> pub trait Foo {} pub struct Struct; impl Foo for Struct {} pub fn main() { match A(~Struct as ~Foo) { A(_a) => 0, }; }<|fim▁end|>
}
<|file_name|>test_clean_provisional.py<|end_file_name|><|fim▁begin|>import unittest from ebird.api.validation import clean_provisional<|fim▁hole|> class CleanProvisionalTests(unittest.TestCase): """Tests for the clean_provisional validation function.""" def test_converts_bool(self): self.assertEqual("true", clean_provisional(True)) self.assertEqual("false", clean_provisional(False)) def test_converts_integer(self): self.assertEqual("true", clean_provisional(1)) self.assertEqual("false", clean_provisional(0))<|fim▁end|>
<|file_name|>modelSelector.tsx<|end_file_name|><|fim▁begin|>// notice_start /* * Copyright 2015 Dev Shop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,<|fim▁hole|>// notice_end import * as React from 'react'; export interface ModelSelectorProps { model: any; view: any; modelSelector: (model: any) => any; } export class ModelSelector extends React.Component<ModelSelectorProps, any> { render() { let {model, view, modelSelector, ...other} = this.props; let childProps = Object.assign({}, {model: modelSelector(model)}, other); return React.createElement(view, childProps); } }<|fim▁end|>
* 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. */
<|file_name|>testDocument.js<|end_file_name|><|fim▁begin|>const fs = require("fs"); const assert = require("assert"); const testMngr = require("test/testManager"); const FormData = require("form-data"); describe("Document No Auth", function () { let client; before(async function () { if (!testMngr.app.config.document) { this.skip(); } client = testMngr.client("bob"); }); after(async () => {}); it("should get a 401 when getting all documents", async () => { try { let tickets = await client.get("v1/document"); assert(tickets); } catch (error) { console.log("error ", error); assert.equal(error.response.status, 401); assert.equal(error.response.data, "Unauthorized"); } }); }); describe("Document", function () { let client; before(async function () { if (!testMngr.app.config.document) { this.skip(); } client = testMngr.client("alice"); await client.login(); }); after(async () => {}); it("should upload a document", async () => { const formData = new FormData(); formData.append("name", "IMG_20180316_153034.jpg"); formData.append("file_type", "image/jpeg"); formData.append( "photo", fs.createReadStream(__dirname + "/testDocument.js") ); await client.upload("v1/document", formData);<|fim▁hole|> formData2.append("name", "IMG_20180316_153035.jpg"); formData2.append("file_type", "image/jpeg"); formData2.append( "photo", fs.createReadStream(__dirname + "/testDocument.js") ); await client.upload("v1/document", formData2); //assert(document); }); it("should upload a specific document", async () => { const formData = new FormData(); formData.append("name", "IMG_20180316_153034.jpg"); formData.append("file_type", "image/jpeg"); formData.append( "photo", fs.createReadStream(__dirname + "/testDocument.js") ); const type = "profile_picture"; await client.upload(`v1/document/${type}`, formData); const picture = await client.get(`v1/document/${type}`); assert.equal(picture.type, type); assert(picture.content); }); it("should return an error when no file is present", async () => { const formData = new FormData(); formData.append("name", "IMG_20180316_153034.jpg"); formData.append("file_type", "image/jpeg"); try { await client.upload("v1/document", formData); assert(false); } catch (error) { assert.equal(error.response.status, 400); } }); });<|fim▁end|>
const formData2 = new FormData();
<|file_name|>test_config_file.py<|end_file_name|><|fim▁begin|>import pytest from path import Path<|fim▁hole|> CHANGE_SET_PARAMETERS, CHANGE_SET_STACK_TAGS, FULL_CONFIG_FILE, CHANGE_SET_CAPABILITIES, ROLE_ARN, VARS) def test_loads_config_file(mocker, tmpdir, session): stacks = mocker.patch('formica.cli.stacks') file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write(yaml.dump(FULL_CONFIG_FILE)) cli.main(['stacks', '-c', file_name]) call_args = stacks.call_args[0][0] assert call_args.region == REGION assert call_args.profile == PROFILE assert call_args.stack == STACK assert call_args.parameters == CHANGE_SET_PARAMETERS assert call_args.tags == CHANGE_SET_STACK_TAGS assert call_args.capabilities == CHANGE_SET_CAPABILITIES assert call_args.role_arn == ROLE_ARN assert call_args.vars == VARS def test_loads_multiple_config_files(mocker, tmpdir, session): stacks = mocker.patch('formica.cli.stacks') file_name = 'test.config.yaml' overwrite_file = 'overwrite.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write(yaml.dump(FULL_CONFIG_FILE)) with open(overwrite_file, 'w') as f: f.write(yaml.dump(dict(stack='someotherstacktestvalue', vars=dict(OtherVar=3)))) cli.main(['stacks', '-c', file_name, overwrite_file]) call_args = stacks.call_args[0][0] assert call_args.stack == 'someotherstacktestvalue' assert call_args.stack != STACK assert call_args.vars['OtherVar'] == 3 assert call_args.vars['OtherVar'] != VARS['OtherVar'] def test_prioritises_cli_args(mocker, tmpdir, session): stacks = mocker.patch('formica.cli.new') cli_stack = str(uuid4()) file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write(yaml.dump(FULL_CONFIG_FILE)) cli.main(['new', '-s', cli_stack, '-c', file_name]) call_args = stacks.call_args[0][0] assert call_args.stack == cli_stack assert call_args.stack != STACK def test_merges_cli_args_on_load(mocker, tmpdir, session): stacks = mocker.patch('formica.cli.new') param1 = str(uuid4()) param2 = str(uuid4()) file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write(yaml.dump(FULL_CONFIG_FILE)) cli.main(['new', '--parameters', "A={}".format(param1), "D={}".format(param2), '-c', file_name]) call_args = stacks.call_args[0][0] assert call_args.parameters == {"A": param1, "B": 2, 'C': True, 'D': param2} def test_merges_vars(mocker, tmpdir, session): stacks = mocker.patch('formica.cli.template') param1 = str(uuid4()) file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write(yaml.dump(FULL_CONFIG_FILE)) with open('test.template.yaml', 'w') as f: f.write('{"Description": "{{ OtherVar }}"}') cli.main(['template', '--vars', "OtherVar={}".format(param1), '-c', file_name]) call_args = stacks.call_args[0][0] assert call_args.vars['OtherVar'] == param1 def test_exception_with_wrong_config_type(mocker, tmpdir, session, logger): file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write(yaml.dump({'stack': ['test', 'test2']})) with pytest.raises(SystemExit): cli.main(['stacks', '-c', file_name]) logger.error.assert_called_with('Config file parameter stack needs to be of type str') def test_exception_with_forbiddeng_config_argument(mocker, tmpdir, session, logger): file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write(yaml.dump({'stacks': 'somestack'})) with pytest.raises(SystemExit): cli.main(['stacks', '-c', file_name]) logger.error.assert_called_with('Config file parameter stacks is not supported') def test_exception_with_failed_yaml_syntax(mocker, tmpdir, session, logger): file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write("stacks: somestack\nprofile testprofile") with pytest.raises(SystemExit): cli.main(['stacks', '-c', file_name]) logger.error.assert_called() def test_loads_empty_config_file(mocker, tmpdir, session): stacks = mocker.patch('formica.cli.stacks') file_name = 'test.config.yaml' with Path(tmpdir): with open(file_name, 'w') as f: f.write('') cli.main(['stacks', '-c', file_name])<|fim▁end|>
import yaml from uuid import uuid4 from formica import cli from tests.unit.constants import (REGION, PROFILE, STACK,
<|file_name|>consts.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use back::abi; use llvm; use llvm::{ConstFCmp, ConstICmp, SetLinkage, PrivateLinkage, ValueRef, Bool, True, False}; use llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE, RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE}; use middle::{const_eval, def}; use trans::{adt, consts, debuginfo, expr, inline, machine}; use trans::base::{self, push_ctxt}; use trans::common::*; use trans::type_::Type; use trans::type_of; use middle::subst::Substs; use middle::ty::{self, Ty}; use util::ppaux::{Repr, ty_to_string}; use std::iter::repeat; use libc::c_uint; use syntax::{ast, ast_util}; use syntax::ptr::P; pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit) -> ValueRef { let _icx = push_ctxt("trans_lit"); debug!("const_lit: {:?}", lit); match lit.node { ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false), ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false), ast::LitInt(i, ast::SignedIntLit(t, _)) => { C_integral(Type::int_from_ty(cx, t), i, true) } ast::LitInt(u, ast::UnsignedIntLit(t)) => { C_integral(Type::uint_from_ty(cx, t), u, false) } ast::LitInt(i, ast::UnsuffixedIntLit(_)) => { let lit_int_ty = ty::node_id_to_type(cx.tcx(), e.id); match lit_int_ty.sty { ty::ty_int(t) => { C_integral(Type::int_from_ty(cx, t), i as u64, true) } ty::ty_uint(t) => { C_integral(Type::uint_from_ty(cx, t), i as u64, false) } _ => cx.sess().span_bug(lit.span, &format!("integer literal has type {} (expected int \ or uint)", ty_to_string(cx.tcx(), lit_int_ty))[]) } } ast::LitFloat(ref fs, t) => { C_floating(fs.get(), Type::float_from_ty(cx, t)) } ast::LitFloatUnsuffixed(ref fs) => { let lit_float_ty = ty::node_id_to_type(cx.tcx(), e.id); match lit_float_ty.sty { ty::ty_float(t) => { C_floating(fs.get(), Type::float_from_ty(cx, t)) } _ => { cx.sess().span_bug(lit.span, "floating point literal doesn't have the right type"); } } } ast::LitBool(b) => C_bool(cx, b), ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()), ast::LitBinary(ref data) => C_binary_slice(cx, &data[]), } } pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef { unsafe { llvm::LLVMConstPointerCast(val, ty.to_ref()) } } fn const_vec(cx: &CrateContext, e: &ast::Expr, es: &[P<ast::Expr>]) -> (ValueRef, Type) { let vec_ty = ty::expr_ty(cx.tcx(), e); let unit_ty = ty::sequence_element_type(cx.tcx(), vec_ty); let llunitty = type_of::type_of(cx, unit_ty); let vs = es.iter().map(|e| const_expr(cx, &**e).0) .collect::<Vec<_>>(); // If the vector contains enums, an LLVM array won't work. let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) { C_struct(cx, &vs[], false) } else { C_array(llunitty, &vs[]) }; (v, llunitty) } pub fn const_addr_of(cx: &CrateContext, cv: ValueRef, mutbl: ast::Mutability) -> ValueRef { unsafe { let gv = llvm::LLVMAddGlobal(cx.llmod(), val_ty(cv).to_ref(), "const\0".as_ptr() as *const _); llvm::LLVMSetInitializer(gv, cv); llvm::LLVMSetGlobalConstant(gv, if mutbl == ast::MutImmutable {True} else {False}); SetLinkage(gv, PrivateLinkage); gv } } fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef { let v = match cx.const_globals().borrow().get(&(v as int)) { Some(&v) => v, None => v }; unsafe { llvm::LLVMGetInitializer(v) } } fn const_deref_newtype<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, v: ValueRef, t: Ty<'tcx>) -> ValueRef { let repr = adt::represent_type(cx, t); adt::const_get_field(cx, &*repr, v, 0, 0) } fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, v: ValueRef, t: Ty<'tcx>, explicit: bool) -> (ValueRef, Ty<'tcx>) { match ty::deref(t, explicit) { Some(ref mt) => { match t.sty { ty::ty_ptr(mt) | ty::ty_rptr(_, mt) => { if type_is_sized(cx.tcx(), mt.ty) { (const_deref_ptr(cx, v), mt.ty) } else { // Derefing a fat pointer does not change the representation, // just the type to ty_open. (v, ty::mk_open(cx.tcx(), mt.ty)) } } ty::ty_enum(..) | ty::ty_struct(..) => { assert!(mt.mutbl != ast::MutMutable); (const_deref_newtype(cx, v, t), mt.ty) } _ => { cx.sess().bug(&format!("unexpected dereferenceable type {}", ty_to_string(cx.tcx(), t))[]) } } } None => { cx.sess().bug(&format!("cannot dereference const of type {}", ty_to_string(cx.tcx(), t))[]) } } } pub fn get_const_val(cx: &CrateContext, mut def_id: ast::DefId) -> ValueRef { let contains_key = cx.const_values().borrow().contains_key(&def_id.node); if !ast_util::is_local(def_id) || !contains_key { if !ast_util::is_local(def_id) { def_id = inline::maybe_instantiate_inline(cx, def_id); } if let ast::ItemConst(..) = cx.tcx().map.expect_item(def_id.node).node { base::get_item_val(cx, def_id.node); } } cx.const_values().borrow()[def_id.node].clone() } pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr) -> (ValueRef, Ty<'tcx>) { let llconst = const_expr_unadjusted(cx, e); let mut llconst = llconst; let ety = ty::expr_ty(cx.tcx(), e); let mut ety_adjusted = ty::expr_ty_adjusted(cx.tcx(), e); let opt_adj = cx.tcx().adjustments.borrow().get(&e.id).cloned(); match opt_adj { None => { } Some(adj) => { match adj { ty::AdjustReifyFnPointer(_def_id) => { // FIXME(#19925) once fn item types are // zero-sized, we'll need to do something here } ty::AdjustDerefRef(ref adj) => { let mut ty = ety; // Save the last autoderef in case we can avoid it. if adj.autoderefs > 0 { for _ in range(0, adj.autoderefs-1) { let (dv, dt) = const_deref(cx, llconst, ty, false); llconst = dv; ty = dt; } } match adj.autoref { None => { let (dv, dt) = const_deref(cx, llconst, ty, false); llconst = dv; // If we derefed a fat pointer then we will have an // open type here. So we need to update the type with // the one returned from const_deref. ety_adjusted = dt; } Some(ref autoref) => { match *autoref { ty::AutoUnsafe(_, None) | ty::AutoPtr(ty::ReStatic, _, None) => { // Don't copy data to do a deref+ref // (i.e., skip the last auto-deref). if adj.autoderefs == 0 { llconst = const_addr_of(cx, llconst, ast::MutImmutable); } } ty::AutoPtr(ty::ReStatic, _, Some(box ty::AutoUnsize(..))) => { if adj.autoderefs > 0 { // Seeing as we are deref'ing here and take a reference // again to make the pointer part of the far pointer below, // we just skip the whole thing. We still need the type // though. This works even if we don't need to deref // because of byref semantics. Note that this is not just // an optimisation, it is necessary for mutable vectors to // work properly. let (_, dt) = const_deref(cx, llconst, ty, false); ty = dt; } else { llconst = const_addr_of(cx, llconst, ast::MutImmutable) } match ty.sty { ty::ty_vec(unit_ty, Some(len)) => { let llunitty = type_of::type_of(cx, unit_ty); let llptr = ptrcast(llconst, llunitty.ptr_to()); assert!(cx.const_globals().borrow_mut() .insert(llptr as int, llconst).is_none()); assert_eq!(abi::FAT_PTR_ADDR, 0); assert_eq!(abi::FAT_PTR_EXTRA, 1); llconst = C_struct(cx, &[ llptr, C_uint(cx, len) ], false); } _ => cx.sess().span_bug(e.span, &format!("unimplemented type in const unsize: {}", ty_to_string(cx.tcx(), ty))[]) } } _ => { cx.sess() .span_bug(e.span, &format!("unimplemented const \ autoref {:?}", autoref)[]) } } } } } } } } let llty = type_of::sizing_type_of(cx, ety_adjusted); let csize = machine::llsize_of_alloc(cx, val_ty(llconst)); let tsize = machine::llsize_of_alloc(cx, llty); if csize != tsize { unsafe { // FIXME these values could use some context llvm::LLVMDumpValue(llconst); llvm::LLVMDumpValue(C_undef(llty)); } cx.sess().bug(&format!("const {} of type {} has size {} instead of {}", e.repr(cx.tcx()), ty_to_string(cx.tcx(), ety), csize, tsize)[]); } (llconst, ety_adjusted) } // the bool returned is whether this expression can be inlined into other crates // if it's assigned to a static. fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { let map_list = |&: exprs: &[P<ast::Expr>]| { exprs.iter().map(|e| const_expr(cx, &**e).0) .fold(Vec::new(), |mut l, val| { l.push(val); l }) }; unsafe { let _icx = push_ctxt("const_expr"); return match e.node { ast::ExprLit(ref lit) => { consts::const_lit(cx, e, &**lit) } ast::ExprBinary(b, ref e1, ref e2) => { let (te1, _) = const_expr(cx, &**e1); let (te2, _) = const_expr(cx, &**e2); let te2 = base::cast_shift_const_rhs(b, te1, te2); /* Neither type is bottom, and we expect them to be unified * already, so the following is safe. */ let ty = ty::expr_ty(cx.tcx(), &**e1); let is_float = ty::type_is_fp(ty); let signed = ty::type_is_signed(ty); return match b { ast::BiAdd => { if is_float { llvm::LLVMConstFAdd(te1, te2) } else { llvm::LLVMConstAdd(te1, te2) } } ast::BiSub => { if is_float { llvm::LLVMConstFSub(te1, te2) } else { llvm::LLVMConstSub(te1, te2) } } ast::BiMul => { if is_float { llvm::LLVMConstFMul(te1, te2) } else { llvm::LLVMConstMul(te1, te2) } } ast::BiDiv => { if is_float { llvm::LLVMConstFDiv(te1, te2) } else if signed { llvm::LLVMConstSDiv(te1, te2) } else { llvm::LLVMConstUDiv(te1, te2) } } ast::BiRem => { if is_float { llvm::LLVMConstFRem(te1, te2) } else if signed { llvm::LLVMConstSRem(te1, te2) } else { llvm::LLVMConstURem(te1, te2) } } ast::BiAnd => llvm::LLVMConstAnd(te1, te2), ast::BiOr => llvm::LLVMConstOr(te1, te2), ast::BiBitXor => llvm::LLVMConstXor(te1, te2), ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2), ast::BiBitOr => llvm::LLVMConstOr(te1, te2), ast::BiShl => llvm::LLVMConstShl(te1, te2), ast::BiShr => { if signed { llvm::LLVMConstAShr(te1, te2) } else { llvm::LLVMConstLShr(te1, te2) } } ast::BiEq => { if is_float { ConstFCmp(RealOEQ, te1, te2) } else { ConstICmp(IntEQ, te1, te2) } }, ast::BiLt => { if is_float { ConstFCmp(RealOLT, te1, te2) } else { if signed { ConstICmp(IntSLT, te1, te2) } else { ConstICmp(IntULT, te1, te2) } } }, ast::BiLe => { if is_float { ConstFCmp(RealOLE, te1, te2) } else { if signed { ConstICmp(IntSLE, te1, te2) } else { ConstICmp(IntULE, te1, te2) } } }, ast::BiNe => { if is_float { ConstFCmp(RealONE, te1, te2) } else { ConstICmp(IntNE, te1, te2) } }, ast::BiGe => { if is_float { ConstFCmp(RealOGE, te1, te2) } else { if signed { ConstICmp(IntSGE, te1, te2) } else { ConstICmp(IntUGE, te1, te2) } } }, ast::BiGt => { if is_float { ConstFCmp(RealOGT, te1, te2) } else { if signed { ConstICmp(IntSGT, te1, te2) } else { ConstICmp(IntUGT, te1, te2) } } }, } }, ast::ExprUnary(u, ref e) => { let (te, _) = const_expr(cx, &**e); let ty = ty::expr_ty(cx.tcx(), &**e); let is_float = ty::type_is_fp(ty); return match u { ast::UnUniq | ast::UnDeref => { let (dv, _dt) = const_deref(cx, te, ty, true); dv } ast::UnNot => llvm::LLVMConstNot(te), ast::UnNeg => { if is_float { llvm::LLVMConstFNeg(te) } else { llvm::LLVMConstNeg(te) } } } } ast::ExprField(ref base, field) => { let (bv, bt) = const_expr(cx, &**base); let brepr = adt::represent_type(cx, bt); expr::with_field_tys(cx.tcx(), bt, None, |discr, field_tys| { let ix = ty::field_idx_strict(cx.tcx(), field.node.name, field_tys); adt::const_get_field(cx, &*brepr, bv, discr, ix) }) } ast::ExprTupField(ref base, idx) => { let (bv, bt) = const_expr(cx, &**base); let brepr = adt::represent_type(cx, bt); expr::with_field_tys(cx.tcx(), bt, None, |discr, _| { adt::const_get_field(cx, &*brepr, bv, discr, idx.node) }) } ast::ExprIndex(ref base, ref index) => { let (bv, bt) = const_expr(cx, &**base); let iv = match const_eval::eval_const_expr(cx.tcx(), &**index) { const_eval::const_int(i) => i as u64, const_eval::const_uint(u) => u, _ => cx.sess().span_bug(index.span, "index is not an integer-constant expression") }; let (arr, len) = match bt.sty { ty::ty_vec(_, Some(u)) => (bv, C_uint(cx, u)), ty::ty_open(ty) => match ty.sty { ty::ty_vec(_, None) | ty::ty_str => { let e1 = const_get_elt(cx, bv, &[0]); (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1])) }, _ => cx.sess().span_bug(base.span, &format!("index-expr base must be a vector \ or string type, found {}", ty_to_string(cx.tcx(), bt))[]) }, ty::ty_rptr(_, mt) => match mt.ty.sty { ty::ty_vec(_, Some(u)) => { (const_deref_ptr(cx, bv), C_uint(cx, u)) },<|fim▁hole|> _ => cx.sess().span_bug(base.span, &format!("index-expr base must be a vector \ or string type, found {}", ty_to_string(cx.tcx(), bt))[]) }, _ => cx.sess().span_bug(base.span, &format!("index-expr base must be a vector \ or string type, found {}", ty_to_string(cx.tcx(), bt))[]) }; let len = llvm::LLVMConstIntGetZExtValue(len) as u64; let len = match bt.sty { ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) => match ty.sty { ty::ty_str => { assert!(len > 0); len - 1 } _ => len }, _ => len }; if iv >= len { // FIXME #3170: report this earlier on in the const-eval // pass. Reporting here is a bit late. cx.sess().span_err(e.span, "const index-expr is out of bounds"); } const_get_elt(cx, arr, &[iv as c_uint]) } ast::ExprCast(ref base, _) => { let ety = ty::expr_ty(cx.tcx(), e); let llty = type_of::type_of(cx, ety); let (v, basety) = const_expr(cx, &**base); return match (expr::cast_type_kind(cx.tcx(), basety), expr::cast_type_kind(cx.tcx(), ety)) { (expr::cast_integral, expr::cast_integral) => { let s = ty::type_is_signed(basety) as Bool; llvm::LLVMConstIntCast(v, llty.to_ref(), s) } (expr::cast_integral, expr::cast_float) => { if ty::type_is_signed(basety) { llvm::LLVMConstSIToFP(v, llty.to_ref()) } else { llvm::LLVMConstUIToFP(v, llty.to_ref()) } } (expr::cast_float, expr::cast_float) => { llvm::LLVMConstFPCast(v, llty.to_ref()) } (expr::cast_float, expr::cast_integral) => { if ty::type_is_signed(ety) { llvm::LLVMConstFPToSI(v, llty.to_ref()) } else { llvm::LLVMConstFPToUI(v, llty.to_ref()) } } (expr::cast_enum, expr::cast_integral) => { let repr = adt::represent_type(cx, basety); let discr = adt::const_get_discrim(cx, &*repr, v); let iv = C_integral(cx.int_type(), discr, false); let ety_cast = expr::cast_type_kind(cx.tcx(), ety); match ety_cast { expr::cast_integral => { let s = ty::type_is_signed(ety) as Bool; llvm::LLVMConstIntCast(iv, llty.to_ref(), s) } _ => cx.sess().bug("enum cast destination is not \ integral") } } (expr::cast_pointer, expr::cast_pointer) => { ptrcast(v, llty) } (expr::cast_integral, expr::cast_pointer) => { llvm::LLVMConstIntToPtr(v, llty.to_ref()) } (expr::cast_pointer, expr::cast_integral) => { llvm::LLVMConstPtrToInt(v, llty.to_ref()) } _ => { cx.sess().impossible_case(e.span, "bad combination of types for cast") } } } ast::ExprAddrOf(mutbl, ref sub) => { // If this is the address of some static, then we need to return // the actual address of the static itself (short circuit the rest // of const eval). let mut cur = sub; loop { match cur.node { ast::ExprParen(ref sub) => cur = sub, _ => break, } } let opt_def = cx.tcx().def_map.borrow().get(&cur.id).cloned(); if let Some(def::DefStatic(def_id, _)) = opt_def { let ty = ty::expr_ty(cx.tcx(), e); return get_static_val(cx, def_id, ty); } // If this isn't the address of a static, then keep going through // normal constant evaluation. let (e, _) = const_expr(cx, &**sub); const_addr_of(cx, e, mutbl) } ast::ExprTup(ref es) => { let ety = ty::expr_ty(cx.tcx(), e); let repr = adt::represent_type(cx, ety); let vals = map_list(&es[]); adt::trans_const(cx, &*repr, 0, &vals[]) } ast::ExprStruct(_, ref fs, ref base_opt) => { let ety = ty::expr_ty(cx.tcx(), e); let repr = adt::represent_type(cx, ety); let tcx = cx.tcx(); let base_val = match *base_opt { Some(ref base) => Some(const_expr(cx, &**base)), None => None }; expr::with_field_tys(tcx, ety, Some(e.id), |discr, field_tys| { let cs = field_tys.iter().enumerate() .map(|(ix, &field_ty)| { match fs.iter().find(|f| field_ty.name == f.ident.node.name) { Some(ref f) => const_expr(cx, &*f.expr).0, None => { match base_val { Some((bv, _)) => { adt::const_get_field(cx, &*repr, bv, discr, ix) } None => { cx.sess().span_bug(e.span, "missing struct field") } } } } }).collect::<Vec<_>>(); adt::trans_const(cx, &*repr, discr, &cs[]) }) } ast::ExprVec(ref es) => { const_vec(cx, e, es.as_slice()).0 } ast::ExprRepeat(ref elem, ref count) => { let vec_ty = ty::expr_ty(cx.tcx(), e); let unit_ty = ty::sequence_element_type(cx.tcx(), vec_ty); let llunitty = type_of::type_of(cx, unit_ty); let n = match const_eval::eval_const_expr(cx.tcx(), &**count) { const_eval::const_int(i) => i as uint, const_eval::const_uint(i) => i as uint, _ => cx.sess().span_bug(count.span, "count must be integral const expression.") }; let vs: Vec<_> = repeat(const_expr(cx, &**elem).0).take(n).collect(); if vs.iter().any(|vi| val_ty(*vi) != llunitty) { C_struct(cx, &vs[], false) } else { C_array(llunitty, &vs[]) } } ast::ExprPath(_) => { let def = cx.tcx().def_map.borrow()[e.id]; match def { def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => { expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val } def::DefConst(def_id) => { get_const_val(cx, def_id) } def::DefVariant(enum_did, variant_did, _) => { let vinfo = ty::enum_variant_with_id(cx.tcx(), enum_did, variant_did); if vinfo.args.len() > 0 { // N-ary variant. expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val } else { // Nullary variant. let ety = ty::expr_ty(cx.tcx(), e); let repr = adt::represent_type(cx, ety); adt::trans_const(cx, &*repr, vinfo.disr_val, &[]) } } def::DefStruct(_) => { let ety = ty::expr_ty(cx.tcx(), e); if let ty::ty_bare_fn(..) = ety.sty { // Tuple struct. expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val } else { // Unit struct. C_null(type_of::type_of(cx, ety)) } } _ => { cx.sess().span_bug(e.span, "expected a const, fn, struct, \ or variant def") } } } ast::ExprCall(ref callee, ref args) => { let opt_def = cx.tcx().def_map.borrow().get(&callee.id).cloned(); match opt_def { Some(def::DefStruct(_)) => { let ety = ty::expr_ty(cx.tcx(), e); let repr = adt::represent_type(cx, ety); let arg_vals = map_list(&args[]); adt::trans_const(cx, &*repr, 0, &arg_vals[]) } Some(def::DefVariant(enum_did, variant_did, _)) => { let ety = ty::expr_ty(cx.tcx(), e); let repr = adt::represent_type(cx, ety); let vinfo = ty::enum_variant_with_id(cx.tcx(), enum_did, variant_did); let arg_vals = map_list(&args[]); adt::trans_const(cx, &*repr, vinfo.disr_val, &arg_vals[]) } _ => cx.sess().span_bug(e.span, "expected a struct or variant def") } } ast::ExprParen(ref e) => const_expr(cx, &**e).0, ast::ExprBlock(ref block) => { match block.expr { Some(ref expr) => const_expr(cx, &**expr).0, None => C_nil(cx) } } _ => cx.sess().span_bug(e.span, "bad constant expression type in consts::const_expr") }; } } pub fn trans_static(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) { unsafe { let _icx = push_ctxt("trans_static"); let g = base::get_item_val(ccx, id); // At this point, get_item_val has already translated the // constant's initializer to determine its LLVM type. let v = ccx.static_values().borrow()[id].clone(); // boolean SSA values are i1, but they have to be stored in i8 slots, // otherwise some LLVM optimization passes don't work as expected let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() { llvm::LLVMConstZExt(v, Type::i8(ccx).to_ref()) } else { v }; llvm::LLVMSetInitializer(g, v); // As an optimization, all shared statics which do not have interior // mutability are placed into read-only memory. if m != ast::MutMutable { let node_ty = ty::node_id_to_type(ccx.tcx(), id); let tcontents = ty::type_contents(ccx.tcx(), node_ty); if !tcontents.interior_unsafe() { llvm::LLVMSetGlobalConstant(g, True); } } debuginfo::create_global_var_metadata(ccx, id, g); } } fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId, ty: Ty<'tcx>) -> ValueRef { if ast_util::is_local(did) { return base::get_item_val(ccx, did.node) } base::trans_external_path(ccx, did, ty) }<|fim▁end|>
<|file_name|>create.rs<|end_file_name|><|fim▁begin|>// https://rustbyexample.com/std_misc/file/create.html // http://rust-lang-ja.org/rust-by-example/std_misc/file/create.html // $ mkdir out<|fim▁hole|>static LOREM_IPSUM: &'static str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. "; use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; fn main() { let path = Path::new("out/lorem_ipsum.txt"); let display = path.display(); // Open a file in write-only mode, returns `io::Result<File>` let mut file = match File::create(&path) { Err(why) => panic!("couldn't create {}: {}", display, why.description()), Ok(file) => file, }; // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>` match file.write_all(LOREM_IPSUM.as_bytes()) { Err(why) => { panic!("couldn't write to {}: {}", display, why.description()) }, Ok(_) => println!("successfully wrote to {}", display), } }<|fim▁end|>
// $ rustc create.rs && ./create // $ cat out/lorem_ipsum.txt // create.rs
<|file_name|>TranslogDocument_0_1_0.java<|end_file_name|><|fim▁begin|>package org.uppermodel.translog; import java.util.LinkedList; import java.util.List; import org.uppermodel.translog.v0v1v0.Event; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; /** * Translog document v.0.1.0 * * @author Daniel Couto-Vale <[email protected]> */ public class TranslogDocument_0_1_0 implements TranslogDocument { private static final String VERSION_EXP = "/LogFile/VersionString"; private static final String TRANSLATOR_ID_EXP = "/LogFile/Subject"; private static final String SOURCE_TEXT_EXP = "/LogFile/Project/Interface/Standard/Settings/SourceTextUTF8"; private static final String TARGET_TEXT_EXP = "/LogFile/Project/Interface/Standard/Settings/TargetTextUTF8"; private static final String FINAL_TARGET_TEXT_EXP = "/LogFile/FinalTextChar/CharPos"; private static final String EVENTS_EXP = "/LogFile/Events/*"; /** * The DOM document */ private Document document; /** * The xPath object */ private final XPath xPath; private XPathExpression versionExp; private XPathExpression translatorIdExp; private XPathExpression sourceTextExp; private XPathExpression targetTextExp; private XPathExpression finalTargetTextExp; private XPathExpression eventsExp; /** * Constructor * * @param document the DOM document */ public TranslogDocument_0_1_0(Document document) { this.document = document; this.xPath = XPathFactory.newInstance().newXPath(); try { this.versionExp = this.xPath.compile(VERSION_EXP); this.translatorIdExp = this.xPath.compile(TRANSLATOR_ID_EXP); this.sourceTextExp = this.xPath.compile(SOURCE_TEXT_EXP); this.targetTextExp = this.xPath.compile(TARGET_TEXT_EXP); this.finalTargetTextExp = this.xPath.compile(FINAL_TARGET_TEXT_EXP); this.eventsExp = this.xPath.compile(EVENTS_EXP); } catch (XPathExpressionException e) { e.printStackTrace(); } } @Override public final String getVersion() { return extractString(versionExp); } @Override public final String getTranslatorId() { return extractString(translatorIdExp); } @Override public final String getSourceText() { return extractString(sourceTextExp); } @Override public final String getInitialTargetText() { return extractString(targetTextExp); } @Override public final String getFinalTargetText() { try { return getFinalTargetTextImpl(); } catch (XPathExpressionException e) { e.printStackTrace(); return ""; } } private final String getFinalTargetTextImpl() throws XPathExpressionException { StringBuffer buffer = new StringBuffer(); NodeList nodeList = (NodeList) finalTargetTextExp.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element)nodeList.item(i); String value = element.getAttribute("Value"); if (value.equals("\n")) { value = "␤"; } buffer.append(value); } return buffer.toString(); }<|fim▁hole|> @Override public final List<TranslogEvent> getEvents() { try { return getEventListImp(); } catch (XPathExpressionException e) { e.printStackTrace(); return new LinkedList<TranslogEvent>(); } } private final List<TranslogEvent> getEventListImp() throws XPathExpressionException { List<TranslogEvent> events = new LinkedList<TranslogEvent>(); NodeList nodeList = (NodeList) eventsExp.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element)nodeList.item(i); events.add(Event.makeNode(element, xPath)); } return events; } private final String extractString(XPathExpression exp) { try { return extractStringImp(exp); } catch (XPathExpressionException e) { e.printStackTrace(); return null; } } private final String extractStringImp(XPathExpression exp) throws XPathExpressionException { NodeList nodeList = (NodeList) exp.evaluate(document, XPathConstants.NODESET); Node node = nodeList.item(0).getFirstChild(); return node == null ? "" : node.getNodeValue(); } @Override public boolean isCompliant() { return document.getDocumentElement().getNodeName().equals("LogFile"); } }<|fim▁end|>
<|file_name|>AutoBuffer.java<|end_file_name|><|fim▁begin|>package water; import java.io.*; import java.lang.reflect.Array; import java.net.*; import java.nio.*; import java.nio.channels.*; import java.util.ArrayList; import java.util.Random; import water.network.SocketChannelUtils; import water.util.Log; import water.util.StringUtils; import water.util.TwoDimTable; /** A ByteBuffer backed mixed Input/Output streaming class, using Iced serialization. * * Reads/writes empty/fill the ByteBuffer as needed. When it is empty/full it * we go to the ByteChannel for more/less. Because DirectByteBuffers are * expensive to make, we keep a few pooled. * * When talking to a remote H2O node, switches between UDP and TCP transport * protocols depending on the message size. The TypeMap is not included, and * is assumed to exist on the remote H2O node. * * Supports direct NIO FileChannel read/write to disk, used during user-mode * swapping. The TypeMap is not included on write, and is assumed to be the * current map on read. * * Support read/write from byte[] - and this defeats the purpose of a * Streaming protocol, but is frequently handy for small structures. The * TypeMap is not included, and is assumed to be the current map on read. * * Supports read/write from a standard Stream, which by default assumes it is * NOT going in and out of the same Cloud, so the TypeMap IS included. The * serialized object can only be read back into the same minor version of H2O. * * @author <a href="mailto:[email protected]"></a> */ public final class AutoBuffer { // Maximum size of an array we allow to allocate (the value is designed // to mimic the behavior of OpenJDK libraries) private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // The direct ByteBuffer for schlorping data about. // Set to null to indicate the AutoBuffer is closed. ByteBuffer _bb; public String sourceName = "???"; public boolean isClosed() { return _bb == null ; } // The ByteChannel for moving data in or out. Could be a SocketChannel (for // a TCP connection) or a FileChannel (spill-to-disk) or a DatagramChannel // (for a UDP connection). Null on closed AutoBuffers. Null on initial // remote-writing AutoBuffers which are still deciding UDP vs TCP. Not-null // for open AutoBuffers doing file i/o or reading any TCP/UDP or having // written at least one buffer to TCP/UDP. private Channel _chan; // A Stream for moving data in. Null unless this AutoBuffer is // stream-based, in which case _chan field is null. This path supports // persistance: reading and writing objects from different H2O cluster // instances (but exactly the same H2O revision). The only required // similarity is same-classes-same-fields; changes here will probably // silently crash. If the fields are named the same but the semantics // differ, then again the behavior is probably silent crash. private InputStream _is; private short[] _typeMap; // Mapping from input stream map to current map, or null // If we need a SocketChannel, raise the priority so we get the I/O over // with. Do not want to have some TCP socket open, blocking the TCP channel // and then have the thread stalled out. If we raise the priority - be sure // to lower it again. Note this is for TCP channels ONLY, and only because // we are blocking another Node with I/O. private int _oldPrior = -1; // Where to send or receive data via TCP or UDP (choice made as we discover // how big the message is); used to lazily create a Channel. If NULL, then // _chan should be a pre-existing Channel, such as a FileChannel. final H2ONode _h2o; // TRUE for read-mode. FALSE for write-mode. Can be flipped for rapid turnaround. private boolean _read; // TRUE if this AutoBuffer has never advanced past the first "page" of data. // The UDP-flavor, port# and task fields are only valid until we read over // them when flipping the ByteBuffer to the next chunk of data. Used in // asserts all over the place. private boolean _firstPage; // Total size written out from 'new' to 'close'. Only updated when actually // reading or writing data, or after close(). For profiling only. int _size; //int _zeros, _arys; // More profiling: start->close msec, plus nano's spent in blocking I/O // calls. The difference between (close-start) and i/o msec is the time the // i/o thread spends doing other stuff (e.g. allocating Java objects or // (de)serializing). long _time_start_ms, _time_close_ms, _time_io_ns; // I/O persistence flavor: Value.ICE, NFS, HDFS, S3, TCP. Used to record I/O time. final byte _persist; // The assumed max UDP packetsize static final int MTU = 1500-8/*UDP packet header size*/; // Enable this to test random TCP fails on open or write static final Random RANDOM_TCP_DROP = null; //new Random(); static final java.nio.charset.Charset UTF_8 = java.nio.charset.Charset.forName("UTF-8"); /** Incoming UDP request. Make a read-mode AutoBuffer from the open Channel, * figure the originating H2ONode from the first few bytes read. */ AutoBuffer( DatagramChannel sock ) throws IOException { _chan = null; _bb = BBP_SML.make(); // Get a small / UDP-sized ByteBuffer _read = true; // Reading by default _firstPage = true; // Read a packet; can get H2ONode from 'sad'? Inet4Address addr = null; SocketAddress sad = sock.receive(_bb); if( sad instanceof InetSocketAddress ) { InetAddress address = ((InetSocketAddress) sad).getAddress(); if( address instanceof Inet4Address ) { addr = (Inet4Address) address; } } _size = _bb.position(); _bb.flip(); // Set limit=amount read, and position==0 if( addr == null ) throw new RuntimeException("Unhandled socket type: " + sad); // Read Inet from socket, port from the stream, figure out H2ONode _h2o = H2ONode.intern(addr, getPort()); _firstPage = true; assert _h2o != null; _persist = 0; // No persistance } /** Incoming TCP request. Make a read-mode AutoBuffer from the open Channel, * figure the originating H2ONode from the first few bytes read. * * remoteAddress set to null means that the communication is originating from non-h2o node, non-null value * represents the case where the communication is coming from h2o node. * */ AutoBuffer( ByteChannel sock, InetAddress remoteAddress ) throws IOException { _chan = sock; raisePriority(); // Make TCP priority high _bb = BBP_BIG.make(); // Get a big / TPC-sized ByteBuffer _bb.flip(); _read = true; // Reading by default _firstPage = true; // Read Inet from socket, port from the stream, figure out H2ONode if(remoteAddress!=null) { _h2o = H2ONode.intern(remoteAddress, getPort()); }else{ // In case the communication originates from non-h2o node, we set _h2o node to null. // It is done for 2 reasons: // - H2ONode.intern creates a new thread and if there's a lot of connections // from non-h2o environment, it could end up with too many open files exception. // - H2OIntern also reads port (getPort()) and additional information which we do not send // in communication originating from non-h2o nodes _h2o = null; } _firstPage = true; // Yes, must reset this. _time_start_ms = System.currentTimeMillis(); _persist = Value.TCP; } /** Make an AutoBuffer to write to an H2ONode. Requests for full buffer will * open a TCP socket and roll through writing to the target. Smaller * requests will send via UDP. Small requests get ordered by priority, so * that e.g. NACK and ACKACK messages have priority over most anything else. * This helps in UDP floods to shut down flooding senders. */ private byte _msg_priority; AutoBuffer( H2ONode h2o, byte priority ) { // If UDP goes via UDP, we write into a DBB up front - because we plan on // sending it out via a Datagram socket send call. If UDP goes via batched // TCP, we write into a HBB up front, because this will be copied again // into a large outgoing buffer. _bb = H2O.ARGS.useUDP // Actually use UDP? ? BBP_SML.make() // Make DirectByteBuffers to start with : ByteBuffer.wrap(new byte[16]).order(ByteOrder.nativeOrder()); _chan = null; // Channel made lazily only if we write alot _h2o = h2o; _read = false; // Writing by default _firstPage = true; // Filling first page assert _h2o != null; _time_start_ms = System.currentTimeMillis(); _persist = Value.TCP; _msg_priority = priority; } /** Spill-to/from-disk request. */ public AutoBuffer( FileChannel fc, boolean read, byte persist ) { _bb = BBP_BIG.make(); // Get a big / TPC-sized ByteBuffer _chan = fc; // Write to read/write _h2o = null; // File Channels never have an _h2o _read = read; // Mostly assert reading vs writing if( read ) _bb.flip(); _time_start_ms = System.currentTimeMillis(); _persist = persist; // One of Value.ICE, NFS, S3, HDFS } /** Read from UDP multicast. Same as the byte[]-read variant, except there is an H2O. */ AutoBuffer( DatagramPacket pack ) { _size = pack.getLength(); _bb = ByteBuffer.wrap(pack.getData(), 0, pack.getLength()).order(ByteOrder.nativeOrder()); _bb.position(0); _read = true; _firstPage = true; _chan = null; _h2o = H2ONode.intern(pack.getAddress(), getPort()); _persist = 0; // No persistance } /** Read from a UDP_TCP buffer; could be in the middle of a large buffer */ AutoBuffer( H2ONode h2o, byte[] buf, int off, int len ) { assert buf != null : "null fed to ByteBuffer.wrap"; _h2o = h2o; _bb = ByteBuffer.wrap(buf,off,len).order(ByteOrder.nativeOrder()); _chan = null; _read = true; _firstPage = true; _persist = 0; // No persistance _size = len; } /** Read from a fixed byte[]; should not be closed. */ public AutoBuffer( byte[] buf ) { this(null,buf,0, buf.length); } /** Write to an ever-expanding byte[]. Instead of calling {@link #close()}, * call {@link #buf()} to retrieve the final byte[]. */ public AutoBuffer( ) { _bb = ByteBuffer.wrap(new byte[16]).order(ByteOrder.nativeOrder()); _chan = null; _h2o = null; _read = false; _firstPage = true; _persist = 0; // No persistance } /** Write to a known sized byte[]. Instead of calling close(), call * {@link #bufClose()} to retrieve the final byte[]. */ public AutoBuffer( int len ) { _bb = ByteBuffer.wrap(MemoryManager.malloc1(len)).order(ByteOrder.nativeOrder()); _chan = null; _h2o = null; _read = false; _firstPage = true; _persist = 0; // No persistance } /** Write to a persistent Stream, including all TypeMap info to allow later * reloading (by the same exact rev of H2O). */ public AutoBuffer( OutputStream os, boolean persist ) { _bb = ByteBuffer.wrap(MemoryManager.malloc1(BBP_BIG._size)).order(ByteOrder.nativeOrder()); _read = false; _chan = Channels.newChannel(os); _h2o = null; _firstPage = true; _persist = 0; if( persist ) put1(0x1C).put1(0xED).putStr(H2O.ABV.projectVersion()).putAStr(TypeMap.CLAZZES); else put1(0); } /** Read from a persistent Stream (including all TypeMap info) into same * exact rev of H2O). */ public AutoBuffer( InputStream is ) { _chan = null; _h2o = null; _firstPage = true; _persist = 0; _read = true; _bb = ByteBuffer.wrap(MemoryManager.malloc1(BBP_BIG._size)).order(ByteOrder.nativeOrder()); _bb.flip(); _is = is; int b = get1U(); if( b==0 ) return; // No persistence info int magic = get1U(); if( b!=0x1C || magic != 0xED ) throw new IllegalArgumentException("Missing magic number 0x1CED at stream start"); String version = getStr(); if( !version.equals(H2O.ABV.projectVersion()) ) throw new IllegalArgumentException("Found version "+version+", but running version "+H2O.ABV.projectVersion()); String[] typeMap = getAStr(); _typeMap = new short[typeMap.length]; for( int i=0; i<typeMap.length; i++ ) _typeMap[i] = (short)(typeMap[i]==null ? 0 : TypeMap.onIce(typeMap[i])); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[AB ").append(_read ? "read " : "write "); sb.append(_firstPage?"first ":"2nd ").append(_h2o); sb.append(" ").append(Value.nameOfPersist(_persist)); if( _bb != null ) sb.append(" 0 <= ").append(_bb.position()).append(" <= ").append(_bb.limit()); if( _bb != null ) sb.append(" <= ").append(_bb.capacity()); return sb.append("]").toString(); } // Fetch a DBB from an object pool... they are fairly expensive to make // because a native call is required to get the backing memory. I've // included BB count tracking code to help track leaks. As of 12/17/2012 the // leaks are under control, but figure this may happen again so keeping these // counters around. // // We use 2 pool sizes: lots of small UDP packet-sized buffers and fewer // larger TCP-sized buffers. private static final boolean DEBUG = Boolean.getBoolean("h2o.find-ByteBuffer-leaks"); private static long HWM=0; static class BBPool { long _made, _cached, _freed; long _numer, _denom, _goal=4*H2O.NUMCPUS, _lastGoal; final ArrayList<ByteBuffer> _bbs = new ArrayList<>(); final int _size; // Big or small size of ByteBuffers BBPool( int sz) { _size=sz; } private ByteBuffer stats( ByteBuffer bb ) { if( !DEBUG ) return bb; if( ((_made+_cached)&255)!=255 ) return bb; // Filter printing to 1 in 256 long now = System.currentTimeMillis(); if( now < HWM ) return bb; HWM = now+1000; water.util.SB sb = new water.util.SB(); sb.p("BB").p(this==BBP_BIG?1:0).p(" made=").p(_made).p(" -freed=").p(_freed).p(", cache hit=").p(_cached).p(" ratio=").p(_numer/_denom).p(", goal=").p(_goal).p(" cache size=").p(_bbs.size()).nl(); for( int i=0; i<H2O.MAX_PRIORITY; i++ ) { int x = H2O.getWrkQueueSize(i); if( x > 0 ) sb.p('Q').p(i).p('=').p(x).p(' '); } Log.warn(sb.nl().toString()); return bb; } ByteBuffer make() { while( true ) { // Repeat loop for DBB OutOfMemory errors ByteBuffer bb=null; synchronized(_bbs) { int sz = _bbs.size(); if( sz > 0 ) { bb = _bbs.remove(sz-1); _cached++; _numer++; } } if( bb != null ) return stats(bb); // Cache empty; go get one from C/Native memory try { bb = ByteBuffer.allocateDirect(_size).order(ByteOrder.nativeOrder()); synchronized(this) { _made++; _denom++; _goal = Math.max(_goal,_made-_freed); _lastGoal=System.nanoTime(); } // Goal was too low, raise it return stats(bb); } catch( OutOfMemoryError oome ) { // java.lang.OutOfMemoryError: Direct buffer memory if( !"Direct buffer memory".equals(oome.getMessage()) ) throw oome; System.out.println("OOM DBB - Sleeping & retrying"); try { Thread.sleep(100); } catch( InterruptedException ignore ) { } } } } void free(ByteBuffer bb) { // Heuristic: keep the ratio of BB's made to cache-hits at a fixed level. // Free to GC if ratio is high, free to internal cache if low. long ratio = _numer/(_denom+1); synchronized(_bbs) { if( ratio < 100 || _bbs.size() < _goal ) { // low hit/miss ratio or below goal bb.clear(); // Clear-before-add _bbs.add(bb); } else _freed++; // Toss the extras (above goal & ratio) long now = System.nanoTime(); if( now-_lastGoal > 1000000000L ) { // Once/sec, drop goal by 10% _lastGoal = now; if( ratio > 110 ) // If ratio is really high, lower goal _goal=Math.max(4*H2O.NUMCPUS,(long)(_goal*0.99)); // Once/sec, lower numer/denom... means more recent activity outweighs really old stuff long denom = (long) (0.99 * _denom); // Proposed reduction if( denom > 10 ) { // Keep a little precision _numer = (long) (0.99 * _numer); // Keep ratio between made & cached the same _denom = denom; // ... by lowering both by 10% } } } } static int FREE( ByteBuffer bb ) { if(bb.isDirect()) (bb.capacity()==BBP_BIG._size ? BBP_BIG : BBP_SML).free(bb); return 0; // Flow coding } } static BBPool BBP_SML = new BBPool( 2*1024); // Bytebuffer "common small size", for UDP static BBPool BBP_BIG = new BBPool(64*1024); // Bytebuffer "common big size", for TCP public static int TCP_BUF_SIZ = BBP_BIG._size; private int bbFree() { if(_bb != null && _bb.isDirect()) BBPool.FREE(_bb); _bb = null; return 0; // Flow-coding } // You thought TCP was a reliable protocol, right? WRONG! Fails 100% of the // time under heavy network load. Connection-reset-by-peer & connection // timeouts abound, even after a socket open and after a 1st successful // ByteBuffer write. It *appears* that the reader is unaware that a writer // was told "go ahead and write" by the TCP stack, so all these fails are // only on the writer-side. public static class AutoBufferException extends RuntimeException { public final IOException _ioe; AutoBufferException( IOException ioe ) { _ioe = ioe; } } // For reads, just assert all was read and close and release resources. // (release ByteBuffer back to the common pool). For writes, force any final // bytes out. If the write is to an H2ONode and is short, send via UDP. // AutoBuffer close calls order; i.e. a reader close() will block until the // writer does a close(). public final int close() { //if( _size > 2048 ) System.out.println("Z="+_zeros+" / "+_size+", A="+_arys); if( isClosed() ) return 0; // Already closed assert _h2o != null || _chan != null || _is != null; // Byte-array backed should not be closed try { if( _chan == null ) { // No channel? if( _read ) { if( _is != null ) _is.close(); return 0; } else { // Write // For small-packet write, send via UDP. Since nothing is sent until // now, this close() call trivially orders - since the reader will not // even start (much less close()) until this packet is sent. if( _bb.position() < MTU) return udpSend(); // oops - Big Write, switch to TCP and finish out there } } // Force AutoBuffer 'close' calls to order; i.e. block readers until // writers do a 'close' - by writing 1 more byte in the close-call which // the reader will have to wait for. if( hasTCP()) { // TCP connection? try { if( _read ) { // Reader? int x = get1U(); // Read 1 more byte assert x == 0xab : "AB.close instead of 0xab sentinel got "+x+", "+this; assert _chan != null; // chan set by incoming reader, since we KNOW it is a TCP // Write the reader-handshake-byte. SocketChannelUtils.underlyingSocketChannel(_chan).socket().getOutputStream().write(0xcd); // do not close actually reader socket; recycle it in TCPReader thread } else { // Writer? put1(0xab); // Write one-more byte ; might set _chan from null to not-null sendPartial(); // Finish partial writes; might set _chan from null to not-null assert _chan != null; // _chan is set not-null now! // Read the writer-handshake-byte. int x = SocketChannelUtils.underlyingSocketChannel(_chan).socket().getInputStream().read(); // either TCP con was dropped or other side closed connection without reading/confirming (e.g. task was cancelled). if( x == -1 ) throw new IOException("Other side closed connection before handshake byte read"); assert x == 0xcd : "Handshake; writer expected a 0xcd from reader but got "+x; } } catch( IOException ioe ) { try { _chan.close(); } catch( IOException ignore ) {} // Silently close _chan = null; // No channel now, since i/o error throw ioe; // Rethrow after close } finally { if( !_read ) _h2o.freeTCPSocket((ByteChannel) _chan); // Recycle writable TCP channel restorePriority(); // And if we raised priority, lower it back } } else { // FileChannel if( !_read ) sendPartial(); // Finish partial file-system writes _chan.close(); _chan = null; // Closed file channel } } catch( IOException e ) { // Dunno how to handle so crash-n-burn throw new AutoBufferException(e); } finally { bbFree(); _time_close_ms = System.currentTimeMillis(); // TimeLine.record_IOclose(this,_persist); // Profile AutoBuffer connections assert isClosed(); } return 0; } // Need a sock for a big read or write operation. // See if we got one already, else open a new socket. private void tcpOpen() throws IOException { assert _firstPage && _bb.limit() >= 1+2+4; // At least something written assert _chan == null; // assert _bb.position()==0; _chan = _h2o.getTCPSocket(); raisePriority(); } // Just close the channel here without reading anything. Without the task // object at hand we do not know what (how many bytes) should we read from // the channel. And since the other side will try to read confirmation from // us before closing the channel, we can not read till the end. So we just // close the channel and let the other side to deal with it and figure out // the task has been cancelled (still sending ack ack back). void drainClose() { if( isClosed() ) return; // Already closed final Channel chan = _chan; // Read before closing assert _h2o != null || chan != null; // Byte-array backed should not be closed if( chan != null ) { // Channel assumed sick from prior IOException try { chan.close(); } catch( IOException ignore ) {} // Silently close _chan = null; // No channel now! if( !_read && SocketChannelUtils.isSocketChannel(chan)) _h2o.freeTCPSocket((ByteChannel) chan); // Recycle writable TCP channel } restorePriority(); // And if we raised priority, lower it back bbFree(); _time_close_ms = System.currentTimeMillis(); // TimeLine.record_IOclose(this,_persist); // Profile AutoBuffer connections assert isClosed(); } // True if we opened a TCP channel, or will open one to close-and-send boolean hasTCP() { assert !isClosed(); return SocketChannelUtils.isSocketChannel(_chan) || (_h2o!=null && _bb.position() >= MTU); } // Size in bytes sent, after a close() int size() { return _size; } //int zeros() { return _zeros; } public int position () { return _bb.position(); } public AutoBuffer position(int p) {_bb.position(p); return this;} /** Skip over some bytes in the byte buffer. Caller is responsible for not * reading off end of the bytebuffer; generally this is easy for * array-backed autobuffers and difficult for i/o-backed bytebuffers. */ public void skip(int skip) { _bb.position(_bb.position()+skip); } // Return byte[] from a writable AutoBuffer public final byte[] buf() { assert _h2o==null && _chan==null && !_read && !_bb.isDirect(); return MemoryManager.arrayCopyOfRange(_bb.array(), _bb.arrayOffset(), _bb.position()); } public final byte[] bufClose() { byte[] res = _bb.array(); bbFree(); return res; } // For TCP sockets ONLY, raise the thread priority. We assume we are // blocking other Nodes with our network I/O, so try to get the I/O // over with. private void raisePriority() { if(_oldPrior == -1){ assert SocketChannelUtils.isSocketChannel(_chan); _oldPrior = Thread.currentThread().getPriority(); Thread.currentThread().setPriority(Thread.MAX_PRIORITY-1); } } private void restorePriority() { if( _oldPrior == -1 ) return; Thread.currentThread().setPriority(_oldPrior); _oldPrior = -1; } // Send via UDP socket. Unlike eg TCP sockets, we only need one for sending // so we keep a global one. Also, we do not close it when done, and we do // not connect it up-front to a target - but send the entire packet right now. private int udpSend() throws IOException { assert _chan == null; TimeLine.record_send(this,false); _size = _bb.position(); assert _size < AutoBuffer.BBP_SML._size; _bb.flip(); // Flip for sending if( _h2o==H2O.SELF ) { // SELF-send is the multi-cast signal water.init.NetworkInit.multicast(_bb, _msg_priority); } else { // Else single-cast send if(H2O.ARGS.useUDP) // Send via UDP directly water.init.NetworkInit.CLOUD_DGRAM.send(_bb, _h2o._key); else // Send via bulk TCP _h2o.sendMessage(_bb, _msg_priority); } return 0; // Flow-coding } // Flip to write-mode AutoBuffer clearForWriting(byte priority) { assert _read; _read = false; _msg_priority = priority; _bb.clear(); _firstPage = true; return this; } // Flip to read-mode public AutoBuffer flipForReading() { assert !_read; _read = true; _bb.flip(); _firstPage = true; return this; } /** Ensure the buffer has space for sz more bytes */ private ByteBuffer getSp( int sz ) { return sz > _bb.remaining() ? getImpl(sz) : _bb; } /** Ensure buffer has at least sz bytes in it. * - Also, set position just past this limit for future reading. */ private ByteBuffer getSz(int sz) { assert _firstPage : "getSz() is only valid for early UDP bytes"; if( sz > _bb.limit() ) getImpl(sz); _bb.position(sz); return _bb; } private ByteBuffer getImpl( int sz ) { assert _read : "Reading from a buffer in write mode"; _bb.compact(); // Move remaining unread bytes to start of buffer; prep for reading // Its got to fit or we asked for too much assert _bb.position()+sz <= _bb.capacity() : "("+_bb.position()+"+"+sz+" <= "+_bb.capacity()+")"; long ns = System.nanoTime(); while( _bb.position() < sz ) { // Read until we got enuf try { int res = readAnInt(); // Read more // Readers are supposed to be strongly typed and read the exact expected bytes. // However, if a TCP connection fails mid-read we'll get a short-read. // This is indistinguishable from a mis-alignment between the writer and reader! if( res <= 0 ) throw new AutoBufferException(new EOFException("Reading "+sz+" bytes, AB="+this)); if( _is != null ) _bb.position(_bb.position()+res); // Advance BB for Streams manually _size += res; // What we read } catch( IOException e ) { // Dunno how to handle so crash-n-burn // Linux/Ubuntu message for a reset-channel if( e.getMessage().equals("An existing connection was forcibly closed by the remote host") ) throw new AutoBufferException(e); // Windows message for a reset-channel if( e.getMessage().equals("An established connection was aborted by the software in your host machine") ) throw new AutoBufferException(e); throw Log.throwErr(e); } } _time_io_ns += (System.nanoTime()-ns); _bb.flip(); // Prep for handing out bytes //for( int i=0; i < _bb.limit(); i++ ) if( _bb.get(i)==0 ) _zeros++; _firstPage = false; // First page of data is gone gone gone return _bb; } private int readAnInt() throws IOException { if (_is == null) return ((ReadableByteChannel) _chan).read(_bb); final byte[] array = _bb.array(); final int position = _bb.position(); final int remaining = _bb.remaining(); try { return _is.read(array, position, remaining); } catch (IOException ioe) { throw new IOException("Failed reading " + remaining + " bytes into buffer[" + array.length + "] at " + position + " from " + sourceName + " " + _is, ioe); } } /** Put as needed to keep from overflowing the ByteBuffer. */ private ByteBuffer putSp( int sz ) { assert !_read; if (sz > _bb.remaining()) { if ((_h2o == null && _chan == null) || (_bb.hasArray() && _bb.capacity() < BBP_BIG._size)) expandByteBuffer(sz); else sendPartial(); assert sz <= _bb.remaining(); } return _bb; } // Do something with partial results, because the ByteBuffer is full. // If we are doing I/O, ship the bytes we have now and flip the ByteBuffer. private ByteBuffer sendPartial() { // Doing I/O with the full ByteBuffer - ship partial results _size += _bb.position(); if( _chan == null ) TimeLine.record_send(this, true); _bb.flip(); // Prep for writing. try { if( _chan == null ) tcpOpen(); // This is a big operation. Open a TCP socket as-needed. //for( int i=0; i < _bb.limit(); i++ ) if( _bb.get(i)==0 ) _zeros++; long ns = System.nanoTime(); while( _bb.hasRemaining() ) { ((WritableByteChannel) _chan).write(_bb); if( RANDOM_TCP_DROP != null && SocketChannelUtils.isSocketChannel(_chan) && RANDOM_TCP_DROP.nextInt(100) == 0 ) throw new IOException("Random TCP Write Fail"); } _time_io_ns += (System.nanoTime()-ns); } catch( IOException e ) { // Some kind of TCP fail? // Change to an unchecked exception (so we don't have to annotate every // frick'n put1/put2/put4/read/write call). Retry & recovery happens at // a higher level. AutoBuffers are used for many things including e.g. // disk i/o & UDP writes; this exception only happens on a failed TCP // write - and we don't want to make the other AutoBuffer users have to // declare (and then ignore) this exception. throw new AutoBufferException(e); } _firstPage = false; _bb.clear(); return _bb; } // Called when the byte buffer doesn't have enough room // If buffer is array backed, and the needed room is small, // increase the size of the backing array, // otherwise dump into a large direct buffer private ByteBuffer expandByteBuffer(int sizeHint) { final long needed = (long) sizeHint - _bb.remaining() + _bb.capacity(); // Max needed is 2G if ((_h2o==null && _chan == null) || (_bb.hasArray() && needed < MTU)) { if (needed > MAX_ARRAY_SIZE) { throw new IllegalArgumentException("Cannot allocate more than 2GB array: sizeHint="+sizeHint+", " + "needed="+needed + ", bb.remaining()=" + _bb.remaining() + ", bb.capacity()="+_bb.capacity()); } byte[] ary = _bb.array(); // just get twice what is currently needed but not more then max array size (2G) // Be careful not to overflow because of integer math! int newLen = (int) Math.min(1L << (water.util.MathUtils.log2(needed)+1), MAX_ARRAY_SIZE); int oldpos = _bb.position(); _bb = ByteBuffer.wrap(MemoryManager.arrayCopyOfRange(ary,0,newLen),oldpos,newLen-oldpos) .order(ByteOrder.nativeOrder()); } else if (_bb.capacity() != BBP_BIG._size) { //avoid expanding existing BBP items int oldPos = _bb.position(); _bb.flip(); _bb = BBP_BIG.make().put(_bb); _bb.position(oldPos); } return _bb; } @SuppressWarnings("unused") public String getStr(int off, int len) { return new String(_bb.array(), _bb.arrayOffset()+off, len, UTF_8); } // ----------------------------------------------- // Utility functions to get various Java primitives @SuppressWarnings("unused") public boolean getZ() { return get1()!=0; } @SuppressWarnings("unused") public byte get1 () { return getSp(1).get (); } @SuppressWarnings("unused") public int get1U() { return get1() & 0xFF; } @SuppressWarnings("unused") public char get2 () { return getSp(2).getChar (); } @SuppressWarnings("unused") public short get2s () { return getSp(2).getShort (); } @SuppressWarnings("unused") public int get3 () { getSp(3); return get1U() | get1U() << 8 | get1U() << 16; } @SuppressWarnings("unused") public int get4 () { return getSp(4).getInt (); } @SuppressWarnings("unused") public float get4f() { return getSp(4).getFloat (); } @SuppressWarnings("unused") public long get8 () { return getSp(8).getLong (); } @SuppressWarnings("unused") public double get8d() { return getSp(8).getDouble(); } int get1U(int off) { return _bb.get (off)&0xFF; } int get4 (int off) { return _bb.getInt (off); } long get8 (int off) { return _bb.getLong(off); } @SuppressWarnings("unused") public AutoBuffer putZ (boolean b){ return put1(b?1:0); } @SuppressWarnings("unused") public AutoBuffer put1 ( int b) { assert b >= -128 && b <= 255 : ""+b+" is not a byte"; putSp(1).put((byte)b); return this; } @SuppressWarnings("unused") public AutoBuffer put2 ( char c) { putSp(2).putChar (c); return this; } @SuppressWarnings("unused") public AutoBuffer put2 ( short s) { putSp(2).putShort (s); return this; } @SuppressWarnings("unused") public AutoBuffer put2s ( short s) { return put2(s); } @SuppressWarnings("unused") public AutoBuffer put3( int x ) { assert (-1<<24) <= x && x < (1<<24); return put1((x)&0xFF).put1((x >> 8)&0xFF).put1(x >> 16); } @SuppressWarnings("unused") public AutoBuffer put4 ( int i) { putSp(4).putInt (i); return this; } @SuppressWarnings("unused") public AutoBuffer put4f( float f) { putSp(4).putFloat (f); return this; } @SuppressWarnings("unused") public AutoBuffer put8 ( long l) { putSp(8).putLong (l); return this; } @SuppressWarnings("unused") public AutoBuffer put8d(double d) { putSp(8).putDouble(d); return this; } public AutoBuffer put(Freezable f) { if( f == null ) return putInt(TypeMap.NULL); assert f.frozenType() > 0 : "No TypeMap for "+f.getClass().getName(); putInt(f.frozenType()); return f.write(this); } public <T extends Freezable> T get() { int id = getInt(); if( id == TypeMap.NULL ) return null; if( _is!=null ) id = _typeMap[id]; return (T)TypeMap.newFreezable(id).read(this); } public <T extends Freezable> T get(Class<T> tc) { int id = getInt(); if( id == TypeMap.NULL ) return null; if( _is!=null ) id = _typeMap[id]; assert tc.isInstance(TypeMap.theFreezable(id)):tc.getName() + " != " + TypeMap.theFreezable(id).getClass().getName() + ", id = " + id; return (T)TypeMap.newFreezable(id).read(this); } // Write Key's target IFF the Key is not null; target can be null. public AutoBuffer putKey(Key k) { if( k==null ) return this; // Key is null ==> write nothing Keyed kd = DKV.getGet(k); put(kd); return kd == null ? this : kd.writeAll_impl(this); } public Keyed getKey(Key k, Futures fs) { return k==null ? null : getKey(fs); // Key is null ==> read nothing } public Keyed getKey(Futures fs) { Keyed kd = get(Keyed.class); if( kd == null ) return null; DKV.put(kd,fs); return kd.readAll_impl(this,fs); } // Put a (compressed) integer. Specifically values in the range -1 to ~250 // will take 1 byte, values near a Short will take 1+2 bytes, values near an // Int will take 1+4 bytes, and bigger values 1+8 bytes. This compression is // optimized for small integers (including -1 which is often used as a "array // is null" flag when passing the array length). public AutoBuffer putInt(int x) { if( 0 <= (x+1)&& (x+1) <= 253 ) return put1(x+1); if( Short.MIN_VALUE <= x && x <= Short.MAX_VALUE ) return put1(255).put2((short)x); return put1(254).put4(x); } // Get a (compressed) integer. See above for the compression strategy and reasoning. int getInt( ) { int x = get1U(); if( x <= 253 ) return x-1; if( x==255 ) return (short)get2(); assert x==254; return get4(); } // Put a zero-compressed array. Compression is: // If null : putInt(-1) // Else // putInt(# of leading nulls) // putInt(# of non-nulls) // If # of non-nulls is > 0, putInt( # of trailing nulls) long putZA( Object[] A ) { if( A==null ) { putInt(-1); return 0; } int x=0; for( ; x<A.length; x++ ) if( A[x ]!=null ) break; int y=A.length; for( ; y>x; y-- ) if( A[y-1]!=null ) break; putInt(x); // Leading zeros to skip putInt(y-x); // Mixed non-zero guts in middle if( y > x ) // If any trailing nulls putInt(A.length-y); // Trailing zeros return ((long)x<<32)|(y-x); // Return both leading zeros, and middle non-zeros } // Get the lengths of a zero-compressed array. // Returns -1 if null. // Returns a long of (leading zeros | middle non-zeros). // If there are non-zeros, caller has to read the trailing zero-length. long getZA( ) { int x=getInt(); // Length of leading zeros if( x == -1 ) return -1; // or a null int nz=getInt(); // Non-zero in the middle return ((long)x<<32)|(long)nz; // Return both ints } // TODO: untested. . . @SuppressWarnings("unused") public AutoBuffer putAEnum(Enum[] enums) { //_arys++; long xy = putZA(enums); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putEnum(enums[i]); return this; } @SuppressWarnings("unused") public <E extends Enum> E[] getAEnum(E[] values) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls E[] ts = (E[]) Array.newInstance(values.getClass().getComponentType(), x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = getEnum(values); return ts; } @SuppressWarnings("unused") public AutoBuffer putA(Freezable[] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) put(fs[i]); return this; } public AutoBuffer putAA(Freezable[][] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putA(fs[i]); return this; } @SuppressWarnings("unused") public AutoBuffer putAAA(Freezable[][][] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putAA(fs[i]); return this; } public <T extends Freezable> T[] getA(Class<T> tc) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls T[] ts = (T[]) Array.newInstance(tc, x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = get(tc); return ts; } public <T extends Freezable> T[][] getAA(Class<T> tc) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls Class<T[]> tcA = (Class<T[]>) Array.newInstance(tc, 0).getClass(); T[][] ts = (T[][]) Array.newInstance(tcA, x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = getA(tc); return ts; } @SuppressWarnings("unused") public <T extends Freezable> T[][][] getAAA(Class<T> tc) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls Class<T[] > tcA = (Class<T[] >) Array.newInstance(tc , 0).getClass(); Class<T[][]> tcAA = (Class<T[][]>) Array.newInstance(tcA, 0).getClass(); T[][][] ts = (T[][][]) Array.newInstance(tcAA, x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = getAA(tc); return ts; } public AutoBuffer putAStr(String[] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putStr(fs[i]); return this; } public String[] getAStr() { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls String[] ts = new String[x+y+z]; for( int i = x; i < x+y; ++i ) ts[i] = getStr(); return ts; } @SuppressWarnings("unused") public AutoBuffer putAAStr(String[][] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putAStr(fs[i]); return this; } @SuppressWarnings("unused") public String[][] getAAStr() { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls String[][] ts = new String[x+y+z][]; for( int i = x; i < x+y; ++i ) ts[i] = getAStr(); return ts; } // Read the smaller of _bb.remaining() and len into buf. // Return bytes read, which could be zero. int read( byte[] buf, int off, int len ) { int sz = Math.min(_bb.remaining(),len); _bb.get(buf,off,sz); return sz; } // ----------------------------------------------- // Utility functions to handle common UDP packet tasks. // Get the 1st control byte int getCtrl( ) { return getSz(1).get(0)&0xFF; } // Get the port in next 2 bytes int getPort( ) { return getSz(1+2).getChar(1); } // Get the task# in the next 4 bytes int getTask( ) { return getSz(1+2+4).getInt(1+2); } // Get the flag in the next 1 byte int getFlag( ) { return getSz(1+2+4+1).get(1+2+4); } // Set the ctrl, port, task. Ready to write more bytes afterwards AutoBuffer putUdp (UDP.udp type) { assert _bb.position() == 0; putSp(_bb.position()+1+2); _bb.put ((byte)type.ordinal()); _bb.putChar((char)H2O.H2O_PORT ); // Outgoing port is always the sender's (me) port return this; } AutoBuffer putTask(UDP.udp type, int tasknum) { return putUdp(type).put4(tasknum); } AutoBuffer putTask(int ctrl, int tasknum) { assert _bb.position() == 0; putSp(_bb.position()+1+2+4); _bb.put((byte)ctrl).putChar((char)H2O.H2O_PORT).putInt(tasknum); return this; } // ----------------------------------------------- // Utility functions to read & write arrays public boolean[] getAZ() { int len = getInt(); if (len == -1) return null; boolean[] r = new boolean[len]; for (int i=0;i<len;++i) r[i] = getZ(); return r; } public byte[] getA1( ) { //_arys++; int len = getInt(); return len == -1 ? null : getA1(len); } public byte[] getA1( int len ) { byte[] buf = MemoryManager.malloc1(len); int sofar = 0; while( sofar < len ) { int more = Math.min(_bb.remaining(), len - sofar); _bb.get(buf, sofar, more); sofar += more; if( sofar < len ) getSp(Math.min(_bb.capacity(), len-sofar)); } return buf; } public short[] getA2( ) { //_arys++; int len = getInt(); if( len == -1 ) return null; short[] buf = MemoryManager.malloc2(len); int sofar = 0; while( sofar < buf.length ) { ShortBuffer as = _bb.asShortBuffer(); int more = Math.min(as.remaining(), len - sofar); as.get(buf, sofar, more); sofar += more; _bb.position(_bb.position() + as.position()*2); if( sofar < len ) getSp(Math.min(_bb.capacity()-1, (len-sofar)*2)); } return buf; } public int[] getA4( ) { //_arys++; int len = getInt(); if( len == -1 ) return null; int[] buf = MemoryManager.malloc4(len); int sofar = 0; while( sofar < buf.length ) { IntBuffer as = _bb.asIntBuffer(); int more = Math.min(as.remaining(), len - sofar); as.get(buf, sofar, more); sofar += more; _bb.position(_bb.position() + as.position()*4); if( sofar < len ) getSp(Math.min(_bb.capacity()-3, (len-sofar)*4)); } return buf; } public float[] getA4f( ) { //_arys++; int len = getInt(); if( len == -1 ) return null; float[] buf = MemoryManager.malloc4f(len); int sofar = 0; while( sofar < buf.length ) { FloatBuffer as = _bb.asFloatBuffer(); int more = Math.min(as.remaining(), len - sofar); as.get(buf, sofar, more); sofar += more; _bb.position(_bb.position() + as.position()*4); if( sofar < len ) getSp(Math.min(_bb.capacity()-3, (len-sofar)*4)); } return buf; } public long[] getA8( ) { //_arys++; // Get the lengths of lead & trailing zero sections, and the non-zero // middle section. int x = getInt(); if( x == -1 ) return null; int y = getInt(); // Non-zero in the middle int z = y==0 ? 0 : getInt();// Trailing zeros long[] buf = MemoryManager.malloc8(x+y+z); switch( get1U() ) { // 1,2,4 or 8 for how the middle section is passed case 1: for( int i=x; i<x+y; i++ ) buf[i] = get1U(); return buf; case 2: for( int i=x; i<x+y; i++ ) buf[i] = (short)get2(); return buf; case 4: for( int i=x; i<x+y; i++ ) buf[i] = get4(); return buf; case 8: break; default: throw H2O.fail(); } int sofar = x; while( sofar < x+y ) { LongBuffer as = _bb.asLongBuffer(); int more = Math.min(as.remaining(), x+y - sofar); as.get(buf, sofar, more); sofar += more; _bb.position(_bb.position() + as.position()*8); if( sofar < x+y ) getSp(Math.min(_bb.capacity()-7, (x+y-sofar)*8)); } return buf; } public double[] getA8d( ) { //_arys++; int len = getInt(); if( len == -1 ) return null; double[] buf = MemoryManager.malloc8d(len); int sofar = 0; while( sofar < len ) { DoubleBuffer as = _bb.asDoubleBuffer(); int more = Math.min(as.remaining(), len - sofar); as.get(buf, sofar, more); sofar += more; _bb.position(_bb.position() + as.position()*8); if( sofar < len ) getSp(Math.min(_bb.capacity()-7, (len-sofar)*8)); } return buf; } @SuppressWarnings("unused") public byte[][] getAA1( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls byte[][] ary = new byte[x+y+z][]; for( int i=x; i<x+y; i++ ) ary[i] = getA1(); return ary; } @SuppressWarnings("unused") public short[][] getAA2( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls short[][] ary = new short[x+y+z][]; for( int i=x; i<x+y; i++ ) ary[i] = getA2(); return ary; } public int[][] getAA4( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls int[][] ary = new int[x+y+z][]; for( int i=x; i<x+y; i++ ) ary[i] = getA4(); return ary; } @SuppressWarnings("unused") public float[][] getAA4f( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls float[][] ary = new float[x+y+z][]; for( int i=x; i<x+y; i++ ) ary[i] = getA4f(); return ary; } public long[][] getAA8( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls long[][] ary = new long[x+y+z][]; for( int i=x; i<x+y; i++ ) ary[i] = getA8(); return ary; } @SuppressWarnings("unused") public double[][] getAA8d( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls double[][] ary = new double[x+y+z][]; for( int i=x; i<x+y; i++ ) ary[i] = getA8d(); return ary; } @SuppressWarnings("unused") public int[][][] getAAA4( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls int[][][] ary = new int[x+y+z][][]; for( int i=x; i<x+y; i++ ) ary[i] = getAA4(); return ary; } @SuppressWarnings("unused") public long[][][] getAAA8( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls long[][][] ary = new long[x+y+z][][]; for( int i=x; i<x+y; i++ ) ary[i] = getAA8(); return ary; } public double[][][] getAAA8d( ) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls double[][][] ary = new double[x+y+z][][]; for( int i=x; i<x+y; i++ ) ary[i] = getAA8d(); return ary; } public String getStr( ) { int len = getInt(); return len == -1 ? null : new String(getA1(len), UTF_8); } public <E extends Enum> E getEnum(E[] values ) { int idx = get1(); return idx == -1 ? null : values[idx]; } public AutoBuffer putAZ( boolean[] ary ) { if( ary == null ) return putInt(-1); putInt(ary.length); for (boolean anAry : ary) putZ(anAry); return this; } public AutoBuffer putA1( byte[] ary ) { //_arys++; if( ary == null ) return putInt(-1); putInt(ary.length); return putA1(ary,ary.length); } public AutoBuffer putA1( byte[] ary, int length ) { return putA1(ary,0,length); } public AutoBuffer putA1( byte[] ary, int sofar, int length ) { if (length - sofar > _bb.remaining()) expandByteBuffer(length-sofar); while( sofar < length ) { int len = Math.min(length - sofar, _bb.remaining()); _bb.put(ary, sofar, len); sofar += len; if( sofar < length ) sendPartial(); } return this; } AutoBuffer putA2( short[] ary ) { //_arys++; if( ary == null ) return putInt(-1); putInt(ary.length); if (ary.length*2 > _bb.remaining()) expandByteBuffer(ary.length*2); int sofar = 0; while( sofar < ary.length ) { ShortBuffer sb = _bb.asShortBuffer(); int len = Math.min(ary.length - sofar, sb.remaining()); sb.put(ary, sofar, len); sofar += len; _bb.position(_bb.position() + sb.position()*2); if( sofar < ary.length ) sendPartial(); } return this; } public AutoBuffer putA4( int[] ary ) { //_arys++; if( ary == null ) return putInt(-1); putInt(ary.length); // Note: based on Brandon commit this should improve performance during parse (7d950d622ee3037555ecbab0e39404f8f0917652) if (ary.length*4 > _bb.remaining()) { expandByteBuffer(ary.length*4); // Try to expand BB buffer to fit input array } int sofar = 0; while( sofar < ary.length ) { IntBuffer ib = _bb.asIntBuffer(); int len = Math.min(ary.length - sofar, ib.remaining()); ib.put(ary, sofar, len); sofar += len; _bb.position(_bb.position() + ib.position()*4); if( sofar < ary.length ) sendPartial(); } return this; } public AutoBuffer putA8( long[] ary ) { //_arys++; if( ary == null ) return putInt(-1); // Trim leading & trailing zeros. Pass along the length of leading & // trailing zero sections, and the non-zero section in the middle. int x=0; for( ; x<ary.length; x++ ) if( ary[x ]!=0 ) break; int y=ary.length; for( ; y>x; y-- ) if( ary[y-1]!=0 ) break; int nzlen = y-x; putInt(x); putInt(nzlen); if( nzlen > 0 ) // If any trailing nulls putInt(ary.length-y); // Trailing zeros // Size trim the NZ section: pass as bytes or shorts if possible. long min=Long.MAX_VALUE, max=Long.MIN_VALUE; for( int i=x; i<y; i++ ) { if( ary[i]<min ) min=ary[i]; if( ary[i]>max ) max=ary[i]; } if( 0 <= min && max < 256 ) { // Ship as unsigned bytes put1(1); for( int i=x; i<y; i++ ) put1((int)ary[i]); return this; } if( Short.MIN_VALUE <= min && max < Short.MAX_VALUE ) { // Ship as shorts put1(2); for( int i=x; i<y; i++ ) put2((short)ary[i]); return this; } if( Integer.MIN_VALUE <= min && max < Integer.MAX_VALUE ) { // Ship as ints put1(4); for( int i=x; i<y; i++ ) put4((int)ary[i]); return this; } put1(8); // Ship as full longs int sofar = x; if ((y-sofar)*8 > _bb.remaining()) expandByteBuffer(ary.length*8); while( sofar < y ) { LongBuffer lb = _bb.asLongBuffer(); int len = Math.min(y - sofar, lb.remaining()); lb.put(ary, sofar, len); sofar += len; _bb.position(_bb.position() + lb.position() * 8); if( sofar < y ) sendPartial(); } return this; } public AutoBuffer putA4f( float[] ary ) { //_arys++; if( ary == null ) return putInt(-1); putInt(ary.length); if (ary.length*4 > _bb.remaining()) expandByteBuffer(ary.length*4); int sofar = 0; while( sofar < ary.length ) { FloatBuffer fb = _bb.asFloatBuffer(); int len = Math.min(ary.length - sofar, fb.remaining()); fb.put(ary, sofar, len); sofar += len; _bb.position(_bb.position() + fb.position()*4); if( sofar < ary.length ) sendPartial(); } return this; } public AutoBuffer putA8d( double[] ary ) { //_arys++; if( ary == null ) return putInt(-1); putInt(ary.length); if (ary.length*8 > _bb.remaining()) expandByteBuffer(ary.length*8); int sofar = 0; while( sofar < ary.length ) { DoubleBuffer db = _bb.asDoubleBuffer(); int len = Math.min(ary.length - sofar, db.remaining()); db.put(ary, sofar, len); sofar += len; _bb.position(_bb.position() + db.position()*8); if( sofar < ary.length ) sendPartial(); } return this; } public AutoBuffer putAA1( byte[][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putA1(ary[i]); return this; } @SuppressWarnings("unused") AutoBuffer putAA2( short[][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putA2(ary[i]); return this; } public AutoBuffer putAA4( int[][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putA4(ary[i]); return this; } @SuppressWarnings("unused") public AutoBuffer putAA4f( float[][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putA4f(ary[i]); return this; } public AutoBuffer putAA8( long[][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putA8(ary[i]); return this; } @SuppressWarnings("unused") public AutoBuffer putAA8d( double[][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putA8d(ary[i]); return this; } public AutoBuffer putAAA4( int[][][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putAA4(ary[i]); return this; } public AutoBuffer putAAA8( long[][][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putAA8(ary[i]); return this; } public AutoBuffer putAAA8d( double[][][] ary ) { //_arys++; long xy = putZA(ary); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putAA8d(ary[i]); return this; } // Put a String as bytes (not chars!) public AutoBuffer putStr( String s ) { if( s==null ) return putInt(-1); return putA1(StringUtils.bytesOf(s)); } @SuppressWarnings("unused") public AutoBuffer putEnum( Enum x ) { return put1(x==null ? -1 : x.ordinal()); } public static byte[] javaSerializeWritePojo(Object o) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = null; try { out = new ObjectOutputStream(bos); out.writeObject(o); out.close(); return bos.toByteArray(); } catch (IOException e) { throw Log.throwErr(e); } } public static Object javaSerializeReadPojo(byte [] bytes) { try { final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object o = ois.readObject(); return o; } catch (IOException e) { String className = nameOfClass(bytes); throw Log.throwErr(new RuntimeException("Failed to deserialize " + className, e)); } catch (ClassNotFoundException e) { throw Log.throwErr(e); } } static String nameOfClass(byte[] bytes) { if (bytes == null) return "(null)"; if (bytes.length < 11) return "(no name)"; int nameSize = Math.min(40, Math.max(3, bytes[7])); return new String(bytes, 8, Math.min(nameSize, bytes.length - 8)); } // ========================================================================== // Java Serializable objects // Note: These are heck-a-lot more expensive than their Freezable equivalents. @SuppressWarnings("unused") public AutoBuffer putSer( Object obj ) { if (obj == null) return putA1(null); return putA1(javaSerializeWritePojo(obj)); } @SuppressWarnings("unused") public AutoBuffer putASer(Object[] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putSer(fs[i]); return this; } @SuppressWarnings("unused") public AutoBuffer putAASer(Object[][] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putASer(fs[i]); return this; } @SuppressWarnings("unused") public AutoBuffer putAAASer(Object[][][] fs) { //_arys++; long xy = putZA(fs); if( xy == -1 ) return this; int x=(int)(xy>>32); int y=(int)xy; for( int i=x; i<x+y; i++ ) putAASer(fs[i]); return this; } @SuppressWarnings("unused") public Object getSer() { byte[] ba = getA1(); return ba == null ? null : javaSerializeReadPojo(ba); } @SuppressWarnings("unused") public <T> T getSer(Class<T> tc) { return (T)getSer(); } @SuppressWarnings("unused") public <T> T[] getASer(Class<T> tc) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls T[] ts = (T[]) Array.newInstance(tc, x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = getSer(tc); return ts; } @SuppressWarnings("unused") public <T> T[][] getAASer(Class<T> tc) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls T[][] ts = (T[][]) Array.newInstance(tc, x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = getASer(tc); return ts; } @SuppressWarnings("unused") public <T> T[][][] getAAASer(Class<T> tc) { //_arys++; long xy = getZA(); if( xy == -1 ) return null; int x=(int)(xy>>32); // Leading nulls int y=(int)xy; // Middle non-zeros int z = y==0 ? 0 : getInt(); // Trailing nulls T[][][] ts = (T[][][]) Array.newInstance(tc, x+y+z); for( int i = x; i < x+y; ++i ) ts[i] = getAASer(tc); return ts; } // ========================================================================== // JSON AutoBuffer printers public AutoBuffer putJNULL( ) { return put1('n').put1('u').put1('l').put1('l'); } // Escaped JSON string private AutoBuffer putJStr( String s ) { byte[] b = StringUtils.bytesOf(s); int off=0; for( int i=0; i<b.length; i++ ) { if( b[i] == '\\' || b[i] == '"') { // Double up backslashes, escape quotes putA1(b,off,i); // Everything so far (no backslashes) put1('\\'); // The extra backslash off=i; // Advance the "so far" variable } // Handle remaining special cases in JSON // if( b[i] == '/' ) { putA1(b,off,i); put1('\\'); put1('/'); off=i+1; continue;} if( b[i] == '\b' ) { putA1(b,off,i); put1('\\'); put1('b'); off=i+1; continue;} if( b[i] == '\f' ) { putA1(b,off,i); put1('\\'); put1('f'); off=i+1; continue;} if( b[i] == '\n' ) { putA1(b,off,i); put1('\\'); put1('n'); off=i+1; continue;} if( b[i] == '\r' ) { putA1(b,off,i); put1('\\'); put1('r'); off=i+1; continue;} if( b[i] == '\t' ) { putA1(b,off,i); put1('\\'); put1('t'); off=i+1; continue;} // ASCII Control characters if( b[i] == 127 ) { putA1(b,off,i); put1('\\'); put1('u'); put1('0'); put1('0'); put1('7'); put1('f'); off=i+1; continue;} if( b[i] >= 0 && b[i] < 32 ) { String hexStr = Integer.toHexString(b[i]); putA1(b, off, i); put1('\\'); put1('u'); for (int j = 0; j < 4 - hexStr.length(); j++) put1('0'); for (int j = 0; j < hexStr.length(); j++) put1(hexStr.charAt(hexStr.length()-j-1)); off=i+1; } } return putA1(b,off,b.length); } public AutoBuffer putJSONStrUnquoted ( String s ) { return s==null ? putJNULL() : putJStr(s); } public AutoBuffer putJSONStrUnquoted ( String name, String s ) { return s==null ? putJSONStr(name).put1(':').putJNULL() : putJSONStr(name).put1(':').putJStr(s); } public AutoBuffer putJSONName( String s ) { return put1('"').putJStr(s).put1('"'); } public AutoBuffer putJSONStr ( String s ) { return s==null ? putJNULL() : putJSONName(s); } public AutoBuffer putJSONAStr(String[] ss) { if( ss == null ) return putJNULL(); put1('['); for( int i=0; i<ss.length; i++ ) { if( i>0 ) put1(','); putJSONStr(ss[i]); } return put1(']'); } private AutoBuffer putJSONAAStr( String[][] sss) { if( sss == null ) return putJNULL(); put1('['); for( int i=0; i<sss.length; i++ ) { if( i>0 ) put1(','); putJSONAStr(sss[i]); } return put1(']'); } @SuppressWarnings("unused") public AutoBuffer putJSONStr (String name, String s ) { return putJSONStr(name).put1(':').putJSONStr(s); } @SuppressWarnings("unused") public AutoBuffer putJSONAStr (String name, String[] ss ) { return putJSONStr(name).put1(':').putJSONAStr(ss); } @SuppressWarnings("unused") public AutoBuffer putJSONAAStr(String name, String[][]sss) { return putJSONStr(name).put1(':').putJSONAAStr(sss); } @SuppressWarnings("unused") public AutoBuffer putJSONSer (String name, Object o ) { return putJSONStr(name).put1(':').putJNULL(); } @SuppressWarnings("unused") public AutoBuffer putJSONASer (String name, Object[] oo ) { return putJSONStr(name).put1(':').putJNULL(); } @SuppressWarnings("unused") public AutoBuffer putJSONAASer (String name, Object[][] ooo ) { return putJSONStr(name).put1(':').putJNULL(); } @SuppressWarnings("unused") public AutoBuffer putJSONAAASer(String name, Object[][][] oooo) { return putJSONStr(name).put1(':').putJNULL(); } public AutoBuffer putJSONAZ( String name, boolean[] f) { return putJSONStr(name).put1(':').putJSONAZ(f); } public AutoBuffer putJSON(Freezable ice) { return ice == null ? putJNULL() : ice.writeJSON(this); } public AutoBuffer putJSONA( Freezable fs[] ) { if( fs == null ) return putJNULL(); put1('['); for( int i=0; i<fs.length; i++ ) { if( i>0 ) put1(','); putJSON(fs[i]); } return put1(']'); } public AutoBuffer putJSONAA( Freezable fs[][]) { if( fs == null ) return putJNULL(); put1('['); for( int i=0; i<fs.length; i++ ) { if( i>0 ) put1(','); putJSONA(fs[i]); } return put1(']'); } public AutoBuffer putJSONAAA( Freezable fs[][][]) { if( fs == null ) return putJNULL(); put1('['); for( int i=0; i<fs.length; i++ ) { if( i>0 ) put1(','); putJSONAA(fs[i]); } return put1(']'); } @SuppressWarnings("unused") public AutoBuffer putJSON ( String name, Freezable f ) { return putJSONStr(name).put1(':').putJSON (f); } public AutoBuffer putJSONA ( String name, Freezable f[] ) { return putJSONStr(name).put1(':').putJSONA (f); } @SuppressWarnings("unused") public AutoBuffer putJSONAA( String name, Freezable f[][]){ return putJSONStr(name).put1(':').putJSONAA(f); } @SuppressWarnings("unused") public AutoBuffer putJSONAAA( String name, Freezable f[][][]){ return putJSONStr(name).put1(':').putJSONAAA(f); } @SuppressWarnings("unused") public AutoBuffer putJSONZ( String name, boolean value ) { return putJSONStr(name).put1(':').putJStr("" + value); } private AutoBuffer putJSONAZ(boolean [] b) { if (b == null) return putJNULL(); put1('['); for( int i = 0; i < b.length; ++i) { if (i > 0) put1(','); putJStr(""+b[i]); } return put1(']'); } // Most simple integers private AutoBuffer putJInt( int i ) { byte b[] = StringUtils.toBytes(i); return putA1(b,b.length); } public AutoBuffer putJSON1( byte b ) { return putJInt(b); } public AutoBuffer putJSONA1( byte ary[] ) { if( ary == null ) return putJNULL(); put1('['); for( int i=0; i<ary.length; i++ ) { if( i>0 ) put1(','); putJSON1(ary[i]); } return put1(']'); } private AutoBuffer putJSONAA1(byte ary[][]) { if( ary == null ) return putJNULL(); put1('['); for( int i=0; i<ary.length; i++ ) { if( i>0 ) put1(','); putJSONA1(ary[i]); } return put1(']'); } @SuppressWarnings("unused") public AutoBuffer putJSON1 (String name, byte b ) { return putJSONStr(name).put1(':').putJSON1(b); } @SuppressWarnings("unused") public AutoBuffer putJSONA1 (String name, byte b[] ) { return putJSONStr(name).put1(':').putJSONA1(b); } @SuppressWarnings("unused") public AutoBuffer putJSONAA1(String name, byte b[][]) { return putJSONStr(name).put1(':').putJSONAA1(b); } public AutoBuffer putJSONAEnum(String name, Enum[] enums) { return putJSONStr(name).put1(':').putJSONAEnum(enums); } public AutoBuffer putJSONAEnum( Enum[] enums ) { if( enums == null ) return putJNULL(); put1('['); for( int i=0; i<enums.length; i++ ) { if( i>0 ) put1(','); putJSONEnum(enums[i]); } return put1(']'); } AutoBuffer putJSON2( char c ) { return putJSON4(c); } AutoBuffer putJSON2( String name, char c ) { return putJSONStr(name).put1(':').putJSON2(c); } AutoBuffer putJSON2( short c ) { return putJSON4(c); } AutoBuffer putJSON2( String name, short c ) { return putJSONStr(name).put1(':').putJSON2(c); } public AutoBuffer putJSONA2( String name, short ary[] ) { return putJSONStr(name).put1(':').putJSONA2(ary); } AutoBuffer putJSONA2( short ary[] ) { if( ary == null ) return putJNULL(); put1('['); for( int i=0; i<ary.length; i++ ) { if( i>0 ) put1(','); putJSON2(ary[i]); } return put1(']'); } AutoBuffer putJSON8 ( long l ) { return putJStr(Long.toString(l)); } AutoBuffer putJSONA8( long ary[] ) { if( ary == null ) return putJNULL(); put1('['); for( int i=0; i<ary.length; i++ ) { if( i>0 ) put1(','); putJSON8(ary[i]); } return put1(']'); } AutoBuffer putJSONAA8( long ary[][] ) { if( ary == null ) return putJNULL(); put1('['); for( int i=0; i<ary.length; i++ ) { if( i>0 ) put1(','); putJSONA8(ary[i]); } return put1(']'); } AutoBuffer putJSONAAA8( long ary[][][] ) { if( ary == null ) return putJNULL(); put1('['); for( int i=0; i<ary.length; i++ ) { if( i>0 ) put1(','); putJSONAA8(ary[i]); } return put1(']'); } AutoBuffer putJSONEnum( Enum e ) { return e==null ? putJNULL() : put1('"').putJStr(e.toString()).put1('"'); } public AutoBuffer putJSON8 ( String name, long l ) { return putJSONStr(name).put1(':').putJSON8(l); } public AutoBuffer putJSONEnum( String name, Enum e ) { return putJSONStr(name).put1(':').putJSONEnum(e); } public AutoBuffer putJSONA8( String name, long ary[] ) { return putJSONStr(name).put1(':').putJSONA8(ary); } public AutoBuffer putJSONAA8( String name, long ary[][] ) { return putJSONStr(name).put1(':').putJSONAA8(ary); } public AutoBuffer putJSONAAA8( String name, long ary[][][] ) { return putJSONStr(name).put1(':').putJSONAAA8(ary); } public AutoBuffer putJSON4(int i) { return putJStr(Integer.toString(i)); } AutoBuffer putJSONA4( int[] a) { if( a == null ) return putJNULL(); put1('['); for( int i=0; i<a.length; i++ ) { if( i>0 ) put1(','); putJSON4(a[i]); } return put1(']'); } AutoBuffer putJSONAA4( int[][] a ) { if( a == null ) return putJNULL();<|fim▁hole|> if( i>0 ) put1(','); putJSONA4(a[i]); } return put1(']'); } AutoBuffer putJSONAAA4( int[][][] a ) { if( a == null ) return putJNULL(); put1('['); for( int i=0; i<a.length; i++ ) { if( i>0 ) put1(','); putJSONAA4(a[i]); } return put1(']'); } public AutoBuffer putJSON4 ( String name, int i ) { return putJSONStr(name).put1(':').putJSON4(i); } public AutoBuffer putJSONA4( String name, int[] a) { return putJSONStr(name).put1(':').putJSONA4(a); } public AutoBuffer putJSONAA4( String name, int[][] a ) { return putJSONStr(name).put1(':').putJSONAA4(a); } public AutoBuffer putJSONAAA4( String name, int[][][] a ) { return putJSONStr(name).put1(':').putJSONAAA4(a); } AutoBuffer putJSON4f ( float f ) { return f==Float.POSITIVE_INFINITY?putJSONStr(JSON_POS_INF):(f==Float.NEGATIVE_INFINITY?putJSONStr(JSON_NEG_INF):(Float.isNaN(f)?putJSONStr(JSON_NAN):putJStr(Float .toString(f)))); } public AutoBuffer putJSON4f ( String name, float f ) { return putJSONStr(name).put1(':').putJSON4f(f); } AutoBuffer putJSONA4f( float[] a ) { if( a == null ) return putJNULL(); put1('['); for( int i=0; i<a.length; i++ ) { if( i>0 ) put1(','); putJSON4f(a[i]); } return put1(']'); } public AutoBuffer putJSONA4f(String name, float[] a) { putJSONStr(name).put1(':'); return putJSONA4f(a); } AutoBuffer putJSONAA4f(String name, float[][] a) { putJSONStr(name).put1(':'); if( a == null ) return putJNULL(); put1('['); for( int i=0; i<a.length; i++ ) { if( i>0 ) put1(','); putJSONA4f(a[i]); } return put1(']'); } AutoBuffer putJSON8d( double d ) { if (TwoDimTable.isEmpty(d)) return putJNULL(); return d==Double.POSITIVE_INFINITY?putJSONStr(JSON_POS_INF):(d==Double.NEGATIVE_INFINITY?putJSONStr(JSON_NEG_INF):(Double.isNaN(d)?putJSONStr(JSON_NAN):putJStr(Double.toString(d)))); } public AutoBuffer putJSON8d( String name, double d ) { return putJSONStr(name).put1(':').putJSON8d(d); } public AutoBuffer putJSONA8d( String name, double[] a ) { return putJSONStr(name).put1(':').putJSONA8d(a); } public AutoBuffer putJSONAA8d( String name, double[][] a) { return putJSONStr(name).put1(':').putJSONAA8d(a); } public AutoBuffer putJSONAAA8d( String name, double[][][] a) { return putJSONStr(name).put1(':').putJSONAAA8d(a); } public AutoBuffer putJSONA8d( double[] a ) { if( a == null ) return putJNULL(); put1('['); for( int i=0; i<a.length; i++ ) { if( i>0 ) put1(','); putJSON8d(a[i]); } return put1(']'); } public AutoBuffer putJSONAA8d( double[][] a ) { if( a == null ) return putJNULL(); put1('['); for( int i=0; i<a.length; i++ ) { if( i>0 ) put1(','); putJSONA8d(a[i]); } return put1(']'); } AutoBuffer putJSONAAA8d( double ary[][][] ) { if( ary == null ) return putJNULL(); put1('['); for( int i=0; i<ary.length; i++ ) { if( i>0 ) put1(','); putJSONAA8d(ary[i]); } return put1(']'); } static final String JSON_NAN = "NaN"; static final String JSON_POS_INF = "Infinity"; static final String JSON_NEG_INF = "-Infinity"; }<|fim▁end|>
put1('['); for( int i=0; i<a.length; i++ ) {
<|file_name|>comm.py<|end_file_name|><|fim▁begin|>import urllib2 import json import time import threading import Queue from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR class CommBase(object): def __init__(self): self.agents = [] def add_agent(self, agent): self.agents.append(agent) class HTTPComm(CommBase): def __init__(self, config, url = 'http://localhost:8080/messages'): super(HTTPComm, self).__init__() self.config = config self.lastpoll = -1 self.url = url self.own_msgids = set() def post_message(self, content): msgid = make_random_id() content['msgid'] = msgid self.own_msgids.add(msgid) LOGDEBUG( "----- POSTING MESSAGE ----") data = json.dumps(content) LOGDEBUG(data) u = urllib2.urlopen(self.url, data) return u.read() == 'Success' def poll_and_dispatch(self): url = self.url if self.lastpoll == -1: url = url + "?from_timestamp_rel=%s" % self.config['offer_expiry_interval'] else: url = url + '?from_serial=%s' % (self.lastpoll+1) print (url) u = urllib2.urlopen(url) resp = json.loads(u.read()) for x in resp: if int(x.get('serial',0)) > self.lastpoll: self.lastpoll = int(x.get('serial',0)) content = x.get('content',None) if content and not content.get('msgid', '') in self.own_msgids: for a in self.agents: a.dispatch_message(content) <|fim▁hole|> self.tc = tc def dispatch_message(self, content): self.tc.receive_queue.put(content) def __init__(self, upstream_comm): super(ThreadedComm, self).__init__() self.upstream_comm = upstream_comm self.send_queue = Queue.Queue() self.receive_queue = Queue.Queue() self.comm_thread = CommThread(self, upstream_comm) upstream_comm.add_agent(self.AgentProxy(self)) def post_message(self, content): self.send_queue.put(content) def poll_and_dispatch(self): while not self.receive_queue.empty(): content = self.receive_queue.get() for a in self.agents: a.dispatch_message(content) def start(self): self.comm_thread.start() def stop(self): self.comm_thread.stop() self.comm_thread.join() class CommThread(threading.Thread): def __init__(self, threaded_comm, upstream_comm): threading.Thread.__init__(self) self._stop = threading.Event() self.threaded_comm = threaded_comm self.upstream_comm = upstream_comm def run(self): send_queue = self.threaded_comm.send_queue receive_queue = self.threaded_comm.receive_queue while not self._stop.is_set(): while not send_queue.empty(): self.upstream_comm.post_message(send_queue.get()) self.upstream_comm.poll_and_dispatch() time.sleep(1) def stop(self): self._stop.set()<|fim▁end|>
class ThreadedComm(CommBase): class AgentProxy(object): def __init__(self, tc):
<|file_name|>http-testing.umd.js<|end_file_name|><|fim▁begin|>/** * @license Angular v6.1.10 * (c) 2010-2018 Google, Inc. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/http'), require('rxjs'), require('rxjs/operators')) : typeof define === 'function' && define.amd ? define('@angular/http/testing', ['exports', '@angular/core', '@angular/http', 'rxjs', 'rxjs/operators'], factory) : (factory((global.ng = global.ng || {}, global.ng.http = global.ng.http || {}, global.ng.http.testing = {}),global.ng.core,global.ng.http,global.rxjs,global.rxjs.operators)); }(this, (function (exports,core,http,rxjs,operators) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, <|fim▁hole|> See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * * Mock Connection to represent a {@link Connection} for tests. * * @usageNotes * ### Example of `mockRespond()` * * ``` * var connection; * backend.connections.subscribe(c => connection = c); * http.request('data.json').subscribe(res => console.log(res.text())); * connection.mockRespond(new Response(new ResponseOptions({ body: 'fake response' }))); //logs * 'fake response' * ``` * * ### Example of `mockError()` * * ``` * var connection; * backend.connections.subscribe(c => connection = c); * http.request('data.json').subscribe(res => res, err => console.log(err))); * connection.mockError(new Error('error')); * ``` * * @deprecated see https://angular.io/guide/http */ var MockConnection = /** @class */ (function () { function MockConnection(req) { this.response = new rxjs.ReplaySubject(1).pipe(operators.take(1)); this.readyState = http.ReadyState.Open; this.request = req; } /** * Sends a mock response to the connection. This response is the value that is emitted to the * {@link EventEmitter} returned by {@link Http}. * */ MockConnection.prototype.mockRespond = function (res) { if (this.readyState === http.ReadyState.Done || this.readyState === http.ReadyState.Cancelled) { throw new Error('Connection has already been resolved'); } this.readyState = http.ReadyState.Done; this.response.next(res); this.response.complete(); }; /** * Not yet implemented! * * Sends the provided {@link Response} to the `downloadObserver` of the `Request` * associated with this connection. */ MockConnection.prototype.mockDownload = function (res) { // this.request.downloadObserver.onNext(res); // if (res.bytesLoaded === res.totalBytes) { // this.request.downloadObserver.onCompleted(); // } }; // TODO(jeffbcross): consider using Response type /** * Emits the provided error object as an error to the {@link Response} {@link EventEmitter} * returned * from {@link Http}. * */ MockConnection.prototype.mockError = function (err) { // Matches ResourceLoader semantics this.readyState = http.ReadyState.Done; this.response.error(err); }; return MockConnection; }()); /** * A mock backend for testing the {@link Http} service. * * This class can be injected in tests, and should be used to override providers * to other backends, such as {@link XHRBackend}. * * @usageNotes * ### Example * * ``` * import {Injectable, Injector} from '@angular/core'; * import {async, fakeAsync, tick} from '@angular/core/testing'; * import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http'; * import {Response, ResponseOptions} from '@angular/http'; * import {MockBackend, MockConnection} from '@angular/http/testing'; * * const HERO_ONE = 'HeroNrOne'; * const HERO_TWO = 'WillBeAlwaysTheSecond'; * * @Injectable() * class HeroService { * constructor(private http: Http) {} * * getHeroes(): Promise<String[]> { * return this.http.get('myservices.de/api/heroes') * .toPromise() * .then(response => response.json().data) * .catch(e => this.handleError(e)); * } * * private handleError(error: any): Promise<any> { * console.error('An error occurred', error); * return Promise.reject(error.message || error); * } * } * * describe('MockBackend HeroService Example', () => { * beforeEach(() => { * this.injector = Injector.create([ * {provide: ConnectionBackend, useClass: MockBackend}, * {provide: RequestOptions, useClass: BaseRequestOptions}, * Http, * HeroService, * ]); * this.heroService = this.injector.get(HeroService); * this.backend = this.injector.get(ConnectionBackend) as MockBackend; * this.backend.connections.subscribe((connection: any) => this.lastConnection = connection); * }); * * it('getHeroes() should query current service url', () => { * this.heroService.getHeroes(); * expect(this.lastConnection).toBeDefined('no http service connection at all?'); * expect(this.lastConnection.request.url).toMatch(/api\/heroes$/, 'url invalid'); * }); * * it('getHeroes() should return some heroes', fakeAsync(() => { * let result: String[]; * this.heroService.getHeroes().then((heroes: String[]) => result = heroes); * this.lastConnection.mockRespond(new Response(new ResponseOptions({ * body: JSON.stringify({data: [HERO_ONE, HERO_TWO]}), * }))); * tick(); * expect(result.length).toEqual(2, 'should contain given amount of heroes'); * expect(result[0]).toEqual(HERO_ONE, ' HERO_ONE should be the first hero'); * expect(result[1]).toEqual(HERO_TWO, ' HERO_TWO should be the second hero'); * })); * * it('getHeroes() while server is down', fakeAsync(() => { * let result: String[]; * let catchedError: any; * this.heroService.getHeroes() * .then((heroes: String[]) => result = heroes) * .catch((error: any) => catchedError = error); * this.lastConnection.mockError(new Response(new ResponseOptions({ * status: 404, * statusText: 'URL not Found', * }))); * tick(); * expect(result).toBeUndefined(); * expect(catchedError).toBeDefined(); * })); * }); * ``` * * @deprecated see https://angular.io/guide/http */ var MockBackend = /** @class */ (function () { function MockBackend() { var _this = this; this.connectionsArray = []; this.connections = new rxjs.Subject(); this.connections.subscribe(function (connection) { return _this.connectionsArray.push(connection); }); this.pendingConnections = new rxjs.Subject(); } /** * Checks all connections, and raises an exception if any connection has not received a response. * * This method only exists in the mock implementation, not in real Backends. */ MockBackend.prototype.verifyNoPendingRequests = function () { var pending = 0; this.pendingConnections.subscribe(function (c) { return pending++; }); if (pending > 0) throw new Error(pending + " pending connections to be resolved"); }; /** * Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve * connections, if it's expected that there are connections that have not yet received a response. * * This method only exists in the mock implementation, not in real Backends. */ MockBackend.prototype.resolveAllConnections = function () { this.connections.subscribe(function (c) { return c.readyState = 4; }); }; /** * Creates a new {@link MockConnection}. This is equivalent to calling `new * MockConnection()`, except that it also will emit the new `Connection` to the `connections` * emitter of this `MockBackend` instance. This method will usually only be used by tests * against the framework itself, not by end-users. */ MockBackend.prototype.createConnection = function (req) { if (!req || !(req instanceof http.Request)) { throw new Error("createConnection requires an instance of Request, got " + req); } var connection = new MockConnection(req); this.connections.next(connection); return connection; }; MockBackend = __decorate([ core.Injectable(), __metadata("design:paramtypes", []) ], MockBackend); return MockBackend; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Generated bundle index. Do not edit. */ exports.MockConnection = MockConnection; exports.MockBackend = MockBackend; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=http-testing.umd.js.map<|fim▁end|>
MERCHANTABLITY OR NON-INFRINGEMENT.
<|file_name|>comment4.rs<|end_file_name|><|fim▁begin|>// rustfmt-normalise_comments: false //! Doc comment fn test() { // comment // comment2 code(); /* leave this comment alone! * ok? */ /* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a * diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam * viverra nec consectetur ante hendrerit. Donec et mollis dolor. * Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam * tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut * libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit * amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis * felis, pulvinar a semper sed, adipiscing id dolor. */ // Very looooooooooooooooooooooooooooooooooooooooooooooooooooooooong comment that should be split // println!("{:?}", rewrite_comment(subslice, // false, // comment_width, // self.block_indent, // self.config) // .unwrap());<|fim▁hole|> funk(); //dontchangeme // or me } /// test123 fn doc_comment() { }<|fim▁end|>
<|file_name|>storageos_util_test.go<|end_file_name|><|fim▁begin|>/* Copyright 2017 The Kubernetes 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 storageos import ( "fmt" "os" storageostypes "github.com/storageos/go-api/types" utiltesting "k8s.io/client-go/util/testing" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" "testing" ) var testApiSecretName = "storageos-api" var testVolName = "storageos-test-vol" var testPVName = "storageos-test-pv" var testNamespace = "storageos-test-namespace" var testSize = 1<|fim▁hole|>var testVolUUID = "01c43d34-89f8-83d3-422b-43536a0f25e6" type fakeConfig struct { apiAddr string apiUser string apiPass string apiVersion string } func (c fakeConfig) GetAPIConfig() *storageosAPIConfig { return &storageosAPIConfig{ apiAddr: "http://5.6.7.8:9999", apiUser: "abc", apiPass: "123", apiVersion: "10", } } func TestClient(t *testing.T) { util := storageosUtil{} cfg := fakeConfig{} err := util.NewAPI(cfg.GetAPIConfig()) if err != nil { t.Fatalf("error getting api config: %v", err) } if util.api == nil { t.Errorf("client() unexpectedly returned nil") } } type fakeAPI struct{} func (f fakeAPI) Volume(namespace string, ref string) (*storageostypes.Volume, error) { if namespace == testNamespace && ref == testVolName { return &storageostypes.Volume{ ID: "01c43d34-89f8-83d3-422b-43536a0f25e6", Name: ref, Pool: "default", Namespace: namespace, Size: 5, }, nil } return nil, fmt.Errorf("not found") } func (f fakeAPI) VolumeCreate(opts storageostypes.VolumeCreateOptions) (*storageostypes.Volume, error) { // Append a label from the api labels := opts.Labels labels["labelfromapi"] = "apilabel" return &storageostypes.Volume{ ID: testVolUUID, Name: opts.Name, Namespace: opts.Namespace, Description: opts.Description, Pool: opts.Pool, Size: opts.Size, FSType: opts.FSType, Labels: labels, }, nil } func (f fakeAPI) VolumeMount(opts storageostypes.VolumeMountOptions) error { return nil } func (f fakeAPI) VolumeUnmount(opts storageostypes.VolumeUnmountOptions) error { return nil } func (f fakeAPI) VolumeDelete(opts storageostypes.DeleteOptions) error { return nil } func TestCreateVolume(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("storageos_test") if err != nil { t.Fatalf("can't make a temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) plug, _ := plugMgr.FindPluginByName("kubernetes.io/storageos") // Use real util with stubbed api util := &storageosUtil{} util.api = fakeAPI{} labels := map[string]string{ "labelA": "valueA", "labelB": "valueB", } options := volume.VolumeOptions{ PVName: testPVName, PVC: volumetest.CreateTestPVC(fmt.Sprintf("%dGi", testSize), []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner := &storageosProvisioner{ storageosMounter: &storageosMounter{ storageos: &storageos{ pvName: testPVName, volName: testVolName, volNamespace: testNamespace, sizeGB: testSize, pool: testPool, description: testDesc, fsType: testFSType, labels: labels, manager: util, plugin: plug.(*storageosPlugin), }, }, options: options, } vol, err := util.CreateVolume(provisioner) if err != nil { t.Errorf("CreateVolume() returned error: %v", err) } if vol == nil { t.Fatalf("CreateVolume() vol is empty") } if vol.ID == "" { t.Error("CreateVolume() vol ID is empty") } if vol.Name != testVolName { t.Errorf("CreateVolume() returned unexpected Name %s", vol.Name) } if vol.Namespace != testNamespace { t.Errorf("CreateVolume() returned unexpected Namespace %s", vol.Namespace) } if vol.Pool != testPool { t.Errorf("CreateVolume() returned unexpected Pool %s", vol.Pool) } if vol.FSType != testFSType { t.Errorf("CreateVolume() returned unexpected FSType %s", vol.FSType) } if vol.SizeGB != testSize { t.Errorf("CreateVolume() returned unexpected Size %d", vol.SizeGB) } if len(vol.Labels) == 0 { t.Error("CreateVolume() Labels are empty") } else { for k, v := range labels { var val string var ok bool if val, ok = vol.Labels[k]; !ok { t.Errorf("CreateVolume() Label %s not set", k) } if val != v { t.Errorf("CreateVolume() returned unexpected Label value %s", val) } } var val string var ok bool if val, ok = vol.Labels["labelfromapi"]; !ok { t.Error("CreateVolume() Label from api not set") } if val != "apilabel" { t.Errorf("CreateVolume() returned unexpected Label value %s", val) } } } func TestAttachVolume(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("storageos_test") if err != nil { t.Fatalf("can't make a temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) plug, _ := plugMgr.FindPluginByName("kubernetes.io/storageos") // Use real util with stubbed api util := &storageosUtil{} util.api = fakeAPI{} mounter := &storageosMounter{ storageos: &storageos{ volName: testVolName, volNamespace: testNamespace, manager: util, mounter: &mount.FakeMounter{}, plugin: plug.(*storageosPlugin), }, devicePath: tmpDir, } if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Errorf("Got a nil Mounter") } }<|fim▁end|>
var testDesc = "testdescription" var testPool = "testpool" var testFSType = "ext2"
<|file_name|>query_directives.js<|end_file_name|><|fim▁begin|>(function() { 'use strict' function queryLink() { return { restrict: 'E', scope: { 'query': '=', 'visualization': '=?' }, template: '<a ng-href="{{link}}" class="query-link">{{query.displayname}}</a>', link: function(scope, element) { var hash = null; if (scope.visualization) { if (scope.visualization.type === 'TABLE') { // link to hard-coded table tab instead of the (hidden) visualization tab hash = 'table'; } else { hash = scope.visualization.id; } } scope.link = scope.query.getUrl(false, hash); } } } function querySourceLink($location) { return { restrict: 'E', template: '<span ng-show="query.id && canViewSource">\ <a ng-show="!sourceMode"\ ng-href="{{query.getUrl(true, selectedTab)}}" class="btn btn-default">Show Source\ </a>\ <a ng-show="sourceMode"\ ng-href="{{query.getUrl(false, selectedTab)}}" class="btn btn-default">Hide Source\ </a>\ </span>' } } function queryResultLink() { return { restrict: 'A', link: function (scope, element, attrs) { var fileType = attrs.fileType ? attrs.fileType : "csv"; scope.$watch('queryResult && queryResult.getData()', function(data) { if (!data) { return; } if (scope.queryResult.getId() == null) { element.attr('href', ''); } else { element.attr('href', 'api/queries/' + scope.query.id + '/results/' + scope.queryResult.getId() + '.' + fileType); element.attr('download', scope.query.name.replace(" ", "_") + moment(scope.queryResult.getUpdatedAt()).format("_YYYY_MM_DD") + "." + fileType); } }); } } } // By default Ace will try to load snippet files for the different modes and fail. We don't need them, so we use these // placeholders until we define our own. function defineDummySnippets(mode) { ace.define("ace/snippets/" + mode, ["require", "exports", "module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = mode; }); }; defineDummySnippets("python"); defineDummySnippets("sql"); defineDummySnippets("json"); function queryEditor(QuerySnippet) { return { restrict: 'E', scope: { 'query': '=', 'lock': '=', 'schema': '=', 'syntax': '=' }, template: '<div ui-ace="editorOptions" ng-model="query.query"></div>', link: { pre: function ($scope, element) { $scope.syntax = $scope.syntax || 'sql'; $scope.editorOptions = { mode: 'json', require: ['ace/ext/language_tools'], advanced: { behavioursEnabled: true, enableSnippets: true, enableBasicAutocompletion: true, enableLiveAutocompletion: true, autoScrollEditorIntoView: true, }, onLoad: function(editor) { QuerySnippet.query(function(snippets) { var snippetManager = ace.require("ace/snippets").snippetManager; var m = { snippetText: '' }; m.snippets = snippetManager.parseSnippetFile(m.snippetText); _.each(snippets, function(snippet) { m.snippets.push(snippet.getSnippet()); }); snippetManager.register(m.snippets || [], m.scope); }); editor.$blockScrolling = Infinity; editor.getSession().setUseWrapMode(true); editor.setShowPrintMargin(false); $scope.$watch('syntax', function(syntax) { var newMode = 'ace/mode/' + syntax; editor.getSession().setMode(newMode); }); $scope.$watch('schema', function(newSchema, oldSchema) { if (newSchema !== oldSchema) { var tokensCount = _.reduce(newSchema, function(totalLength, table) { return totalLength + table.columns.length }, 0); // If there are too many tokens we disable live autocomplete, as it makes typing slower. if (tokensCount > 5000) { editor.setOption('enableLiveAutocompletion', false); } else { editor.setOption('enableLiveAutocompletion', true); } } }); $scope.$parent.$on("angular-resizable.resizing", function (event, args) { editor.resize(); }); editor.focus(); } }; var langTools = ace.require("ace/ext/language_tools"); var schemaCompleter = { getCompletions: function(state, session, pos, prefix, callback) { if (prefix.length === 0 || !$scope.schema) { callback(null, []); return; } if (!$scope.schema.keywords) { var keywords = {}; _.each($scope.schema, function (table) { keywords[table.name] = 'Table'; _.each(table.columns, function (c) { keywords[c] = 'Column'; keywords[table.name + "." + c] = 'Column'; }); }); $scope.schema.keywords = _.map(keywords, function(v, k) { return { name: k, value: k, score: 0, meta: v }; }); } callback(null, $scope.schema.keywords); } }; langTools.addCompleter(schemaCompleter); } } }; } function queryFormatter($http, growl) { return { restrict: 'E', // don't create new scope to avoid ui-codemirror bug // seehttps://github.com/angular-ui/ui-codemirror/pull/37 scope: false, template: '<button type="button" class="btn btn-default btn-s"\ ng-click="formatQuery()">\ <span class="zmdi zmdi-format-indent-increase"></span>\ Format Query\ </button>', link: function($scope) { $scope.formatQuery = function formatQuery() { if ($scope.dataSource.syntax == 'json') { try { $scope.query.query = JSON.stringify(JSON.parse($scope.query.query), ' ', 4); } catch(err) { growl.addErrorMessage(err); } } else if ($scope.dataSource.syntax =='sql') { $scope.queryFormatting = true; $http.post('api/queries/format', { 'query': $scope.query.query }).success(function (response) { $scope.query.query = response; }).finally(function () { $scope.queryFormatting = false; }); } else { growl.addInfoMessage("Query formatting is not supported for your data source syntax."); } }; } } } function schemaBrowser() { return { restrict: 'E', scope: { schema: '=' }, templateUrl: '/views/directives/schema_browser.html', link: function ($scope) { $scope.showTable = function(table) { table.collapsed = !table.collapsed; $scope.$broadcast('vsRepeatTrigger'); } $scope.getSize = function(table) { var size = 18; if (!table.collapsed) { size += 18 * table.columns.length; } return size; } } } } function queryTimePicker() { return { restrict: 'E', template: '<select ng-disabled="refreshType != \'daily\'" ng-model="hour" ng-change="updateSchedule()" ng-options="c as c for c in hourOptions"></select> :\ <select ng-disabled="refreshType != \'daily\'" ng-model="minute" ng-change="updateSchedule()" ng-options="c as c for c in minuteOptions"></select>', link: function($scope) { var padWithZeros = function(size, v) { v = String(v); if (v.length < size) { v = "0" + v; } return v; }; <|fim▁hole|> $scope.hourOptions = _.map(_.range(0, 24), _.partial(padWithZeros, 2)); $scope.minuteOptions = _.map(_.range(0, 60, 5), _.partial(padWithZeros, 2)); if ($scope.query.hasDailySchedule()) { var parts = $scope.query.scheduleInLocalTime().split(':'); $scope.minute = parts[1]; $scope.hour = parts[0]; } else { $scope.minute = "15"; $scope.hour = "00"; } $scope.updateSchedule = function() { var newSchedule = moment().hour($scope.hour).minute($scope.minute).utc().format('HH:mm'); if (newSchedule != $scope.query.schedule) { $scope.query.schedule = newSchedule; $scope.saveQuery(); } }; $scope.$watch('refreshType', function() { if ($scope.refreshType == 'daily') { $scope.updateSchedule(); } }); } } } function queryRefreshSelect() { return { restrict: 'E', template: '<select\ ng-disabled="refreshType != \'periodic\'"\ ng-model="query.schedule"\ ng-change="saveQuery()"\ ng-options="c.value as c.name for c in refreshOptions">\ <option value="">No Refresh</option>\ </select>', link: function($scope) { $scope.refreshOptions = [ { value: "60", name: '每分钟' } ]; _.each([5, 10, 15, 30], function(i) { $scope.refreshOptions.push({ value: String(i*60), name: "每" + i + "分钟" }) }); _.each(_.range(1, 13), function (i) { $scope.refreshOptions.push({ value: String(i * 3600), name: '每' + i + '小时' }); }) $scope.refreshOptions.push({ value: String(24 * 3600), name: '每24小时' }); $scope.refreshOptions.push({ value: String(7 * 24 * 3600), name: '每7天' }); $scope.refreshOptions.push({ value: String(14 * 24 * 3600), name: '每14天' }); $scope.refreshOptions.push({ value: String(30 * 24 * 3600), name: '每30天' }); $scope.$watch('refreshType', function() { if ($scope.refreshType == 'periodic') { if ($scope.query.hasDailySchedule()) { $scope.query.schedule = null; $scope.saveQuery(); } } }); } } } angular.module('redash.directives') .directive('queryLink', queryLink) .directive('querySourceLink', ['$location', querySourceLink]) .directive('queryResultLink', queryResultLink) .directive('queryEditor', ['QuerySnippet', queryEditor]) .directive('queryRefreshSelect', queryRefreshSelect) .directive('queryTimePicker', queryTimePicker) .directive('schemaBrowser', schemaBrowser) .directive('queryFormatter', ['$http', 'growl', queryFormatter]); })();<|fim▁end|>
<|file_name|>set_select.js<|end_file_name|><|fim▁begin|>function Controller() { function closeModal(e) { $.modal.fireEvent("removeClose", e); } function handleTableViewClick(e) { if (1 == Alloy.Globals.purchases[e.index] || 1 == Alloy.Globals.purchases[1]) { for (var i = 0; $.tv.data[0].rows.length > i; i++) $.tv.data[0].rows[i].hasCheck = false; for (var i = 0; $.tv.data[1].rows.length > i; i++) $.tv.data[1].rows[i].hasCheck = false; e.row.hasCheck = true; Ti.API.info(" e.index: " + e.index); settings.set({ question_set: e.index }); settings.save(); } else alert("You must purchase this item before being able to select it"); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "set_select"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; var __defers = {}; $.__views.modal = Ti.UI.createWindow(function() { var o = {}; _.extend(o, {}); Alloy.isTablet && _.extend(o, { width: "100%", height: "90%", borderRadius: 5, top: 0, backgroundColor: "#eeeeee" }); _.extend(o, {}); Alloy.isHandheld && _.extend(o, { backgroundColor: "#f1f1f1" }); _.extend(o, { id: "modal", navBarHidden: "true" }); return o; }()); $.__views.modal && $.addTopLevelView($.__views.modal); $.__views.vertical = Ti.UI.createView({ id: "vertical" }); $.__views.modal.add($.__views.vertical); $.__views.header = Ti.UI.createView(function() { var o = {}; _.extend(o, { top: 0, backgroundColor: "#1b4fb4" }); Alloy.isTablet && _.extend(o, { height: 60, backgroundColor: "#1b4fb4" }); _.extend(o, {}); Alloy.isHandheld && _.extend(o, { height: 45 }); _.extend(o, { id: "header" }); return o; }()); $.__views.vertical.add($.__views.header); $.__views.title = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { font: { fontSize: 21, fontFamily: "AvenirLTStd-Medium" }, color: "#fff" }); Alloy.isTablet && _.extend(o, { font: { fontSize: 30, fontFamily: "AvenirLTStd-Medium" }, color: "#fff" }); _.extend(o, { text: "Question Set", id: "title" }); return o; }()); $.__views.header.add($.__views.title); $.__views.settings_back_btn = Alloy.createController("settings_back_btn", { id: "settings_back_btn", __parentSymbol: $.__views.header }); $.__views.settings_back_btn.setParent($.__views.header); closeModal ? $.__views.settings_back_btn.on("click", closeModal) : __defers["$.__views.settings_back_btn!click!closeModal"] = true; $.__views.scrollView = Ti.UI.createScrollView(function() { var o = {}; _.extend(o, { layout: "vertical", top: 45, bottom: 0 }); Alloy.isTablet && _.extend(o, { layout: "vertical", top: 80, width: "100%", height: "90%", bottom: 0 }); _.extend(o, { id: "scrollView", showVerticalScrollIndicator: "true" }); return o; }()); $.__views.vertical.add($.__views.scrollView); $.__views.description = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { font: { fontSize: 14, fontFamily: "AvenirLTStd-Roman" }, color: "#222222", left: 10, right: 10, top: 10 }); Alloy.isTablet && _.extend(o, { font: { fontSize: 25, fontFamily: "AvenirLTStd-Roman" }, color: "#222222", left: 10, right: 10, top: 10 }); _.extend(o, { text: "Choose where your questions will come from.\n\nThe starter and full sets have questions from every topic. You can also choose to study just one subject if you’ve purchased it.", id: "description" }); return o; }()); $.__views.scrollView.add($.__views.description); $.__views.page_title = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222", left: 10, right: 10, top: 10 }); Alloy.isTablet && _.extend(o, { font: { fontSize: 25, fontFamily: "AvenirLTStd-Black" }, color: "#222222", left: 10, right: 10, top: 10 }); _.extend(o, { text: "Question Sets", id: "page_title" }); return o; }()); $.__views.scrollView.add($.__views.page_title); $.__views.__alloyId170 = Ti.UI.createTableViewSection({ id: "__alloyId170" }); var __alloyId171 = []; __alloyId171.push($.__views.__alloyId170); $.__views.__alloyId172 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 60 }); Alloy.isTablet && _.extend(o, { height: 100 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId172" }); return o; }()); $.__views.__alloyId170.add($.__views.__alloyId172); $.__views.__alloyId173 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId173" }); $.__views.__alloyId172.add($.__views.__alloyId173); $.__views.__alloyId174 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId174" }); $.__views.__alloyId173.add($.__views.__alloyId174); $.__views.__alloyId175 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Starter Set", id: "__alloyId175" }); return o; }()); $.__views.__alloyId174.add($.__views.__alloyId175); $.__views.__alloyId176 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 14, fontFamily: "AvenirLTStd-Roman" }, color: "#666666" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 25, fontFamily: "AvenirLTStd-Roman" }, color: "#666666" }); _.extend(o, { text: "A sample set from every subject", id: "__alloyId176" }); return o; }()); $.__views.__alloyId174.add($.__views.__alloyId176); $.__views.__alloyId177 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 60 }); Alloy.isTablet && _.extend(o, { height: 100 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId177" }); return o; }()); $.__views.__alloyId170.add($.__views.__alloyId177); $.__views.__alloyId178 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId178" }); $.__views.__alloyId177.add($.__views.__alloyId178); $.__views.__alloyId179 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId179" }); $.__views.__alloyId178.add($.__views.__alloyId179); $.__views.__alloyId180 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Full Set", id: "__alloyId180" }); return o; }()); $.__views.__alloyId179.add($.__views.__alloyId180); $.__views.__alloyId181 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 14, fontFamily: "AvenirLTStd-Roman" }, color: "#666666" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 25, fontFamily: "AvenirLTStd-Roman" }, color: "#666666" }); _.extend(o, { text: "All the blocks at a discount", id: "__alloyId181" }); return o; }()); $.__views.__alloyId179.add($.__views.__alloyId181); $.__views.__alloyId182 = Ti.UI.createTableViewSection({ id: "__alloyId182" }); __alloyId171.push($.__views.__alloyId182); $.__views.__alloyId183 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 45 }); Alloy.isTablet && _.extend(o, { height: 90 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId183" }); return o; }()); $.__views.__alloyId182.add($.__views.__alloyId183); $.__views.__alloyId184 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId184" }); $.__views.__alloyId183.add($.__views.__alloyId184); $.__views.__alloyId185 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId185" }); $.__views.__alloyId184.add($.__views.__alloyId185); $.__views.__alloyId186 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Block A", id: "__alloyId186" }); return o; }()); $.__views.__alloyId185.add($.__views.__alloyId186); $.__views.__alloyId187 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 45 }); Alloy.isTablet && _.extend(o, { height: 90 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId187" }); return o; }()); $.__views.__alloyId182.add($.__views.__alloyId187); $.__views.__alloyId188 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId188" }); $.__views.__alloyId187.add($.__views.__alloyId188); $.__views.__alloyId189 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId189" }); $.__views.__alloyId188.add($.__views.__alloyId189); $.__views.__alloyId190 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Block B",<|fim▁hole|> id: "__alloyId190" }); return o; }()); $.__views.__alloyId189.add($.__views.__alloyId190); $.__views.__alloyId191 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 45 }); Alloy.isTablet && _.extend(o, { height: 90 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId191" }); return o; }()); $.__views.__alloyId182.add($.__views.__alloyId191); $.__views.__alloyId192 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId192" }); $.__views.__alloyId191.add($.__views.__alloyId192); $.__views.__alloyId193 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId193" }); $.__views.__alloyId192.add($.__views.__alloyId193); $.__views.__alloyId194 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Block C", id: "__alloyId194" }); return o; }()); $.__views.__alloyId193.add($.__views.__alloyId194); $.__views.__alloyId195 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 45 }); Alloy.isTablet && _.extend(o, { height: 90 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId195" }); return o; }()); $.__views.__alloyId182.add($.__views.__alloyId195); $.__views.__alloyId196 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId196" }); $.__views.__alloyId195.add($.__views.__alloyId196); $.__views.__alloyId197 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId197" }); $.__views.__alloyId196.add($.__views.__alloyId197); $.__views.__alloyId198 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Block D", id: "__alloyId198" }); return o; }()); $.__views.__alloyId197.add($.__views.__alloyId198); $.__views.__alloyId199 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 45 }); Alloy.isTablet && _.extend(o, { height: 90 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId199" }); return o; }()); $.__views.__alloyId182.add($.__views.__alloyId199); $.__views.__alloyId200 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId200" }); $.__views.__alloyId199.add($.__views.__alloyId200); $.__views.__alloyId201 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId201" }); $.__views.__alloyId200.add($.__views.__alloyId201); $.__views.__alloyId202 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Block E", id: "__alloyId202" }); return o; }()); $.__views.__alloyId201.add($.__views.__alloyId202); $.__views.__alloyId203 = Ti.UI.createTableViewRow(function() { var o = {}; _.extend(o, { height: 45 }); Alloy.isTablet && _.extend(o, { height: 90 }); _.extend(o, { touchEnabled: "false", backgroundColor: "white", selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY, id: "__alloyId203" }); return o; }()); $.__views.__alloyId182.add($.__views.__alloyId203); $.__views.__alloyId204 = Ti.UI.createView({ left: "10", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId204" }); $.__views.__alloyId203.add($.__views.__alloyId204); $.__views.__alloyId205 = Ti.UI.createView({ layout: "vertical", width: Ti.UI.SIZE, height: Ti.UI.SIZE, id: "__alloyId205" }); $.__views.__alloyId204.add($.__views.__alloyId205); $.__views.__alloyId206 = Ti.UI.createLabel(function() { var o = {}; _.extend(o, { left: 0, font: { fontSize: 16, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); Alloy.isTablet && _.extend(o, { left: 0, font: { fontSize: 30, fontFamily: "AvenirLTStd-Black" }, color: "#222222" }); _.extend(o, { text: "Block F", id: "__alloyId206" }); return o; }()); $.__views.__alloyId205.add($.__views.__alloyId206); $.__views.tv = Ti.UI.createTableView(function() { var o = {}; _.extend(o, { height: 460 }); Alloy.isTablet && _.extend(o, { height: 800, width: 600 }); _.extend(o, { data: __alloyId171, id: "tv", style: Ti.UI.iPhone.TableViewStyle.GROUPED, backgroundColor: "transparent", scrollable: "false" }); return o; }()); $.__views.scrollView.add($.__views.tv); handleTableViewClick ? $.__views.tv.addEventListener("click", handleTableViewClick) : __defers["$.__views.tv!click!handleTableViewClick"] = true; exports.destroy = function() {}; _.extend($, $.__views); var settings = Alloy.Models.settings; 2 > settings.toJSON().question_set ? $.tv.data[0].rows[settings.toJSON().question_set].hasCheck = true : $.tv.data[1].rows[Number(settings.toJSON().question_set) - 2].hasCheck = true; __defers["$.__views.settings_back_btn!click!closeModal"] && $.__views.settings_back_btn.on("click", closeModal); __defers["$.__views.tv!click!handleTableViewClick"] && $.__views.tv.addEventListener("click", handleTableViewClick); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;<|fim▁end|>
<|file_name|>table_caption.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/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use block::BlockFlow; use context::LayoutContext; use euclid::{Point2D, Rect}; use flow::{Flow, FlowClass, OpaqueFlow}; use fragment::{Fragment, FragmentBorderBoxIterator}; use std::fmt; use std::sync::Arc; use style::properties::ComputedValues; use util::geometry::Au; use util::logical_geometry::LogicalSize; /// A table formatting context. pub struct TableCaptionFlow { pub block_flow: BlockFlow, } impl TableCaptionFlow { pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow { TableCaptionFlow { block_flow: BlockFlow::from_fragment(fragment, None) } } } impl Flow for TableCaptionFlow { fn class(&self) -> FlowClass { FlowClass::TableCaption } fn as_mut_table_caption(&mut self) -> &mut TableCaptionFlow { self } fn as_mut_block(&mut self) -> &mut BlockFlow { &mut self.block_flow } fn as_block(&self) -> &BlockFlow { &self.block_flow } fn bubble_inline_sizes(&mut self) { self.block_flow.bubble_inline_sizes(); } fn assign_inline_sizes(&mut self, ctx: &LayoutContext) { debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption"); self.block_flow.assign_inline_sizes(ctx); } fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { debug!("assign_block_size: assigning block_size for table_caption"); self.block_flow.assign_block_size(layout_context); } fn compute_absolute_position(&mut self, layout_context: &LayoutContext) { self.block_flow.compute_absolute_position(layout_context) } fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) { self.block_flow.update_late_computed_inline_position_if_necessary(inline_position) } fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) { self.block_flow.update_late_computed_block_position_if_necessary(block_position) } fn build_display_list(&mut self, layout_context: &LayoutContext) { debug!("build_display_list_table_caption: same process as block flow"); self.block_flow.build_display_list(layout_context) } fn repair_style(&mut self, new_style: &Arc<ComputedValues>) { self.block_flow.repair_style(new_style) } fn compute_overflow(&self) -> Rect<Au> { self.block_flow.compute_overflow() } fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> { self.block_flow.generated_containing_block_size(flow) } fn iterate_through_fragment_border_boxes(&self, iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D<Au>) { self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position) } <|fim▁hole|> } } impl fmt::Debug for TableCaptionFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TableCaptionFlow: {:?}", self.block_flow) } }<|fim▁end|>
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator)
<|file_name|>DefaultMultifactorTriggerSelectionStrategy.java<|end_file_name|><|fim▁begin|>package org.apereo.cas.authentication; import com.google.common.base.Splitter; import org.apereo.cas.authentication.principal.Principal; import org.apereo.cas.services.MultifactorAuthenticationProvider; import org.apereo.cas.services.RegisteredService; import org.apereo.cas.services.RegisteredServiceMultifactorPolicy; import org.apereo.cas.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * Default MFA Trigger selection strategy. This strategy looks for valid triggers in the following order: request * parameter, RegisteredService policy, principal attribute. * * @author Daniel Frett * @since 5.0.0 */ public class DefaultMultifactorTriggerSelectionStrategy implements MultifactorTriggerSelectionStrategy { <|fim▁hole|> private static final Splitter ATTR_NAMES = Splitter.on(',').trimResults().omitEmptyStrings(); private final String requestParameter; private final String globalPrincipalAttributeNameTriggers; public DefaultMultifactorTriggerSelectionStrategy(final String attributeNameTriggers, final String requestParameter) { this.globalPrincipalAttributeNameTriggers = attributeNameTriggers; this.requestParameter = requestParameter; } @Override public Optional<String> resolve(final Collection<MultifactorAuthenticationProvider> providers, final HttpServletRequest request, final RegisteredService service, final Principal principal) { Optional<String> provider = Optional.empty(); // short-circuit if we don't have any available MFA providers if (providers == null || providers.isEmpty()) { return provider; } final Set<String> validProviderIds = providers.stream() .map(MultifactorAuthenticationProvider::getId) .collect(Collectors.toSet()); // check for an opt-in provider id parameter trigger, we only care about the first value if (!provider.isPresent() && request != null) { provider = Optional.ofNullable(request.getParameter(requestParameter)) .filter(validProviderIds::contains); } // check for a RegisteredService configured trigger if (!provider.isPresent() && service != null) { final RegisteredServiceMultifactorPolicy policy = service.getMultifactorPolicy(); if (shouldApplyRegisteredServiceMultifactorPolicy(policy, principal)) { provider = policy.getMultifactorAuthenticationProviders().stream() .filter(validProviderIds::contains) .findFirst(); } } // check for principal attribute trigger if (!provider.isPresent() && principal != null && StringUtils.hasText(globalPrincipalAttributeNameTriggers)) { provider = StreamSupport.stream(ATTR_NAMES.split(globalPrincipalAttributeNameTriggers).spliterator(), false) // principal.getAttribute(name).values .map(principal.getAttributes()::get).filter(Objects::nonNull) .map(CollectionUtils::toCollection).flatMap(Set::stream) // validProviderIds.contains((String) value) .filter(String.class::isInstance).map(String.class::cast).filter(validProviderIds::contains) .findFirst(); } // return the resolved trigger return provider; } private static boolean shouldApplyRegisteredServiceMultifactorPolicy(final RegisteredServiceMultifactorPolicy policy, final Principal principal) { final String attrName = policy.getPrincipalAttributeNameTrigger(); final String attrValue = policy.getPrincipalAttributeValueToMatch(); // Principal attribute name and/or value is not defined if (!StringUtils.hasText(attrName) || !StringUtils.hasText(attrValue)) { return true; } // no Principal, we should enforce policy if (principal == null) { return true; } // check to see if any of the specified attributes match the attrValue pattern final Predicate<String> attrValuePredicate = Pattern.compile(attrValue).asPredicate(); return StreamSupport.stream(ATTR_NAMES.split(attrName).spliterator(), false) .map(principal.getAttributes()::get) .filter(Objects::nonNull) .map(CollectionUtils::toCollection) .flatMap(Set::stream) .filter(String.class::isInstance) .map(String.class::cast) .anyMatch(attrValuePredicate); } }<|fim▁end|>
<|file_name|>connect.py<|end_file_name|><|fim▁begin|>import pymongo def connect (): ''' Create the connection to the MongoDB and create 3 collections needed<|fim▁hole|> conn = pymongo.MongoClient() print 'MongoDB Connection Successful' except pymongo.errors.ConnectionFailure, err: print 'MongoDB Connection Unsuccessful' return False # This is the name of the database -'GtownTwitter' db = conn['GtownTwitter_PROD'] return db<|fim▁end|>
''' try: # Create the connection to the local host
<|file_name|>doc.go<|end_file_name|><|fim▁begin|>// Package rpctest provides a ltcd-specific RPC testing harness crafting and // executing integration tests by driving a `ltcd` instance via the `RPC` // interface. Each instance of an active harness comes equipped with a simple<|fim▁hole|>// This package was designed specifically to act as an RPC testing harness for // `ltcd`. However, the constructs presented are general enough to be adapted to // any project wishing to programmatically drive a `ltcd` instance of its // systems/integration tests. package rpctest<|fim▁end|>
// in-memory HD wallet capable of properly syncing to the generated chain, // creating new addresses, and crafting fully signed transactions paying to an // arbitrary set of outputs. //
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .version import version as __version__ from oplus.configuration import CONF from oplus.epm.api import * from oplus.weather_data.api import * from oplus.standard_output.api import * from oplus.eio import Eio from oplus.mtd import Mtd<|fim▁hole|><|fim▁end|>
from oplus.err import Err from oplus.summary_table import SummaryTable from oplus.output_table import OutputTable from oplus.simulation import Simulation, simulate
<|file_name|>test_resource_class.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 #<|fim▁hole|># # 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 mock import tuskarclient.tests.utils as tutils from tuskarclient.v1 import resource_classes class ResourceClassManagerTest(tutils.TestCase): def setUp(self): super(ResourceClassManagerTest, self).setUp() self.api = mock.Mock() self.rcm = resource_classes.ResourceClassManager(self.api) def test_get(self): self.rcm._get = mock.Mock(return_value='fake_resource_class') self.assertEqual(self.rcm.get(42), 'fake_resource_class') self.rcm._get.assert_called_with('/v1/resource_classes/42') def test_list(self): self.rcm._list = mock.Mock(return_value=['fake_resource_class']) self.assertEqual(self.rcm.list(), ['fake_resource_class']) self.rcm._list.assert_called_with('/v1/resource_classes') def test_create(self): self.rcm._create = mock.Mock(return_value=['fake_resource_class']) self.assertEqual( self.rcm.create(dummy='dummy resource class data'), ['fake_resource_class']) self.rcm._create.assert_called_with( '/v1/resource_classes', {'dummy': 'dummy resource class data'}) def test_update(self): self.rcm._update = mock.Mock(return_value=['fake_resource_class']) self.assertEqual( self.rcm.update(42, dummy='dummy resource class data'), ['fake_resource_class']) self.rcm._update.assert_called_with( '/v1/resource_classes/42', {'dummy': 'dummy resource class data'}) def test_delete(self): self.rcm._delete = mock.Mock(return_value=None) self.assertEqual(self.rcm.delete(42), None) self.rcm._delete.assert_called_with('/v1/resource_classes/42')<|fim▁end|>
# http://www.apache.org/licenses/LICENSE-2.0