prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>bolter-memory.js<|end_file_name|><|fim▁begin|>'use strict';
var Q = require('q')
, _ = require('underscore');
exports.defaults = function () { return { storage: {} }; };
exports.mixin = {
/**
* Converts `arguments` to a key to be stored.
*/
toKey: function () {
return _.toArray(arguments);
},
contains: function () {<|fim▁hole|> return Q.when(_.has(this.storage, key));
},
del: function () {
var args = _.toArray(arguments)
, key = this.toKey.apply(this, arguments);
if (!this.containsKey(key)) return Q.when(false);
this.emit.apply(this, [ 'del' ].concat(args));
delete this.storage[key];
return Q.when(true);
},
set: function (key, val) {
this.storage[key] = val;
return Q.when(true);
},
get: function (key) {
return Q.when(this.storage[key]);
}
};<|fim▁end|> | return this.containsKey(this.toKey.apply(this, _.toArray(arguments)));
},
containsKey: function (key) { |
<|file_name|>ccc10j1.cpp<|end_file_name|><|fim▁begin|>#include <iostream>
using namespace std;
<|fim▁hole|>int main()
{
int n;
cin >> n;
if(n<6)
cout << n/2+1 <<endl;
else
cout << (10-n)/2+1 <<endl;
return 0;
}<|fim▁end|> | |
<|file_name|>boss_drakkari_colossus.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Comment: The event with the Living Mojos is not implemented, just is done that when one of the mojos around the boss take damage will make the boss enter in combat!
*/
#include "ScriptPCH.h"
#include "gundrak.h"
enum Spells
{
SPELL_EMERGE = 54850,
SPELL_MIGHTY_BLOW = 54719,
SPELL_MERGE = 54878,
SPELL_SURGE = 54801,
SPELL_FREEZE_ANIM = 16245,
SPELL_MOJO_PUDDLE = 55627,
H_SPELL_MOJO_PUDDLE = 58994,
SPELL_MOJO_WAVE = 55626,
H_SPELL_MOJO_WAVE = 58993
};
struct boss_drakkari_colossusAI : public ScriptedAI
{
boss_drakkari_colossusAI(Creature* pCreature) : ScriptedAI(pCreature)
{
pInstance = pCreature->GetInstanceData();
}
ScriptedInstance* pInstance;
bool bHealth;
bool bHealth1;
uint32 MightyBlowTimer;
void Reset()
{
if (pInstance)
pInstance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, NOT_STARTED);
if (!me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->clearUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT);
me->SetReactState(REACT_PASSIVE);
MightyBlowTimer = 10*IN_MILLISECONDS;
bHealth = false;
bHealth1 = false;
}
void EnterCombat(Unit* /*who*/)
{
if (pInstance)
pInstance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, IN_PROGRESS);
}
void CreatureState(Creature* pWho, bool bRestore = false)
{
if (!pWho)
return;
if (bRestore)
{
pWho->clearUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT);
pWho->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
if (pWho == me)
me->RemoveAura(SPELL_FREEZE_ANIM);
}else
{
pWho->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
pWho->addUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT);
if (pWho == me)
DoCast(me,SPELL_FREEZE_ANIM);
}
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
if (!bHealth && HealthBelowPct(50) && !HealthBelowPct(5))
{
CreatureState(me, false);
DoCast(me,SPELL_FREEZE_ANIM);
DoCast(me,SPELL_EMERGE);
bHealth = true;
}
if (!bHealth1 && HealthBelowPct(5))
{
DoCast(me,SPELL_EMERGE);
CreatureState(me, false);
bHealth1 = true;
me->RemoveAllAuras();
}
if (MightyBlowTimer <= diff)
{
DoCast(me->getVictim(), SPELL_MIGHTY_BLOW, true);
MightyBlowTimer = 10*IN_MILLISECONDS;
} else MightyBlowTimer -= diff;
if (!me->hasUnitState(UNIT_STAT_STUNNED))
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/)
{
if (pInstance)
pInstance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, DONE);
}
void JustSummoned(Creature* pSummon)
{
if (HealthBelowPct(5))
pSummon->DealDamage(pSummon, pSummon->GetHealth() * 0.5 , NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
pSummon->AI()->AttackStart(me->getVictim());
}
};
struct boss_drakkari_elementalAI : public ScriptedAI
{
boss_drakkari_elementalAI(Creature* pCreature) : ScriptedAI(pCreature)
{
pInstance = pCreature->GetInstanceData();
}
ScriptedInstance* pInstance;
uint32 uiSurgeTimer;
bool bGoToColossus;
void Reset()
{
if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0))
CAST_AI(boss_drakkari_colossusAI, pColossus->AI())->CreatureState(me, true);
uiSurgeTimer = 7*IN_MILLISECONDS;
bGoToColossus = false;
}
void EnterEvadeMode()
{
me->RemoveFromWorld();
}
void MovementInform(uint32 uiType, uint32 /*uiId*/)
{
if (uiType != POINT_MOTION_TYPE)
return;
if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0))
{
CAST_AI(boss_drakkari_colossusAI, pColossus->AI())->CreatureState(pColossus, true);
CAST_AI(boss_drakkari_colossusAI, pColossus->AI())->bHealth1 = false;
}
me->RemoveFromWorld();
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
if (!bGoToColossus && HealthBelowPct(50))
{
if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0))
{
if (!CAST_AI(boss_drakkari_colossusAI,pColossus->AI())->HealthBelowPct(6))
{
me->InterruptNonMeleeSpells(true);
DoCast(pColossus, SPELL_MERGE);
bGoToColossus = true;
}
}
}
if (uiSurgeTimer <= diff)
{
DoCast(me->getVictim(), SPELL_SURGE);
uiSurgeTimer = 7*IN_MILLISECONDS;
} else uiSurgeTimer -= diff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/)
{
if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0))
pColossus->Kill(pColossus);
}
};
struct npc_living_mojoAI : public ScriptedAI
{
npc_living_mojoAI(Creature* pCreature) : ScriptedAI(pCreature)
{
pInstance = pCreature->GetInstanceData();
}
ScriptedInstance* pInstance;
uint32 uiMojoWaveTimer;
uint32 uiMojoPuddleTimer;
void Reset()
{
uiMojoWaveTimer = 2*IN_MILLISECONDS;
uiMojoPuddleTimer = 7*IN_MILLISECONDS;
}
void EnterCombat(Unit* /*who*/)
{
//Check if the npc is near of Drakkari Colossus.
if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0))
{
if (pColossus->isAlive() && me->IsInRange3d(pColossus->GetHomePosition().GetPositionX(),pColossus->GetHomePosition().GetPositionY(),pColossus->GetHomePosition().GetPositionZ(),0.0f,17.0f))
me->SetReactState(REACT_PASSIVE);
else
me->SetReactState(REACT_AGGRESSIVE);
}
}
void DamageTaken(Unit* pDone_by, uint32& /*uiDamage*/)
{
if (me->HasReactState(REACT_PASSIVE))
{
if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0))
{
if (pColossus->isAlive() && !pColossus->isInCombat())
{
pColossus->RemoveAura(SPELL_FREEZE_ANIM);
pColossus->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
pColossus->SetReactState(REACT_AGGRESSIVE);
if (pDone_by && pDone_by->isAlive())
pColossus->AI()->AttackStart(pDone_by);
EnterEvadeMode();
}
}
}
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
if (uiMojoWaveTimer <= diff)
{
DoCast(me->getVictim(), SPELL_MOJO_WAVE);
uiMojoWaveTimer = 15*IN_MILLISECONDS;
} else uiMojoWaveTimer -= diff;
if (uiMojoPuddleTimer <= diff)
{
DoCast(me->getVictim(), SPELL_MOJO_PUDDLE);
uiMojoPuddleTimer = 18*IN_MILLISECONDS;
} else uiMojoPuddleTimer -= diff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_drakkari_colossus(Creature* pCreature)
{
return new boss_drakkari_colossusAI (pCreature);
}
CreatureAI* GetAI_boss_drakkari_elemental(Creature* pCreature)
{
return new boss_drakkari_elementalAI (pCreature);
}
CreatureAI* GetAI_npc_living_mojo(Creature* pCreature)
{<|fim▁hole|>
void AddSC_boss_drakkari_colossus()
{
Script* newscript;
newscript = new Script;
newscript->Name = "boss_drakkari_colossus";
newscript->GetAI = &GetAI_boss_drakkari_colossus;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "boss_drakkari_elemental";
newscript->GetAI = &GetAI_boss_drakkari_elemental;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "npc_living_mojo";
newscript->GetAI = &GetAI_npc_living_mojo;
newscript->RegisterSelf();
}<|fim▁end|> | return new npc_living_mojoAI (pCreature);
} |
<|file_name|>fileio.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright (C) 2014 Swift Navigation Inc.
# Contact: Gareth McMullin <[email protected]>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
import struct
import sys
import serial_link
import threading
from sbp.file_io import *
class FileIO(object):
def __init__(self, link):
self.link = link
def read(self, filename):
"""
Read the contents of a file.
Parameters
----------
filename : str
Name of the file to read.
Returns
-------
out : str
Contents of the file.
"""
chunksize = 255 - 6 - len(filename)
buf = ''
while True:
msg = struct.pack("<IB", len(buf), chunksize) + filename + '\0'
self.link.send(SBP_MSG_FILEIO_READ, msg)
data = self.link.wait(SBP_MSG_FILEIO_READ, timeout=1.0)
if not data:
raise Exception("Timeout waiting for FILEIO_READ reply")
if data[:len(msg)] != msg:
raise Exception("Reply FILEIO_READ doesn't match request")
chunk = data[len(msg):]
buf += chunk
if len(chunk) != chunksize:
return buf
def readdir(self, dirname='.'):
"""
List the files in a directory.
Parameters
----------
dirname : str (optional)
Name of the directory to list. Defaults to the root directory.
Returns
-------
out : [str]
List of file names.
"""
files = []
while True:
msg = struct.pack("<I", len(files)) + dirname + '\0'
self.link.send(SBP_MSG_FILEIO_READ_DIR, msg)
data = self.link.wait(SBP_MSG_FILEIO_READ_DIR, timeout=1.0)
if not data:
raise Exception("Timeout waiting for FILEIO_READ_DIR reply")
if data[:len(msg)] != msg:
raise Exception("Reply FILEIO_READ_DIR doesn't match request")
chunk = data[len(msg):].split('\0')
files += chunk[:-1]
if chunk[-1] == '\xff':
return files
def remove(self, filename):
"""<|fim▁hole|> ----------
filename : str
Name of the file to delete.
"""
self.link.send(SBP_MSG_FILEIO_REMOVE, filename + '\0')
def write(self, filename, data, offset=0, trunc=True):
"""
Write to a file.
Parameters
----------
filename : str
Name of the file to write to.
data : str
Data to write
offset : int (optional)
Offset into the file at which to start writing in bytes.
trunc : bool (optional)
Overwite the file, i.e. delete any existing file before writing. If
this option is not specified and the existing file is longer than the
current write then the contents of the file beyond the write will
remain. If offset is non-zero then this flag is ignored.
Returns
-------
out : str
Contents of the file.
"""
if trunc and offset == 0:
self.remove(filename)
chunksize = 255 - len(filename) - 5
while data:
chunk = data[:chunksize]
data = data[chunksize:]
header = struct.pack("<I", offset) + filename + '\0'
self.link.send(SBP_MSG_FILEIO_WRITE, header + chunk)
reply = self.link.wait(SBP_MSG_FILEIO_WRITE, timeout=1.0)
if not reply:
raise Exception("Timeout waiting for FILEIO_WRITE reply")
if reply != header:
raise Exception("Reply FILEIO_WRITE doesn't match request")
offset += len(chunk)
def hexdump(data):
"""
Print a hex dump.
Parameters
----------
data : indexable
Data to display dump of, can be anything that supports length and index
operations.
"""
ret = ''
ofs = 0
while data:
chunk = data[:16]
data = data[16:]
s = "%08X " % ofs
s += " ".join("%02X" % ord(c) for c in chunk[:8]) + " "
s += " ".join("%02X" % ord(c) for c in chunk[8:])
s += "".join(" " for i in range(60 - len(s))) + "|"
for c in chunk:
s += c if 32 <= ord(c) < 128 else '.'
s += '|\n'
ofs += 16
ret += s
return ret
def print_dir_listing(files):
"""
Print a directory listing.
Parameters
----------
files : [str]
List of file names in the directory.
"""
for f in files:
print f
def get_args():
"""
Get and parse arguments.
"""
import argparse
parser = argparse.ArgumentParser(description='Swift Nav File I/O Utility.')
parser.add_argument('-r', '--read', nargs=1,
help='read a file')
parser.add_argument('-l', '--list', default=None, nargs=1,
help='list a directory')
parser.add_argument('-d', '--delete', nargs=1,
help='delete a file')
parser.add_argument('-p', '--port',
default=[serial_link.SERIAL_PORT], nargs=1,
help='specify the serial port to use.')
parser.add_argument("-b", "--baud",
default=[serial_link.SERIAL_BAUD], nargs=1,
help="specify the baud rate to use.")
parser.add_argument("-v", "--verbose",
help="print extra debugging information.",
action="store_true")
parser.add_argument("-x", "--hex",
help="output in hex dump format.",
action="store_true")
parser.add_argument("-f", "--ftdi",
help="use pylibftdi instead of pyserial.",
action="store_true")
return parser.parse_args()
def main():
args = get_args()
port = args.port[0]
baud = args.baud[0]
# Driver with context
with serial_link.get_driver(args.ftdi, port, baud) as driver:
# Handler with context
with Handler(driver.read, driver.write, args.verbose) as link:
f = FileIO(link)
try:
if args.read:
data = f.read(args.read[0])
if args.hex:
print hexdump(data)
else:
print data
elif args.delete:
f.remove(args.delete[0])
elif args.list is not None:
print_dir_listing(f.readdir(args.list[0]))
else:
print "No command given, listing root directory:"
print_dir_listing(f.readdir())
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()<|fim▁end|> | Delete a file.
Parameters |
<|file_name|>main.js<|end_file_name|><|fim▁begin|>require.config({ urlArgs: "v=" + (new Date()).getTime() });
require(["game"], function(game) {
// I know it's ugly but it works, make game a global object
G = game;<|fim▁hole|> G.init();
$(window).resize(G.camera.resize);
G.render();
});<|fim▁end|> | |
<|file_name|>netfilter.py<|end_file_name|><|fim▁begin|>import sys
import threading
from netfilterqueue import NetfilterQueue
import dpkt
import socket
import config
logger = config.logger
class FlowControlQueue:
''' The class creates a NetfilterQueue that blocks/releases IP packets of
given types.
'''
def __init__(self, worker, queue_num=config.WorkerConfig.queue_num):
self.worker = worker
self.queue_num = queue_num
self.nfqueue = None<|fim▁hole|> self.lck = threading.Lock()
self.block_table = {} # map "$dip:$dport.$proto" -> [blocked_pkts]
self.worker_already_informed = {}
self._debug_flag = True # nfqueue is sensitive of performance
@classmethod
def _block_name(cls, dip, dport, proto):
return "{0}:{1}.{2}".format(dip, dport, proto)
# need parameter to say whether you should inform us based on this rule
# because that callback should only be called once
def block(self, dip, dport, proto):
bname = self._block_name(dip, dport, proto)
with self.lck:
if bname not in self.block_table:
self.block_table[bname] = []
self.worker_already_informed[bname] = False
self._debug("block {0}".format(bname))
def release(self, dip, dport, proto):
bname = self._block_name(dip, dport, proto)
blocked_pkts = []
with self.lck:
if bname in self.block_table:
blocked_pkts = self.block_table[bname]
del self.block_table[bname]
del self.worker_already_informed[bname]
n = len(blocked_pkts)
for pkt in blocked_pkts:
pkt.accept()
self._debug("release {0} packets of {1}".format(n, bname))
def _run_nfqueue(self):
self.nfqueue = NetfilterQueue()
self.nfqueue.bind(self.queue_num, self._process_pkt)
try:
self._debug("bind to queue #{0}".format(self.queue_num))
self.nfqueue.run()
except KeyboardInterrupt:
self._debug("No.%s nfqueue stops.", self.queue_num)
self.nfqueue.unbind()
self.nfqueue = None
def async_run_nfqueue(self):
is_alive = self.thread_recv_pkt and self.thread_recv_pkt.is_alive()
if is_alive or self.nfqueue:
raise Exception("NetfilterQueue has started.")
self.thread_recv_pkt = threading.Thread(target=self._run_nfqueue)
self.thread_recv_pkt.daemon = True # kill thread if main exits
self.thread_recv_pkt.start()
def inform_worker(self, dip, dport, proto):
self.worker.loop.add_callback(
lambda: self.worker.port_callback(dip, dport, proto)
)
def _process_pkt(self, pkt):
# pkt has these functions
# ['accept', 'drop', 'get_payload', 'get_payload_len',
# 'get_timestamp', 'hook', 'hw_protocol', 'id', 'payload', 'set_mark']
data = pkt.get_payload()
ip = dpkt.ip.IP(data)
# sip = socket.inet_ntop(socket.AF_INET, ip.src)
# sport = ip.data.sport
dip = socket.inet_ntop(socket.AF_INET, ip.dst)
dport = ip.data.dport
proto = "UNKNOWN"
if ip.p == dpkt.ip.IP_PROTO_TCP:
proto = "TCP"
elif ip.p == dpkt.ip.IP_PROTO_UDP:
proto = "UDP"
bname = self._block_name(dip, dport, proto)
blocked = False
already_informed = False
with self.lck:
if bname in self.block_table:
self.block_table[bname].append(pkt)
blocked = True
if bname in self.worker_already_informed:
already_informed = self.worker_already_informed[bname]
if (blocked and (not already_informed)):
self.inform_worker(dip, dport, proto)
self.worker_already_informed[bname] = True
else:
pkt.accept()
self._debug("_process_pkt {0}".format(bname))
def _debug(self, msg):
if self._debug_flag:
logger.debug("[FlowControlQueue] "+msg)<|fim▁end|> | self.thread_recv_pkt = None |
<|file_name|>control.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2012 Fabian Barkhau <[email protected]>
# License: MIT (see LICENSE.TXT file)
import os
from django.core.exceptions import PermissionDenied
from apps.gallery.models import Gallery
from apps.gallery.models import Picture
from apps.team.utils import assert_member
from apps.team import control as team_control
def can_edit(account, gallery):
return not ((gallery.team and not team_control.is_member(account, gallery.team)) or
(not gallery.team and gallery.created_by != account))
def _assert_can_edit(account, gallery):
if not can_edit(account, gallery):
raise PermissionDenied
def delete(account, gallery):
""" Delete gallery and all pictures belonging to it. """
_assert_can_edit(account, gallery)
for picture in gallery.pictures.all():
remove(account, picture)
gallery.delete()
def remove(account, picture):
""" Remove picture from the gallery and delete the image file on server. """
gallery = picture.gallery
_assert_can_edit(account, gallery)
if gallery.primary == picture:
gallery.primary = None
gallery.updated_by = account
gallery.save()
os.remove(picture.image.path)
os.remove(picture.preview.path)
os.remove(picture.thumbnail.path)
picture.delete()
return gallery
def setprimary(account, picture):
""" Set picture as the galleries primary picture. """
gallery = picture.gallery
_assert_can_edit(account, gallery)
gallery.primary = picture
gallery.save()
def add(account, image, gallery):
""" Add a picture to the gallery. """
_assert_can_edit(account, gallery)
picture = Picture()
picture.image = image
picture.preview = image
picture.thumbnail = image
picture.gallery = gallery
picture.created_by = account
picture.updated_by = account
picture.save()
return picture
def create(account, image, team):
""" Create a new gallery. """
if team:
assert_member(account, team)
gallery = Gallery()
gallery.created_by = account
gallery.updated_by = account
gallery.team = team
gallery.save()
picture = add(account, image, gallery)
gallery.primary = picture<|fim▁hole|> gallery.save()
return gallery<|fim▁end|> | |
<|file_name|>configcache.py<|end_file_name|><|fim▁begin|># vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2018-2021 Jay Kamat <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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.<|fim▁hole|>
"""Implementation of a basic config cache."""
from typing import Any, Dict
from qutebrowser.config import config
class ConfigCache:
"""A 'high-performance' cache for the config system.
Useful for areas which call out to the config system very frequently, DO
NOT modify the value returned, DO NOT require per-url settings, and do not
require partially 'expanded' config paths.
If any of these requirements are broken, you will get incorrect or slow
behavior.
"""
def __init__(self) -> None:
self._cache: Dict[str, Any] = {}
config.instance.changed.connect(self._on_config_changed)
def _on_config_changed(self, attr: str) -> None:
if attr in self._cache:
del self._cache[attr]
def __getitem__(self, attr: str) -> Any:
try:
return self._cache[attr]
except KeyError:
assert not config.instance.get_opt(attr).supports_pattern
result = self._cache[attr] = config.instance.get(attr)
return result<|fim▁end|> | #
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
|
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO
import tempfile
import os
import time
import shutil
from contextlib import contextmanager
import six
import sys
from netlib import utils, tcp, http
def treader(bytes):
"""
Construct a tcp.Read object from bytes.
"""
fp = BytesIO(bytes)
return tcp.Reader(fp)
@contextmanager
def tmpdir(*args, **kwargs):
orig_workdir = os.getcwd()
temp_workdir = tempfile.mkdtemp(*args, **kwargs)
os.chdir(temp_workdir)
yield temp_workdir
os.chdir(orig_workdir)
shutil.rmtree(temp_workdir)
def _check_exception(expected, actual, exc_tb):
if isinstance(expected, six.string_types):
if expected.lower() not in str(actual).lower():
six.reraise(AssertionError, AssertionError(
"Expected %s, but caught %s" % (
repr(expected), repr(actual)
)
), exc_tb)
else:
if not isinstance(actual, expected):
six.reraise(AssertionError, AssertionError(
"Expected %s, but caught %s %s" % (
expected.__name__, actual.__class__.__name__, repr(actual)
)
), exc_tb)
def raises(expected_exception, obj=None, *args, **kwargs):
"""
Assert that a callable raises a specified exception.
:exc An exception class or a string. If a class, assert that an
exception of this type is raised. If a string, assert that the string
occurs in the string representation of the exception, based on a
case-insenstivie match.
:obj A callable object.
:args Arguments to be passsed to the callable.
:kwargs Arguments to be passed to the callable.
"""
if obj is None:
return RaisesContext(expected_exception)
else:
try:
ret = obj(*args, **kwargs)
except Exception as actual:
_check_exception(expected_exception, actual, sys.exc_info()[2])
else:
raise AssertionError("No exception raised. Return value: {}".format(ret))
class RaisesContext(object):
def __init__(self, expected_exception):
self.expected_exception = expected_exception
def __enter__(self):
return
def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_type:
raise AssertionError("No exception raised.")
else:
_check_exception(self.expected_exception, exc_val, exc_tb)
return True
test_data = utils.Data(__name__)
# FIXME: Temporary workaround during repo merge.
test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib")
def treq(**kwargs):
"""
Returns:
netlib.http.Request
"""
default = dict(
first_line_format="relative",
method=b"GET",<|fim▁hole|> http_version=b"HTTP/1.1",
headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))),
content=b"content"
)
default.update(kwargs)
return http.Request(**default)
def tresp(**kwargs):
"""
Returns:
netlib.http.Response
"""
default = dict(
http_version=b"HTTP/1.1",
status_code=200,
reason=b"OK",
headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))),
content=b"message",
timestamp_start=time.time(),
timestamp_end=time.time(),
)
default.update(kwargs)
return http.Response(**default)<|fim▁end|> | scheme=b"http",
host=b"address",
port=22,
path=b"/path", |
<|file_name|>basic.details.component.ts<|end_file_name|><|fim▁begin|>import {AbstractControl, FormBuilder, FormGroup, Validators} from "@angular/forms";
import {DatePickerOptions} from "ng2-datepicker";
import {MatchesDataStoreService} from "../../matches-data-store";
import {MatchesConstants} from "../../matches.constant.service";
import {IOption} from "ng-select";
import {Component, EventEmitter, Output} from "@angular/core";
import {Subject} from "rxjs/Subject";
import {MatchesService} from "../../../../common/services/matches.service";
/**
* Created by HudaZulifqar on 8/22/2017.
*/
/* tslint:disable */
@Component({
selector: 'score-basic-details',
templateUrl: 'basic.details.html',
//styleUrls: ['../../../../theme/components/baCheckbox/baCheckbox.scss'],
styleUrls: ['../submitScore.scss'],
})
export class matchBasicDetailsComponent {
@Output() notify_homeTeam: EventEmitter<string> = new EventEmitter<string>();
@Output() notify_awayTeam: EventEmitter<string> = new EventEmitter<string>();
@Output() notify_date: EventEmitter<string> = new EventEmitter<string>();
@Output() notify_matchCall: EventEmitter<string> = new EventEmitter<string>();
private ngUnsubscribe: Subject<void> = new Subject<void>();
//@Input() innings: string;
options: DatePickerOptions;
inningsId: number;
submiScoreStatus: any;
public form: FormGroup;
// public extrasDetails
public name: AbstractControl;
public teams;
public password: AbstractControl;
//FIRSR BLOCK
public league_id: AbstractControl;
public season: AbstractControl;
public week: AbstractControl;
weekNo: number;
selectedLeague: string;
public ground_id: AbstractControl;
public ground_name: AbstractControl;
public result: AbstractControl;
public game_date;
public dateFlag: boolean = true;
//Second Blcok: drop down
public awayteam: AbstractControl;
public hometeam: AbstractControl;
public umpireTeam: AbstractControl;
public toss_won_id: AbstractControl;
public batting_first_id: AbstractControl;
public batting_second_id: AbstractControl;
public result_won_id: AbstractControl;
public umpire1: AbstractControl;
public umpire2: AbstractControl;
public mom: AbstractControl;
public maxovers: AbstractControl;
public matchResult: AbstractControl;
//Results options
public completed: AbstractControl;
public forfeit: AbstractControl;
public cancelled: AbstractControl;
public tied: AbstractControl;
public cancelledplay: AbstractControl;
private teamsname;
teamsList: Array<any>;
myOptions2: any;
dateValue: any = null;
playersList: Array<any>;
batFirstPlayers: Array<any>;
batSecondPlayers: Array<any>;
playersByTeamsIds: Array<any>;
playersForHomeTeam: Array<any>;
playersForAwayTeam: Array<any>;
playersForUmpiringTeam: Array<any>;
matchByDate;
homeTeamsIds: Array<number> = [];
awayTeamsIds: Array<number> = [];
umpiringTeamsIds: Array<number> = [];
teams_playings: Array<IOption> = [
{label: 'Select Home Team First', value: '0'},
{label: 'Select Guest Team First', value: '0'}
];
public submitted_step1: boolean = false;
public submitted_step2: boolean = false;
public battingForm: FormGroup;
public battingName: AbstractControl;
constructor(fb: FormBuilder, private matchesService: MatchesService,
private matchesConstants: MatchesConstants,
private matchesDataStoreService: MatchesDataStoreService) {
this.options = new DatePickerOptions();
this.form = fb.group({
'name': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
'league_id': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'season': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'ground_id': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'ground_name': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'week': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'result': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'game_date': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'awayteam': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'hometeam': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'umpireTeam': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'toss_won_id': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'batting_first_id': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'batting_second_id': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'result_won_id': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'umpire1': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'umpire2': ['', Validators.compose([Validators.required, Validators.minLength(1)])],<|fim▁hole|> //Results options
'completed': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'forfeit': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'cancelled': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'tied': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'cancelledplay': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
});
this.name = this.form.controls['name'];
this.teams = this.form.controls['teams'];
this.league_id = this.form.controls['league_id'];
this.season = this.form.controls['season'];
this.ground_id = this.form.controls['ground_id'];
this.ground_name = this.form.controls['ground_name'];
this.week = this.form.controls['week'];
this.result = this.form.controls['result'];
this.game_date = this.form.controls['game_date'];
this.awayteam = this.form.controls['awayteam'];
this.hometeam = this.form.controls['hometeam'];
this.umpireTeam = this.form.controls['umpireTeam'];
this.toss_won_id = this.form.controls['toss_won_id'];
this.batting_first_id = this.form.controls['batting_first_id'];
this.batting_second_id = this.form.controls['batting_second_id'];
this.result_won_id = this.form.controls['result_won_id'];
this.umpire1 = this.form.controls['umpire1'];
this.umpire2 = this.form.controls['umpire2'];
this.mom = this.form.controls['mom'];
this.maxovers = this.form.controls['maxovers'];
this.matchResult = this.form.controls['matchResult'];
//Results options
this.completed = this.form.controls['completed'];
this.forfeit = this.form.controls['forfeit'];
this.cancelled = this.form.controls['cancelled'];
this.tied = this.form.controls['tied'];
this.cancelledplay = this.form.controls['cancelledplay'];
this.battingForm = fb.group({
'battingName': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
});
this.battingName = this.battingForm.controls['battingName'];
}
ngOnInit(): void {
this.getTeamslist();
this.getPlayerslist();
console.warn("dateValue : ", this.dateValue)
this.myOptions2 = {
theme: 'green',
range: 'tm',
dayNames: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
presetNames: ['This Month', 'Last Month', 'This Week', 'Last Week', 'This Year', 'Last Year', 'Start', 'End'],
dateFormat: 'yMd',
outputFormat: 'MM/DD/YYYY',
startOfWeek: 1
};
}
//eague_id,season,week,awayteam,hometeam,game_date,result_won_id,forfeit,mom,umpire1,umpire2,maxovers,isactive
checkLeagues = this.matchesConstants.getLeagues()
checkVenues = this.matchesConstants.getCheckVenues();
checkResults = this.matchesConstants.getCheckResults();
checkStatus = this.matchesConstants.getYesNo();
public checkboxPropertiesMapping = {
model: 'checked',
value: 'name',
label: 'name',
baCheckboxClass: 'class'
};
getTeamslist() {
console.info("Fetching results for teams list :")
const teams$ = this.matchesService.getTeamslist();
console.log('this.teamsname', this.teamsList)
teams$.takeUntil(this.ngUnsubscribe).subscribe(responce => this.teamsList = responce,
(err) => console.error(err),
() => console.info("responce for teamList", this.teamsList));
}
getPlayerslist() {
console.info("Fetching Players list")
const teams$ = this.matchesService.getPlayerslist();
teams$.takeUntil(this.ngUnsubscribe).subscribe(responce => this.playersList = responce,
(err) => console.error(err),
() => console.info("responce", this.playersList));
}
playersListByTeamsIds(teamIds) {
console.info("Fetching Players list for TeamsIds: ", teamIds)
const teams$ = this.matchesService.getPlayersByTeamsIds(teamIds);
teams$.takeUntil(this.ngUnsubscribe).subscribe(responce => this.playersByTeamsIds = responce,
(err) => console.error(err),
() => console.info("responce", this.playersList));
}
onSelected(type: any, value: any) {
console.log('type: ', type, ' value: ', value);
(this.form.controls[type]).setValue(value);
}
onTeamsSelected(type: any, value: any) {
console.info("onTeamsSelected: Type:", type, 'Value: ', value)
if (type === 'homeTeamsPortable' || type === 'homeTeam') {
this.homeTeamsIds.push(value);
if (type === 'homeTeam') {
console.info("Fetching Players for Home Teams with => Ids: ", this.homeTeamsIds)
const teams$ = this.matchesService.getPlayersByTeamsIds(this.homeTeamsIds);
teams$.takeUntil(this.ngUnsubscribe).subscribe(responce => this.playersForHomeTeam = responce);
}
}
if (type === 'awayTeamsPortable' || type === 'awayTeam') {
this.awayTeamsIds.push(value);
if (type === 'awayTeam') {
console.info("Fetching Players for Away with => Ids: ", this.awayTeamsIds)
const teams$ = this.matchesService.getPlayersByTeamsIds(this.awayTeamsIds);
teams$.takeUntil(this.ngUnsubscribe).subscribe(responce => this.playersForAwayTeam = responce);
}
}
if (type === 'umpiringTeam') {
this.umpiringTeamsIds.push(value);
console.info("Fetching Players for Umpiring with => Ids: ", this.umpiringTeamsIds)
const teams$ = this.matchesService.getPlayersByTeamsIds(this.umpiringTeamsIds);
teams$.takeUntil(this.ngUnsubscribe).subscribe(responce => this.playersForUmpiringTeam = responce);
}
}
battingOrderStatus(teamId) {
console.log('homeTeam Ids ', this.homeTeamsIds);
if (this.homeTeamsIds.indexOf(teamId) > -1) {
console.log("Home Team is Batting First id: ", teamId)
this.batFirstPlayers = this.playersForHomeTeam;
this.batSecondPlayers = this.playersForAwayTeam;
} else {
console.log("Away Team is Batting First id: ", teamId)
this.batFirstPlayers = this.playersForAwayTeam;
this.batSecondPlayers = this.playersForHomeTeam;
}
}
onSelectedResult(type: any, value: any) {
console.log('type: ', type, ' value: ', value);
if (type == 'forfeit') {
(this.form.controls[type]).setValue(value);
(this.form.controls['cancelled']).setValue(0);
(this.form.controls['tied']).setValue(0);
(this.form.controls['cancelledplay']).setValue(0);
} else if (type == 'completed') {
(this.form.controls[type]).setValue(value);
(this.form.controls['forfeit']).setValue(0);
(this.form.controls['cancelled']).setValue(0);
(this.form.controls['tied']).setValue(0);
(this.form.controls['cancelledplay']).setValue(0);
} else if (type == 'cancelled') {
(this.form.controls[type]).setValue(value);
(this.form.controls['completed']).setValue(0);
(this.form.controls['forfeit']).setValue(0);
(this.form.controls['tied']).setValue(0);
(this.form.controls['cancelledplay']).setValue(0);
} else if (type == 'tied') {
(this.form.controls[type]).setValue(value);
(this.form.controls['completed']).setValue(0);
(this.form.controls['cancelled']).setValue(0);
(this.form.controls['forfeit']).setValue(0);
(this.form.controls['cancelledplay']).setValue(0);
} else if (type == 'cancelledplay') {
(this.form.controls[type]).setValue(value);
(this.form.controls['completed']).setValue(0);
(this.form.controls['cancelled']).setValue(0);
(this.form.controls['forfeit']).setValue(0);
(this.form.controls['tied']).setValue(0);
}
}
dateEmit() {
if (this.dateValue != null || this.dateValue == 'undefined') {
this.notify_date.emit(this.dateValue);
}
}
playing_teams(type: any, obj: any) {
console.log('type: ', type, ' obj: ', obj)
if (type === 'hometeam') {
//Passing value to parent ***** !!!
this.notify_homeTeam.emit(obj);
this.dateEmit();
//Passing value to parent ***** !!
this.teams_playings[0].label = obj.label;
this.teams_playings[0].value = obj.value;
}
if (type === 'awayteam') {
//Passing value to parent ***** !!!
this.notify_awayTeam.emit(obj);
this.dateEmit();
//Passing value to parent ***** !!
this.teams_playings[1].label = obj.label
this.teams_playings[1].value = obj.value
}
console.log('Playing teams for Match :: ', this.teams_playings)
}
onNotify(val: any): void {
console.log('this.totalsForm.value frrom total in Parent: ', val)
}
onNotify_batting(val: any): void {
console.log('Batting_parent ==> this.totalsForm.value: ', val)
}
player_out_type = this.matchesConstants.getPlayerOutType();
batting_poistion = this.matchesConstants.getBattingPositions();
public onSubmitBasicDetails(values: Object): void {
this.submitted_step1 = true;
this.inningsId = 1;
let matchDetailsObject = values;
//Making sure only date value submitting instead whole date object
//this.dateValue ? this.dateValue.formatted : this.dateValue;
this.dateValue ? matchDetailsObject['game_date'] = this.dateValue.formatted : this.dateValue;
console.log(" ***onSubmitBasicDetails**** HTTP Request => ", matchDetailsObject);
this.matchesService.updateScorecardGameDetails(matchDetailsObject).takeUntil(this.ngUnsubscribe).subscribe(
res => this.submiScoreStatus = res,
(err) => console.error('onSubmitBasicDetails: Res Error =>', err),
() => this.notify_matchCall.emit(this.dateValue));
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}<|fim▁end|> | 'mom': ['', Validators.compose([Validators.required, Validators.minLength(1000000)])],
'maxovers': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
'matchResult': ['', Validators.compose([Validators.required, Validators.minLength(1)])], |
<|file_name|>ValidConfigurationWithoutDefaults.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
* <|fim▁hole|> * 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.river.test.spec.config.configurationprovider;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationProvider;
import net.jini.config.ConfigurationException;
import net.jini.config.ConfigurationNotFoundException;
/**
* Some Configuration that can be instantiated but can not be
* really used. This configuration provider doesn't have default
* for options
*/
public class ValidConfigurationWithoutDefaults implements Configuration {
public static boolean wasCalled = false;
public ValidConfigurationWithoutDefaults(String[] options)
throws ConfigurationException {
this(options, null);
wasCalled = true;
}
public ValidConfigurationWithoutDefaults(String[] options, ClassLoader cl)
throws ConfigurationException {
wasCalled = true;
if (options == null) {
throw new ConfigurationNotFoundException(
"default options are not supplied");
}
}
public Object getEntry(String component, String name, Class type)
throws ConfigurationException {
throw new AssertionError();
};
public Object getEntry(String component, String name, Class type,
Object defaultValue) throws ConfigurationException {
throw new AssertionError();
};
public Object getEntry(String component, String name, Class type,
Object defaultValue, Object data) throws ConfigurationException {
throw new AssertionError();
};
}<|fim▁end|> | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software |
<|file_name|>lights.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/. */
//! Module that implements lights for `PhilipsHueAdapter`
//!
//! This module implements AdapterManager-facing functionality.
//! It registers a service for every light and adds setters and
//! getters according to the light type.
use foxbox_taxonomy::api::Error;
use foxbox_taxonomy::channel::*;
use foxbox_taxonomy::manager::*;
use foxbox_taxonomy::services::*;
use super::*;
use super::hub_api::HubApi;
use std::sync::{ Arc, Mutex };
const CUSTOM_PROPERTY_MANUFACTURER: &'static str = "manufacturer";
const CUSTOM_PROPERTY_MODEL: &'static str = "model";
const CUSTOM_PROPERTY_NAME: &'static str = "name";
const CUSTOM_PROPERTY_TYPE: &'static str = "type";
#[derive(Clone)]
pub struct Light {
api: Arc<Mutex<HubApi>>,
hub_id: String,
light_id: String,
service_id: Id<ServiceId>,
pub get_available_id: Id<Channel>,
pub channel_power_id: Id<Channel>,
pub channel_color_id: Id<Channel>,
}
impl Light {
pub fn new(api: Arc<Mutex<HubApi>>, hub_id: &str, light_id: &str)
-> Self
{
Light {
api: api,
hub_id: hub_id.to_owned(),
light_id: light_id.to_owned(),
service_id: create_light_id(&hub_id, &light_id),
get_available_id: create_channel_id("available", &hub_id, &light_id),
channel_power_id: create_channel_id("power", &hub_id, &light_id),
channel_color_id: create_channel_id("color", &hub_id, &light_id),
}
}
pub fn start(&self) {
// Nothing to do, yet
}
pub fn stop(&self) {
// Nothing to do, yet
}
pub fn init_service(&mut self, manager: Arc<AdapterManager>,
services: LightServiceMap) -> Result<(), Error>
{
let adapter_id = create_adapter_id();
let status = self.api.lock().unwrap().get_light_status(&self.light_id);
if status.lighttype == "Extended color light" {
info!("New Philips Hue `Extended Color Light` service for light {} on bridge {}",
self.light_id, self.hub_id);
let mut service = Service::empty(&self.service_id, &adapter_id);
service.properties.insert(CUSTOM_PROPERTY_MANUFACTURER.to_owned(),
status.manufacturername.to_owned());
service.properties.insert(CUSTOM_PROPERTY_MODEL.to_owned(),
status.modelid.to_owned());
service.properties.insert(CUSTOM_PROPERTY_NAME.to_owned(),
status.name.to_owned());
service.properties.insert(CUSTOM_PROPERTY_TYPE.to_owned(),
"Light/ColorLight".to_owned());
service.tags.insert(tag_id!("type:Light/ColorLight"));
try!(manager.add_service(service));
// The `available` getter yields `On` when the light
// is plugged in and `Off` when it is not. Availability
// Has no effect on the API other than that you won't
// see the light change because it lacks external power.
try!(manager.add_channel(Channel {
id: self.get_available_id.clone(),
service: self.service_id.clone(),
adapter: adapter_id.clone(),
..AVAILABLE.clone()
}));
try!(manager.add_channel(Channel {
id: self.channel_power_id.clone(),
service: self.service_id.clone(),
adapter: adapter_id.clone(),
supports_watch: None,
..LIGHT_IS_ON.clone()<|fim▁hole|>
try!(manager.add_channel(Channel {
id: self.channel_color_id.clone(),
service: self.service_id.clone(),
adapter: adapter_id.clone(),
supports_watch: None,
..LIGHT_COLOR_HSV.clone()
}));
let mut services_lock = services.lock().unwrap();
services_lock.getters.insert(self.get_available_id.clone(), self.clone());
services_lock.getters.insert(self.channel_power_id.clone(), self.clone());
services_lock.setters.insert(self.channel_power_id.clone(), self.clone());
services_lock.getters.insert(self.channel_color_id.clone(), self.clone());
services_lock.setters.insert(self.channel_color_id.clone(), self.clone());
} else if status.lighttype == "Dimmable light" {
info!("New Philips Hue `Dimmable Light` service for light {} on bridge {}",
self.light_id, self.hub_id);
let mut service = Service::empty(&self.service_id, &adapter_id);
service.properties.insert(CUSTOM_PROPERTY_MANUFACTURER.to_owned(),
status.manufacturername.to_owned());
service.properties.insert(CUSTOM_PROPERTY_MODEL.to_owned(),
status.modelid.to_owned());
service.properties.insert(CUSTOM_PROPERTY_NAME.to_owned(),
status.name.to_owned());
service.properties.insert(CUSTOM_PROPERTY_TYPE.to_owned(),
"Light/DimmerLight".to_owned());
service.tags.insert(tag_id!("type:Light/DimmerLight"));
try!(manager.add_service(service));
try!(manager.add_channel(Channel {
id: self.get_available_id.clone(),
service: self.service_id.clone(),
adapter: adapter_id.clone(),
..AVAILABLE.clone()
}));
try!(manager.add_channel(Channel {
id: self.channel_power_id.clone(),
service: self.service_id.clone(),
adapter: adapter_id.clone(),
supports_watch: None,
..LIGHT_IS_ON.clone()
}));
let mut services_lock = services.lock().unwrap();
services_lock.getters.insert(self.get_available_id.clone(), self.clone());
services_lock.getters.insert(self.channel_power_id.clone(), self.clone());
services_lock.setters.insert(self.channel_power_id.clone(), self.clone());
} else {
warn!("Ignoring unsupported Hue light type {}, ID {} on bridge {}",
status.lighttype, self.light_id, self.hub_id);
}
Ok(())
}
pub fn get_available(&self) -> bool {
let status = self.api.lock().unwrap().get_light_status(&self.light_id);
status.state.reachable
}
pub fn get_power(&self) -> bool {
let status = self.api.lock().unwrap().get_light_status(&self.light_id);
status.state.on
}
pub fn set_power(&self, on: bool) {
self.api.lock().unwrap().set_light_power(&self.light_id, on);
}
#[allow(dead_code)]
pub fn get_brightness(&self) -> f64 {
// Hue API gives brightness value in [0, 254]
let ls = self.api.lock().unwrap().get_light_status(&self.light_id);
ls.state.bri as f64 / 254f64
}
#[allow(dead_code)]
pub fn set_brightness(&self, bri: f64) {
// Hue API takes brightness value in [0, 254]
let bri = bri.max(0f64).min(1f64); // [0,1]
// convert to value space used by Hue
let bri: u32 = (bri * 254f64) as u32;
self.api.lock().unwrap().set_light_brightness(&self.light_id, bri);
}
pub fn get_color(&self) -> (f64, f64, f64) {
// Hue API gives hue angle in [0, 65535], and sat and val in [0, 254]
let ls = self.api.lock().unwrap().get_light_status(&self.light_id);
let hue: f64 = ls.state.hue.unwrap_or(0) as f64 / 65536f64 * 360f64;
let sat: f64 = ls.state.sat.unwrap_or(0) as f64 / 254f64;
let val: f64 = ls.state.bri as f64 / 254f64;
(hue, sat, val)
}
pub fn set_color(&self, hsv: (f64, f64, f64)) {
// Hue API takes hue angle in [0, 65535], and sat and val in [0, 254]
let (hue, sat, val) = hsv;
let hue = ((hue % 360f64) + 360f64) % 360f64; // [0,360)
let sat = sat.max(0f64).min(1f64); // [0,1]
let val = val.max(0f64).min(1f64); // [0,1]
// convert to value space used by Hue
let hue: u32 = (hue * 65536f64 / 360f64) as u32;
let sat: u32 = (sat * 254f64) as u32;
let val: u32 = (val * 254f64) as u32;
self.api.lock().unwrap().set_light_color(&self.light_id, (hue, sat, val));
}
}<|fim▁end|> | })); |
<|file_name|>escp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2007 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
## USA.
##
## Author(s): Johan Dahlin <[email protected]>
##
#
# Documentation references:
#
# http://en.wikipedia.org/wiki/ESC/P
# http://www.epson.co.uk/support/manuals/pdf/ESCP/Part_1.pdf
# http://www.epson.co.uk/support/manuals/pdf/ESCP/Part_2.pdf
#
""" Driver for EPSON Esc/P and Esc/P2 printers. """
import struct
ESC = '\x1b'
CMD_INIT = '@'
CMD_PRINT_QUALITY = 'x'
CMD_PROPORTIONAL = 'p'
CMD_FORM_FEED = '\xff'
CMD_EJECT = '\x19'
QUALITY_DRAFT = '0'
QUALITY_LQ = '1'
QUALITY_NLQ = '1'
class EscPPrinter(object):
def __init__(self, device):
self.device = device
self.fp = open(device, 'w')
self._command(CMD_INIT)
def _command(self, command, *args):
chars = command
for arg in args:
if arg is True:
v = '1'
elif arg is False:
v = '0'
else:
v = arg
chars += v
cmd = '%s%s' % (ESC, chars)
self.send(cmd)
def send(self, data):<|fim▁hole|> self.fp.write(data)
self.fp.flush()
def set_draft_mode(self):
self._command(CMD_PRINT_QUALITY, QUALITY_DRAFT)
def set_proportional(self, proportional):
self._command(CMD_PROPORTIONAL, proportional)
def done(self):
self._command(CMD_INIT)
def form_feed(self):
self._command(CMD_FORM_FEED)
def set_vertical_position(self, position):
args = struct.pack('b', position)
self._command('J', *args)
def test():
printer = EscPPrinter('/dev/lp0')
printer.send(
'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. '
'Ut a velit sit amet nisl hendrerit lacinia. Nunc eleifend '
'cursus risus. Vivamus libero libero, dignissim ut, pulvinar id, '
'blandit a, leo amet.\n'.upper())
printer.done()
if __name__ == '__main__':
test()<|fim▁end|> | |
<|file_name|>render_options.rs<|end_file_name|><|fim▁begin|>use piston_window::*;
use piston_window::character::CharacterCache;
use game::config::Config;
pub struct RenderOptions<'a, G: 'a, C: 'a>
where C: CharacterCache,
G: Graphics<Texture = <C as CharacterCache>::Texture>
{<|fim▁hole|> pub character_cache: &'a mut C,
pub context: &'a mut Context,
pub graphics: &'a mut G,
}<|fim▁end|> | pub config: &'a Config, |
<|file_name|>webpack.config.js<|end_file_name|><|fim▁begin|>/*global module, process*/
/*eslint no-use-before-define:0 */
var webpack = require('webpack');
var webpackDevServer = require('webpack-dev-server');
var path = require('path');
// Support for extra commandline arguments
var argv = require('optimist')
//--env=XXX: sets a global ENV variable (i.e. window.ENV='XXX')
.alias('e', 'env').default('e', 'dev')
.argv;
var config = {
context: __dirname,
entry: {'bundle': './main'},<|fim▁hole|> path: path.join(__dirname, 'dist'),
filename: '[name].js',
publicPath: isDevServer() ? '/' : ''
},
devServer: {
publicPath: '/'
},
reload: isDevServer() ? 'localhost' : null,
module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' },
{ test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=5000&name=[path][name].[ext]&context=./src' },
{ test: /\.eot$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /\.ttf$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /\.svg$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /\.woff$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /index\.html$/, loader: 'file-loader?name=[path][name].[ext]&context=.' }
]
},
resolve: {
alias: {
'famous-flex': 'famous-flex/src'
}
},
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(require('../package.json').version),
ENV: JSON.stringify(argv.env)
})
]
};
function isDevServer() {
return process.argv.join('').indexOf('webpack-dev-server') > -1;
}
module.exports = config;<|fim▁end|> | output: { |
<|file_name|>0110-Balanced Binary Tree.py<|end_file_name|><|fim▁begin|># Definition for a binary tree node.
class TreeNode:<|fim▁hole|> self.left = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def dfs(root):
if root is None:
return (True, 0)
lb, lh = dfs(root.left)
rb, rh = dfs(root.right)
h = max(lh, rh) + 1
return (lb and rb and abs(lh - rh) <= 1, h)
return dfs(root)[0]<|fim▁end|> | def __init__(self, x):
self.val = x |
<|file_name|>ga.js<|end_file_name|><|fim▁begin|>function populate(form)
{
form.options.length = 0;
form.options[0] = new Option("Select a county of Georgia","");
form.options[1] = new Option("Appling County","Appling County");
form.options[2] = new Option("Atkinson County","Atkinson County");
form.options[3] = new Option("Bacon County","Bacon County");
form.options[4] = new Option("Baker County","Baker County");
form.options[5] = new Option("Baldwin County","Baldwin County");
form.options[6] = new Option("Banks County","Banks County");
form.options[7] = new Option("Barrow County","Barrow County");
form.options[8] = new Option("Bartow County","Bartow County");
form.options[9] = new Option("Ben Hill County","Ben Hill County");
form.options[10] = new Option("Berrien County","Berrien County");
form.options[11] = new Option("Bibb County","Bibb County");
form.options[12] = new Option("Bleckley County","Bleckley County");
form.options[13] = new Option("Brantley County","Brantley County");
form.options[14] = new Option("Brooks County","Brooks County");
form.options[15] = new Option("Bryan County","Bryan County");
form.options[16] = new Option("Bulloch County","Bulloch County");
form.options[17] = new Option("Burke County","Burke County");
form.options[18] = new Option("Butts County","Butts County");
form.options[19] = new Option("Calhoun County","Calhoun County");
form.options[20] = new Option("Camden County","Camden County");
form.options[21] = new Option("Candler County","Candler County");
form.options[22] = new Option("Carroll County","Carroll County");
form.options[23] = new Option("Catoosa County","Catoosa County");
form.options[24] = new Option("Charlton County","Charlton County");
form.options[25] = new Option("Chatham County","Chatham County");
form.options[26] = new Option("Chattahoochee County","Chattahoochee County");
form.options[27] = new Option("Chattooga County","Chattooga County");
form.options[28] = new Option("Cherokee County","Cherokee County");
form.options[29] = new Option("Clarke County","Clarke County");
form.options[30] = new Option("Clay County","Clay County");
form.options[31] = new Option("Clayton County","Clayton County");
form.options[32] = new Option("Clinch County","Clinch County");
form.options[33] = new Option("Cobb County","Cobb County");
form.options[34] = new Option("Coffee County","Coffee County");
form.options[35] = new Option("Colquitt County","Colquitt County");
form.options[36] = new Option("Columbia County","Columbia County");
form.options[37] = new Option("Cook County","Cook County");
form.options[38] = new Option("Coweta County","Coweta County");
form.options[39] = new Option("Crawford County","Crawford County");
form.options[40] = new Option("Crisp County","Crisp County");
form.options[41] = new Option("Dade County","Dade County");
form.options[42] = new Option("Dawson County","Dawson County");
form.options[43] = new Option("Decatur County","Decatur County");
form.options[44] = new Option("DeKalb County","DeKalb County");
form.options[45] = new Option("Dodge County","Dodge County");
form.options[46] = new Option("Dooly County","Dooly County");
form.options[47] = new Option("Dougherty County","Dougherty County");
form.options[48] = new Option("Douglas County","Douglas County");
form.options[49] = new Option("Early County","Early County");
form.options[50] = new Option("Echols County","Echols County");
form.options[51] = new Option("Effingham County","Effingham County");
form.options[52] = new Option("Elbert County","Elbert County");
form.options[53] = new Option("Emanuel County","Emanuel County");
form.options[54] = new Option("Evans County","Evans County");
form.options[55] = new Option("Fannin County","Fannin County");
form.options[56] = new Option("Fayette County","Fayette County");
form.options[57] = new Option("Floyd County","Floyd County");
form.options[58] = new Option("Forsyth County","Forsyth County");
form.options[59] = new Option("Franklin County","Franklin County");
form.options[60] = new Option("Fulton County","Fulton County");
form.options[61] = new Option("Gilmer County","Gilmer County");
form.options[62] = new Option("Glascock County","Glascock County");
form.options[63] = new Option("Glynn County","Glynn County");
form.options[64] = new Option("Gordon County","Gordon County");
form.options[65] = new Option("Grady County","Grady County");
form.options[66] = new Option("Greene County","Greene County");
form.options[67] = new Option("Gwinnett County","Gwinnett County");
form.options[68] = new Option("Habersham County","Habersham County");
form.options[69] = new Option("Hall County","Hall County");
form.options[70] = new Option("Hancock County","Hancock County");
form.options[71] = new Option("Haralson County","Haralson County");
form.options[72] = new Option("Harris County","Harris County");
form.options[73] = new Option("Hart County","Hart County");
form.options[74] = new Option("Heard County","Heard County");
form.options[75] = new Option("Henry County","Henry County");
form.options[76] = new Option("Houston County","Houston County");
form.options[77] = new Option("Irwin County","Irwin County");
form.options[78] = new Option("Jackson County","Jackson County");
form.options[79] = new Option("Jasper County","Jasper County");
form.options[80] = new Option("Jeff Davis County","Jeff Davis County");
form.options[81] = new Option("Jefferson County","Jefferson County");
form.options[82] = new Option("Jenkins County","Jenkins County");
form.options[83] = new Option("Johnson County","Johnson County");
form.options[84] = new Option("Jones County","Jones County");
form.options[85] = new Option("Lamar County","Lamar County");
form.options[86] = new Option("Lanier County","Lanier County");
form.options[87] = new Option("Laurens County","Laurens County");
form.options[88] = new Option("Lee County","Lee County");
form.options[89] = new Option("Liberty County","Liberty County");
form.options[90] = new Option("Lincoln County","Lincoln County");
form.options[91] = new Option("Long County","Long County");
form.options[92] = new Option("Lowndes County","Lowndes County");
form.options[93] = new Option("Lumpkin County","Lumpkin County");
form.options[94] = new Option("Macon County","Macon County");
form.options[95] = new Option("Madison County","Madison County");
form.options[96] = new Option("Marion County","Marion County");
form.options[97] = new Option("McDuffie County","McDuffie County");
form.options[98] = new Option("McIntosh County","McIntosh County");
form.options[99] = new Option("Meriwether County","Meriwether County");
form.options[100] = new Option("Miller County","Miller County");
form.options[101] = new Option("Mitchell County","Mitchell County");
form.options[102] = new Option("Monroe County","Monroe County");
form.options[103] = new Option("Montgomery County","Montgomery County");
form.options[104] = new Option("Morgan County","Morgan County");
form.options[105] = new Option("Murray County","Murray County");
form.options[106] = new Option("Muscogee County","Muscogee County");
form.options[107] = new Option("Newton County","Newton County");
form.options[108] = new Option("Oconee County","Oconee County");
form.options[109] = new Option("Oglethorpe County","Oglethorpe County");
form.options[110] = new Option("Paulding County","Paulding County");
form.options[111] = new Option("Peach County","Peach County");
form.options[112] = new Option("Pickens County","Pickens County");
form.options[113] = new Option("Pierce County","Pierce County");
form.options[114] = new Option("Pike County","Pike County");
form.options[115] = new Option("Polk County","Polk County");
form.options[116] = new Option("Pulaski County","Pulaski County");
form.options[117] = new Option("Putnam County","Putnam County");
form.options[118] = new Option("Quitman County","Quitman County");
form.options[119] = new Option("Rabun County","Rabun County");
form.options[120] = new Option("Randolph County","Randolph County");
form.options[121] = new Option("Richmond County","Richmond County");
form.options[122] = new Option("Rockdale County","Rockdale County");
form.options[123] = new Option("Schley County","Schley County");
form.options[124] = new Option("Screven County","Screven County");
form.options[125] = new Option("Seminole County","Seminole County");
form.options[126] = new Option("Spalding County","Spalding County");<|fim▁hole|>form.options[128] = new Option("Stewart County","Stewart County");
form.options[129] = new Option("Sumter County","Sumter County");
form.options[130] = new Option("Talbot County","Talbot County");
form.options[131] = new Option("Taliaferro County","Taliaferro County");
form.options[132] = new Option("Tattnall County","Tattnall County");
form.options[133] = new Option("Taylor County","Taylor County");
form.options[134] = new Option("Telfair County","Telfair County");
form.options[135] = new Option("Terrell County","Terrell County");
form.options[136] = new Option("Thomas County","Thomas County");
form.options[137] = new Option("Tift County","Tift County");
form.options[138] = new Option("Toombs County","Toombs County");
form.options[139] = new Option("Towns County","Towns County");
form.options[140] = new Option("Treutlen County","Treutlen County");
form.options[141] = new Option("Troup County","Troup County");
form.options[142] = new Option("Turner County","Turner County");
form.options[143] = new Option("Twiggs County","Twiggs County");
form.options[144] = new Option("Union County","Union County");
form.options[145] = new Option("Upson County","Upson County");
form.options[146] = new Option("Walker County","Walker County");
form.options[147] = new Option("Walton County","Walton County");
form.options[148] = new Option("Ware County","Ware County");
form.options[149] = new Option("Warren County","Warren County");
form.options[150] = new Option("Washington County","Washington County");
form.options[151] = new Option("Wayne County","Wayne County");
form.options[152] = new Option("Webster County","Webster County");
form.options[153] = new Option("Wheeler County","Wheeler County");
form.options[154] = new Option("White County","White County");
form.options[155] = new Option("Whitfield County","Whitfield County");
form.options[156] = new Option("Wilcox County","Wilcox County");
form.options[157] = new Option("Wilkes County","Wilkes County");
form.options[158] = new Option("Wilkinson County","Wilkinson County");
form.options[159] = new Option("Worth County","Worth County");
}<|fim▁end|> | form.options[127] = new Option("Stephens County","Stephens County"); |
<|file_name|>CdbReaderFactory.java<|end_file_name|><|fim▁begin|>package org.eso.ias.cdb;<|fim▁hole|>
import org.eso.ias.cdb.json.CdbFiles;
import org.eso.ias.cdb.json.CdbJsonFiles;
import org.eso.ias.cdb.json.JsonReader;
import org.eso.ias.cdb.rdb.RdbReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* The factory to get the CdbReader implementation to use.
*
* This class checks the parameters of the command line, the java properties
* and the environment variable to build and return the {@link CdbReader} to use
* for reading the CDB.
*
* It offers a common strategy to be used consistently by all the IAS tools.
*
* The strategy is as follow:
* - if -cdbClass java.class param is present in the command line then the passed class
* is dynamically loaded and built (empty constructor); the configuration
* parameters eventually expected by such class will be passed by means of java
* properties (-D...)
* - else if jCdb file.path param is present in the command line then the JSON CDB
* implementation will be returned passing the passed file path
* - else the RDB implementation is returned (note that the parameters to connect to the RDB are passed
* in the hibernate configuration file
*
* RDB implementation is the fallback if none of the other possibilities succeeds.
*
*/
public class CdbReaderFactory {
/**
* The logger
*/
private static final Logger logger = LoggerFactory.getLogger(CdbReaderFactory.class);
/**
* The parameter to set in the command line to build a CdbReader from a custom java class
*/
public static final String cdbClassCmdLineParam="-cdbClass";
/**
* The long parameter to set in the command line to build a JSON CdbReader
*/
public static final String jsonCdbCmdLineParamLong ="-jCdb";
/**
* The short parameter to set in the command line to build a JSON CdbReader
*/
public static final String jsonCdbCmdLineParamShort ="-j";
/**
* get the value of the passed parameter from the eray of strings.
*
* The value of the parameter is in the position next to the passed param name like in
* -jcdb path
*
* @param paramName the not null nor empty parameter
* @param cmdLine the command line
* @return the value of the parameter or empty if not found in the command line
*/
private static Optional<String> getValueOfParam(String paramName, String cmdLine[]) {
if (paramName==null || paramName.isEmpty()) {
throw new IllegalArgumentException("Invalid null/empty name of parameter");
}
if (cmdLine==null || cmdLine.length<2) {
return Optional.empty();
}
List<String> params = Arrays.asList(cmdLine);
int pos=params.indexOf(paramName);
if (pos==-1) {
// Not found
return Optional.empty();
}
String ret = null;
try {
ret=params.get(pos+1);
} catch (IndexOutOfBoundsException e) {
logger.error("Missing parameter for {}}",paramName);
}
return Optional.ofNullable(ret);
}
/**
* Build and return the user provided CdbReader from the passed class using introspection
*
* @param cls The class implementing the CdbReader
* @return the user defined CdbReader
*/
private static final CdbReader loadUserDefinedReader(String cls) throws IasCdbException {
if (cls==null || cls.isEmpty()) {
throw new IllegalArgumentException("Invalid null/empty class");
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<?> theClass=null;
try {
theClass=classLoader.loadClass(cls);
} catch (Exception e) {
throw new IasCdbException("Error loading the external class "+cls,e);
}
Constructor constructor = null;
try {
constructor=theClass.getConstructor(null);
} catch (Exception e) {
throw new IasCdbException("Error getting the default (empty) constructor of the external class "+cls,e);
}
Object obj=null;
try {
obj=constructor.newInstance(null);
} catch (Exception e) {
throw new IasCdbException("Error building an object of the external class "+cls,e);
}
return (CdbReader)obj;
}
/**
* Gets and return the CdbReader to use to read the CDB applying the policiy described in the javadoc
* of the class
*
* @param cmdLine The command line
* @return the CdbReader to read th CDB
* @throws Exception in case of error building the CdbReader
*/
public static CdbReader getCdbReader(String[] cmdLine) throws Exception {
Objects.requireNonNull(cmdLine,"Invalid null command line");
Optional<String> userCdbReader = getValueOfParam(cdbClassCmdLineParam,cmdLine);
if (userCdbReader.isPresent()) {
logger.info("Using external (user provided) CdbReader from class {}",userCdbReader.get());
return loadUserDefinedReader(userCdbReader.get());
} else {
logger.debug("No external CdbReader found");
}
Optional<String> jsonCdbReaderS = getValueOfParam(jsonCdbCmdLineParamShort,cmdLine);
Optional<String> jsonCdbReaderL = getValueOfParam(jsonCdbCmdLineParamLong,cmdLine);
if (jsonCdbReaderS.isPresent() && jsonCdbReaderL.isPresent()) {
throw new Exception("JSON CDB path defined twice: check "+jsonCdbCmdLineParamShort+"and "+jsonCdbCmdLineParamLong+" params in cmd line");
}
if (jsonCdbReaderL.isPresent() || jsonCdbReaderS.isPresent()) {
String cdbPath = jsonCdbReaderL.orElseGet(() -> jsonCdbReaderS.get());
logger.info("Loading JSON CdbReader with folder {}",cdbPath);
CdbFiles cdbfiles = new CdbJsonFiles(cdbPath);
return new JsonReader(cdbfiles);
} else {
logger.debug("NO JSON CdbReader requested");
}
return new RdbReader();
}
}<|fim▁end|> | |
<|file_name|>product-filter.pipe.ts<|end_file_name|><|fim▁begin|>import { PipeTransform, Pipe } from '@angular/core';
import { IProduct } from './product'
@Pipe({
name: 'productFilter'
})
export class ProductFilterPipe implements PipeTransform {
transform(value: IProduct[], filterBy: string): IProduct[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
return filterBy ? value.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;<|fim▁hole|>}<|fim▁end|> | } |
<|file_name|>regions-fn-subtyping.rs<|end_file_name|><|fim▁begin|>// run-pass
#![allow(dead_code)]
#![allow(unused_assignments)]
// Issue #2263.
// pretty-expanded FIXME #23616
#![allow(unused_variables)]
// Should pass region checking.<|fim▁hole|> // f's type should be a subtype of g's type), because f can be
// used in any context that expects g's type. But this currently
// fails.
let mut g: Box<dyn for<'r> FnMut(&'r usize)> = Box::new(|x| { });
g = f;
}
// This version is the same as above, except that here, g's type is
// inferred.
fn ok_inferred(f: Box<dyn FnMut(&usize)>) {
let mut g: Box<dyn for<'r> FnMut(&'r usize)> = Box::new(|_| {});
g = f;
}
pub fn main() {
}<|fim▁end|> | fn ok(f: Box<dyn FnMut(&usize)>) {
// Here, g is a function that can accept a usize pointer with
// lifetime r, and f is a function that can accept a usize pointer
// with any lifetime. The assignment g = f should be OK (i.e., |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>#coding: utf-8
__author__ = 'horacioibrahim'
import unittest, os
import datetime
from time import sleep, ctime, time
from random import randint
from hashlib import md5
from types import StringType
# python-iugu package modules
import merchant, customers, config, invoices, errors, plans, subscriptions
def check_tests_environment():
"""
For tests is need environment variables to instantiate merchant. Or
Edit tests file to instantiate merchant.IuguMerchant(account_id=YOUR_ID)
"""
try:
global ACCOUNT_ID
ACCOUNT_ID = os.environ["ACCOUNT_ID"]
except KeyError:
raise errors.IuguConfigTestsErrors("Only for tests is required an environment " \
"variable ACCOUNT_ID or edit file tests.py")
class TestMerchant(unittest.TestCase):
check_tests_environment() # Checks if enviroment variables defined
def setUp(self):
self.EMAIL_CUSTOMER = "[email protected]"
self.client = merchant.IuguMerchant(account_id=ACCOUNT_ID,
api_mode_test=True)
def tearDown(self):
pass
def test_create_payment_token_is_test(self):
response = self.client.create_payment_token('4111111111111111', 'JA', 'Silva',
'12', '2010', '123')
self.assertTrue(response.is_test)
def test_create_payment_token(self):
response = self.client.create_payment_token('4111111111111111', 'JA', 'Silva',
'12', '2010', '123')
self.assertEqual(response.status, 200)
def test_create_charge_credit_card(self):
item = merchant.Item("Produto My Test", 1, 10000)
token = self.client.create_payment_token('4111111111111111', 'JA', 'Silva',
'12', '2010', '123')
charge = self.client.create_charge(self.EMAIL_CUSTOMER, item, token=token)
self.assertEqual(charge.is_success(), True)
def test_create_charge_bank_slip(self):
item = merchant.Item("Produto Bank Slip", 1, 1000)
charge = self.client.create_charge(self.EMAIL_CUSTOMER, item)
self.assertEqual(charge.is_success(), True)
class TestCustomer(unittest.TestCase):
def setUp(self):
hash_md5 = md5()
number = randint(1, 50)
hash_md5.update(str(number))
email = "{email}@test.com".format(email=hash_md5.hexdigest())
self.random_user_email = email
def test_create_customer_basic_info(self):
consumer = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
c = consumer.create()
c.remove()
self.assertEqual(consumer.email, c.email)
def test_create_customer_basic_email(self):
consumer = customers.IuguCustomer()
c = consumer.create(email=self.random_user_email)
c.remove()
self.assertEqual(consumer.email, c.email)
def test_create_customer_extra_attrs(self):
consumer = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
c = consumer.create(name="Mario Lago", notes="It's the man",
custom_variables={'local':'cup'})
c.remove()
self.assertEqual(c.custom_variables[0]['name'], "local")
self.assertEqual(c.custom_variables[0]['value'], "cup")
def test_get_customer(self):
consumer = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
consumer_new = consumer.create()
c = consumer.get(customer_id=consumer_new.id)
consumer_new.remove()
self.assertEqual(consumer.email, c.email)
def test_set_customer(self):
consumer = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
consumer_new = consumer.create(name="Mario Lago", notes="It's the man",
custom_variables={'local':'cup'})
c = consumer.set(consumer_new.id, name="Lago Mario")
consumer_new.remove()
self.assertEqual(c.name, "Lago Mario")
def test_customer_save(self):
consumer = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
consumer_new = consumer.create(name="Mario Lago", notes="It's the man",
custom_variables={'local':'cup'})
# Edit info
consumer_new.name = "Ibrahim Horacio"
# Save as instance
consumer_new.save()
# verify results
check_user = consumer.get(consumer_new.id)
consumer_new.remove()
self.assertEqual(check_user.name, "Ibrahim Horacio")
def test_customer_delete_by_id(self):
consumer = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
consumer_new = consumer.create(name="Mario Lago", notes="It's the man",
custom_variables={'local':'cup'})
consumer.delete(consumer_new.id)
self.assertRaises(errors.IuguGeneralException, consumer.get,
consumer_new.id)
def test_customer_delete_instance(self):
consumer = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
consumer_new = consumer.create(name="Mario Lago", notes="It's the man",
custom_variables={'local':'cup'})
r = consumer_new.remove()
self.assertRaises(errors.IuguGeneralException, consumer.get,
consumer_new.id)
class TestCustomerLists(unittest.TestCase):
def setUp(self):
hash_md5 = md5()
number = randint(1, 50)
hash_md5.update(str(number))
email = "{email}@test.com".format(email=hash_md5.hexdigest())
self.random_user_email = email
self.c = customers.IuguCustomer(api_mode_test=True,
email=self.random_user_email)
# creating customers for tests with lists
p1, p2, p3 = "Andrea", "Bruna", "Carol"
self.one = self.c.create(name=p1, notes="It's the man",
custom_variables={'local':'cup'})
# I'm not happy with it (sleep), but was need. This certainly occurs because
# time data is not a timestamp.
sleep(1)
self.two = self.c.create(name=p2, notes="It's the man",
custom_variables={'local':'cup'})
sleep(1)
self.three = self.c.create(name=p3, notes="It's the man",
custom_variables={'local':'cup'})
sleep(1)
self.p1, self.p2, self.p3 = p1, p2, p3
def tearDown(self):
self.one.remove()
self.two.remove()
self.three.remove()
def test_getitems(self):
customers_list = self.c.getitems()
self.assertEqual(type(customers_list), list)
def test_getitems_limit(self):
# get items with auto DESC order
customers_list = self.c.getitems(limit=2)
self.assertEqual(len(customers_list), 2)
def test_getitems_start(self):
# get items with auto DESC order
sleep(2)
customers_list = self.c.getitems(limit=3) # get latest three customers
reference_customer = customers_list[2].name
customers_list = self.c.getitems(skip=2)
self.assertEqual(customers_list[0].name, reference_customer)
def test_getitems_query_by_match_in_name(self):
hmd5 = md5()
hmd5.update(ctime(time()))
salt = hmd5.hexdigest()
term = 'name_inexistent_or_improbable_here_{salt}'.format(salt=salt)
# test value/term in >>name<<
customer = self.c.create(name=term)
sleep(2)
items = self.c.getitems(query=term) # assert valid because name
customer.remove()
self.assertEqual(items[0].name, term)
def test_getitems_query_by_match_in_notes(self):
hmd5 = md5()
hmd5.update(ctime(time()))
salt = hmd5.hexdigest()
term = 'name_inexistent_or_improbable_here_{salt}'.format(salt=salt)
# test value/term in >>notes<<
customer = self.c.create(name="Sub Zero", notes=term)
sleep(2)
items = self.c.getitems(query=term)
customer.remove()
self.assertEqual(items[0].notes, term)
def test_getitems_query_by_match_in_email(self):
hmd5 = md5()
hmd5.update(ctime(time()))
salt = hmd5.hexdigest()
term = 'name_inexistent_or_improbable_here_{salt}'.format(salt=salt)
# test value/term in >>email<<
email = term + '@email.com'
self.c.email = email
customer = self.c.create()
sleep(2)
items = self.c.getitems(query=term)
customer.remove()
self.assertIn(term, items[0].email)
# Uncomment/comment the next one line to disable/enable the test
@unittest.skip("Database of webservice is not empty")
def test_getitems_sort(self):
sleep(1) # Again. It's need
# Useful to test database with empty data (previous data, old tests)
customers_list = self.c.getitems(sort="name")
# monkey skip
if len(customers_list) < 4:
self.assertEqual(customers_list[0].name, self.p1)
else:
raise TypeError("API Database is not empty. This test isn't useful. " \
"Use unittest.skip() before this method.")
def test_getitems_created_at_from(self):
sleep(1)
customers_list = self.c.getitems(created_at_from=self.three.created_at)
self.assertEqual(customers_list[0].id, self.three.id)
# Uncomment the next one line to disable the test
# @unittest.skip("Real-time interval not reached")
def test_getitems_created_at_to(self):
sleep(1)
customers_list = self.c.getitems(created_at_to=self.one.created_at)
self.assertEqual(customers_list[0].id, self.three.id)
def test_getitems_updated_since(self):
# get items with auto DESC order
sleep(1)
customers_list = self.c.getitems(updated_since=self.three.created_at)
self.assertEqual(customers_list[0].id, self.three.id)
class TestCustomerPayments(unittest.TestCase):
def setUp(self):
hash_md5 = md5()
number = randint(1, 50)
hash_md5.update(str(number))
email = "{email}@test.com".format(email=hash_md5.hexdigest())
self.random_user_email = email
self.client = customers.IuguCustomer(email="[email protected]")
self.customer = self.client.create()
self.instance_payment = self.customer.payment.create(description="New payment method",
number='4111111111111111',
verification_value=123,
first_name="Joao", last_name="Maria",
month=12, year=2014)
def tearDown(self):
self.instance_payment.remove()
self.customer.remove() # if you remove customer also get payment
def test_create_payment_method_new_user_by_create(self):
""" Test create payment method to new recent user returned by create()
of IuguCustomer
"""
instance_payment = self.customer.payment.create(description="New payment method",
number='4111111111111111',
verification_value=123,
first_name="Joao", last_name="Maria",
month=12, year=2014)
instance_payment.remove()
self.assertTrue(isinstance(instance_payment, customers.IuguPaymentMethod))
def test_create_payment_method_existent_user_by_get(self):
""" Test create payment method of existent user returned by get()
of IuguCustomer.
"""
new_customer = self.client.create()
# Test with user from get()
existent_customer = self.client.get(new_customer.id)
instance_payment = existent_customer.payment.create(description="New payment method",
number='4111111111111111',
verification_value=123,
first_name="Joao", last_name="Maria",
month=12, year=2015)
instance_payment.remove()
self.assertTrue(isinstance(instance_payment, customers.IuguPaymentMethod))
def test_create_payment_method_existent_user_by_getitems(self):
""" Test create payment method of existent user returned by getitems()
of IuguCustomer
"""
# Test with user from getitems()
customers_list = self.client.getitems()
c_0 = customers_list[0]
instance_payment = c_0.payment.create(description="New payment method",
number='4111111111111111',
verification_value=123,
first_name="Joao", last_name="Maria",
month=12, year=2016)
instance_payment.remove()
self.assertTrue(isinstance(instance_payment, customers.IuguPaymentMethod))
def test_create_payment_method_non_existent_user_by_instance(self):
""" Test create payment method to instance's user before it was
created in API. So without ID.
"""
create = self.client.payment.create
self.assertRaises(errors.IuguPaymentMethodException,
create, description="New payment method",
number='4111111111111111',
verification_value=123, first_name="Joao",
last_name="Maria", month=12, year=2016)
def test_create_payment_method_raise_general(self):
# Create payment method without data{} where API returns error.
customer = self.client.create()
self.assertRaises(errors.IuguGeneralException, customer.payment.create,
description="Second payment method")
customer.remove()
def test_get_payment_method_by_payment_id_customer_id(self):
# Test get payment based payment_id and customer_id
id = self.instance_payment.id
# two args passed
payment = self.client.payment.get(id, customer_id=self.customer.id)
self.assertTrue(isinstance(payment, customers.IuguPaymentMethod))
def test_get_payment_by_customer(self):
# Test get payment by instance's customer (existent in API)
id = self.instance_payment.id
# one arg passed. user is implicit to customer
payment = self.customer.payment.get(id)
self.assertTrue(isinstance(payment, customers.IuguPaymentMethod))
def test_set_payment_by_payment_id_customer_id(self):
# Changes payment method base payment_id and customer_id
id = self.instance_payment.id
# two args passed
payment = self.client.payment.set(id, "New Card Name",
customer_id=self.customer.id)
self.assertTrue(isinstance(payment, customers.IuguPaymentMethod))
payment_test = self.customer.payment.get(payment.id)
self.assertEqual(payment_test.description, payment.description)
def test_set_payment_by_customer(self):
# Changes payment method base payment_id of an intance's customer
id = self.instance_payment.id
# one arg passed. user is implicit to customer
payment = self.customer.payment.set(id, "New Card Name")
self.assertTrue(isinstance(payment, customers.IuguPaymentMethod))
payment_test = self.customer.payment.get(payment.id)
self.assertEqual(payment_test.description, payment.description)
def test_set_payment_by_customer_by_save(self):
""" Changes payment method of an instance's payment no payment_id or
no customer_id is need"""
self.instance_payment.description = "New Card Name"
# no args passed. To payment method instance this is implicit
payment = self.instance_payment.save()
self.assertTrue(isinstance(payment, customers.IuguPaymentMethod))
payment_test = self.customer.payment.get(payment.id)
self.assertEqual(payment_test.description, payment.description)
def test_set_payment_remove(self):
""" Changes payment method of an instance's payment no payment_id or
no customer_id is need"""
instance_payment = self.customer.payment.create(description="New payment method",
number='4111111111111111',
verification_value=123,
first_name="Joao", last_name="Maria",
month=12, year=2014)
instance_payment.remove()
# Try get payment already removed
payment_test = self.customer.payment.get # copy method
self.assertRaises(errors.IuguGeneralException, payment_test,
instance_payment.id)
def test_set_payment_remove_by_attrs(self):
"""
"""
instance_payment = self.customer.payment
instance_payment.payment_data.description = "New payment method"
instance_payment.payment_data.number = number='4111111111111111'
instance_payment.payment_data.verification_value = 123
instance_payment.payment_data.first_name = "Joao"
instance_payment.payment_data.last_name = "Silva"
instance_payment.payment_data.month = 12
instance_payment.payment_data.year = 2015
instance_payment = instance_payment.create(description="Meu cartao")
instance_payment.remove()
self.assertRaises(errors.IuguGeneralException, instance_payment.get, instance_payment.id)
def test_getitems_payments(self):
payment_one = self.customer.payment.create(description="New payment One",
number='4111111111111111',
verification_value=123,
first_name="World", last_name="Cup",
month=12, year=2014)
payment_two = self.customer.payment.create(description="New payment Two",
number='4111111111111111',
verification_value=123,
first_name="Is a ", last_name="Problem",
month=12, year=2015)
payment_three = self.customer.payment.create(description="New payment Three",
number='4111111111111111',
verification_value=123,
first_name="To Brazil", last_name="Worry",
month=12, year=2015)
list_of_payments = self.customer.payment.getitems()
self.assertTrue(isinstance(list_of_payments, list))
self.assertTrue(isinstance(list_of_payments[0],
customers.IuguPaymentMethod))
class TestInvoice(unittest.TestCase):
TODAY = datetime.date.today().strftime("%d/%m/%Y")
check_tests_environment() # Checks if enviroment variables defined
def setUp(self):
hash_md5 = md5()
number = randint(1, 50)
hash_md5.update(str(number))
email = "{email}@test.com".format(email=hash_md5.hexdigest())
self.customer_email = email
# create a customer for tests
c = customers.IuguCustomer()
self.consumer = c.create(email="[email protected]")
# create a invoice
item = merchant.Item("Prod 1", 1, 1190)
self.item = item
self.invoice_obj = invoices.IuguInvoice(email=self.customer_email,
item=item, due_date=self.TODAY)
self.invoice = self.invoice_obj.create(draft=True)
# to tests for refund
self.EMAIL_CUSTOMER = "[email protected]"
self.client = merchant.IuguMerchant(account_id=ACCOUNT_ID,
api_mode_test=True)
def tearDown(self):
if self.invoice.id: # if id is None already was removed
self.invoice.remove()
self.consumer.remove()
def test_invoice_raise_required_email(self):
i = invoices.IuguInvoice()
self.assertRaises(errors.IuguInvoiceException, i.create,
due_date="30/11/2020", items=self.item)
def test_invoice_raise_required_due_date(self):
i = invoices.IuguInvoice()
self.assertRaises(errors.IuguInvoiceException, i.create,
email="[email protected]", items=self.item)
def test_invoice_raise_required_items(self):
i = invoices.IuguInvoice()
self.assertRaises(errors.IuguInvoiceException, i.create,
due_date="30/11/2020", email="[email protected]")
def test_invoice_create_basic(self):
self.assertTrue(isinstance(self.invoice, invoices.IuguInvoice))
def test_invoice_with_customer_id(self):
res = self.invoice_obj.create(customer_id=self.consumer.id)
self.assertEqual(res.customer_id, self.consumer.id)
def test_invoice_create_all_fields_as_draft(self):
response = self.invoice_obj.create(draft=True, return_url='http://hipy.co/success',
expired_url='http://hipy.co/expired',
notification_url='http://hipy.co/webhooks',
tax_cents=200, discount_cents=500,
customer_id=self.consumer.id,
ignore_due_email=True)
self.assertTrue(isinstance(response, invoices.IuguInvoice))
existent_invoice = invoices.IuguInvoice.get(response.id)
self.assertEqual(existent_invoice.expiration_url, response.expiration_url)
response.remove()
def test_invoice_create_all_fields_as_pending(self):
response = self.invoice_obj.create(draft=False,
return_url='http://example.com/success',
expired_url='http://example.com/expired',
notification_url='http://example.com/webhooks',
tax_cents=200, discount_cents=500,
customer_id=self.consumer.id,
ignore_due_email=True)
self.assertTrue(isinstance(response, invoices.IuguInvoice))
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund.
# response.remove()
def test_invoice_created_check_id(self):
self.assertIsNotNone(self.invoice.id)
def test_invoice_create_with_custom_variables_in_create(self):
invoice = self.invoice_obj.create(draft=True,
custom_variables={'city': 'Brasilia'})
self.assertEqual(invoice.custom_variables[0]["name"], "city")
self.assertEqual(invoice.custom_variables[0]["value"], "Brasilia")
invoice.remove()
def test_invoice_create_with_custom_variables_in_set(self):
invoice = self.invoice_obj.set(invoice_id=self.invoice.id,
custom_variables={'city': 'Brasilia'})
self.assertEqual(invoice.custom_variables[0]["name"], "city")
self.assertEqual(invoice.custom_variables[0]["value"], "Brasilia")
def test_invoice_get_one(self):
# test start here
res = invoices.IuguInvoice.get(self.invoice.id)
self.assertEqual(res.items[0].description, "Prod 1")
def test_invoice_create_as_draft(self):
self.assertEqual(self.invoice.status, 'draft')
def test_invoice_edit_email_with_set(self):
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id, email="[email protected]")
self.assertEqual(invoice_edited.email, u"[email protected]")
def test_invoice_edit_return_url_with_set(self):
return_url = "http://hipy.co"
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
return_url=return_url)
self.assertEqual(invoice_edited.return_url, return_url)
@unittest.skip("It isn't support by API")
def test_invoice_edit_expired_url_with_set(self):
expired_url = "http://hipy.co"
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
expired_url=expired_url)
self.assertEqual(invoice_edited.expiration_url, expired_url)
def test_invoice_edit_notification_url_with_set(self):
notification_url = "http://hipy.co"
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
notification_url=notification_url)
self.assertEqual(invoice_edited.notification_url, notification_url)
def test_invoice_edit_tax_cents_with_set(self):
tax_cents = 200
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
tax_cents=tax_cents)
self.assertEqual(invoice_edited.tax_cents, tax_cents)
def test_invoice_edit_discount_cents_with_set(self):
discount_cents = 500
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
discount_cents=discount_cents)
self.assertEqual(invoice_edited.discount_cents, discount_cents)
def test_invoice_edit_customer_id_with_set(self):
customer_id = self.consumer.id
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
customer_id=customer_id)
self.assertEqual(invoice_edited.customer_id, customer_id)
@unittest.skip("without return from API of the field/attribute ignore_due_email")
def test_invoice_edit_ignore_due_email_with_set(self):
ignore_due_email = True
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
ignore_due_email=ignore_due_email)
self.assertEqual(invoice_edited.ignore_due_email, ignore_due_email)
# TODO: def test_invoice_edit_subscription_id_with_set(self):
# TODO: test_invoice_edit_credits_with_set(self):
def test_invoice_edit_due_date_with_set(self):
due_date = self.TODAY
response_from_api = str(datetime.date.today())
id = self.invoice.id
invoice_edited = self.invoice_obj.set(invoice_id=id,
due_date=due_date)
self.assertEqual(invoice_edited.due_date, response_from_api)
def test_invoice_edit_items_with_set(self):
self.invoice.items[0].description = "Prod Fixed Text and Value"
id = self.invoice.id
items = self.invoice.items[0]
invoice_edited = self.invoice_obj.set(invoice_id=id, items=items)
self.assertEqual(invoice_edited.items[0].description, "Prod Fixed Text and Value")
def test_invoice_changed_items_with_save(self):
self.invoice.items[0].description = "Prod Saved by Instance"
# inv_one is instance not saved. Now, we have invoice saved
# and invoice_edited that is the response of webservice
res = self.invoice.save()
self.assertEqual(res.items[0].description, "Prod Saved by Instance")
def test_invoice_destroy_item(self):
# Removes one item, the unique, created in invoice
self.invoice.items[0].remove()
re_invoice = self.invoice.save()
self.assertEqual(re_invoice.items, None)
def test_invoice_remove(self):
# wait webservice response time
sleep(3)
self.invoice.remove()
self.assertEqual(self.invoice.id, None)
def test_invoice_get_and_save(self):
inv = invoices.IuguInvoice.get(self.invoice.id)
inv.email = "[email protected]"
obj = inv.save()
self.assertEqual(obj.email, inv.email)
def test_invoice_getitems_and_save(self):
sleep(2) # wating...API to persist data
inv = None
invs = invoices.IuguInvoice.getitems()
for i in invs:
if i.id == self.invoice.id:
inv = i
inv.email = "[email protected]"
obj = inv.save()
self.assertEqual(obj.email, inv.email)
def test_invoice_cancel(self):
invoice = self.invoice_obj.create(draft=False)
re_invoice = invoice.cancel()
self.assertEqual(re_invoice.status, "canceled")
invoice.remove()
#@unittest.skip("Support only invoice paid") # TODO
def test_invoice_refund(self):
item = merchant.Item("Produto My Test", 1, 10000)
token = self.client.create_payment_token('4111111111111111', 'JA', 'Silva',
'12', '2010', '123')
charge = self.client.create_charge(self.EMAIL_CUSTOMER, item, token=token)
invoice = invoices.IuguInvoice.get(charge.invoice_id)
re_invoice = invoice.refund()
self.assertEqual(re_invoice.status, "refunded")
def test_invoice_getitems(self):
# wait webservice response time
sleep(3)
l = invoices.IuguInvoice.getitems()
self.assertIsInstance(l, list)
self.assertIsInstance(l[0], invoices.IuguInvoice)
def test_invoice_getitems_limit(self):
invoice_2 = self.invoice_obj.create()
sleep(3)
l = invoices.IuguInvoice.getitems(limit=2)
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund.
# invoice_2.remove()
self.assertEqual(len(l), 2)
def test_invoice_getitems_skip(self):
invoice_1 = self.invoice_obj.create()
invoice_2 = self.invoice_obj.create()
invoice_3 = self.invoice_obj.create()
sleep(3)
l1 = invoices.IuguInvoice.getitems(limit=3)
keep_checker = l1[2]
l2 = invoices.IuguInvoice.getitems(skip=2)
skipped = l2[0] # after skip 2 the first must be keep_checker
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund.
# invoice_1.remove()
# invoice_2.remove()
# invoice_3.remove()
self.assertEqual(keep_checker.id, skipped.id)
# TODO: def test_invoice_getitems_created_at_from(self):
# TODO:def test_invoice_getitems_created_at_to(self):
# TODO: def test_invoice_getitems_updated_since(self):
def test_invoice_getitems_query(self):
res = self.invoice_obj.create(customer_id=self.consumer.id)
sleep(3)
queryset = invoices.IuguInvoice.getitems(query=res.id)
self.assertEqual(queryset[0].customer_id, res.customer_id)
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund.
# res.remove()
def test_invoice_getitems_customer_id(self):
res = self.invoice_obj.create(customer_id=self.consumer.id)
sleep(3)
queryset = invoices.IuguInvoice.getitems(query=res.id)
self.assertEqual(queryset[0].customer_id, res.customer_id)
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund.
# res.remove()
@unittest.skip("API no support sort (in moment)")
def test_invoice_getitems_sort(self):
invoice_1 = self.invoice_obj.create()
invoice_2 = self.invoice_obj.create()
invoice_3 = self.invoice_obj.create()
sleep(3)
l1 = invoices.IuguInvoice.getitems(limit=3)
keep_checker = l1[2]
l2 = invoices.IuguInvoice.getitems(limit=3, sort="id")
skipped = l2[0] # after skip 2 the first must be keep_checker
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund.
# invoice_1.remove()
# invoice_2.remove()
# invoice_3.remove()
self.assertEqual(keep_checker.id, skipped.id)
class TestPlans(unittest.TestCase):
def setUp(self):
hash_md5 = md5()
seed = randint(1, 199)
variation = randint(4, 8)
hash_md5.update(str(seed))
identifier = hash_md5.hexdigest()[:variation]
self.identifier = identifier # random because can't be repeated
plan = plans.IuguPlan()
self.plan = plan.create(name="My SetUp Plan", identifier=self.identifier,
interval=1, interval_type="months",
currency="BRL", value_cents=1500)
# features
self.features = plans.Feature()
self.features.name = "Add feature %s" % self.identifier
self.features.identifier = self.identifier
self.features.value = 11
def tearDown(self):
self.plan.remove()
def test_plan_create(self):
plan = plans.IuguPlan()
identifier = self.identifier + "salt"
new_plan = plan.create(name="My first lib Plan", identifier=identifier,
interval=1, interval_type="months",
currency="BRL", value_cents=1000)
self.assertIsInstance(new_plan, plans.IuguPlan)
self.assertTrue(new_plan.id)
new_plan.remove()
def test_plan_create_without_required_fields(self):
plan = plans.IuguPlan()
self.assertRaises(errors.IuguPlansException, plan.create)
def test_plan_create_features(self):
salt = randint(1, 99)
identifier = self.identifier + str(salt)
# init object
plan = plans.IuguPlan(name="Plan with features", identifier=identifier,
interval=1, interval_type="months",
currency="BRL", value_cents=1000)
plan.features = [self.features,]
new_plan_with_features = plan.create()
self.assertIsInstance(new_plan_with_features.features[0], plans.Feature)
self.assertEqual(new_plan_with_features.features[0].value, self.features.value)
new_plan_with_features.remove()
def test_plan_get(self):
plan_id = self.plan.id
plan = plans.IuguPlan.get(plan_id)
self.assertEqual(self.identifier, plan.identifier)
def test_plan_get_identifier(self):
plan = plans.IuguPlan.get_by_identifier(self.identifier)
self.assertEqual(self.identifier, plan.identifier)
def test_plan_remove(self):
plan = plans.IuguPlan()
new_plan = plan.create(name="Remove me", identifier="to_remove",
interval=1, interval_type="months",
currency="BRL", value_cents=2000)
removed_id = new_plan.id
new_plan.remove()
self.assertRaises(errors.IuguGeneralException,
plans.IuguPlan.get, removed_id)
def test_plan_edit_changes_name_by_set(self):
plan_id = self.plan.id
new_name = "New name %s" % self.identifier
modified_plan = self.plan.set(plan_id, name=new_name)
self.assertEqual(new_name, modified_plan.name)
def test_plan_edit_changes_identifier_by_set(self):
plan_id = self.plan.id
new_identifier = "New identifier %s" % self.identifier
modified_plan = self.plan.set(plan_id, identifier=new_identifier)
self.assertEqual(new_identifier, modified_plan.identifier)
def test_plan_edit_changes_interval_by_set(self):
plan_id = self.plan.id
new_interval = 3
modified_plan = self.plan.set(plan_id, interval=new_interval)
self.assertEqual(new_interval, modified_plan.interval)
def test_plan_edit_changes_currency_by_set(self):
plan_id = self.plan.id
new_currency = "US"
self.assertRaises(errors.IuguPlansException, self.plan.set,
plan_id, currency=new_currency)
def test_plan_edit_changes_value_cents_by_set(self):
plan_id = self.plan.id
value_cents = 3000
modified_plan = self.plan.set(plan_id, value_cents=value_cents)
self.assertEqual(value_cents, modified_plan.prices[0].value_cents)
def test_plan_edit_changes_features_name_by_set(self):
salt = randint(1, 99)
identifier = self.identifier + str(salt)
# creating a plan with features
plan = plans.IuguPlan()
plan.features = [self.features,]
plan.name = "Changes Features Name"
plan.identifier = identifier # workaround: setUp already creates
plan.interval = 2
plan.interval_type = "weeks"
plan.currency = "BRL"
plan.value_cents = 3000
plan_returned = plan.create()
# to change features name where features already has an id
changed_features = plan_returned.features
changed_features[0].name = "Changed Name of Features"
# return plan changed
plan_changed = plan.set(plan_returned.id, features=[changed_features[0]])
self.assertEqual(plan_changed.features[0].name,
plan_returned.features[0].name)
plan_returned.remove()
def test_plan_edit_changes_features_identifier_by_set(self):
salt = randint(1, 99)
identifier = self.identifier + str(salt)
# creating a plan with features
plan = plans.IuguPlan()
plan.features = [self.features,]
plan.name = "Changes Features Identifier"
plan.identifier = identifier # workaround: setUp already creates
plan.interval = 2
plan.interval_type = "weeks"
plan.currency = "BRL"
plan.value_cents = 3000
plan_returned = plan.create()
# to change features name where features already has an id
changed_features = plan_returned.features
changed_features[0].identifier = "Crazy_Change"
# return plan changed
plan_changed = plan.set(plan_returned.id, features=[changed_features[0]])
self.assertEqual(plan_changed.features[0].identifier,
plan_returned.features[0].identifier)
plan_returned.remove()
<|fim▁hole|> identifier = self.identifier + str(salt)
# creating a plan with features
plan = plans.IuguPlan()
plan.features = [self.features,]
plan.name = "Changes Features Identifier"
plan.identifier = identifier # workaround: setUp already creates
plan.interval = 2
plan.interval_type = "weeks"
plan.currency = "BRL"
plan.value_cents = 3000
plan_returned = plan.create()
# to change features name where features already has an id
changed_features = plan_returned.features
changed_features[0].value = 10000
# return plan changed
plan_changed = plan.set(plan_returned.id, features=[changed_features[0]])
self.assertEqual(plan_changed.features[0].value,
plan_returned.features[0].value)
plan_returned.remove()
def test_plan_edit_changes_name_by_save(self):
self.plan.name = "New name %s" % self.identifier
response = self.plan.save()
self.assertEqual(response.name, self.plan.name)
def test_plan_edit_changes_identifier_by_save(self):
seed = randint(1, 999)
self.plan.identifier = "New_identifier_%s_%s" % (self.identifier,
seed)
response = self.plan.save()
self.assertEqual(response.identifier, self.plan.identifier)
def test_plan_edit_changes_interval_by_save(self):
self.plan.interval = 4
response = self.plan.save()
self.assertEqual(response.interval, 4)
def test_plan_edit_changes_currency_by_save(self):
# API only support BRL
self.plan.currency = "US"
# response = self.plan.save()
self.assertRaises(errors.IuguPlansException, self.plan.save)
def test_plan_edit_changes_value_cents_by_save(self):
self.plan.value_cents = 4000
response = self.plan.save()
self.assertEqual(response.prices[0].value_cents, 4000)
# TODO: test prices attribute of plan in level one
def test_plan_edit_changes_features_name_by_save(self):
salt = randint(1, 99)
identifier = self.identifier + str(salt)
# creating a plan with features
plan = plans.IuguPlan()
plan.features = [self.features,]
plan.name = "Changes Features by Save"
plan.identifier = identifier # workaround: setUp already creates
plan.interval = 2
plan.interval_type = "weeks"
plan.currency = "BRL"
plan.value_cents = 3000
plan_returned = plan.create()
# to change features name where features already has an id
to_change_features = plan_returned.features
to_change_features[0].name = "Features New by Save"
# return plan changed and to save instance
plan_returned.features = [to_change_features[0]]
plan_changed = plan_returned.save()
self.assertEqual(plan_changed.features[0].name, "Features New by Save")
plan_returned.remove()
def test_plan_edit_changes_features_identifier_by_save(self):
salt = randint(1, 99)
identifier = self.identifier + str(salt)
# creating a plan with features
plan = plans.IuguPlan()
plan.features = [self.features,]
plan.name = "Changes Features by Save"
plan.identifier = identifier # workaround: setUp already creates
plan.interval = 2
plan.interval_type = "weeks"
plan.currency = "BRL"
plan.value_cents = 3000
plan_returned = plan.create()
# to change features name where features already has an id
to_change_features = plan_returned.features
to_change_features[0].identifier = "Crazy_Changed"
# return plan changed and to save instance
plan_returned.features = [to_change_features[0]]
plan_changed = plan_returned.save()
self.assertEqual(plan_changed.features[0].identifier, "Crazy_Changed")
plan_returned.remove()
def test_plan_edit_changes_features_value_by_save(self):
salt = randint(1, 99)
identifier = self.identifier + str(salt)
# creating a plan with features
plan = plans.IuguPlan()
plan.features = [self.features,]
plan.name = "Changes Features by Save"
plan.identifier = identifier # workaround: setUp already creates
plan.interval = 2
plan.interval_type = "weeks"
plan.currency = "BRL"
plan.value_cents = 3000
plan_returned = plan.create()
# to change features name where features already has an id
to_change_features = plan_returned.features
to_change_features[0].value = 8000
# return plan changed and to save instance
plan_returned.features = [to_change_features[0]]
plan_changed = plan_returned.save()
self.assertEqual(plan_changed.features[0].value, 8000)
plan_returned.remove()
def test_plan_getitems_filter_limit(self):
# creating a plan with features
salt = str(randint(1, 199)) + self.identifier
plan = plans.IuguPlan()
plan_a = plan.create(name="Get Items...",
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=1000)
salt = str(randint(1, 199)) + self.identifier
plan_b = plan.create(name="Get Items...",
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=2000)
salt = str(randint(1, 199)) + self.identifier
plan_c = plan.create(name="Get Items...",
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=3000)
all_plans = plans.IuguPlan.getitems(limit=3)
self.assertEqual(len(all_plans), 3)
plan_a.remove()
plan_b.remove()
plan_c.remove()
def test_plan_getitems_filter_skip(self):
# creating a plan with features
salt = str(randint(1, 199)) + self.identifier
plan = plans.IuguPlan()
plan_a = plan.create(name="Get Items...",
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=1000)
salt = str(randint(1, 199)) + self.identifier
plan_b = plan.create(name="Get Items...",
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=2000)
salt = str(randint(1, 199)) + self.identifier
plan_c = plan.create(name="Get Items...",
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=3000)
sleep(2)
all_plans_limit = plans.IuguPlan.getitems(limit=3)
all_plans_skip = plans.IuguPlan.getitems(skip=2, limit=3)
self.assertEqual(all_plans_limit[2].id, all_plans_skip[0].id)
plan_a.remove()
plan_b.remove()
plan_c.remove()
def test_plan_getitems_filter_query(self):
salt = str(randint(1, 199)) + self.identifier
name_repeated = salt
plan = plans.IuguPlan()
plan_a = plan.create(name=name_repeated,
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=1000)
salt = str(randint(1, 199)) + self.identifier
plan_b = plan.create(name=name_repeated,
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=2000)
salt = str(randint(1, 199)) + self.identifier
plan_c = plan.create(name=name_repeated,
identifier=salt, interval=2,
interval_type="weeks", currency="BRL",
value_cents=3000)
sleep(3) # waiting API to keep data
all_filter_query = plans.IuguPlan.getitems(query=name_repeated)
self.assertEqual(all_filter_query[0].name, name_repeated)
self.assertEqual(len(all_filter_query), 3)
plan_a.remove()
plan_b.remove()
plan_c.remove()
#@unittest.skip("TODO support this test")
# TODO: def test_plan_getitems_filter_updated_since(self):
#@unittest.skip("Sort not work fine. Waiting support of API providers")
#def test_plan_getitems_filter_sort(self):
class TestSubscriptions(unittest.TestCase):
def clean_invoices(self, recent_invoices):
"""
Removes invoices created in backgrounds of tests
"""
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund. (API CHANGED)
#
#if recent_invoices:
# invoice = recent_invoices[0]
# invoices.IuguInvoice().remove(invoice_id=invoice["id"])
pass
def setUp(self):
# preparing object...
seed = randint(1, 10000)
md5_hash = md5()
md5_hash.update(str(seed))
plan_id_random = md5_hash.hexdigest()[:12]
plan_name = "Subs Plan %s" % plan_id_random
name = "Ze %s" % plan_id_random
email = "{name}@example.com".format(name=plan_id_random)
# plans for multiple tests
self.plan_new = plans.IuguPlan().create(name=plan_name,
identifier=plan_id_random,
interval=1,
interval_type="weeks",
currency="BRL",
value_cents=9900)
plan_identifier = "plan_for_changes_%s" % plan_id_random
self.plan_two = plans.IuguPlan().create(name="Plan Two",
identifier=plan_identifier, interval=1,
interval_type="weeks", currency="BRL",
value_cents=8800)
# one client
self.customer = customers.IuguCustomer().create(name=name, email=email)
# for tests to edit subscriptions
subs_obj = subscriptions.IuguSubscription()
self.subscription = subs_obj.create(customer_id=self.customer.id,
plan_identifier=self.plan_two.identifier)
def tearDown(self):
# Attempt to delete the invoices created by subscriptions cases
# But this not remove all invoices due not recognizable behavior
# as the API no forever return recents_invoices for created
# invoices
# The comments below was put because API don't exclude
# an invoice that was paid. So only does refund. (API CHANGED)
#### if self.subscription.recent_invoices:
#### invoice = self.subscription.recent_invoices[0]
#### # to instanciate invoice from list of the invoices returned by API
#### invoice_obj = invoices.IuguInvoice.get(invoice["id"])
#### # The comments below was put because API don't exclude
#### # an invoice that was paid. So only does refund.
#### invoice_obj.remove()
self.plan_new.remove()
self.plan_two.remove()
self.subscription.remove()
self.customer.remove()
def test_subscription_create(self):
# Test to create a subscription only client_id and plan_identifier
p_obj = subscriptions.IuguSubscription()
subscription_new = p_obj.create(self.customer.id, self.plan_new.identifier)
self.assertIsInstance(subscription_new, subscriptions.IuguSubscription)
self.assertEqual(subscription_new.plan_identifier, self.plan_new.identifier)
self.clean_invoices(subscription_new.recent_invoices)
subscription_new.remove()
def test_subscription_create_with_custom_variables(self):
p_obj = subscriptions.IuguSubscription()
subscription_new = p_obj.create(self.customer.id,
self.plan_new.identifier,
custom_variables={'city':'Recife'})
self.assertEqual(subscription_new.custom_variables[0]["name"], "city")
self.assertEqual(subscription_new.custom_variables[0]["value"], "Recife")
self.clean_invoices(subscription_new.recent_invoices)
subscription_new.remove()
def test_subscription_set_with_custom_variables(self):
p_obj = subscriptions.IuguSubscription()
subscription_new = p_obj.set(sid=self.subscription.id,
custom_variables={'city':'Recife'})
self.assertEqual(subscription_new.custom_variables[0]["name"], "city")
self.assertEqual(subscription_new.custom_variables[0]["value"], "Recife")
# self.clean_invoices(subscription_new.recent_invoices)
@unittest.skip("API does not support this only_on_charge_success. CHANGED")
def test_subscription_create_only_on_charge_success_with_payment(self):
# Test to create subscriptions with charge only
customer = customers.IuguCustomer().create(name="Pay now",
email="[email protected]")
pay = customer.payment.create(description="Payment X",
number="4111111111111111",
verification_value='123',
first_name="Romario", last_name="Baixo",
month=12, year=2018)
p_obj = subscriptions.IuguSubscription()
new_subscription = p_obj.create(customer.id, self.plan_new.identifier,
only_on_charge_success=True)
self.assertEqual(new_subscription.recent_invoices[0]["status"], "paid")
self.clean_invoices(new_subscription.recent_invoices)
new_subscription.remove()
customer.remove()
def test_subscription_create_only_on_charge_success_less_payment(self):
# Test to create subscriptions with charge only
p_obj = subscriptions.IuguSubscription()
self.assertRaises(errors.IuguGeneralException, p_obj.create,
self.customer.id, self.plan_new.identifier,
only_on_charge_success=True)
def test_subscription_remove(self):
# Test to remove subscription
p_obj = subscriptions.IuguSubscription()
subscription_new = p_obj.create(self.customer.id, self.plan_new.identifier)
sid = subscription_new.id
self.clean_invoices(subscription_new.recent_invoices)
subscription_new.remove()
self.assertRaises(errors.IuguGeneralException,
subscriptions.IuguSubscription.get, sid)
def test_subscription_get(self):
subscription = subscriptions.IuguSubscription.get(self.subscription.id)
self.assertIsInstance(subscription, subscriptions.IuguSubscription)
def test_subscription_getitems(self):
subscription_list = subscriptions.IuguSubscription.getitems()
self.assertIsInstance(subscription_list[0], subscriptions.IuguSubscription)
def test_subscription_getitem_limit(self):
client_subscriptions = subscriptions.IuguSubscription()
sub_1 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_2 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_3 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_4 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sleep(3) # slower API
subscriptions_list = subscriptions.IuguSubscription.getitems(limit=1)
self.assertEqual(len(subscriptions_list), 1)
self.assertEqual(subscriptions_list[0].id, sub_4.id)
self.clean_invoices(sub_1.recent_invoices)
self.clean_invoices(sub_2.recent_invoices)
self.clean_invoices(sub_3.recent_invoices)
self.clean_invoices(sub_4.recent_invoices)
a, b, c, d = sub_1.remove(), sub_2.remove(), sub_3.remove(), sub_4.remove()
def test_subscription_getitem_skip(self):
client_subscriptions = subscriptions.IuguSubscription()
sub_1 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_2 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_3 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_4 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sleep(2)
subscriptions_list = subscriptions.IuguSubscription.getitems(skip=1)
self.assertEqual(subscriptions_list[0].id, sub_3.id)
self.clean_invoices(sub_1.recent_invoices)
self.clean_invoices(sub_2.recent_invoices)
self.clean_invoices(sub_3.recent_invoices)
self.clean_invoices(sub_4.recent_invoices)
a, b, c, d = sub_1.remove(), sub_2.remove(), sub_3.remove(), sub_4.remove()
# TODO: def test_subscription_getitem_created_at_from(self):
def test_subscription_getitem_query(self):
term = self.customer.name
sleep(3) # very slow API! waiting...
subscriptions_list = subscriptions.IuguSubscription.getitems(query=term)
self.assertGreaterEqual(len(subscriptions_list), 1)
# TODO: def test_subscription_getitem_updated_since(self):
@unittest.skip("API not support this. No orders is changed")
def test_subscription_getitem_sort(self):
client_subscriptions = subscriptions.IuguSubscription()
sub_1 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_2 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_3 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_4 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
subscriptions_list = subscriptions.IuguSubscription.getitems(sort="-created_at")
#self.assertEqual(subscriptions_list[0].id, sub_3.id)
self.clean_invoices(sub_1.recent_invoices)
self.clean_invoices(sub_2.recent_invoices)
self.clean_invoices(sub_3.recent_invoices)
self.clean_invoices(sub_4.recent_invoices)
a, b, c, d = sub_1.remove(), sub_2.remove(), sub_3.remove(), sub_4.remove()
def test_subscription_getitem_customer_id(self):
client_subscriptions = subscriptions.IuguSubscription()
# previous subscription was created in setUp
sub_1 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sub_2 = client_subscriptions.create(self.customer.id, self.plan_new.identifier)
sleep(3)
subscriptions_list = subscriptions.IuguSubscription.\
getitems(customer_id=self.customer.id)
self.assertEqual(len(subscriptions_list), 3) # sub_1 + sub_2 + setUp
self.clean_invoices(sub_1.recent_invoices)
self.clean_invoices(sub_2.recent_invoices)
a, b = sub_1.remove(), sub_2.remove()
def test_subscription_set_plan(self):
# Test to change an existent plan in subscription
subs = subscriptions.IuguSubscription()
subscription = subs.create(self.customer.id, self.plan_new.identifier)
sid = subscription.id
plan_identifier = self.plan_new.identifier + str("_Newest_ID")
# changes to this new plan
plan_newest = plans.IuguPlan().create("Plan Name: Newest",
plan_identifier, 1, "months", "BRL", 5000)
# editing...
subscription = subscriptions.IuguSubscription().set(sid,
plan_identifier=plan_newest.identifier)
self.assertEqual(subscription.plan_identifier, plan_identifier)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
plan_newest.remove()
@unittest.skip("API does not support. It returns error 'Subscription Not Found'")
def test_subscription_set_customer_id(self):
# Test if customer_id changed. Iugu's support (number 782)
customer = customers.IuguCustomer().create(name="Cortella",
email="[email protected]")
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, customer_id=customer.id)
self.assertEqual(subscription.customer_id, customer.id)
customer.remove()
def test_subscription_set_expires_at(self):
# Test if expires_at was changed
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, expires_at="12/12/2014")
self.assertEqual(subscription.expires_at, "2014-12-12")
def test_subscription_set_suspended(self):
# Test if suspended was changed
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, suspended=True)
self.assertEqual(subscription.suspended, True)
@unittest.skip("Waiting API developers to support this question")
def test_subscription_set_skip_charge(self):
# Test if skip_charge was marked
print self.subscription.id
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, skip_charge=True)
self.assertEqual(subscription.suspended, True)
def test_subscription_set_subitems(self):
# Test if to insert a new item
subitem = merchant.Item("Subitems", 1, 2345)
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[subitem,])
self.assertEqual(subscription.subitems[0].description,
subitem.description)
def test_subscription_set_subitems_description(self):
# Test if subitem/item descriptions was changed
subitem = merchant.Item("Subitems", 1, 2345)
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[subitem,])
item_with_id = subscription.subitems[0]
item_with_id.description = "Subitems Edited"
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[item_with_id,] )
self.assertEqual(subscription.subitems[0].description,
item_with_id.description)
def test_subscription_set_subitems_price_cents(self):
# Test if subitem/item price_cents was changed
subitem = merchant.Item("Subitems", 1, 2345)
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[subitem,])
item_with_id = subscription.subitems[0]
item_with_id.price_cents = 2900
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[item_with_id,] )
self.assertEqual(subscription.subitems[0].price_cents,
item_with_id.price_cents)
def test_subscription_set_subitems_quantity(self):
# Test if subitem/item quantity was changed
subitem = merchant.Item("Subitems", 1, 2345)
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[subitem,])
item_with_id = subscription.subitems[0]
item_with_id.quantity = 4
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[item_with_id,] )
self.assertEqual(subscription.subitems[0].quantity,
item_with_id.quantity)
def test_subscription_set_subitems_recurrent(self):
# Test if subitem/item recurrent was changed
subitem = merchant.Item("Subitems", 1, 2345)
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[subitem,])
item_with_id = subscription.subitems[0]
item_with_id.recurrent = True
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[item_with_id,])
self.assertEqual(subscription.subitems[0].recurrent,
item_with_id.recurrent)
def test_subscription_set_subitems_destroy(self):
# Test if subitem/item was erased
subitem = merchant.Item("Subitems", 1, 2345)
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[subitem,])
item_with_id = subscription.subitems[0]
item_with_id.destroy = True
subscription = subscriptions.IuguSubscription().\
set(self.subscription.id, subitems=[item_with_id,])
self.assertEqual(subscription.subitems, [])
def test_subscription_create_credit_based_with_custom_variables(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=10,
custom_variables={'city':"Recife"})
self.assertEqual(subscription.custom_variables[0]['name'], "city")
self.assertEqual(subscription.custom_variables[0]['value'], "Recife")
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_set_credit_based_with_custom_variables(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=10)
subscription = subscriptions.SubscriptionCreditsBased().\
set(subscription.id, custom_variables={'city':"Madrid"})
self.assertEqual(subscription.custom_variables[0]['name'], "city")
self.assertEqual(subscription.custom_variables[0]['value'], "Madrid")
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_create_credit_based(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=10)
self.assertIsInstance(subscription, subscriptions.SubscriptionCreditsBased)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_create_credit_based_error_price_cents(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased()
self.assertRaises(errors.IuguSubscriptionsException,
subscription.create, self.customer.id,
credits_cycle=2, price_cents=0)
def test_subscription_create_credit_based_error_price_cents_empty(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased()
self.assertRaises(errors.IuguSubscriptionsException,
subscription.create, self.customer.id,
credits_cycle=2, price_cents=None)
def test_subscription_create_credit_based_price_cents(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=2000)
self.assertEqual(subscription.price_cents, 2000)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_create_credit_based_credits_cycle(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=2000)
self.assertEqual(subscription.credits_cycle, 2)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_create_credit_based_credits_min(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=2000,
credits_min=4000)
self.assertEqual(subscription.credits_min, 4000)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_set_credit_based_price_cents(self):
# Test if price_cents changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=1200)
subscription = subscriptions.SubscriptionCreditsBased().\
set(subscription.id, price_cents=3249)
self.assertEqual(subscription.price_cents, 3249)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_set_credits_cycle(self):
# Test if credits_cycle changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=1300)
subscription = subscriptions.SubscriptionCreditsBased().\
set(subscription.id, credits_cycle=10)
self.assertEqual(subscription.credits_cycle, 10)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_set_credits_min(self):
# Test if credits_min changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=1400)
subscription = subscriptions.SubscriptionCreditsBased().\
set(subscription.id, credits_min=2000)
self.assertEqual(subscription.credits_min, 2000)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_credit_based_get(self):
# Test if credits_min changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=2000)
subscription = subscriptions.SubscriptionCreditsBased().\
get(subscription.id)
self.assertIsInstance(subscription, subscriptions.SubscriptionCreditsBased)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_credit_based_getitems(self):
# Test if credits_min changed
subscription = subscriptions.SubscriptionCreditsBased().\
create(self.customer.id, credits_cycle=2, price_cents=2000)
sleep(2)
subscription_list = subscriptions.SubscriptionCreditsBased().\
getitems()
self.assertIsInstance(subscription_list[0], subscriptions.SubscriptionCreditsBased)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
# Test save method
@unittest.skip("This is not support by API. Return not found")
def test_subscription_save_customer_id(self):
# Iugu's support (number 782)
customer = customers.IuguCustomer().create(name="Subs save",
email="[email protected]")
self.subscription.customer_id = customer.id
obj = self.subscription.save()
self.assertEqual(customer.id, obj.customer_id)
customer.remove()
def test_subscription_save_expires_at(self):
self.subscription.expires_at = "12/12/2020"
obj = self.subscription.save()
self.assertEqual(obj.expires_at, "2020-12-12")
def test_subscription_save_subitems(self):
# Test if to save a new item
subitem = merchant.Item("Subitems", 1, 2345)
self.subscription.subitems = [subitem,]
obj = self.subscription.save()
self.assertEqual(obj.subitems[0].description,
subitem.description)
def test_subscription_save_subitems_description(self):
# Test if subitem/item descriptions was changed
subitem = merchant.Item("Subitems", 1, 2345)
self.subscription.subitems = [subitem,]
new_subscription = self.subscription.save()
item_with_id = new_subscription.subitems[0]
item_with_id.description = "Subitems Edited"
self.subscription.subitems = [item_with_id]
obj = self.subscription.save()
self.assertEqual(obj.subitems[0].description,
item_with_id.description)
def test_subscription_save_subitems_price_cents(self):
# Test if subitem/item price_cents was changed
subitem = merchant.Item("Subitems", 1, 2345)
self.subscription.subitems = [subitem,]
new_subscription = self.subscription.save()
item_with_id = new_subscription.subitems[0]
item_with_id.price_cents = 2900
self.subscription.subitems = [item_with_id,]
obj = self.subscription.save()
self.assertEqual(obj.subitems[0].price_cents,
item_with_id.price_cents)
def test_subscription_save_subitems_quantity(self):
# Test if subitem/item quantity was changed
subitem = merchant.Item("Subitems", 1, 2345)
self.subscription.subitems = [subitem,]
new_subscription = self.subscription.save()
item_with_id = new_subscription.subitems[0]
item_with_id.quantity = 4
self.subscription.subitems = [item_with_id,]
obj = self.subscription.save()
self.assertEqual(obj.subitems[0].quantity,
item_with_id.quantity)
def test_subscription_save_subitems_recurrent(self):
# Test if subitem/item recurrent was changed
subitem = merchant.Item("Subitems", 1, 2345)
self.subscription.subitems = [subitem,]
new_subscription = self.subscription.save()
item_with_id = new_subscription.subitems[0]
item_with_id.recurrent = True
self.subscription.subitems = [item_with_id,]
obj = self.subscription.save()
self.assertEqual(obj.subitems[0].recurrent,
item_with_id.recurrent)
def test_subscription_save_subitems__destroy(self):
# Test if subitem/item was erased
subitem = merchant.Item("Subitems", 1, 2345)
self.subscription.subitems = [subitem,]
new_subscription = self.subscription.save()
item_with_id = new_subscription.subitems[0]
item_with_id.destroy = True
self.subscription.subitems = [item_with_id,]
obj = self.subscription.save()
self.assertEqual(obj.subitems, [])
def test_subscription_save_suspended(self):
self.subscription.suspended = True
obj = self.subscription.save()
self.assertEqual(obj.suspended, True)
# @unittest.skip("Waiting API developers to support this question")
# TODO: def test_subscription_save_skip_charge(self):
def test_subscription_save_price_cents(self):
subscription = subscriptions.SubscriptionCreditsBased()
subscription = subscription.create(customer_id=self.customer.id,
credits_cycle=2, price_cents=1000)
subscription.price_cents = 8188
obj = subscription.save()
self.assertEqual(obj.price_cents, 8188)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_save_credits_cycle(self):
subscription = subscriptions.SubscriptionCreditsBased()
subscription = subscription.create(customer_id=self.customer.id,
credits_cycle=2, price_cents=1000)
subscription.credits_cycle = 5
obj = subscription.save()
self.assertEqual(obj.credits_cycle, 5)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_save_credits_min(self):
subscription = subscriptions.SubscriptionCreditsBased()
subscription = subscription.create(customer_id=self.customer.id,
credits_cycle=2, price_cents=1100)
subscription.credits_min = 9000
obj = subscription.save()
self.assertEqual(obj.credits_min, 9000)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_suspend(self):
obj = subscriptions.IuguSubscription().suspend(self.subscription.id)
self.assertEqual(obj.suspended, True)
@unittest.skip("API not support this activate by REST .../activate")
def test_subscription_activate(self):
obj = subscriptions.IuguSubscription().suspend(self.subscription.id)
self.subscription.suspended = True
self.subscription.save()
obj = subscriptions.IuguSubscription().activate(self.subscription.id)
self.assertEqual(obj.suspended, False)
def test_subscription_change_plan(self):
seed = randint(1, 999)
identifier = "%s_%s" % (self.plan_new.identifier, str(seed))
plan_again_change = plans.IuguPlan().create(name="Change Test",
identifier=identifier,
interval=1, interval_type="months",
currency="BRL", value_cents=1111)
obj = subscriptions.IuguSubscription().change_plan(
plan_again_change.identifier,
sid=self.subscription.id)
self.assertEqual(obj.plan_identifier, identifier)
self.clean_invoices(obj.recent_invoices)
plan_again_change.remove()
def test_subscription_change_plan_by_instance(self):
seed = randint(1, 999)
identifier = "%s_%s" % (self.plan_new.identifier, str(seed))
plan_again_change = plans.IuguPlan().create(name="Change Test",
identifier=identifier,
interval=1, interval_type="months",
currency="BRL", value_cents=1112)
obj = self.subscription.change_plan(plan_again_change.identifier)
self.assertEqual(obj.plan_identifier, identifier)
self.clean_invoices(obj.recent_invoices)
plan_again_change.remove()
def test_subscription_add_credits(self):
subscription = subscriptions.SubscriptionCreditsBased()
subscription = subscription.create(customer_id=self.customer.id,
credits_cycle=2, price_cents=1100)
obj = subscriptions.SubscriptionCreditsBased().add_credits(sid=subscription.id,
quantity=20)
self.assertEqual(obj.credits, 20)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_add_credits_by_instance(self):
subscription = subscriptions.SubscriptionCreditsBased()
subscription = subscription.create(customer_id=self.customer.id,
credits_cycle=2, price_cents=1100)
obj = subscription.add_credits(sid=subscription.id,
quantity=20)
self.assertEqual(obj.credits, 20)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_remove_credits(self):
subscription = subscriptions.SubscriptionCreditsBased()
subscription = subscription.create(customer_id=self.customer.id,
credits_cycle=2, price_cents=1100)
subscription.add_credits(quantity=20)
obj = subscriptions.SubscriptionCreditsBased().\
remove_credits(sid=subscription.id, quantity=5)
self.assertEqual(obj.credits, 15)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
def test_subscription_remove_credits_by_instance(self):
subscription = subscriptions.SubscriptionCreditsBased()
subscription = subscription.create(customer_id=self.customer.id,
credits_cycle=2, price_cents=1100)
subscription.add_credits(quantity=20)
sleep(2)
obj = subscription.remove_credits(quantity=5)
self.assertEqual(obj.credits, 15)
self.clean_invoices(subscription.recent_invoices)
subscription.remove()
class TestTransfer(unittest.TestCase):
# TODO: to create this tests
pass
if __name__ == '__main__':
unittest.main()<|fim▁end|> | def test_plan_edit_changes_features_value_by_set(self):
salt = randint(1, 99) |
<|file_name|>reporter.js<|end_file_name|><|fim▁begin|><|fim▁hole|>jasmine.getEnv().clearReporters(); // remove default reporter logs
jasmine.getEnv().addReporter(new SpecReporter({ // add jasmine-spec-reporter
spec: {
displayPending: true,
},
summary: {
displayDuration: true,
}
}));<|fim▁end|> | const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
|
<|file_name|>page-tests.ts<|end_file_name|><|fim▁begin|>import page = require("page");
//***********************************************************************
// Basic Example
// https://github.com/visionmedia/page.js/tree/master/examples/basic
//************************************************************************
page.base('/basic');
page('/', index);
page('/about', about);
page('/contact', contact);
page('/contact/:contactName', contact);
page('/contact/inline/:contactName', ctx => { });
page();
var index: PageJS.Callback = function() {
document.querySelector('p')
.textContent = 'viewing index';
}
var about: PageJS.Callback = function() {
document.querySelector('p')
.textContent = 'viewing about';
}
var contact: PageJS.Callback = function(ctx) {
document.querySelector('p')
.textContent = 'viewing contact ' + (ctx.params.contactName || '');
}
//***********************************************************************
// State Example
// https://github.com/visionmedia/page.js/tree/master/examples/state/app.js
//************************************************************************
interface Avatars {
[idx: string]: string;
}
var avatars: Avatars = {
glottis: 'http://homepage.ntlworld.com/stureek/images/glottis03.jpg',
manny: 'http://kprojekt.net/wp-content/uploads/manny.jpg',
sal: 'http://homepage.ntlworld.com/stureek/images/sal01.jpg'
};
page.base('/state');
page('/', index2);
page('/user/:name', load, show);
page('*', notfound);
page();
// everything below is not part of page.js
// just callbacks etc..
function text(str: string) {
document.querySelector('p').textContent = str;
}
function index2() {
text('Click a user below to load their avatar');
(<HTMLElement>document.querySelector('img'))
.style.display = 'none';
}
var load: PageJS.Callback = function (ctx, next) {<|fim▁hole|> if (ctx.state.avatar) {
ctx['avatar'] = ctx.state.avatar;
next();
return;
}
// pretend we're querying some database etc
setTimeout(function () {
// you can assign properties to the context
// for use between these functions. The .state
// property is what's saved in history.
ctx.state.avatar = ctx['avatar'] = avatars[ctx.params.name];
ctx.save();
next();
}, 600);
}
var show: PageJS.Callback = function (ctx) {
var img: any = document.querySelector('img');
img.src = ctx['avatar'];
img.style.display = 'block';
text('Showing ' + ctx.params.name);
}
function notfound() {
document.querySelector('p')
.textContent = 'not found';
}<|fim▁end|> | // check if we have .state.avatar already available
// this could for example be a cached html fragment. |
<|file_name|>astconv.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.
/*!
* Conversion from AST representation of types to the ty.rs
* representation. The main routine here is `ast_ty_to_ty()`: each use
* is parameterized by an instance of `AstConv` and a `region_scope`.
*
* The parameterization of `ast_ty_to_ty()` is because it behaves
* somewhat differently during the collect and check phases, particularly
* with respect to looking up the types of top-level items. In the
* collect phase, the crate context is used as the `AstConv` instance;
* in this phase, the `get_item_ty()` function triggers a recursive call
* to `ty_of_item()` (note that `ast_ty_to_ty()` will detect recursive
* types and report an error). In the check phase, when the @FnCtxt is
* used as the `AstConv`, `get_item_ty()` just looks up the item type in
* `tcx.tcache`.
*
* The `region_scope` trait controls how region references are
* handled. It has two methods which are used to resolve anonymous
* region references (e.g., `&T`) and named region references (e.g.,
* `&a.T`). There are numerous region scopes that can be used, but most
* commonly you want either `empty_rscope`, which permits only the static
* region, or `type_rscope`, which permits the self region if the type in
* question is parameterized by a region.
*
* Unlike the `AstConv` trait, the region scope can change as we descend
* the type. This is to accommodate the fact that (a) fn types are binding
* scopes and (b) the default region may change. To understand case (a),
* consider something like:
*
* type foo = { x: &a.int, y: &fn(&a.int) }
*
* The type of `x` is an error because there is no region `a` in scope.
* In the type of `y`, however, region `a` is considered a bound region
* as it does not already appear in scope.
*
* Case (b) says that if you have a type:
* type foo<'self> = ...;
* type bar = fn(&foo, &a.foo)
* The fully expanded version of type bar is:
* type bar = fn(&'foo &, &a.foo<'a>)
* Note that the self region for the `foo` defaulted to `&` in the first
* case but `&a` in the second. Basically, defaults that appear inside
* an rptr (`&r.T`) use the region `r` that appears in the rptr.
*/
use core::prelude::*;
use middle::const_eval;
use middle::ty::{arg, substs};
use middle::ty::{ty_param_substs_and_ty};
use middle::ty;
use middle::typeck::rscope::in_binding_rscope;
use middle::typeck::rscope::{region_scope, RegionError};
use middle::typeck::rscope::RegionParamNames;
use core::result;
use core::vec;
use syntax::abi::AbiSet;
use syntax::{ast, ast_util};
use syntax::codemap::span;
use syntax::opt_vec::OptVec;
use syntax::opt_vec;
use syntax::print::pprust::{lifetime_to_str, path_to_str};
use syntax::parse::token::special_idents;
use util::common::indenter;
pub trait AstConv {
fn tcx(&self) -> ty::ctxt;
fn get_item_ty(&self, id: ast::def_id) -> ty::ty_param_bounds_and_ty;
// what type should we use when a type is omitted?
fn ty_infer(&self, span: span) -> ty::t;
}
pub fn get_region_reporting_err(
tcx: ty::ctxt,
span: span,
a_r: Option<@ast::Lifetime>,
res: Result<ty::Region, RegionError>) -> ty::Region
{
match res {
result::Ok(r) => r,
result::Err(ref e) => {
let descr = match a_r {
None => ~"anonymous lifetime",
Some(a) => fmt!("lifetime %s",
lifetime_to_str(a, tcx.sess.intr()))
};
tcx.sess.span_err(
span,
fmt!("Illegal %s: %s",
descr, e.msg));
e.replacement
}
}
}
pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
default_span: span,
opt_lifetime: Option<@ast::Lifetime>) -> ty::Region
{
let (span, res) = match opt_lifetime {
None => {
(default_span, rscope.anon_region(default_span))
}
Some(ref lifetime) if lifetime.ident == special_idents::static => {
(lifetime.span, Ok(ty::re_static))
}
Some(ref lifetime) if lifetime.ident == special_idents::self_ => {
(lifetime.span, rscope.self_region(lifetime.span))
}
Some(ref lifetime) => {
(lifetime.span, rscope.named_region(lifetime.span,
lifetime.ident))
}
};
get_region_reporting_err(self.tcx(), span, opt_lifetime, res)
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty {
let tcx = self.tcx();
let ty::ty_param_bounds_and_ty {
bounds: decl_bounds,
region_param: decl_rp,
ty: decl_ty
} = self.get_item_ty(did);
debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?",
did, decl_rp);
// If the type is parameterized by the self region, then replace self
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let self_r = match (decl_rp, path.rp) {
(None, None) => {
None
}
(None, Some(_)) => {
tcx.sess.span_err(
path.span,
fmt!("no region bound is allowed on `%s`, \
which is not declared as containing region pointers",
ty::item_path_str(tcx, did)));
None
}
(Some(_), None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(self.tcx(), path.span, None, res);
Some(r)
}
(Some(_), Some(_)) => {
Some(ast_region_to_region(self, rscope, path.span, path.rp))
}
};
// Convert the type parameters supplied by the user.
if !vec::same_length(*decl_bounds, path.types) {
self.tcx().sess.span_fatal(
path.span,
fmt!("wrong number of type arguments: expected %u but found %u",
(*decl_bounds).len(), path.types.len()));
}
let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t));
let substs = substs {self_r:self_r, self_ty:None, tps:tps};
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(self, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type. `getter` is a function that returns the type
// corresponding to a definition ID:
pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t {
fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean estrs and evecs.
// If a_seq_ty is a str or a vec, make it an estr/evec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a_seq_ty: &ast::mt,
vst: ty::vstore,
constr: &fn(ty::mt) -> ty::t) -> ty::t
{
let tcx = self.tcx();
match a_seq_ty.ty.node {
ast::ty_vec(ref mt) => {
let mut mt = ast_mt_to_mt(self, rscope, mt);
if a_seq_ty.mutbl == ast::m_mutbl ||
a_seq_ty.mutbl == ast::m_const {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
return ty::mk_evec(tcx, mt, vst);
}
ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => {
match tcx.def_map.find(&id) {
Some(&ast::def_prim_ty(ast::ty_str)) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_estr(tcx, vst);
}
Some(&ast::def_ty(type_def_id)) => {
let result = ast_path_to_substs_and_ty(
self, rscope,
type_def_id, path);
match ty::get(result.ty).sty {
ty::ty_trait(trait_def_id, ref substs, _) => {
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(*) => {
tcx.sess.span_err(
path.span,
~"@trait, ~trait or &trait \
are the only supported \
forms of casting-to-\
trait");
ty::BoxTraitStore
}
};
return ty::mk_trait(tcx,
trait_def_id,
/*bad*/copy *substs,
trait_store);
}
_ => {}
}
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: @ast::path,
flags: uint) {
if (flags & NO_TPS) != 0u {
if path.types.len() > 0u {
tcx.sess.span_err(
path.span,
~"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS) != 0u {
if path.rp.is_some() {
tcx.sess.span_err(
path.span,
~"region parameters are not allowed on this type");
}
}
}
let tcx = self.tcx();
match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \
insert an enum in the cycle, \
if this is desired");
}
None => { /* go on */ }
}
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
let typ = match ast_ty.node {
ast::ty_nil => ty::mk_nil(tcx),
ast::ty_bot => ty::mk_bot(tcx),
ast::ty_box(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt))
}
ast::ty_uniq(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt))
}
ast::ty_vec(ref mt) => {
tcx.sess.span_err(ast_ty.span,
~"bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt),
ty::vstore_uniq)
}
ast::ty_ptr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt))
}
ast::ty_rptr(region, ref mt) => {
let r = ast_region_to_region(self, rscope, ast_ty.span, region);
mk_pointer(self, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::ty_tup(ref fields) => {
let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t));
ty::mk_tup(tcx, flds)
}
ast::ty_bare_fn(ref bf) => {
ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity,
bf.abis, &bf.lifetimes, &bf.decl))
}
ast::ty_closure(ref f) => {
let fn_decl = ty_of_closure(self,
rscope,
f.sigil,
f.purity,
f.onceness,
f.region,
&f.decl,
None,
&f.lifetimes,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::ty_path(path, id) => {
let a_def = match tcx.def_map.find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, fmt!("unbound path %s",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
match a_def {
ast::def_ty(did) | ast::def_struct(did) => {
ast_path_to_ty(self, rscope, did, path).ty
}
ast::def_prim_ty(nty) => {
match nty {
ast::ty_bool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool(tcx)
}
ast::ty_int(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(tcx, it)
}
ast::ty_uint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(tcx, uit)
}
ast::ty_float(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(tcx, ft)
}
ast::ty_str => {
tcx.sess.span_err(ast_ty.span,
~"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_estr(tcx, ty::vstore_uniq)
}
}
}
ast::def_ty_param(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::def_self_ty(id) => {
// n.b.: resolve guarantees that the self type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
let did = ast_util::local_def(id);
ty::mk_self(tcx, did)
}
_ => {
tcx.sess.span_fatal(ast_ty.span,
~"found type name used as a variable");
}
}
}
ast::ty_fixed_length_vec(ref a_mt, e) => {
match const_eval::eval_const_expr_partial(tcx, e) {
Ok(ref r) => {
match *r {
const_eval::const_int(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
const_eval::const_uint(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
_ => {
tcx.sess.span_fatal(
ast_ty.span, ~"expected constant expr for vector length");
}
}
}
Err(ref r) => {
tcx.sess.span_fatal(
ast_ty.span,
fmt!("expected constant expr for vector length: %s",
*r));
}
}
}
ast::ty_infer => {
// ty_infer should only appear as the type of arguments or return
// values in a fn_expr, or as the type of local variables. Both of
// these cases are handled specially and should not descend into this
// routine.
self.tcx().sess.span_bug(
ast_ty.span,
~"found `ty_infer` in unexpected place");
}
ast::ty_mac(_) => {
tcx.sess.span_bug(ast_ty.span,
~"found `ty_mac` in unexpected place");
}
};
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ));
return typ;
}
pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a: ast::arg,
expected_ty: Option<ty::arg>)
-> ty::arg {
let ty = match a.ty.node {
ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty,
ast::ty_infer => self.ty_infer(a.ty.span),
_ => ast_ty_to_ty(self, rscope, a.ty)
};
let mode = {
match a.mode {
ast::infer(_) if expected_ty.is_some() => {
result::get(&ty::unify_mode(
self.tcx(),
ty::expected_found {expected: expected_ty.get().mode,
found: a.mode}))
}
ast::infer(_) => {
match ty::get(ty).sty {
// If the type is not specified, then this must be a fn expr.
// Leave the mode as infer(_), it will get inferred based
// on constraints elsewhere.<|fim▁hole|> // If the type is known, then use the default for that type.
// Here we unify m and the default. This should update the
// tables in tcx but should never fail, because nothing else
// will have been unified with m yet:
_ => {
let m1 = ast::expl(ty::default_arg_mode_for_ty(self.tcx(),
ty));
result::get(&ty::unify_mode(
self.tcx(),
ty::expected_found {expected: m1,
found: a.mode}))
}
}
}
ast::expl(_) => a.mode
}
};
arg {mode: mode, ty: ty}
}
pub fn bound_lifetimes<AC:AstConv>(
self: &AC,
ast_lifetimes: &OptVec<ast::Lifetime>) -> OptVec<ast::ident>
{
/*!
*
* Converts a list of lifetimes into a list of bound identifier
* names. Does not permit special names like 'static or 'self to
* be bound. Note that this function is for use in closures,
* methods, and fn definitions. It is legal to bind 'self in a
* type. Eventually this distinction should go away and the same
* rules should apply everywhere ('self would not be a special name
* at that point).
*/
let special_idents = [special_idents::static, special_idents::self_];
let mut bound_lifetime_names = opt_vec::Empty;
ast_lifetimes.map_to_vec(|ast_lifetime| {
if special_idents.any(|&i| i == ast_lifetime.ident) {
self.tcx().sess.span_err(
ast_lifetime.span,
fmt!("illegal lifetime parameter name: `%s`",
lifetime_to_str(ast_lifetime, self.tcx().sess.intr())));
} else {
bound_lifetime_names.push(ast_lifetime.ident);
}
});
bound_lifetime_names
}
pub fn ty_of_bare_fn<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
purity: ast::purity,
abi: AbiSet,
lifetimes: &OptVec<ast::Lifetime>,
decl: &ast::fn_decl) -> ty::BareFnTy
{
debug!("ty_of_bare_fn");
// new region names that appear inside of the fn decl are bound to
// that function type
let bound_lifetime_names = bound_lifetimes(self, lifetimes);
let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names));
let input_tys = decl.inputs.map(|a| ty_of_arg(self, &rb, *a, None));
let output_ty = match decl.output.node {
ast::ty_infer => self.ty_infer(decl.output.span),
_ => ast_ty_to_ty(self, &rb, decl.output)
};
ty::BareFnTy {
purity: purity,
abis: abi,
sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names,
inputs: input_tys,
output: output_ty}
}
}
pub fn ty_of_closure<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
sigil: ast::Sigil,
purity: ast::purity,
onceness: ast::Onceness,
opt_lifetime: Option<@ast::Lifetime>,
decl: &ast::fn_decl,
expected_sig: Option<ty::FnSig>,
lifetimes: &OptVec<ast::Lifetime>,
span: span)
-> ty::ClosureTy
{
// The caller should not both provide explicit bound lifetime
// names and expected types. Either we infer the bound lifetime
// names or they are provided, but not both.
assert!(lifetimes.is_empty() || expected_sig.is_none());
debug!("ty_of_fn_decl");
let _i = indenter();
// resolve the function bound region in the original region
// scope `rscope`, not the scope of the function parameters
let bound_region = match opt_lifetime {
Some(_) => {
ast_region_to_region(self, rscope, span, opt_lifetime)
}
None => {
match sigil {
ast::OwnedSigil | ast::ManagedSigil => {
// @fn(), ~fn() default to static as the bound
// on their upvars:
ty::re_static
}
ast::BorrowedSigil => {
// &fn() defaults as normal for an omitted lifetime:
ast_region_to_region(self, rscope, span, opt_lifetime)
}
}
}
};
// new region names that appear inside of the fn decl are bound to
// that function type
let bound_lifetime_names = bound_lifetimes(self, lifetimes);
let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names));
let input_tys = do decl.inputs.mapi |i, a| {
let expected_arg_ty = do expected_sig.chain_ref |e| {
// no guarantee that the correct number of expected args
// were supplied
if i < e.inputs.len() {Some(e.inputs[i])} else {None}
};
ty_of_arg(self, &rb, *a, expected_arg_ty)
};
let expected_ret_ty = expected_sig.map(|e| e.output);
let output_ty = match decl.output.node {
ast::ty_infer if expected_ret_ty.is_some() => expected_ret_ty.get(),
ast::ty_infer => self.ty_infer(decl.output.span),
_ => ast_ty_to_ty(self, &rb, decl.output)
};
ty::ClosureTy {
purity: purity,
sigil: sigil,
onceness: onceness,
region: bound_region,
sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names,
inputs: input_tys,
output: output_ty}
}
}<|fim▁end|> | ty::ty_infer(_) => a.mode,
|
<|file_name|>ArchiveController.java<|end_file_name|><|fim▁begin|>package com.ihidea.component.datastore.archive;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ihidea.component.datastore.FileSupportService;
import com.ihidea.component.datastore.fileio.FileIoEntity;
import com.ihidea.core.CoreConstants;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.support.servlet.ServletHolderFilter;
import com.ihidea.core.util.ImageUtilsEx;
import com.ihidea.core.util.ServletUtilsEx;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 收件扫描
* @author TYOTANN
*/
@Controller
public class ArchiveController {
protected Log logger = LogFactory.getLog(getClass());
@Autowired
private FileSupportService fileSupportService;
@Autowired
private ArchiveService archiveService;
@RequestMapping("/twain.do")
public String doTwain(ModelMap model, HttpServletRequest request) {
String twainHttp = CoreConstants.twainHost;
model.addAttribute("path", request.getParameter("path"));
model.addAttribute("params", request.getParameter("cs"));
model.addAttribute("picname", request.getParameter("picname"));
model.addAttribute("frame", request.getParameter("frame"));
model.addAttribute("HostIP", twainHttp.split(":")[0]);
model.addAttribute("HTTPPort", twainHttp.split(":")[1]);
model.addAttribute("storeName", "ds_archive");
model.addAttribute("storeType", "2");
return "archive/twain";
}
@RequestMapping("/editPicture.do")
public String doEditPicture(ModelMap model, HttpServletRequest request) {
model.addAttribute("ywid", request.getParameter("ywid"));
model.addAttribute("img", request.getParameter("img"));
model.addAttribute("name", request.getParameter("name"));
return "aie/imageeditor";
}
@RequestMapping("/showPicture.do")
public void showPicture(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
OutputStream os = null;
String id = request.getParameter("id");
FileIoEntity file = fileSupportService.get(id);
byte[] b = file.getContent();
response.setContentType("image/png");
try {
os = response.getOutputStream();
FileCopyUtils.copy(b, os);
} catch (IOException e) {
logger.debug("出错啦!", e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
logger.debug("出错啦!", e);
}
}
}
}
/**
* 扫描收件获取图片信息
* @param request
* @param response
* @param model
*/
@RequestMapping("/doPictureData.do")
public void doPictureData(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String tid = request.getParameter("id");
String spcode = request.getParameter("spcode");
String sncode = request.getParameter("sncode");
String typeid = request.getParameter("typeid");
String dm = request.getParameter("dm");
String dwyq = request.getParameter("dwyq");
if (tid == null || tid.trim().equals("") || tid.trim().equals("null")) {
tid = "-1";
}
List<Map<String, Object>> pList = null;
// 根据sncode或spcode查询所有收件
if (StringUtils.isBlank(spcode) && StringUtils.isBlank(sncode)) {
pList = archiveService.getPicture(Integer.valueOf(tid));
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("spcode", spcode);
params.put("sncode", sncode);
params.put("typeid", typeid);
params.put("dm", dm);
pList = archiveService.getPicture("09100E", params);
}
// 查询单位印签只需要最后一张
List<Map<String, Object>> picList = new ArrayList<Map<String, Object>>();
if (!StringUtils.isBlank(dwyq)) {
for (int i = 0; i < pList.size(); i++) {
Map<String, Object> pic = pList.get(i);
if (dwyq.equals(pic.get("ino").toString())) {
picList.add(pic);
break;
}
}
} else {
picList = pList;
}
Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
map.put("images", picList);
ServletUtilsEx.renderJson(response, map);
}
@SuppressWarnings({ "unchecked" })
@RequestMapping("/uploadDataFile.do")
public String uploadFjToFile(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String ino = null;
int id = request.getParameter("id") == null ? 0 : Integer.valueOf(request.getParameter("id"));
String strFileName = request.getParameter("filename");
Map<String, Object> paramMap = ServletHolderFilter.getContext().getParamMap();
FileItem cfile = null;
// 得到上传的文件
for (String key : paramMap.keySet()) {
if (paramMap.get(key) instanceof List) {
if (((List) paramMap.get(key)).get(0) instanceof FileItem)
cfile = ((List<FileItem>) paramMap.get(key)).get(0);
break;
}
}
ino = fileSupportService.add(cfile.getName(), cfile.get(), "ds_archive");
fileSupportService.submit(ino, "收件扫描-扫描");
// 保存到收件明细表ARCSJMX
archiveService.savePicture(id, ino, strFileName, "");
return null;
}
/**
* 扫描收件时上传图片
* @param request
* @param response
* @param model
* @return
* @throws Exception
*/
@SuppressWarnings({ "unchecked" })
@RequestMapping("/uploadUnScanDataFile.do")
public String uploadUnScanFjToFile(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
Map<String, Object> paramMap = ServletHolderFilter.getContext().getParamMap();
int id = paramMap.get("id") == null ? 0 : Integer.valueOf(String.valueOf(paramMap.get("id")));
String strFileName = paramMap.get("filename") == null ? StringUtils.EMPTY : String.valueOf(paramMap.get("filename"));
String storeName = "ds_archive";
FileOutputStream fos = null;
String ino = null;
try {
List<FileItem> remoteFile = (List<FileItem>) paramMap.get("uploadFile");
FileItem cfile = remoteFile.get(0);
String cfileOrjgName = cfile.getName();
String cfileName = cfileOrjgName.substring(0, cfileOrjgName.lastIndexOf("."));
ino = fileSupportService.add(cfile.getName(), cfile.get(), "ds_archive");
fileSupportService.submit(ino, "收件扫描-本地上传");
if (strFileName != null) {
cfileName = strFileName;
}
// 保存到收件明细表ARCSJMX
archiveService.savePicture(id, ino, cfileName, "");
} catch (Exception e) {
throw new ServiceException(e.getMessage());
} finally {
if (fos != null) {
fos.flush();
fos.close();
}
}
model.addAttribute("isSubmit", "1");
model.addAttribute("params", id);
model.addAttribute("path", "");
model.addAttribute("picname", strFileName);
model.addAttribute("storeName", storeName);
model.addAttribute("success", "上传成功!");
model.addAttribute("ino", ino);
return "archive/twain";
}
/**
* 扫描收件时查看
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping("/doPicture.do")
public String doPicture(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String img = request.getParameter("img");
String ywid = request.getParameter("ywid");
model.addAttribute("img", img);
model.addAttribute("ywid", ywid);
model.addAttribute("storeName", "ds_archive");
return "aie/showPicture";
}
/**
* 下载图片
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadFj.do")
public void downloadFj(HttpServletRequest request, HttpServletResponse response) throws Exception {
String id = request.getParameter("id") == null ? "" : String.valueOf(request.getParameter("id"));
if (StringUtils.isBlank(id)) {
id = request.getParameter("file") == null ? "" : String.valueOf(request.getParameter("file"));
}
ServletOutputStream fos = null;
try {
fos = response.getOutputStream();
response.setContentType("application/octet-stream");
FileIoEntity file = fileSupportService.get(id);
FileCopyUtils.copy(file.getContent(), fos);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (fos != null) {
fos.flush();
fos.close();
}
}
}
@RequestMapping("/changePicture.do")
public void changePicture(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String type = request.getParameter("type");
String path = request.getParameter("imagepath");
// 旋转
if (type.equals("rotate")) {
String aktion = request.getParameter("aktion");
// 角度
if (aktion.equals("rotieren")) {
int degree = Integer.valueOf(request.getParameter("degree"));
try {
Image imageOriginal = ImageIO.read(new ByteArrayInputStream(fileSupportService.get(path).getContent()));
// if (uploadType.equals("file")) { // 文件方式存储
// File tfile = new File(path);
// if (!tfile.exists()) {
// return;
// }
// imageOriginal = ImageIO.read(tfile);
// } else { // 数据库方式存储
// String errfilename =
// this.getClass().getResource("/").getPath()
// .replace("WEB-INF/classes",
// "resources/images/sjerr.png");
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// archiveService.getPictureFromDB(request.getParameter("imagepath"),
// errfilename, os);
// byte[] data = os.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// imageOriginal = ImageIO.read(is);
// }
int widthOriginal = imageOriginal.getWidth(null);
int heightOriginal = imageOriginal.getHeight(null);
BufferedImage bi = new BufferedImage(widthOriginal, heightOriginal, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(imageOriginal, 0, 0, null);
BufferedImage bu = ImageUtilsEx.rotateImage(bi, degree);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bu);
byte[] data = bos.toByteArray();
// 更新文件内容
fileSupportService.updateContent(path, data);
// if (uploadType.equals("file")) { // 文件方式存储
// FileOutputStream fos = new FileOutputStream(path);
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(fos);
// encoder.encode(bu);
//
// fos.flush();
// fos.close();
// fos = null;
// } else { // 数据库方式存储
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(bos);
// encoder.encode(bu);
// byte[] data = bos.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// archiveService.updatePictureToDB(request.getParameter("imagepath"),
// is, data.length);
//
// bos.flush();
// bos.close();
// bos = null;
//
// is.close();
// is = null;
// }
} catch (IOException e) {
e.printStackTrace();
logger.error("错误:" + e.getMessage());
}
// 翻转
} else {
String degree = request.getParameter("degree");
try {
Image imageOriginal = ImageIO.read(new ByteArrayInputStream(fileSupportService.get(path).getContent()));
// if (uploadType.equals("file")) { // 文件方式存储
// File tfile = new File(path);
// if (!tfile.exists()) {
// return;<|fim▁hole|> // }
// imageOriginal = ImageIO.read(tfile);
// } else { // 数据库方式存储
// String errfilename =
// this.getClass().getResource("/").getPath()
// .replace("WEB-INF/classes",
// "resources/images/sjerr.png");
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// archiveService.getPictureFromDB(request.getParameter("imagepath"),
// errfilename, os);
// byte[] data = os.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// imageOriginal = ImageIO.read(is);
// }
int widthOriginal = imageOriginal.getWidth(null);
int heightOriginal = imageOriginal.getHeight(null);
BufferedImage bi = new BufferedImage(widthOriginal, heightOriginal, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(imageOriginal, 0, 0, null);
BufferedImage bu = null;
if (degree.equals("flip")) {
bu = ImageUtilsEx.flipImage(bi);
} else {
bu = ImageUtilsEx.flopImage(bi);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bu);
byte[] data = bos.toByteArray();
// 更新文件内容
fileSupportService.updateContent(path, data);
// if (uploadType.equals("file")) { // 文件方式存储
// FileOutputStream fos = new FileOutputStream(path);
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(fos);
// encoder.encode(bu);
//
// fos.flush();
// fos.close();
// fos = null;
// } else { // 数据库方式存储
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(bos);
// encoder.encode(bu);
// byte[] data = bos.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// archiveService.updatePictureToDB(request.getParameter("imagepath"),
// is, data.length);
//
// bos.flush();
// bos.close();
// bos = null;
//
// is.close();
// is = null;
// }
} catch (IOException e) {
e.printStackTrace();
logger.error("错误:" + e.getMessage());
}
}
}
}
// 公共方法
// 下载附件
@RequestMapping("/arcDownloadFj.do")
public void arcDownloadFj(HttpServletRequest request, HttpServletResponse response) {
int id = Integer.parseInt(request.getParameter("id"));
Map<String, Object> map = this.archiveService.getArcfj(id);
if (map == null) {
return;
}
ServletOutputStream fos = null;
FileInputStream fis = null;
BufferedInputStream bfis = null;
BufferedOutputStream bfos = null;
try {
File file = new File(map.get("filepath").toString());
if (!file.exists()) {
response.setCharacterEncoding("GBK");
response.getWriter().write("<script>alert('文件不存在');window.history.back();</script>");
return;
}
fos = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment; filename=\""
+ new String(map.get("filename").toString().getBytes("GBK"), "ISO8859_1") + "\"");
fis = new FileInputStream(file);
bfis = new BufferedInputStream(fis);
bfos = new BufferedOutputStream(fos);
FileCopyUtils.copy(bfis, bfos);
} catch (Exception e) {
// e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (bfis != null) {
bfis.close();
}
if (bfos != null) {
bfos.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
}
}
}
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
##############################################################################<|fim▁hole|># OpenERP, Open Source Management Solution
# Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import ir_translation
import update<|fim▁end|> | # |
<|file_name|>semdb.cc<|end_file_name|><|fim▁begin|>//////////////////////////////////////////////////////////////////
//
// FreeLing - Open Source Language Analyzers
//
// Copyright (C) 2014 TALP Research Center
// Universitat Politecnica de Catalunya
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// contact: Lluis Padro ([email protected])
// TALP Research Center
// despatx C6.212 - Campus Nord UPC
// 08034 Barcelona. SPAIN
//
////////////////////////////////////////////////////////////////
#include <sstream>
#include <fstream>
#include "freeling/morfo/traces.h"
#include "freeling/morfo/util.h"
#include "freeling/morfo/configfile.h"
#include "freeling/morfo/semdb.h"
using namespace std;
namespace freeling {
#define MOD_TRACENAME L"SEMDB"
#define MOD_TRACECODE SENSES_TRACE
///////////////////////////////////////////////////////////////<|fim▁hole|>
sense_info::sense_info(const wstring &syn, const wstring &data) {
// store sense identifier
sense=syn;
if (not data.empty()) {
// split data string into fields
list<wstring> fields=util::wstring2list(data,L" ");
// iterate over field list and store each appropriately
list<wstring>::iterator f=fields.begin();
//first field: list of hypernyms
if ((*f)!=L"-") parents=util::wstring2list(*f,L":");
// second field: WN semantic file
f++; semfile=(*f);
// third filed: List of EWN top-ontology labels
f++; if ((*f)!=L"-") tonto=util::wstring2list(*f,L":");
// fourth field: SUMO concept
f++; if ((*f)!=L"-") sumo=*f;
// fifth field: OpenCYC concept
f++; if ((*f)!=L"-") cyc=*f;
}
}
///////////////////////////////////////////////////////////////
/// Obtain parent list as string (useful for Java API
///////////////////////////////////////////////////////////////
wstring sense_info::get_parents_string() const {
return util::list2wstring(parents,L":");
}
///////////////////////////////////////////////////////////////
/// Create the sense annotator
///////////////////////////////////////////////////////////////
semanticDB::semanticDB(const std::wstring &wsdFile) {
wstring formFile,dictFile,wnFile;
wstring path=wsdFile.substr(0,wsdFile.find_last_of(L"/\\")+1);
// store PoS appearing in mapping to select relevant dictionary entries later.
set<wstring> posset;
enum sections {WN_POS_MAP, DATA_FILES};
config_file cfg(true);
cfg.add_section(L"WNposMap",WN_POS_MAP);
cfg.add_section(L"DataFiles",DATA_FILES);
if (not cfg.open(wsdFile))
ERROR_CRASH(L"Error opening configuration file "+wsdFile);
// read disambiguator configuration file
wstring line;
while (cfg.get_content_line(line)) {
switch (cfg.get_section()) {
case WN_POS_MAP: { // reading map freeling PoS -> WNPoS lemma
wistringstream sin;
sin.str(line);
posmaprule r; // read and store a posmap rule, eg: "VMP v (VMP00SM)" or "N n L"
sin>>r.pos>>r.wnpos>>r.lemma;
posmap.push_back(r);
if (r.lemma!=L"L" and r.lemma!=L"F")
posset.insert(r.lemma);
break;
}
case DATA_FILES: { // reading names for data files
wistringstream sin;
sin.str(line);
wstring key; wstring fname;
sin>>key>>fname;
if (key==L"formDictFile") formFile=util::absolute(fname,path);
else if (key==L"senseDictFile") dictFile=util::absolute(fname,path);
else if (key==L"wnFile") wnFile=util::absolute(fname,path);
break;
}
default: break;
}
}
cfg.close();
// load the necessary entries from the form dictionary,
// store them reversed for access (lema,PoS)->form
if (formFile.empty() or posset.size()==0)
form_dict=NULL;
else {
wifstream fform;
util::open_utf8_file(fform, formFile);
if (fform.fail()) ERROR_CRASH(L"Error opening formDict file "+formFile);
form_dict = new database(DB_MAP);
while (getline(fform,line)) {
wistringstream sin; sin.str(line);
// get form, 1st field
wstring form;
sin>>form;
// get pairs lemma-pos and select those relevant
wstring lema,tag;
while (sin>>lema>>tag) {
if (posset.find(tag)!=posset.end())
form_dict->add_database(lema+L" "+tag,form);
}
}
fform.close();
}
// load semanticDB if needed.
if (dictFile.empty())
sensesdb=NULL;
else {
wifstream fsens;
util::open_utf8_file(fsens, dictFile);
if (fsens.fail()) ERROR_CRASH(L"Error opening senseDict file "+dictFile);
sensesdb = new database(DB_MAP);
while (getline(fsens,line)) {
wistringstream sin; sin.str(line);
// get sense, 1st field
wstring sens;
sin>>sens;
wstring tag= sens.substr(sens.find(L"-")+1);
// get words for current sense. Store both sense->words and word->sense records
wstring wd;
while (sin>>wd) {
sensesdb->add_database(L"S:"+sens,wd);
sensesdb->add_database(L"W:"+wd+L":"+tag, sens);
}
}
fsens.close();
}
// load WN structure if needed
if (wnFile.empty())
wndb=NULL;
else
wndb = new database(wnFile) ;
}
////////////////////////////////////////////////
/// Destroy sense annotator module, close database.
////////////////////////////////////////////////
semanticDB::~semanticDB() {
delete sensesdb;
delete wndb;
delete form_dict;
}
///////////////////////////////////////////////////////////////
/// Get senses for a lemma+pos
///////////////////////////////////////////////////////////////
list<wstring> semanticDB::get_word_senses(const wstring &form, const wstring &lemma, const wstring &pos) const {
// get pairs (lemma,pos) to search in WN for this analysis
list<pair<wstring,wstring> > searchlist;
get_WN_keys(form, lemma, pos, searchlist);
// search senses for each lemma/tag in the list
list<wstring> lsen;
list<pair<wstring,wstring> >::iterator p;
for (p=searchlist.begin(); p!=searchlist.end(); p++) {
TRACE(4,L" .. searching "+p->first+L" "+p->second);
list<wstring> s = util::wstring2list(sensesdb->access_database(L"W:"+p->first+L":"+p->second), L" ");
lsen.insert(lsen.end(),s.begin(),s.end());
}
if (not lsen.empty()) {
TRACE(4,L" .. senses found: "+util::list2wstring(lsen,L"/"));
}
return lsen;
}
///////////////////////////////////////////////////////////////
/// Get synonyms for a sense+pos
///////////////////////////////////////////////////////////////
list<wstring> semanticDB::get_sense_words(const wstring &sens) const{
return util::wstring2list(sensesdb->access_database(L"S:"+sens), L" ");
}
///////////////////////////////////////////////////////////////
/// Get info for a sense+pos
///////////////////////////////////////////////////////////////
sense_info semanticDB::get_sense_info(const wstring &syn) const{
/// access DB and split obtained data_string into fields
/// and store appropriately in a sense_info object
sense_info sinf(syn,wndb->access_database(syn));
/// add also list of synset words
sinf.words=get_sense_words(syn);
return sinf;
}
//////////////////////////////////////////////
/// Compute list of lemma-pos to search in WN for given
/// word and analysis, according to mapping rules.
//////////////////////////////////////////////
void semanticDB::get_WN_keys(const wstring &form, const wstring &lemma, const wstring &tag, list<pair<wstring,wstring> > &searchlist) const {
searchlist.clear();
// check all possible mappings to WN-PoS
list<posmaprule>::const_iterator p;
for (p=posmap.begin(); p!=posmap.end(); p++) {
TRACE(4,L"Check tag "+tag+L" with posmap: "+p->pos+L" "+p->wnpos+L" "+p->lemma);
if (tag.find(p->pos)==0) {
TRACE(4,L" matched");
// rule matches word PoS. Add pair lemma/pos to the list
wstring lm;
if (p->lemma==L"L") lm=lemma;
else if (p->lemma==L"F") lm=form;
else { // interpret it as a PoS tag
TRACE(3,L"Found word matching special map: "+lemma+L" "+p->lemma);
lm = form_dict->access_database(lemma+L" "+p->lemma);
}
// split list in case there are more than one form
list<wstring> fms=util::wstring2list(lm,L" ");
for (list<wstring>::iterator ifm=fms.begin(); ifm!=fms.end(); ifm++) {
TRACE(3,L"Adding word '"+form+L"' to be searched with pos="+p->wnpos+L" and lemma="+(*ifm));
searchlist.push_back(make_pair(*ifm,p->wnpos));
}
}
}
}
} // namespace<|fim▁end|> | /// Constructor of the auxiliary class "sense_info"
/////////////////////////////////////////////////////////////// |
<|file_name|>recu.rs<|end_file_name|><|fim▁begin|>/*
recu.rs
demonstrates enums, recursive datatypes, and methdos
vanilla
*/
<|fim▁hole|> println!("Product of all values in the list {:i}.",list2.prod());
}
enum IntList {
Node(int, ~IntList),
Empty
}
impl IntList {
fn sum(~self) -> int {
// As in C and C++, pointers are dereferenced with the asterisk `*` operator.
match *self {
Node(value, next) => value + next.sum(),
Empty => 0
}
}
fn prod(~self) -> int {
match *self {
Node(value,next) => value * next.prod(),
Empty => 1
}
}
}<|fim▁end|> | fn main() {
let list = ~Node(1, ~Node(2, ~Node(3, ~Empty)));
let list2 = ~Node(2, ~Node(3, ~Node(5, ~Empty)));
println!("Sum of all values in the list: {:i}.", list.sum()); |
<|file_name|>fix_nt_file.py<|end_file_name|><|fim▁begin|>import sys
def fix(element):
if element and element[0] == '<':
new = '<'
for c in element[1:-1]:
if c == '<':
new += '<'
elif c == '>':<|fim▁hole|> new += c
new += '>'
return new
else:
return element
for line in open(sys.argv[1]):
cols = line.strip().split('\t')
if len(cols) != 4 or cols[3] != '.':
sys.err.write('Ignoring malformed line: ' + line)
else:
# for now only touch subject for efficiency reasons.
cols[0] = fix(cols[0])
print '\t'.join(cols)<|fim▁end|> | new += '>'
else: |
<|file_name|>templatetags.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.template import Context, Template
from pootle.core.delegate import scores
def _render_str(string, context=None):
context = context or {}
context = Context(context)
return Template(string).render(context)
def test_templatetag_progress_bar():
rendered = _render_str("{% load common_tags %}{% progress_bar 0 0 0 %}")
assert "<span class=\'value translated\'>0%</span>" in rendered
assert '<span class=\'value fuzzy\'>0%</span>' in rendered
assert '<span class=\'value untranslated\'>0%</span>' in rendered
rendered = _render_str(
"{% load common_tags %}{% progress_bar 123 23 73 %}")
assert "<span class=\'value translated\'>59.3%</span>" in rendered
assert "<span class=\'value fuzzy\'>18.7%</span>" in rendered
assert "<span class=\'value untranslated\'>22.0%</span>" in rendered
assert '<td class="translated" style="width: 59.3%">' in rendered
assert '<td class="fuzzy" style="width: 18.7%">' in rendered
assert '<td class="untranslated" style="width: 22.0%">' in rendered
@pytest.mark.django_db
def test_inclusion_tag_top_scorers(project_set, member):
score_data = scores.get(project_set.__class__)(project_set)
rendered = _render_str(
"{% load common_tags %}{% top_scorers user score_data %}",
context=dict(
user=member,
score_data=score_data.display()))
top_scorer = list(score_data.display())[0]
assert top_scorer["public_total_score"] in rendered<|fim▁hole|><|fim▁end|> | assert top_scorer["user"].email_hash in rendered |
<|file_name|>generic-fn-box.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.
fn f<T>(x: @T) -> @T { return x; }<|fim▁hole|><|fim▁end|> |
pub fn main() { let x = f(@3); debug!(*x); } |
<|file_name|>config.spec.ts<|end_file_name|><|fim▁begin|>import config from '../src/config';
import skift from '../src/index';
describe('Config', () => {
it('should get default configuration', () => {
expect(config).toBeDefined();
expect(config.cookieName).toBeDefined();
expect(config.globalCondition).toBeDefined();<|fim▁hole|> expect(config.tracking).toBeDefined();
expect(config.uiCondition).toBeDefined();
expect(config.userSessionDaysToLive).toBeDefined();
});
it('should override default config', () => {
skift.config({
cookieName: 'Test',
});
expect(config).toBeDefined();
expect(config.cookieName).toEqual('Test');
});
});<|fim▁end|> | expect(config.sessionPersister).toBeDefined(); |
<|file_name|>css-find.js<|end_file_name|><|fim▁begin|>var search = require('simple-object-query').search,
CssSelectorParser = require('css-selector-parser').CssSelectorParser,
cssParser = new CssSelectorParser();
cssParser
.registerNestingOperators('>')
.registerAttrEqualityMods('^', '$', '*', '~')
;
module.exports = cssFind;
function cssFind(root, rule) {
if (typeof rule === 'string') {
rule = cssParser.parse(rule);
}
if (rule.type === 'selectors') {
for (var i = 0, len = rule.selectors.length; i < len; i++) {
var res = cssFind(root, rule.selectors[i].rule);
if (res) return res;
}
return;
}
else if (rule.type === 'ruleSet') {
rule = rule.rule;
}
return search({
source: root,
query: {
type: 'tag'
},
include: function (item) {
if (rule.nestingOperator === '>' && item.parent && item.parent !== root) return false;
return (
item.field === 'children' ||
item.path[item.path.length - 1] === 'children'
);
},
callback: function (item) {
if (item.target === root) return;
var node = item.target;
if (isCssValid(node, rule)) {
if (!rule.rule) {
return node;
}
return cssFind(node, rule.rule);
}
}
});
}
function isCssValid(node, rule) {
var i, len;
if (rule.tagName) {
if (node.name !== rule.tagName) return false;
}
if (rule.classNames) {
var classes = (node.attr['class'] || '').split(/\s+/);
for (i = 0, len = rule.classNames.length; i < len; i++) {
if (classes.indexOf(rule.classNames[i]) === -1) return false;
}
}
if (rule.attrs) {
for (i = 0, len = rule.attrs.length; i < len; i++) {
var attr = rule.attrs[i];
if (!node.attr.hasOwnProperty(attr.name)) return false;
switch (attr.operator) {
case '=':
if (node.attr[attr.name] !== attr.value) return false;
break;
case '^=':
if (node.attr[attr.name].indexOf(attr.value) !== 0) return false;
break;
case '$=':
if (node.attr[attr.name].slice(-attr.value.length) !== attr.value) return false;
break;
case '*=':
if (node.attr[attr.name].indexOf(attr.value) === -1) return false;
break;
}
}
}
if (rule.pseudos) {
for (i = 0, len = rule.pseudos.length; i < len; i++) {
var pseudo = rule.pseudos[i];
switch (pseudo.name) {
case 'nth-child':
case 'eq':
if (getChildNodes(node.parent).indexOf(node) !== Number(pseudo.value) - 1) return false;
break;
}
}
}
return true;
}
function getChildNodes(node) {
var nodes = [];
for (var i = 0, len = node.children.length; i < len; i++) {
if (node.children[i].type === 'tag') {
nodes.push(node.children[i]);<|fim▁hole|> return nodes;
}<|fim▁end|> | }
}
|
<|file_name|>amp-3q-player.js<|end_file_name|><|fim▁begin|><|fim▁hole|>/**
* Copyright 2017 The AMP HTML 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.
*/
import {isLayoutSizeDefined} from '../../../src/layout';
import {tryParseJson} from '../../../src/json';
import {user} from '../../../src/log';
import {removeElement} from '../../../src/dom';
import {
installVideoManagerForDoc,
} from '../../../src/service/video-manager-impl';
import {isObject} from '../../../src/types';
import {listen} from '../../../src/event-helper';
import {VideoEvents} from '../../../src/video-interface';
import {videoManagerForDoc} from '../../../src/services';
/**
* @implements {../../../src/video-interface.VideoInterface}
*/
class Amp3QPlayer extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {?Element} */
this.iframe_ = null;
/** @private {?Function} */
this.unlistenMessage_ = null;
/** @private {?Promise} */
this.playerReadyPromise_ = null;
/** @private {?Function} */
this.playerReadyResolver_ = null;
this.dataId = null;
}
/**
* @param {boolean=} opt_onLayout
* @override
*/
preconnectCallback(opt_onLayout) {
this.preconnect.url('https://playout.3qsdn.com', opt_onLayout);
}
/** @override */
buildCallback() {
this.dataId = user().assert(
this.element.getAttribute('data-id'),
'The data-id attribute is required for <amp-3q-player> %s',
this.element);
this.playerReadyPromise_ = new Promise(resolve => {
this.playerReadyResolver_ = resolve;
});
installVideoManagerForDoc(this.element);
videoManagerForDoc(this.element).register(this);
}
/** @override */
layoutCallback() {
const iframe = this.element.ownerDocument.createElement('iframe');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', 'true');
this.iframe_ = iframe;
this.unlistenMessage_ = listen(
this.win,
'message',
this.sdnBridge_.bind(this)
);
this.applyFillContent(iframe, true);
iframe.src = 'https://playout.3qsdn.com/' +
encodeURIComponent(this.dataId) + '?autoplay=false&=true';
this.element.appendChild(iframe);
return this.loadPromise(this.iframe_).then(() =>
this.playerReadyPromise_);
}
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
}
if (this.unlistenMessage_) {
this.unlistenMessage_();
}
this.playerReadyPromise_ = new Promise(resolve => {
this.playerReadyResolver_ = resolve;
});
return true;
}
/** @override */
isLayoutSupported(layout) {
return isLayoutSizeDefined(layout);
}
/** @override */
viewportCallback(visible) {
this.element.dispatchCustomEvent(VideoEvents.VISIBILITY, {visible});
}
/** @override */
pauseCallback() {
if (this.iframe_) {
this.pause();
}
}
sdnBridge_(event) {
if (event.source) {
if (event.source != this.iframe_.contentWindow) {
return;
}
}
const data = isObject(event.data) ? event.data : tryParseJson(event.data);
if (data === undefined) {
return;
}
switch (data.data) {
case 'ready':
this.element.dispatchCustomEvent(VideoEvents.LOAD);
this.playerReadyResolver_();
break;
case 'playing':
this.element.dispatchCustomEvent(VideoEvents.PLAY);
break;
case 'paused':
this.element.dispatchCustomEvent(VideoEvents.PAUSE);
break;
case 'muted':
this.element.dispatchCustomEvent(VideoEvents.MUTED);
break;
case 'unmuted':
this.element.dispatchCustomEvent(VideoEvents.UNMUTED);
break;
}
}
sdnPostMessage_(message) {
this.playerReadyPromise_.then(() => {
if (this.iframe_ && this.iframe_.contentWindow) {
this.iframe_.contentWindow./*OK*/postMessage(message, '*');
}
});
}
// VideoInterface Implementation. See ../src/video-interface.VideoInterface
/** @override */
play() {
this.sdnPostMessage_('play2');
}
/** @override */
pause() {
this.sdnPostMessage_('pause');
}
/** @override */
mute() {
this.sdnPostMessage_('mute');
}
/** @override */
unmute() {
this.sdnPostMessage_('unmute');
}
/** @override */
supportsPlatform() {
return true;
}
/** @override */
isInteractive() {
return true;
}
/** @override */
showControls() {
this.sdnPostMessage_('showControlbar');
}
/** @override */
hideControls() {
this.sdnPostMessage_('hideControlbar');
}
};
AMP.registerElement('amp-3q-player', Amp3QPlayer);<|fim▁end|> | |
<|file_name|>rasterize.js<|end_file_name|><|fim▁begin|>var system = require('system');
var args = system.args;
var url = "http://"+args[1],
filename = args[2]+".png",
timeout = args[3],
savePath = args[4],
page = require('webpage').create();
//setTimeout(function(){phantom.exit();}, timeout)
page.viewportSize = { width: 1200, height: 700 };
page.clipRect = { top: 0, left: 0, width: 1200, height: 700 };
var f = false;
page.onLoadFinished = function(status) {
console.log('Status: ' + status);
setTimeout(function(){
render(page);
phantom.exit();
}, 15000)
};<|fim▁hole|>
page.onResourceReceived = function(response) {
if (response.url === url && !f) {
setTimeout(function(){
render(page);
phantom.exit();
}, 15000)
f = true
}
};
function render(page) {
var resPath
if (savePath == "") {
resPath = filename
} else {
resPath = savePath + "/" + filename
}
page.render(resPath)
}
console.log("start get " + url)
page.open(url, function() {
});<|fim▁end|> | |
<|file_name|>BookUpdaterProgram.java<|end_file_name|><|fim▁begin|>package com.osiykm.flist.services.programs;
import com.osiykm.flist.entities.Book;
import com.osiykm.flist.enums.BookStatus;<|fim▁hole|>import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/***
* @author osiykm
* created 28.09.2017 22:49
*/
@Component
@Slf4j
public class BookUpdaterProgram extends BaseProgram {
private final FanfictionUrlParserService urlParserService;
private final BookRepository bookRepository;
@Autowired
public BookUpdaterProgram(FanfictionUrlParserService urlParserService, BookRepository bookRepository) {
this.urlParserService = urlParserService;
this.bookRepository = bookRepository;
}
@Override
public void run() {
List<Book> books;
List<Book> updatedBooks;
log.info("Start update books");
books = bookRepository.findByStatusNot(BookStatus.COMPLETED);
log.info("find " + books.size() + "books for update");
updatedBooks = new ArrayList<>();
for (Book book :
books) {
if (isAlive()) {
Book updatedBook = urlParserService.getBook(book.getUrl());
updatedBooks.add(book.setSize(updatedBook.getSize()).setChapters(updatedBook.getChapters()).setStatus(updatedBook.getStatus()));
} else {
break;
}
}
log.info("updated " + updatedBooks.size() + " books");
bookRepository.save(updatedBooks);
stop();
}
}<|fim▁end|> | import com.osiykm.flist.repositories.BookRepository;
import com.osiykm.flist.services.parser.FanfictionUrlParserService; |
<|file_name|>assign_generic_numbers_gpcr.py<|end_file_name|><|fim▁begin|>from django.conf import settings
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.PDB import *
from Bio.PDB.PDBIO import Select
from common.definitions import *
from protein.models import Protein, ProteinSegment
from residue.models import Residue
from structure.functions import BlastSearch, MappedResidue, StructureSeqNumOverwrite
from structure.sequence_parser import *
import Bio.PDB.Polypeptide as polypeptide
import os,logging
<|fim▁hole|>
logger = logging.getLogger("protwis")
#==============================================================================
#Class for annotating the pdb structures with generic numbers
class GenericNumbering(object):
residue_list = ["ARG","ASP","GLU","HIS","ASN","GLN","LYS","SER","THR","HID","PHE","LEU","ILE","TYR","TRP","VAL","MET","PRO","CYS","ALA","GLY"]
exceptions = {'6GDG':[255, 10]}
def __init__ (self, pdb_file=None, pdb_filename=None, structure=None, pdb_code=None, blast_path='blastp',
blastdb=os.sep.join([settings.STATICFILES_DIRS[0], 'blast', 'protwis_blastdb']),top_results=1, sequence_parser=False, signprot=False):
# pdb_file can be either a name/path or a handle to an open file
self.pdb_file = pdb_file
self.pdb_filename = pdb_filename
# if pdb 4 letter code is specified
self.pdb_code = pdb_code
# dictionary of 'MappedResidue' object storing information about alignments and bw numbers
self.residues = {}
self.pdb_seq = {} #Seq('')
# list of uniprot ids returned from blast
self.prot_id_list = []
#setup for local blast search
self.blast = BlastSearch(blast_path=blast_path, blastdb=blastdb,top_results=top_results)
# calling sequence parser
if sequence_parser:
if pdb_code:
struct = Structure.objects.get(pdb_code__index=self.pdb_code)
if not signprot:
if pdb_code:
s = SequenceParser(pdb_file=self.pdb_file, wt_protein_id=struct.protein_conformation.protein.parent.id)
else:
s = SequenceParser(pdb_file=self.pdb_file)#, wt_protein_id=struct.protein_conformation.protein.parent.id)
else:
s = SequenceParser(pdb_file=self.pdb_file, wt_protein_id=signprot.id)
self.pdb_structure = s.pdb_struct
self.mapping = s.mapping
self.wt = s.wt
else:
if self.pdb_file:
self.pdb_structure = PDBParser(PERMISSIVE=True, QUIET=True).get_structure('ref', self.pdb_file)[0]
elif self.pdb_filename:
self.pdb_structure = PDBParser(PERMISSIVE=True, QUIET=True).get_structure('ref', self.pdb_filename)[0]
else:
self.pdb_structure = structure
self.parse_structure(self.pdb_structure)
def parse_structure(self, pdb_struct):
"""
extracting sequence and preparing dictionary of residues
bio.pdb reads pdb in the following cascade: model->chain->residue->atom
"""
for chain in pdb_struct:
self.residues[chain.id] = {}
self.pdb_seq[chain.id] = Seq('')
for res in chain:
#in bio.pdb the residue's id is a tuple of (hetatm flag, residue number, insertion code)
if res.resname == "HID":
resname = polypeptide.three_to_one('HIS')
else:
if res.resname not in self.residue_list:
continue
self.residues[chain.id][res.id[1]] = MappedResidue(res.id[1], polypeptide.three_to_one(res.resname))
self.pdb_seq[chain.id] = ''.join([self.residues[chain.id][x].name for x in sorted(self.residues[chain.id].keys())])
for pos, res in enumerate(sorted(self.residues[chain.id].keys()), start=1):
self.residues[chain.id][res].pos_in_aln = pos
def locate_res_by_pos (self, chain, pos):
for res in self.residues[chain].keys():
if self.residues[chain][res].pos_in_aln == pos:
return res
return 0
def map_blast_seq (self, prot_id, hsps, chain):
#find uniprot residue numbers corresponding to those in pdb file
q_seq = list(hsps.query)
tmp_seq = list(hsps.sbjct)
subj_counter = hsps.sbjct_start
q_counter = hsps.query_start
logger.info("{}\n{}".format(hsps.query, hsps.sbjct))
logger.info("{:d}\t{:d}".format(hsps.query_start, hsps.sbjct_start))
rs = Residue.objects.prefetch_related('display_generic_number', 'protein_segment').filter(
protein_conformation__protein=prot_id)
residues = {}
for r in rs:
residues[r.sequence_number] = r
while tmp_seq:
#skipping position if there is a gap in either of sequences
if q_seq[0] == '-' or q_seq[0] == 'X' or q_seq[0] == ' ':
subj_counter += 1
tmp_seq.pop(0)
q_seq.pop(0)
continue
if tmp_seq[0] == '-' or tmp_seq[0] == 'X' or tmp_seq[0] == ' ':
q_counter += 1
tmp_seq.pop(0)
q_seq.pop(0)
continue
if tmp_seq[0] == q_seq[0]:
resn = self.locate_res_by_pos(chain, q_counter)
if resn != 0:
if subj_counter in residues:
db_res = residues[subj_counter]
if db_res.protein_segment:
segment = db_res.protein_segment.slug
self.residues[chain][resn].add_segment(segment)
if db_res.display_generic_number:
num = db_res.display_generic_number.label
bw, gpcrdb = num.split('x')
gpcrdb = "{}.{}".format(bw.split('.')[0], gpcrdb)
self.residues[chain][resn].add_bw_number(bw)
self.residues[chain][resn].add_gpcrdb_number(gpcrdb)
self.residues[chain][resn].add_gpcrdb_number_id(db_res.display_generic_number.id)
self.residues[chain][resn].add_display_number(num)
self.residues[chain][resn].add_residue_record(db_res)
else:
logger.warning("Could not find residue {} {} in the database.".format(resn, subj_counter))
if prot_id not in self.prot_id_list:
self.prot_id_list.append(prot_id)
q_counter += 1
subj_counter += 1
tmp_seq.pop(0)
q_seq.pop(0)
def get_substructure_mapping_dict(self):
mapping_dict = {}
for chain in self.residues.keys():
for res in self.residues[chain].keys():
if self.residues[chain][res].segment in mapping_dict.keys():
mapping_dict[self.residues[chain][res].segment].append(self.residues[chain][res].number)
else:
mapping_dict[self.residues[chain][res].segment] = [self.residues[chain][res].number,]
return mapping_dict
def get_annotated_structure(self):
for chain in self.pdb_structure:
for residue in chain:
if residue.id[1] in self.residues[chain.id].keys():
if self.residues[chain.id][residue.id[1]].gpcrdb != 0.:
residue["CA"].set_bfactor(float(self.residues[chain.id][residue.id[1]].gpcrdb))
if self.residues[chain.id][residue.id[1]].bw != 0.:
residue["N"].set_bfactor(float(self.residues[chain.id][residue.id[1]].bw))
return self.pdb_structure
def save_gn_to_pdb(self):
#replace bfactor field of CA atoms with b-w numbers and return filehandle with the structure written
for chain in self.pdb_structure:
for residue in chain:
if residue.id[1] in self.residues[chain.id].keys():
if self.residues[chain.id][residue.id[1]].gpcrdb != 0.:
residue["CA"].set_bfactor(float(self.residues[chain.id][residue.id[1]].gpcrdb))
if self.residues[chain.id][residue.id[1]].bw != 0.:
residue["N"].set_bfactor(float(self.residues[chain.id][residue.id[1]].bw))
r = self.residues[chain.id][residue.id[1]]
#get the basename, extension and export the pdb structure with b-w numbers
root, ext = os.path.splitext(self.pdb_filename)
io=PDBIO()
io.set_structure(self.pdb_structure)
io.save("%s_GPCRDB%s" %(root, ext))
def assign_generic_numbers(self):
alignments = {}
#blast search goes first, looping through all the chains
for chain in self.pdb_seq.keys():
alignments[chain] = self.blast.run(self.pdb_seq[chain])
#map the results onto pdb sequence for every sequence pair from blast
for chain in self.pdb_seq.keys():
for alignment in alignments[chain]:
if alignment == []:
continue
for hsps in alignment[1].hsps:
self.map_blast_seq(alignment[0], hsps, chain)
return self.get_annotated_structure()
def assign_generic_numbers_with_sequence_parser(self):
for chain in self.pdb_structure:
for residue in chain:
if chain.id in self.mapping:
if residue.id[1] in self.mapping[chain.id].keys():
gpcrdb_num = self.mapping[chain.id][residue.id[1]].gpcrdb
if gpcrdb_num != '' and len(gpcrdb_num.split('x'))==2:
bw, gn = gpcrdb_num.split('x')
gn = "{}.{}".format(bw.split('.')[0], gn)
if len(gn.split('.')[1])==3:
gn = '-'+gn[:-1]
try:
residue["CA"].set_bfactor(float(gn))
residue["N"].set_bfactor(float(bw))
except:
pass
return self.pdb_structure
def assign_cgn_with_sequence_parser(self, target_chain):
pdb_array = OrderedDict()
for s in G_PROTEIN_SEGMENTS['Full']:
pdb_array[s] = OrderedDict()
i, j = 0, 0
key_list = [i.gpcrdb for i in list(self.mapping[target_chain].values())]
for key, vals in self.mapping[target_chain].items():
category, segment, num = vals.gpcrdb.split('.')
if self.pdb_code in self.exceptions:
try:
if self.pdb_structure[target_chain][key].get_id()[1]>=self.exceptions[self.pdb_code][0]:
if i<self.exceptions[self.pdb_code][1]:
pdb_array[segment][vals.gpcrdb] = 'x'
i+=1
continue
except:
pass
this_cat, this_seg, this_num = key_list[j].split('.')
try:
pdb_array[segment][vals.gpcrdb] = self.pdb_structure[target_chain][key-i].get_list()
except:
pdb_array[segment][vals.gpcrdb] = 'x'
j+=1
return pdb_array<|fim▁end|> | from collections import OrderedDict
|
<|file_name|>main.controller.ts<|end_file_name|><|fim▁begin|>import * as _ from 'lodash';
import { IAppService } from '../app.service';
export class mainCtrl {
title: string;
static $inject = ['$scope', '$state', 'appService', '$mdDialog'];
constructor(private $scope, private $state: ng.ui.IStateService, private appService: IAppService, private $mdDialog: ng.material.IDialogService) {
this.title = 'MAIN';
var clearEvt1 = appService.events.filter(x => x.target === 'websocket@open').subscribe(data => this.appService.send('login', {}));
var clearEvt2 = appService.events.filter(x => x.target === 'websocket@close').subscribe(data => this.OnWSClose(data));
var clearEvt3 = appService.events.filter(x => x.target === 'websocket@error').subscribe(data => this.OnWSError(data));
var clearEvt4 = appService.events.filter(x => x.target === 'login').subscribe(data => {
if (this.$state.current.name === 'login') return;
if (data && !data.error) {
this.appService.permissions = data.content.permissions;
this.appService.username = data.content.username;
}
else {
this.$state.go('login');
}
});
this.appService.connect();
$scope.$on("$destroy", () => {
clearEvt1.unsubscribe();
clearEvt2.unsubscribe();
clearEvt3.unsubscribe();
clearEvt4.unsubscribe();
});
}<|fim▁hole|> console.error('error: ', data);
}
OnWSClose(data) {
this.appService.permissions = '';
this.appService.username = '';
if (data.code === 3001) return;
this.$mdDialog.show(this.$mdDialog.confirm()
.cancel('No')
.ok('Yes')
.textContent('The server connection is closed. Do you want to open it back?')
.clickOutsideToClose(true)
.escapeToClose(true)
//.focusOnOpen(false)
//.onComplete(() => {
// this.appService.connect();
)
.then(() => {
this.appService.connect();
});
}
}<|fim▁end|> |
OnWSError(data) { |
<|file_name|>unit.go<|end_file_name|><|fim▁begin|>// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
// UnitType is Unit's Type
type UnitType int
// Enumerate all the unit types
const (
UnitTypeCode UnitType = iota + 1 // 1 code
UnitTypeIssues // 2 issues
UnitTypePullRequests // 3 PRs
UnitTypeCommits // 4 Commits
UnitTypeReleases // 5 Releases
UnitTypeWiki // 6 Wiki
UnitTypeSettings // 7 Settings
UnitTypeExternalWiki // 8 ExternalWiki
UnitTypeExternalTracker // 9 ExternalTracker
)
var (
// allRepUnitTypes contains all the unit types
allRepUnitTypes = []UnitType{
UnitTypeCode,
UnitTypeIssues,
UnitTypePullRequests,
UnitTypeCommits,
UnitTypeReleases,
UnitTypeWiki,
UnitTypeSettings,
UnitTypeExternalWiki,
UnitTypeExternalTracker,
}
// defaultRepoUnits contains the default unit types
defaultRepoUnits = []UnitType{
UnitTypeCode,
UnitTypeIssues,
UnitTypePullRequests,
UnitTypeCommits,
UnitTypeReleases,
UnitTypeWiki,
UnitTypeSettings,
}
// MustRepoUnits contains the units could be disabled currently
MustRepoUnits = []UnitType{
UnitTypeCode,
UnitTypeCommits,
UnitTypeReleases,
UnitTypeSettings,
}
)
// Unit is a tab page of one repository
type Unit struct {
Type UnitType
NameKey string
URI string
DescKey string
Idx int
}
// CanDisable returns if this unit could be disabled.
func (u *Unit) CanDisable() bool {
return u.Type != UnitTypeSettings
}
// Enumerate all the units
var (
UnitCode = Unit{
UnitTypeCode,
"repo.code",
"/",
"repo.code.desc",
0,
}
UnitIssues = Unit{
UnitTypeIssues,
"repo.issues",
"/issues",
"repo.issues.desc",
1,
}
UnitExternalTracker = Unit{
UnitTypeExternalTracker,
"repo.ext_issues",
"/issues",
"repo.ext_issues.desc",<|fim▁hole|> }
UnitPullRequests = Unit{
UnitTypePullRequests,
"repo.pulls",
"/pulls",
"repo.pulls.desc",
2,
}
UnitCommits = Unit{
UnitTypeCommits,
"repo.commits",
"/commits/master",
"repo.commits.desc",
3,
}
UnitReleases = Unit{
UnitTypeReleases,
"repo.releases",
"/releases",
"repo.releases.desc",
4,
}
UnitWiki = Unit{
UnitTypeWiki,
"repo.wiki",
"/wiki",
"repo.wiki.desc",
5,
}
UnitExternalWiki = Unit{
UnitTypeExternalWiki,
"repo.ext_wiki",
"/wiki",
"repo.ext_wiki.desc",
5,
}
UnitSettings = Unit{
UnitTypeSettings,
"repo.settings",
"/settings",
"repo.settings.desc",
6,
}
// Units contains all the units
Units = map[UnitType]Unit{
UnitTypeCode: UnitCode,
UnitTypeIssues: UnitIssues,
UnitTypeExternalTracker: UnitExternalTracker,
UnitTypePullRequests: UnitPullRequests,
UnitTypeCommits: UnitCommits,
UnitTypeReleases: UnitReleases,
UnitTypeWiki: UnitWiki,
UnitTypeExternalWiki: UnitExternalWiki,
UnitTypeSettings: UnitSettings,
}
)<|fim▁end|> | 1, |
<|file_name|>shared.ts<|end_file_name|><|fim▁begin|>/**
* @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
*/
import {Parser as ExpressionParser} from '../expression_parser/parser';
import {StringWrapper, isBlank, isPresent} from '../facade/lang';
import {HtmlAst, HtmlAstVisitor, HtmlAttrAst, HtmlCommentAst, HtmlElementAst, HtmlExpansionAst, HtmlExpansionCaseAst, HtmlTextAst, htmlVisitAll} from '../html_ast';
import {InterpolationConfig} from '../interpolation_config';
import {ParseError, ParseSourceSpan} from '../parse_util';
import {Message} from './message';
export const I18N_ATTR = 'i18n';
export const I18N_ATTR_PREFIX = 'i18n-';
const _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*"([\s\S]*?)"[\s\S]*\)/g;
/**
* An i18n error.
*/
export class I18nError extends ParseError {
constructor(span: ParseSourceSpan, msg: string) { super(span, msg); }
}
export function partition(nodes: HtmlAst[], errors: ParseError[], implicitTags: string[]): Part[] {
let parts: Part[] = [];
for (let i = 0; i < nodes.length; ++i) {
let node = nodes[i];
let msgNodes: HtmlAst[] = [];
// Nodes between `<!-- i18n -->` and `<!-- /i18n -->`
if (_isOpeningComment(node)) {
let i18n = (<HtmlCommentAst>node).value.replace(/^i18n:?/, '').trim();
while (++i < nodes.length && !_isClosingComment(nodes[i])) {
msgNodes.push(nodes[i]);
}
if (i === nodes.length) {
errors.push(new I18nError(node.sourceSpan, 'Missing closing \'i18n\' comment.'));
break;
}
parts.push(new Part(null, null, msgNodes, i18n, true));
} else if (node instanceof HtmlElementAst) {
// Node with an `i18n` attribute
let i18n = _findI18nAttr(node);
let hasI18n: boolean = isPresent(i18n) || implicitTags.indexOf(node.name) > -1;
parts.push(new Part(node, null, node.children, isPresent(i18n) ? i18n.value : null, hasI18n));
} else if (node instanceof HtmlTextAst) {
parts.push(new Part(null, node, null, null, false));
}
}
return parts;
}
export class Part {
constructor(
public rootElement: HtmlElementAst, public rootTextNode: HtmlTextAst,
public children: HtmlAst[], public i18n: string, public hasI18n: boolean) {}
get sourceSpan(): ParseSourceSpan {
if (isPresent(this.rootElement)) {
return this.rootElement.sourceSpan;
}
if (isPresent(this.rootTextNode)) {
return this.rootTextNode.sourceSpan;
}
return new ParseSourceSpan(
this.children[0].sourceSpan.start, this.children[this.children.length - 1].sourceSpan.end);
}
createMessage(parser: ExpressionParser, interpolationConfig: InterpolationConfig): Message {
return new Message(
stringifyNodes(this.children, parser, interpolationConfig), meaning(this.i18n),
description(this.i18n));
}
}
function _isOpeningComment(n: HtmlAst): boolean {
return n instanceof HtmlCommentAst && isPresent(n.value) && n.value.startsWith('i18n');
}
function _isClosingComment(n: HtmlAst): boolean {
return n instanceof HtmlCommentAst && isPresent(n.value) && n.value === '/i18n';
}
function _findI18nAttr(p: HtmlElementAst): HtmlAttrAst {
let attrs = p.attrs;
for (let i = 0; i < attrs.length; i++) {
if (attrs[i].name === I18N_ATTR) {
return attrs[i];
}
}
return null;
}
export function meaning(i18n: string): string {
if (isBlank(i18n) || i18n == '') return null;
return i18n.split('|')[0];
}
export function description(i18n: string): string {
if (isBlank(i18n) || i18n == '') return null;
let parts = i18n.split('|', 2);
return parts.length > 1 ? parts[1] : null;
}
/**
* Extract a translation string given an `i18n-` prefixed attribute.
*
* @internal
*/
export function messageFromI18nAttribute(
parser: ExpressionParser, interpolationConfig: InterpolationConfig, p: HtmlElementAst,
i18nAttr: HtmlAttrAst): Message {
const expectedName = i18nAttr.name.substring(5);
const attr = p.attrs.find(a => a.name == expectedName);
if (attr) {
return messageFromAttribute(
parser, interpolationConfig, attr, meaning(i18nAttr.value), description(i18nAttr.value));
}
throw new I18nError(p.sourceSpan, `Missing attribute '${expectedName}'.`);
}
export function messageFromAttribute(
parser: ExpressionParser, interpolationConfig: InterpolationConfig, attr: HtmlAttrAst,
meaning: string = null, description: string = null): Message {
const value = removeInterpolation(attr.value, attr.sourceSpan, parser, interpolationConfig);
return new Message(value, meaning, description);
}
/**
* Replace interpolation in the `value` string with placeholders
*/
export function removeInterpolation(
value: string, source: ParseSourceSpan, expressionParser: ExpressionParser,
interpolationConfig: InterpolationConfig): string {
try {
const parsed =
expressionParser.splitInterpolation(value, source.toString(), interpolationConfig);
const usedNames = new Map<string, number>();
if (isPresent(parsed)) {
let res = '';
for (let i = 0; i < parsed.strings.length; ++i) {
res += parsed.strings[i];
if (i != parsed.strings.length - 1) {
let customPhName = extractPhNameFromInterpolation(parsed.expressions[i], i);
customPhName = dedupePhName(usedNames, customPhName);
res += `<ph name="${customPhName}"/>`;
}
}<|fim▁hole|> } catch (e) {
return value;
}
}
/**
* Extract the placeholder name from the interpolation.
*
* Use a custom name when specified (ie: `{{<expression> //i18n(ph="FIRST")}}`) otherwise generate a
* unique name.
*/
export function extractPhNameFromInterpolation(input: string, index: number): string {
let customPhMatch = StringWrapper.split(input, _CUSTOM_PH_EXP);
return customPhMatch.length > 1 ? customPhMatch[1] : `INTERPOLATION_${index}`;
}
/**
* Return a unique placeholder name based on the given name
*/
export function dedupePhName(usedNames: Map<string, number>, name: string): string {
const duplicateNameCount = usedNames.get(name);
if (duplicateNameCount) {
usedNames.set(name, duplicateNameCount + 1);
return `${name}_${duplicateNameCount}`;
}
usedNames.set(name, 1);
return name;
}
/**
* Convert a list of nodes to a string message.
*
*/
export function stringifyNodes(
nodes: HtmlAst[], expressionParser: ExpressionParser,
interpolationConfig: InterpolationConfig): string {
const visitor = new _StringifyVisitor(expressionParser, interpolationConfig);
return htmlVisitAll(visitor, nodes).join('');
}
class _StringifyVisitor implements HtmlAstVisitor {
private _index: number = 0;
constructor(
private _parser: ExpressionParser, private _interpolationConfig: InterpolationConfig) {}
visitElement(ast: HtmlElementAst, context: any): any {
let name = this._index++;
let children = this._join(htmlVisitAll(this, ast.children), '');
return `<ph name="e${name}">${children}</ph>`;
}
visitAttr(ast: HtmlAttrAst, context: any): any { return null; }
visitText(ast: HtmlTextAst, context: any): any {
let index = this._index++;
let noInterpolation =
removeInterpolation(ast.value, ast.sourceSpan, this._parser, this._interpolationConfig);
if (noInterpolation != ast.value) {
return `<ph name="t${index}">${noInterpolation}</ph>`;
}
return ast.value;
}
visitComment(ast: HtmlCommentAst, context: any): any { return ''; }
visitExpansion(ast: HtmlExpansionAst, context: any): any { return null; }
visitExpansionCase(ast: HtmlExpansionCaseAst, context: any): any { return null; }
private _join(strs: string[], str: string): string {
return strs.filter(s => s.length > 0).join(str);
}
}<|fim▁end|> | return res;
}
return value; |
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Role',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=255)),
('special_role', models.CharField(max_length=255, null=True, blank=True)),
('pickled_permissions', models.TextField(null=True, blank=True)),
],
options={<|fim▁hole|> 'abstract': False,
},
bases=(models.Model,),
),
]<|fim▁end|> | |
<|file_name|>helloworld.rs<|end_file_name|><|fim▁begin|>#include <constants.rh>
#include <crctools.rh>
#include <math.rh>
#include <util.rh>
; vim: syntax=fasm
; Test RAR assembly file that just demonstrates the syntax.
;
; Usage:
;
; $ unrar p -inul helloworld.rar
; Hello, World!
;<|fim▁hole|> ; Install our message in the output buffer
mov r3, #0x1000 ; Output buffer.
mov [r3+#0], #0x6c6c6548 ; 'lleH'
mov [r3+#4], #0x57202c6f ; 'W ,o'
mov [r3+#8], #0x646c726f ; 'dlro'
mov [r3+#12], #0x00000a21 ; '!\n'
mov [VMADDR_NEWBLOCKPOS], r3 ; Pointer
mov [VMADDR_NEWBLOCKSIZE], #14 ; Size
call $_success<|fim▁end|> |
_start: |
<|file_name|>quotasv2.py<|end_file_name|><|fim▁begin|># Copyright 2011 OpenStack Foundation.
# 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.
from oslo_config import cfg
from oslo_utils import importutils
import webob
from neutron._i18n import _
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.api.v2 import base
from neutron.api.v2 import resource
from neutron.common import constants as const
from neutron.common import exceptions as n_exc
from neutron import manager<|fim▁hole|>from neutron import wsgi
RESOURCE_NAME = 'quota'
RESOURCE_COLLECTION = RESOURCE_NAME + "s"
QUOTAS = quota.QUOTAS
DB_QUOTA_DRIVER = 'neutron.db.quota.driver.DbQuotaDriver'
EXTENDED_ATTRIBUTES_2_0 = {
RESOURCE_COLLECTION: {}
}
class QuotaSetsController(wsgi.Controller):
def __init__(self, plugin):
self._resource_name = RESOURCE_NAME
self._plugin = plugin
self._driver = importutils.import_class(
cfg.CONF.QUOTAS.quota_driver
)
self._update_extended_attributes = True
def _update_attributes(self):
for quota_resource in resource_registry.get_all_resources().keys():
attr_dict = EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION]
attr_dict[quota_resource] = {
'allow_post': False,
'allow_put': True,
'convert_to': attributes.convert_to_int,
'validate': {'type:range': [-1, const.DB_INTEGER_MAX_VALUE]},
'is_visible': True}
self._update_extended_attributes = False
def _get_quotas(self, request, tenant_id):
return self._driver.get_tenant_quotas(
request.context,
resource_registry.get_all_resources(),
tenant_id)
def create(self, request, body=None):
msg = _('POST requests are not supported on this resource.')
raise webob.exc.HTTPNotImplemented(msg)
def index(self, request):
context = request.context
self._check_admin(context)
return {self._resource_name + "s":
self._driver.get_all_quotas(
context, resource_registry.get_all_resources())}
def tenant(self, request):
"""Retrieve the tenant info in context."""
context = request.context
if not context.tenant_id:
raise n_exc.QuotaMissingTenant()
return {'tenant': {'tenant_id': context.tenant_id}}
def show(self, request, id):
if id != request.context.tenant_id:
self._check_admin(request.context,
reason=_("Only admin is authorized "
"to access quotas for another tenant"))
return {self._resource_name: self._get_quotas(request, id)}
def _check_admin(self, context,
reason=_("Only admin can view or configure quota")):
if not context.is_admin:
raise n_exc.AdminRequired(reason=reason)
def delete(self, request, id):
self._check_admin(request.context)
self._driver.delete_tenant_quota(request.context, id)
def update(self, request, id, body=None):
self._check_admin(request.context)
if self._update_extended_attributes:
self._update_attributes()
body = base.Controller.prepare_request_body(
request.context, body, False, self._resource_name,
EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION])
for key, value in body[self._resource_name].items():
self._driver.update_quota_limit(request.context, id, key, value)
return {self._resource_name: self._get_quotas(request, id)}
class Quotasv2(extensions.ExtensionDescriptor):
"""Quotas management support."""
@classmethod
def get_name(cls):
return "Quota management support"
@classmethod
def get_alias(cls):
return RESOURCE_COLLECTION
@classmethod
def get_description(cls):
description = 'Expose functions for quotas management'
if cfg.CONF.QUOTAS.quota_driver == DB_QUOTA_DRIVER:
description += ' per tenant'
return description
@classmethod
def get_updated(cls):
return "2012-07-29T10:00:00-00:00"
@classmethod
def get_resources(cls):
"""Returns Ext Resources."""
controller = resource.Resource(
QuotaSetsController(manager.NeutronManager.get_plugin()),
faults=base.FAULT_MAP)
return [extensions.ResourceExtension(
Quotasv2.get_alias(),
controller,
collection_actions={'tenant': 'GET'})]
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}<|fim▁end|> | from neutron import quota
from neutron.quota import resource_registry |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#from flask.templating import render_template
# Also installed redis
from app import app
from flask import Flask, request, url_for, Response, redirect
from extended_client import extended_client
import json
from jinja2 import Environment, PackageLoader
import logging
from time import sleep
#To access JMX Rest api
import requests
#To allow calling of sh commands from python
import commands
#Threading purposes
import threading
#For async tasks
from celery import Celery
#For doing msg_out rate calculations
import math
#For the timing of things
import datetime
#messages_in_topic_per_second = 'java -cp $JAVA_HOME/lib/tools.jar:../target/scala-2.10/cjmx.jar cjmx.Main 3628 \"mbeans \'kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec,*\' select *\"'
#For getting the process id of kafka
#import os
#PIDs = os.system("ps aux | grep \"kafka.Kafka\" | grep -v grep | awk '{print $2}'")
#For getting ipaddress
import socket<|fim▁hole|>host["ip"] = ip
#Jinja templating
env = Environment(loader=PackageLoader('app','templates'))
ext_client=None
json_data=None
json_nodes=None
zk=None
json_topics=None
remote_server = {}
remote_server["host"]= "John"
local = "local"
remote = "remote"
#CSS File
#reading_from={}
reading_from=""
#Store the offsets for each topic all consumers consume from
#Objects for keeping track of rates for CONSUMERS
prev_consumer_info = {}
prev_consumer_counts = {}
#Store the accumulated offset
accumulated_topic_rates = {}
consumers = ""
#Stores information for msgs_out
second_counter = 0
seconds_in_a_day = 86400 #(60*60*24)
#Objects for keeping track of rates for TOPICS
topic_sums = {}
prev_topic_info = {}
prev_topic_counts = {}
#Proxy server
proxy = None
#reading_from["data"] = None
#
#
# FUNCTIONS
#
#
# The thing that the user sees
@app.route('/')
@app.route('/index')
def index():
print "Index called"
template = env.get_template('index.html')
title = "Fufuka"
client_url = ""#ext_client.url_port
return template.render(page_title=title, zk_client=client_url)
# Gets all the form data from the "Start visualization page"
@app.route('/', methods=['POST'])
def index_return_values():
print "/ with data. Form received"
start = datetime.datetime.now()
#hostname = request.local
dictionary = request.form
print "Dict: " + str(dictionary) + " :" + str(len(dictionary))
#print list(v for k,v in dictionary.iteritems() if 'jmx' in k)
if len(dictionary) > 1:
#Dealing with a remote connection
print "Remotely"
global reading_from
#reading_from["data"] = str(remote)
reading_from = str(remote)
hostname = request.form.get("hostname", None)
zkhostnamePort = request.form.get("zkhostnameport", None)
proxy = request.form.get("proxy", None)
print "Connecting to: " + hostname
print "With zk at: " + zkhostnamePort
global proxy
print "Proxy: " + proxy
global hostandport
#Set the remote host
remote_server["host"] = str(hostname)
#Set all the JMX ports that need to be listened to
jmx_ports = list(v for k,v in dictionary.iteritems() if 'jmx' in k)
remote_server["ports"] = []
for port in jmx_ports:
print "JMX ports: " + str(port)
remote_server["ports"].append(str(port))
else:
#Dealing with a local connection
global reading_from
#reading_from["data"] = str(local)
reading_from = str(local)
print "Local"
zkhostnamePort = request.form.get("zkhostnameport", None)
print "Connecting to: " + zkhostnamePort
# Process data for getting to zk instance
#
#
split = zkhostnamePort.index(':')
hostname = zkhostnamePort[:split]
port = int(zkhostnamePort[split+1:])
#Start an instance of the extended_client
global ext_client
ext_client = extended_client(hostname, port)
#Start zookeeper client
global zk
zk = ext_client.zk
zk.start()
#Once the returned values are found, set them all
#Get consumers and producers
topics = ext_client.show_all_topics(zk)
#Populate topic holder
for t in topics:
topic_sums[t] = 0
prev_topic_info[t] = {}
prev_topic_counts[t] = []
global json_topics
json_topics = json.dumps(topics)
#Get the json data and store it
global json_data
json_data = json.dumps(ext_client.get_json(zk))
global json_nodes
json_nodes = json.dumps(ext_client.get_nodes_json(zk))
json_edges = json.dumps(ext_client.get_edges_json(zk))
end = datetime.datetime.now()
print "Total time to load zk information: " + str(end-start)
return redirect("/zk")
# Main viewing area for zks
@app.route('/zk')
def zk_client():
print "/zk called"
#Set the consumers then continously calculate their offsets
print "Creating consumer holders:"
start_time = datetime.datetime.now()
global consumers
consumers = ext_client.show_all_consumers(zk)
#Populate consumer holders
for c in consumers:
prev_consumer_info[c] = {}
prev_consumer_counts[c] = []
for c in consumers:
topics = ext_client.show_topics_consumed(zk, c)
for t in topics:
prev_consumer_info[c][t] = {}
#print prev_consumer_info
end_time = datetime.datetime.now()
calculate_offsets()
#Set the template of the page
template = env.get_template('zk_client.html')
#brokers = ext_client.show_brokers_ids(zk)
#Get the information of the current zookeeper instance
data = {}
data["zkinfo"] = str(ext_client.url_port)
print "Total con: " + str(len(consumers))
print "Total time to load /zk page: " + str(end_time-start_time)
return template.render(data=data)#consumers=consumers, brokers=brokers, producers=producers, topics=topics)#, r=r.content)
# Loads the d3 graph onto the iframe
@app.route('/test')
def test_2():
print "/test called"
start = datetime.datetime.now()
template = env.get_template('test2_graph.html')
js_url = url_for('static', filename='js/loadGraph.js')
# graph={}
# graph["nodes"] = json_nodes
# graph["edges"] = json_edges
data = {}
data["json_data"] = json_data
data["json_nodes"] = json_nodes
data["json_topics"] = json_topics
data["js_url"] = js_url
data["host"] = host
data["remote_server"] = remote_server
data["reading_from"] = reading_from
data["largest_weight"] = ext_client.get_largest_weight(zk)
data["smallest_weight"] = ext_client.get_smallest_weight(zk)
data["proxy"] = proxy
sendData = json.dumps(data)
# print "---------------------------"
# print "---------------------------"
# print "---------------------------"
end = datetime.datetime.now()
print "Total time to load /test page: " + str(end-start)
#print data
return template.render(data=sendData)#json_data=json_data, json_nodes=json_nodes, json_topics=json_topics, js_url=js_url, host=host, remote_server=remote_server, readingFrom=reading_from)
# Method to return offset rates
def get_rate(rate_type, prevData):
one_minute = 60
if rate_type == "minute":
#Get the minute rate
if len(prevData) > one_minute:
#print " Min rate "
#print "L: " + str(prevData[second_counter+1]) + " S: " + str(prevData[second_counter-one_minute])
#min_rate = abs(prevData[second_counter+1] - prevData[second_counter-one_minute])
min_rate = abs(prevData[second_counter] - prevData[second_counter-one_minute])/(one_minute + 0.0)
return min_rate
else:
min_rate = 0
return min_rate
if rate_type == "mean":
#Get the mean rate
global second_counter
if second_counter > 0:
#print " Mean rate"
#Method 1
#global predata_sum
#mean_rate = predata_sum/(second_counter+0.0)
#Method 2
# print "L: " + str(prevData[second_counter+1]) + " S: " + str(prevData[0])
# mean_rate = abs(prevData[second_counter+1] - prevData[0])/(second_counter+0.0)
#Method 3
# print " ArrLen: " + str(len(prevData))
# print " SC: " + str(second_counter)
# print " L: " + str(prevData[second_counter])+ " S: " + str(prevData[0])
mean_rate = abs(prevData[second_counter] - prevData[0])/(second_counter+0.0)
#print " MeanR " + str(mean_rate)
return mean_rate
else:
mean_rate = -1
return mean_rate
# Threaded method which calculates the offsets
def calculate_offsets():
#Get individual offsets of a consumer
for c in consumers:
global prev_consumer_info
#prev_consumer_info[c] = {}
topics = ext_client.show_topics_consumed(zk, c)
for t in topics:
#
#
# Consumer Rates
#
#
# Get the offsets for every consumer and correpsonding topic
offset = ext_client.get_consumer_offset(zk, c, t)
#Append count to the array holder
prev_consumer_counts[c].append(offset)
#Get the msg_out_minute_rate for this topic
min_rate = get_rate("minute", prev_consumer_counts[c])
#print "Min: " + str(min_rate)
mean_rate = get_rate("mean", prev_consumer_counts[c])
#print "Mean: " + str(mean_rate)
if mean_rate == -1:
mean_rate = 0
#Update the holder for this topic
global prev_consumer_info
prev_consumer_info[c][t]["count"] = offset
prev_consumer_info[c][t]["min_rate"] = min_rate
prev_consumer_info[c][t]["mean_rate"] = mean_rate
#
#
# Topic rates
#
#
#Get the count for this topic
count = ext_client.get_accumulated_topic_offset(zk, t)
#Update the sum for this topic
topic_sums[t] = topic_sums[t] + count
#Append count to the array holder
prev_topic_counts[t].append(count)
#Get the msg_out_minute_rate for this topic
min_rate = get_rate("minute", prev_topic_counts[t])
mean_rate = get_rate("mean", prev_topic_counts[t])
if mean_rate == -1:
mean_rate = 0
#Update the holder for this topic
global prev_topic_info
prev_topic_info[t]["count"] = count
prev_topic_info[t]["min_rate"] = min_rate
prev_topic_info[t]["mean_rate"] = mean_rate
global second_counter
second_counter = second_counter + 1
#Reset the rate calculations every 24hrs
if second_counter == seconds_in_a_day:
second_counter = 0
threading.Timer(1, calculate_offsets).start()
# Returns the consumer offsets
@app.route('/getconsumerrates')
def get_consumer_offsets():
return json.dumps(prev_consumer_info)
# Returns the accumulated offsets for each topic
@app.route('/getaccumulatedrates')
def get_accumulated_offsets():
return json.dumps(prev_topic_info)
# Takes care of the currently selected node
@app.route('/current_node')
def draw_node():
print "Draw node called"
template = env.get_template('node.html')
return template.render(json_data=json_data)
@app.route('/orgraph')
def or_graph():
template = env.get_template('orgraph.html')
return template.render(json_data=json_data)<|fim▁end|> | ip = socket.gethostbyname(socket.gethostname()) + ""
host = {} |
<|file_name|>bitcoin_mk_MK.ts<|end_file_name|><|fim▁begin|><TS language="mk_MK" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Десен клик за уредување на адреса или етикета</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Креирај нова адреса</translation>
</message>
<message>
<source>&New</source>
<translation>&Нова</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копирај ја избраната адреса на системскиот клипборд</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Копирај</translation>
</message>
<message>
<source>C&lose</source>
<translation>З&атвори</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Избриши ја избраната адреса од листата</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Експортирај ги податоците од активното јазиче во датотека</translation>
</message>
<message>
<source>&Export</source>
<translation>&Експорт</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Избриши</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>Внеси тајна фраза</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Нова тајна фраза</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Повторете ја новата тајна фраза</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Потпиши &порака...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Синхронизација со мрежата...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Преглед</translation>
</message>
<message>
<source>Node</source>
<translation>Јазол</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Трансакции</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Преглед на историјата на трансакции</translation>
</message>
<message>
<source>E&xit</source>
<translation>И&злез</translation>
</message>
<message>
<source>Quit application</source>
<translation>Напушти ја апликацијата</translation>
</message>
<message>
<source>About &Qt</source>
<translation>За &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Прикажи информации за Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Опции...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Криптирање на Паричник...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Бекап на Паричник...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Измени Тајна Фраза...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>&Адреси за Испраќање...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>&Адреси за Примање...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Отвори &URI...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Повторно индексирање на блокови од дискот...</translation>
</message>
<message>
<source>Send coins to a Einsteinium address</source>
<translation>Испрати биткоини на Биткоин адреса</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Потврди порака...</translation>
</message>
<message>
<source>Einsteinium</source>
<translation>Биткоин</translation>
</message>
<message>
<source>Wallet</source>
<translation>Паричник</translation>
</message>
<message>
<source>&Send</source>
<translation>&Испрати</translation>
</message>
<message>
<source>&Receive</source>
<translation>&Прими</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Прикажи / Сокриј</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Криптирај ги приватните клучеви кои припаѓаат на твојот паричник</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Подесувања</translation>
</message>
<message>
<source>&Help</source>
<translation>&Помош</translation>
</message>
<message numerus="yes">
<source>Processed %n block(s) of transaction history.</source>
<translation><numerusform>Обработен %n блок од историјата на трансакции.</numerusform><numerusform>Обработени %n блокови од историјата на трансакции.</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 позади</translation>
</message>
<message>
<source>Error</source>
<translation>Грешка</translation>
</message>
<message>
<source>Warning</source>
<translation>Предупредување</translation>
</message>
<message>
<source>Up to date</source>
<translation>Во тек</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Дата: %1
</translation>
</message>
<message>
<source>Amount: %1
</source>
<translation>Сума: %1
</translation>
</message>
<message>
<source>Type: %1
</source>
<translation>Тип: %1
</translation>
</message>
<message>
<source>Label: %1
</source>
<translation>Етикета: %1
</translation>
</message>
<message>
<source>Address: %1
</source>
<translation>Адреса: %1
</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Bytes:</source>
<translation>Бајти:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Сума:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Провизија:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Прашина:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>После Провизија:</translation>
</message>
<message>
<source>Change:</source>
<translation>Кусур:</translation>
</message>
<message>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Измени Адреса</translation>
</message>
<message>
<source>&Label</source>
<translation>&Етикета</translation>
</message>
<message>
<source>&Address</source>
<translation>&Адреса</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>name</source>
<translation>име</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>верзија</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-бит)</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>Грешка</translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>Отвори URI</translation>
</message>
<message>
<source>URI:</source>
<translation>URI:</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Опции</translation>
</message>
<message>
<source>MB</source>
<translation>МБ</translation>
</message>
<message>
<source>&Network</source>
<translation>&Мрежа</translation>
</message>
<message>
<source>W&allet</source>
<translation>П&аричник</translation>
</message>
<message>
<source>&Window</source>
<translation>&Прозорец</translation>
</message>
<message>
<source>&OK</source>
<translation>&ОК</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Откажи</translation>
</message>
<message>
<source>none</source>
<translation>нема</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Total:</source>
<translation>Вкупно:</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 д</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 ч</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 м</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 с</translation><|fim▁hole|> </message>
<message>
<source>%1 and %2</source>
<translation>%1 и %2</translation>
</message>
</context>
<context>
<name>QObject::QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>Network</source>
<translation>Мрежа</translation>
</message>
<message>
<source>Name</source>
<translation>Име</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Број на конекции</translation>
</message>
<message>
<source>Block chain</source>
<translation>Block chain</translation>
</message>
<message>
<source>Sent</source>
<translation>Испратени</translation>
</message>
<message>
<source>Version</source>
<translation>Верзија</translation>
</message>
<message>
<source>&Console</source>
<translation>&Конзола</translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 Б</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 КБ</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 МБ</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 ГБ</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>&Сума:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Етикета:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Порака:</translation>
</message>
<message>
<source>Show</source>
<translation>Прикажи</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>QR Код</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>Копирај &URI</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>Копирај &Адреса</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>&Сними Слика...</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Bytes:</source>
<translation>Бајти:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Сума:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Провизија:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>После Провизија:</translation>
</message>
<message>
<source>Change:</source>
<translation>Кусур:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Прашина:</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Сума:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Етикета:</translation>
</message>
<message>
<source>Message:</source>
<translation>Порака:</translation>
</message>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
</context>
<context>
<name>TransactionView</name>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Опции:</translation>
</message>
<message>
<source>Einsteinium Core</source>
<translation>Биткоин Core</translation>
</message>
<message>
<source>Warning</source>
<translation>Предупредување</translation>
</message>
<message>
<source>Error</source>
<translation>Грешка</translation>
</message>
</context>
</TS><|fim▁end|> | </message>
<message>
<source>%1 ms</source>
<translation>%1 мс</translation> |
<|file_name|>scheduler.cc<|end_file_name|><|fim▁begin|>// Copyright 2007-2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, 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.
// ========================================================================
#include "omaha/core/scheduler.h"
#include "omaha/base/debug.h"
#include "omaha/base/error.h"
#include "omaha/base/logging.h"
namespace omaha {
Scheduler::SchedulerItem::SchedulerItem(HANDLE timer_queue,
int start_delay_ms,
int interval_ms,
bool has_debug_timer,
ScheduledWorkWithTimer work)
: start_delay_ms_(start_delay_ms), interval_ms_(interval_ms), work_(work) {
if (has_debug_timer) {
debug_timer_.reset(new HighresTimer());
}
if (timer_queue) {
timer_.reset(
new QueueTimer(timer_queue, &SchedulerItem::TimerCallback, this));
VERIFY_SUCCEEDED(
ScheduleNext(timer_.get(), debug_timer_.get(), start_delay_ms));
}
}
Scheduler::SchedulerItem::~SchedulerItem() {
// QueueTimer dtor may block for pending callbacks.
if (timer_) {
timer_.reset();
}
if (debug_timer_) {
debug_timer_.reset();
}
}
// static
HRESULT Scheduler::SchedulerItem::ScheduleNext(QueueTimer* timer,
HighresTimer* debug_timer,
int start_after_ms) {
if (!timer) {
return E_FAIL;
}
if (debug_timer) {
debug_timer->Start();
}
const HRESULT hr = timer->Start(start_after_ms, 0, WT_EXECUTEONLYONCE);
if (FAILED(hr)) {
CORE_LOG(LE, (L"[can't start queue timer][0x%08x]", hr));
}
return hr;
}
// static
void Scheduler::SchedulerItem::TimerCallback(QueueTimer* timer) {
ASSERT1(timer);
if (!timer) {
return;
}
SchedulerItem* item = reinterpret_cast<SchedulerItem*>(timer->ctx());
ASSERT1(item);
if (!item) {
CORE_LOG(LE, (L"[Expected timer context to contain SchedulerItem]"));
return;
}
// This may be long running, |item| may be deleted in the meantime,<|fim▁hole|> // however the dtor should block on deleting the |timer| and allow
// pending callbacks to run.
if (item && item->work_) {
item->work_(item->debug_timer());
}
if (item) {
const HRESULT hr = SchedulerItem::ScheduleNext(timer,
item->debug_timer(),
item->interval_ms());
if (FAILED(hr)) {
CORE_LOG(L1, (L"[Scheduling next timer callback failed][0x%08x]", hr));
}
}
}
Scheduler::Scheduler() {
CORE_LOG(L1, (L"[Scheduler::Scheduler]"));
timer_queue_ = ::CreateTimerQueue();
if (!timer_queue_) {
CORE_LOG(LE, (L"[Failed to create Timer Queue][%d]", ::GetLastError()));
}
}
Scheduler::~Scheduler() {
CORE_LOG(L1, (L"[Scheduler::~Scheduler]"));
timers_.clear();
if (timer_queue_) {
// The destructor blocks on deleting the timer queue and it waits for
// all timer callbacks to complete.
::DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE);
timer_queue_ = NULL;
}
}
HRESULT Scheduler::StartWithDebugTimer(int interval,
ScheduledWorkWithTimer work) const {
return DoStart(interval, interval, work, true /*has_debug_timer*/);
}
HRESULT Scheduler::StartWithDelay(int delay,
int interval,
ScheduledWork work) const {
return DoStart(delay, interval, std::bind(work));
}
HRESULT Scheduler::Start(int interval, ScheduledWork work) const {
return DoStart(interval, interval, std::bind(work));
}
HRESULT Scheduler::DoStart(int start_delay,
int interval,
ScheduledWorkWithTimer work_fn,
bool has_debug_timer) const {
CORE_LOG(L1, (L"[Scheduler::Start]"));
if (!timer_queue_) {
return HRESULTFromLastError();
}
timers_.emplace_back(timer_queue_, start_delay, interval, has_debug_timer,
work_fn);
return S_OK;
}
} // namespace omaha<|fim▁end|> | |
<|file_name|>bitcoin_tr.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="tr" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About FlorijnCoin</source>
<translation>FlorijnCoin hakkında</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="53"/>
<source><b>FlorijnCoin</b> version</source>
<translation><b>FlorijnCoin</b> sürüm</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="97"/>
<source>Copyright © 2009-2012 FlorijnCoin 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>Telif hakkı © 2009-2012 FlorijnCoin geliştiricileri
Bu yazılım deneme safhasındadır.
MIT/X11 yazılım lisansı kapsamında yayınlanmıştır, license.txt dosyasına ya da http://www.opensource.org/licenses/mit-license.php sayfasına bakınız.
Bu ürün OpenSSL projesi tarafından OpenSSL araç takımı (http://www.openssl.org/) için geliştirilen yazılımlar, Eric Young ([email protected]) tarafından yazılmış şifreleme yazılımları ve Thomas Bernard tarafından programlanmış UPnP yazılımı içerir.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>Adres defteri</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your FlorijnCoin 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>Bunlar, ödemeleri almak için FlorijnCoin adresleridir. Kimin ödeme yaptığını izleyebilmek için her ödeme yollaması gereken kişiye değişik bir adres verebilirsiniz.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="36"/>
<source>Double-click to edit address or label</source>
<translation>Adresi ya da etiketi düzenlemek için çift tıklayınız</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="63"/>
<source>Create a new address</source>
<translation>Yeni bir adres oluştur</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="77"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Şu anda seçili olan adresi panoya kopyalar</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="66"/>
<source>&New Address</source>
<translation>&Yeni adres</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="80"/>
<source>&Copy Address</source>
<translation>Adresi &kopyala</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="91"/>
<source>Show &QR Code</source>
<translation>&QR kodunu göster</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="102"/>
<source>Sign a message to prove you own this address</source>
<translation>Bu adresin sizin olduğunu ispatlamak için mesaj imzalayın</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="105"/>
<source>&Sign Message</source>
<translation>Mesaj &imzala</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="116"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Seçilen adresi listeden siler. Sadece gönderi adresleri silinebilir.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="119"/>
<source>&Delete</source>
<translation>&Sil</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="63"/>
<source>Copy &Label</source>
<translation>&Etiketi kopyala</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="65"/>
<source>&Edit</source>
<translation>&Düzenle</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="292"/>
<source>Export Address Book Data</source>
<translation>Adres defteri verilerini dışa aktar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="293"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="306"/>
<source>Error exporting</source>
<translation>Dışa aktarımda hata oluştu</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="306"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="142"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="142"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="178"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Passphrase Dialog</source>
<translation>Parola diyaloğu</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="47"/>
<source>Enter passphrase</source>
<translation>Parolayı giriniz</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="61"/>
<source>New passphrase</source>
<translation>Yeni parola</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="75"/>
<source>Repeat new passphrase</source>
<translation>Yeni parolayı tekrarlayınız</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Cüzdanınız için yeni parolayı giriniz.<br/>Lütfen <b>10 ya da daha fazla rastgele karakter</b> veya <b>sekiz ya da daha fazla kelime</b> içeren bir parola seçiniz.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="34"/>
<source>Encrypt wallet</source>
<translation>Cüzdanı şifrele</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="37"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Bu işlem cüzdan kilidini açmak için cüzdan parolanızı gerektirir.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="42"/>
<source>Unlock wallet</source>
<translation>Cüzdan kilidini aç</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="45"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Bu işlem, cüzdan şifresini açmak için cüzdan parolasını gerektirir.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="50"/>
<source>Decrypt wallet</source>
<translation>Cüzdan şifresini aç</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="53"/>
<source>Change passphrase</source>
<translation>Parolayı değiştir</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Cüzdan için eski ve yeni parolaları giriniz.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="100"/>
<source>Confirm wallet encryption</source>
<translation>Cüzdan şifrelenmesini teyit eder</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="101"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation>UYARI: Eğer cüzdanınızı şifrelerseniz ve parolanızı kaybederseniz, <b>TÜM BİTCOİNLERİNİZİ KAYBEDERSİNİZ</b>!
Cüzdanınızı şifrelemek istediğinizden emin misiniz?</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="110"/>
<location filename="../askpassphrasedialog.cpp" line="159"/>
<source>Wallet encrypted</source>
<translation>Cüzdan şifrelendi</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="111"/>
<source>FlorijnCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Şifreleme işlemini tamamlamak için FlorijnCoin şimdi kapanacaktır. Cüzdanınızı şifrelemenin, FlorijnCoinlerinizin bilgisayara bulaşan kötücül bir yazılım tarafından çalınmaya karşı tamamen koruyamayacağını unutmayınız.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="207"/>
<location filename="../askpassphrasedialog.cpp" line="231"/>
<source>Warning: The Caps Lock key is on.</source>
<translation>Uyarı: Caps Lock tuşu etkin durumda.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="116"/>
<location filename="../askpassphrasedialog.cpp" line="123"/>
<location filename="../askpassphrasedialog.cpp" line="165"/>
<location filename="../askpassphrasedialog.cpp" line="171"/>
<source>Wallet encryption failed</source>
<translation>Cüzdan şifrelemesi başarısız oldu</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dahili bir hata sebebiyle cüzdan şifrelemesi başarısız oldu. Cüzdanınız şifrelenmedi.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="124"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>The supplied passphrases do not match.</source>
<translation>Girilen parolalar birbirleriyle uyumlu değil.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="135"/>
<source>Wallet unlock failed</source>
<translation>Cüzdan kilidinin açılması başarısız oldu</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="136"/>
<location filename="../askpassphrasedialog.cpp" line="147"/>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Cüzdan şifresinin açılması için girilen parola yanlıştı.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="146"/>
<source>Wallet decryption failed</source>
<translation>Cüzdan şifresinin açılması başarısız oldu</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="160"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Cüzdan parolası başarılı bir şekilde değiştirildi.</translation>
</message>
</context>
<context>
<name>FlorijnCoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="73"/>
<source>FlorijnCoin Wallet</source>
<translation>FlorijnCoin cüzdanı</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="215"/>
<source>Sign &message...</source>
<translation>&Mesaj imzala...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="248"/>
<source>Show/Hide &FlorijnCoin</source>
<translation>&FlorijnCoin'i Göster/Sakla</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="515"/>
<source>Synchronizing with network...</source>
<translation>Şebeke ile senkronizasyon...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="185"/>
<source>&Overview</source>
<translation>&Genel bakış</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="186"/>
<source>Show general overview of wallet</source>
<translation>Cüzdana genel bakışı gösterir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="191"/>
<source>&Transactions</source>
<translation>&Muameleler</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="192"/>
<source>Browse transaction history</source>
<translation>Muamele tarihçesini tara</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="197"/>
<source>&Address Book</source>
<translation>&Adres defteri</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="198"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Saklanan adres ve etiket listesini düzenler</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="203"/>
<source>&Receive coins</source>
<translation>FlorijnCoin &al</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="204"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Ödeme alma adreslerinin listesini gösterir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="209"/>
<source>&Send coins</source>
<translation>FlorijnCoin &yolla</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="216"/>
<source>Prove you control an address</source>
<translation>Bu adresin kontrolünüz altında olduğunu ispatlayın</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="235"/>
<source>E&xit</source>
<translation>&Çık</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="236"/>
<source>Quit application</source>
<translation>Uygulamadan çıkar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="239"/>
<source>&About %1</source>
<translation>%1 &hakkında</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="240"/>
<source>Show information about FlorijnCoin</source>
<translation>FlorijnCoin hakkında bilgi gösterir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="242"/>
<source>About &Qt</source>
<translation>&Qt hakkında</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="243"/>
<source>Show information about Qt</source>
<translation>Qt hakkında bilgi görüntüler</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="245"/>
<source>&Options...</source>
<translation>&Seçenekler...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="252"/>
<source>&Encrypt Wallet...</source>
<translation>Cüzdanı &şifrele...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="255"/>
<source>&Backup Wallet...</source>
<translation>Cüzdanı &yedekle...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="257"/>
<source>&Change Passphrase...</source>
<translation>Parolayı &değiştir...</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="517"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>~%n blok kaldı</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="528"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Muamele tarihçesinden %1 blok indirildi (toplam %2 blok, %%3 tamamlandı).</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="250"/>
<source>&Export...</source>
<translation>&Dışa aktar...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="210"/>
<source>Send coins to a FlorijnCoin address</source>
<translation>Bir FlorijnCoin adresine FlorijnCoin yollar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="246"/>
<source>Modify configuration options for FlorijnCoin</source>
<translation>FlorijnCoin seçeneklerinin yapılandırmasını değiştirir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>Show or hide the FlorijnCoin window</source>
<translation>FlorijnCoin penceresini göster ya da sakla</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="251"/>
<source>Export the data in the current tab to a file</source>
<translation>Güncel sekmedeki verileri bir dosyaya aktar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="253"/>
<source>Encrypt or decrypt wallet</source>
<translation>Cüzdanı şifreler ya da şifreyi açar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="256"/>
<source>Backup wallet to another location</source>
<translation>Cüzdanı diğer bir konumda yedekle</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="258"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cüzdan şifrelemesi için kullanılan parolayı değiştirir</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="259"/>
<source>&Debug window</source>
<translation>&Hata ayıklama penceresi</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="260"/>
<source>Open debugging and diagnostic console</source>
<translation>Hata ayıklama ve teşhis penceresini aç</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="261"/>
<source>&Verify message...</source>
<translation>&Mesaj kontrol et...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="262"/>
<source>Verify a message signature</source>
<translation>Mesaj imzasını kontrol et</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="286"/>
<source>&File</source>
<translation>&Dosya</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="296"/>
<source>&Settings</source>
<translation>&Ayarlar</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="302"/>
<source>&Help</source>
<translation>&Yardım</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="311"/>
<source>Tabs toolbar</source>
<translation>Sekme araç çubuğu</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="322"/>
<source>Actions toolbar</source>
<translation>Faaliyet araç çubuğu</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="334"/>
<location filename="../bitcoingui.cpp" line="343"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="343"/>
<location filename="../bitcoingui.cpp" line="399"/>
<source>FlorijnCoin client</source>
<translation>FlorijnCoin istemcisi</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="492"/>
<source>%n active connection(s) to FlorijnCoin network</source>
<translation><numerusform>FlorijnCoin şebekesine %n etkin bağlantı</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="540"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Muamele tarihçesinin %1 adet bloku indirildi.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="555"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n saniye önce</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="559"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n dakika önce</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="563"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n saat önce</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="567"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n gün önce</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="573"/>
<source>Up to date</source>
<translation>Güncel</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="580"/>
<source>Catching up...</source>
<translation>Aralık kapatılıyor...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="590"/>
<source>Last received block was generated %1.</source>
<translation>Son alınan blok şu vakit oluşturulmuştu: %1.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="649"/>
<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>Bu muamele boyut sınırlarını aşmıştır. Gene de %1 ücret ödeyerek gönderebilirsiniz, ki bu ücret muamelenizi işleyen ve şebekeye yardım eden düğümlere ödenecektir. Ücreti ödemek istiyor musunuz?</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="654"/>
<source>Confirm transaction fee</source>
<translation>Muamele ücretini teyit et</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="681"/>
<source>Sent transaction</source>
<translation>Muamele yollandı</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="682"/>
<source>Incoming transaction</source>
<translation>Gelen muamele</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="683"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tarih: %1
Miktar: %2
Tür: %3
Adres: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="804"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilidi açılmıştır</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="812"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilitlidir</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="835"/>
<source>Backup Wallet</source>
<translation>Cüzdanı yedekle</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="835"/>
<source>Wallet Data (*.dat)</source>
<translation>Cüzdan verileri (*.dat)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="838"/>
<source>Backup Failed</source>
<translation>Yedekleme başarısız oldu</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="838"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Cüzdan verilerinin başka bir konumda kaydedilmesi sırasında bir hata meydana geldi.</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="112"/>
<source>A fatal error occured. FlorijnCoin can no longer continue safely and will quit.</source>
<translation>Ciddi bir hata oluştu. Artık FlorijnCoin güvenli bir şekilde işlemeye devam edemez ve kapanacaktır.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="84"/>
<source>Network Alert</source>
<translation>Şebeke hakkında uyarı</translation>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="246"/>
<source>Display</source>
<translation>Görünüm</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="257"/>
<source>default</source>
<translation>varsayılan</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="263"/>
<source>The user interface language can be set here. This setting will only take effect after restarting FlorijnCoin.</source>
<translation>Kullanıcı arayüzünün dili burada belirtilebilir. Bu ayar FlorijnCoin tekrar başlatıldığında etkinleşecektir.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="252"/>
<source>User Interface &Language:</source>
<translation>Kullanıcı arayüzü &lisanı:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="273"/>
<source>&Unit to show amounts in:</source>
<translation>Miktarı göstermek için &birim: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="277"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>FlorijnCoin gönderildiğinde arayüzde gösterilecek varsayılan alt birimi seçiniz</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="284"/>
<source>&Display addresses in transaction list</source>
<translation>Muamele listesinde adresleri &göster</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="285"/>
<source>Whether to show FlorijnCoin addresses in the transaction list</source>
<translation>Muamele listesinde FlorijnCoin adreslerinin gösterilip gösterilmeyeceklerini belirler</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="303"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="303"/>
<source>This setting will take effect after restarting FlorijnCoin.</source>
<translation>Bu ayarlar FlorijnCoin tekrar başlatıldığında etkinleşecektir.</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="14"/>
<source>Edit Address</source>
<translation>Adresi düzenle</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>Bu adres defteri unsuru ile ilişkili etiket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Adres</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>Bu adres defteri unsuru ile ilişkili adres. Bu, sadece gönderi adresi için değiştirilebilir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>Yeni alım adresi</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Yeni gönderi adresi</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Alım adresini düzenle</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Gönderi adresini düzenle</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Girilen "%1" adresi hâlihazırda adres defterinde mevcuttur.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid FlorijnCoin address.</source>
<translation>Girilen "%1" adresi geçerli bir FlorijnCoin adresi değildir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>Cüzdan kilidi açılamadı.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>Yeni anahtar oluşturulması başarısız oldu.</translation>
</message>
</context>
<context>
<name>HelpMessageBox</name>
<message>
<location filename="../bitcoin.cpp" line="133"/>
<location filename="../bitcoin.cpp" line="143"/>
<source>FlorijnCoin-Qt</source>
<translation>FlorijnCoin-Qt</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="133"/>
<source>version</source>
<translation>sürüm</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="135"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="136"/>
<source>options</source>
<translation>seçenekler</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="138"/>
<source>UI options</source>
<translation>Kullanıcı arayüzü seçenekleri</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="139"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Lisan belirt, mesela "de_De" (varsayılan: sistem dili)</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="140"/>
<source>Start minimized</source>
<translation>Küçültülmüş olarak başla</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="141"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Başlatıldığında başlangıç ekranını göster (varsayılan: 1)</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="227"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>Çıkışta blok ve adres veri tabanlarını ayırır. Bu, kapanışı yavaşlatır ancak veri tabanlarının başka klasörlere taşınabilmelerine imkân sağlar. Cüzdan daima ayırılır.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="212"/>
<source>Pay transaction &fee</source>
<translation>Muamele ücreti &öde</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="204"/>
<source>Main</source>
<translation>Ana menü</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="206"/>
<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>Muamelelerin hızlı işlenmesini garantilemeye yardım eden, seçime dayalı kB başı muamele ücreti. Muamelelerin çoğunluğunun boyutu 1 kB'dir. 0.01 ücreti önerilir. </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="222"/>
<source>&Start FlorijnCoin on system login</source>
<translation>FlorijnCoin'i sistem oturumuyla &başlat</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Automatically start FlorijnCoin after logging in to the system</source>
<translation>Sistemde oturum açıldığında FlorijnCoin'i otomatik olarak başlat</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="226"/>
<source>&Detach databases at shutdown</source>
<translation>Kapanışta veritabanlarını &ayır</translation>
</message>
</context>
<context>
<name>MessagePage</name>
<message>
<location filename="../forms/messagepage.ui" line="14"/>
<source>Sign Message</source>
<translation>Mesaj imzala</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>Bir adresin sizin olduğunu ispatlamak için adresinizle mesaj imzalayabilirsiniz. Oltalama saldırılarının kimliğinizi imzanızla elde etmeyi deneyebilecekleri için belirsiz hiçbir şey imzalamamaya dikkat ediniz. Sadece ayrıntılı açıklaması olan ve tümüne katıldığınız ifadeleri imzalayın.</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="38"/>
<source>The address to sign the message with (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>Mesajı imzalamak için kullanılacak adres (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="48"/>
<source>Choose adress from address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="58"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="71"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="81"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="93"/>
<source>Enter the message you want to sign here</source>
<translation>İmzalamak istediğiniz mesajı burada giriniz</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="128"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Güncel imzayı sistem panosuna kopyala</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="131"/>
<source>&Copy Signature</source>
<translation>İmzayı &kopyala</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="142"/>
<source>Reset all sign message fields</source>
<translation>Tüm mesaj alanlarını sıfırla</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="145"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="31"/>
<source>Click "Sign Message" to get signature</source>
<translation>İmza elde etmek için "Mesaj İmzala" unsurunu tıklayın</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="114"/>
<source>Sign a message to prove you own this address</source>
<translation>Bu adresin sizin olduğunu ispatlamak için bir mesaj imzalayın</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="117"/>
<source>&Sign Message</source>
<translation>Mesaj &İmzala</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="30"/>
<source>Enter a FlorijnCoin address (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>FlorijnCoin adresi giriniz (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="83"/>
<location filename="../messagepage.cpp" line="90"/>
<location filename="../messagepage.cpp" line="105"/>
<location filename="../messagepage.cpp" line="117"/>
<source>Error signing</source>
<translation>İmza sırasında hata meydana geldi</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="83"/>
<source>%1 is not a valid address.</source>
<translation>%1 geçerli bir adres değildir.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="90"/>
<source>%1 does not refer to a key.</source>
<translation>%1 herhangi bir anahtara işaret etmemektedir.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="105"/>
<source>Private key for %1 is not available.</source>
<translation>%1 için özel anahtar mevcut değil.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="117"/>
<source>Sign failed</source>
<translation>İmzalama başarısız oldu</translation>
</message>
</context>
<context>
<name>NetworkOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="345"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="347"/>
<source>Map port using &UPnP</source>
<translation>Portları &UPnP kullanarak haritala</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="348"/>
<source>Automatically open the FlorijnCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Yönlendiricide FlorijnCoin istemci portlarını otomatik olarak açar. Bu, sadece yönlendiricinizin UPnP desteği bulunuyorsa ve etkinse çalışabilir.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="351"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>SOCKS4 vekil sunucusu vasıtasıyla ba&ğlan:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="352"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>FlorijnCoin şebekesine SOCKS4 vekil sunucusu vasıtasıyla bağlanır (mesela Tor ile bağlanıldığında)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="357"/>
<source>Proxy &IP:</source>
<translation>Vekil &İP:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="366"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="363"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Vekil sunucunun İP adresi (mesela 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="372"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Vekil sunucun portu (örneğin 1234)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="135"/>
<source>Options</source>
<translation>Seçenekler</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="47"/>
<location filename="../forms/overviewpage.ui" line="204"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the FlorijnCoin network after a connection is established, but this process has not completed yet.</source>
<translation>Görüntülenen veriler zaman aşımını uğramış olabilir. Bağlantı kurulduğunda cüzdanınız otomatik olarak şebeke ile eşleşir ancak bu işlem henüz tamamlanmamıştır.</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="89"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="147"/>
<source>Number of transactions:</source>
<translation>Muamele sayısı:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="118"/>
<source>Unconfirmed:</source>
<translation>Doğrulanmamış:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="197"/>
<source><b>Recent transactions</b></source>
<translation><b>Son muameleler</b></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="105"/>
<source>Your current balance</source>
<translation>Güncel bakiyeniz</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="134"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Doğrulanması beklenen ve henüz güncel bakiyeye ilâve edilmemiş muamelelerin toplamı</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="154"/>
<source>Total number of transactions in wallet</source>
<translation>Cüzdandaki muamelelerin toplam sayısı</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="110"/>
<location filename="../overviewpage.cpp" line="111"/>
<source>out of sync</source>
<translation>eşleşme dışı</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>QR Code Dialog</source>
<translation>QR kodu diyaloğu</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation>QR Kodu</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="55"/>
<source>Request Payment</source>
<translation>Ödeme isteği</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="70"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="105"/>
<source>BTC</source>
<translation>BTC</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="121"/>
<source>Label:</source>
<translation>Etiket:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="144"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="186"/>
<source>&Save As...</source>
<translation>&Farklı kaydet...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="45"/>
<source>Error encoding URI into QR Code.</source>
<translation>URI'nin QR koduna kodlanmasında hata oluştu.</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="63"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Sonuç URI çok uzun, etiket ya da mesaj metnini kısaltmayı deneyiniz.</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="120"/>
<source>Save QR Code</source>
<translation>QR kodu kaydet</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="120"/>
<source>PNG Images (*.png)</source>
<translation>PNG resimleri (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="14"/>
<source>FlorijnCoin debug window</source>
<translation>FlorijnCoin hata ayıklama penceresi</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="46"/>
<source>Client name</source>
<translation>İstemci ismi</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="56"/>
<location filename="../forms/rpcconsole.ui" line="79"/>
<location filename="../forms/rpcconsole.ui" line="102"/>
<location filename="../forms/rpcconsole.ui" line="125"/>
<location filename="../forms/rpcconsole.ui" line="161"/>
<location filename="../forms/rpcconsole.ui" line="214"/>
<location filename="../forms/rpcconsole.ui" line="237"/>
<location filename="../forms/rpcconsole.ui" line="260"/>
<location filename="../rpcconsole.cpp" line="245"/>
<source>N/A</source>
<translation>Mevcut değil</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="69"/>
<source>Client version</source>
<translation>İstemci sürümü</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="24"/>
<source>&Information</source>
<translation>&Malumat</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="39"/>
<source>Client</source>
<translation>İstemci</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="115"/>
<source>Startup time</source>
<translation>Başlama zamanı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="144"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="151"/>
<source>Number of connections</source>
<translation>Bağlantı sayısı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="174"/>
<source>On testnet</source>
<translation>Testnet üzerinde</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="197"/>
<source>Block chain</source>
<translation>Blok zinciri</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="204"/>
<source>Current number of blocks</source>
<translation>Güncel blok sayısı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="227"/>
<source>Estimated total blocks</source>
<translation>Tahmini toplam blok sayısı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="250"/>
<source>Last block time</source>
<translation>Son blok zamanı</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="292"/>
<source>Debug logfile</source>
<translation>Hata ayıklama kütük dosyası</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="299"/>
<source>Open the FlorijnCoin debug logfile from the current data directory. This can take a few seconds for large logfiles.</source>
<translation>Güncel veri klasöründen FlorijnCoin hata ayıklama kütüğünü aç. Büyük kütük dosyaları için bu birkaç saniye alabilir.</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="302"/>
<source>&Open</source>
<translation>&Aç</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="323"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="92"/>
<source>Build date</source>
<translation>Derleme tarihi</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="372"/>
<source>Clear console</source>
<translation>Konsolu temizle</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="212"/>
<source>Welcome to the FlorijnCoin RPC console.</source>
<translation>FlorijnCoin RPC konsoluna hoş geldiniz.</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="213"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Tarihçede gezinmek için imleç tuşlarını kullanınız, <b>Ctrl-L</b> ile de ekranı temizleyebilirsiniz.</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="214"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Mevcut komutların listesi için <b>help</b> yazınız.</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>FlorijnCoin yolla</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="64"/>
<source>Send to multiple recipients at once</source>
<translation>Birçok alıcıya aynı anda gönder</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="67"/>
<source>&Add Recipient</source>
<translation>Alıcı &ekle</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="84"/>
<source>Remove all transaction fields</source>
<translation>Bütün muamele alanlarını kaldır</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="87"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="106"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="113"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="144"/>
<source>Confirm the send action</source>
<translation>Yollama etkinliğini teyit ediniz</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="147"/>
<source>&Send</source>
<translation>&Gönder</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="94"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> şu adrese: %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="99"/>
<source>Confirm send coins</source>
<translation>Gönderiyi teyit ediniz</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source>Are you sure you want to send %1?</source>
<translation>%1 göndermek istediğinizden emin misiniz?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source> and </source>
<translation> ve </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="123"/>
<source>The recepient address is not valid, please recheck.</source>
<translation>Alıcı adresi geçerli değildir, lütfen denetleyiniz.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="128"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Ödeyeceğiniz tutarın sıfırdan yüksek olması gerekir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="133"/>
<source>The amount exceeds your balance.</source>
<translation>Tutar bakiyenizden yüksektir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="138"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Toplam, %1 muamele ücreti ilâve edildiğinde bakiyenizi geçmektedir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="144"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Çift adres bulundu, belli bir gönderi sırasında her adrese sadece tek bir gönderide bulunulabilir.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="149"/>
<source>Error: Transaction creation failed.</source>
<translation>Hata: Muamele oluşturması başarısız oldu.</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>Hata: Muamele reddedildi. Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>M&iktar:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>&Şu kişiye öde:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Adres defterinize eklemek için bu adrese ilişik bir etiket giriniz</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>Ödemenin gönderileceği adres (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Bu alıcıyı kaldır</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a FlorijnCoin address (e.g. FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</source>
<translation>FlorijnCoin adresi giriniz (mesela FY36Zmi14ZU4XyfYmMdoV9i8cN1po3qyr9)</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="21"/>
<source>Open for %1 blocks</source>
<translation>%1 blok için açık</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="23"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="29"/>
<source>%1/offline?</source>
<translation>%1/çevrimdışı mı?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="31"/>
<source>%1/unconfirmed</source>
<translation>%1/doğrulanmadı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="33"/>
<source>%1 confirmations</source>
<translation>%1 teyit</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="51"/>
<source><b>Status:</b> </source>
<translation><b>Durum:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, has not been successfully broadcast yet</source>
<translation>, henüz başarılı bir şekilde yayınlanmadı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="58"/>
<source>, broadcast through %1 node</source>
<translation>, %1 düğüm vasıtasıyla yayınlandı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source>, broadcast through %1 nodes</source>
<translation>, %1 düğüm vasıtasıyla yayınlandı</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="64"/>
<source><b>Date:</b> </source>
<translation><b>Tarih:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="71"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Kaynak:</b> Oluşturuldu<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="77"/>
<location filename="../transactiondesc.cpp" line="94"/>
<source><b>From:</b> </source>
<translation><b>Gönderen:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source>unknown</source>
<translation>bilinmiyor</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="95"/>
<location filename="../transactiondesc.cpp" line="118"/>
<location filename="../transactiondesc.cpp" line="178"/>
<source><b>To:</b> </source>
<translation><b>Alıcı:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="98"/>
<source> (yours, label: </source>
<translation> (sizin, etiket: </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="100"/>
<source> (yours)</source>
<translation> (sizin)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="136"/>
<location filename="../transactiondesc.cpp" line="150"/>
<location filename="../transactiondesc.cpp" line="195"/>
<location filename="../transactiondesc.cpp" line="212"/>
<source><b>Credit:</b> </source>
<translation><b>Gelir:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="138"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1, %2 ek blok sonrasında olgunlaşacak)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="142"/>
<source>(not accepted)</source>
<translation>(kabul edilmedi)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="186"/>
<location filename="../transactiondesc.cpp" line="194"/>
<location filename="../transactiondesc.cpp" line="209"/>
<source><b>Debit:</b> </source>
<translation><b>Gider:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="200"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Muamele ücreti:<b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="216"/>
<source><b>Net amount:</b> </source>
<translation><b>Net miktar:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="222"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="224"/>
<source>Comment:</source>
<translation>Yorum:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="226"/>
<source>Transaction ID:</source>
<translation>Muamele kimliği:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="229"/>
<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 "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Oluşturulan FlorijnCoin'lerin harcanabilmelerinden önce 120 blok beklemeleri gerekmektedir. Bu blok, oluşturduğunuzda, blok zincirine eklenmesi için ağda yayınlandı. Zincire eklenmesi başarısız olursa, "kabul edilmedi" olarak değiştirilecek ve harcanamayacaktır. Bu, bazen başka bir düğüm sizden birkaç saniye önce ya da sonra blok oluşturursa meydana gelebilir.</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>Muamele detayları</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Bu pano muamelenin ayrıntılı açıklamasını gösterir</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="281"/>
<source>Open for %n block(s)</source>
<translation><numerusform>%n blok için açık</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="284"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="287"/>
<source>Offline (%1 confirmations)</source>
<translation>Çevrimdışı (%1 teyit)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="290"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Doğrulanmadı (%1 (toplam %2 üzerinden) teyit)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="293"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Doğrulandı (%1 teyit)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>Mined balance will be available in %n more blocks</source>
<translation><numerusform>Madenden çıkarılan bakiye %n ek blok sonrasında kullanılabilecektir</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="307"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Bu blok başka hiçbir düğüm tarafından alınmamıştır ve muhtemelen kabul edilmeyecektir!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="310"/>
<source>Generated but not accepted</source>
<translation>Oluşturuldu ama kabul edilmedi</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="353"/>
<source>Received with</source>
<translation>Şununla alındı</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="355"/>
<source>Received from</source>
<translation>Alındığı kişi</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="358"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="360"/>
<source>Payment to yourself</source>
<translation>Kendinize ödeme</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="362"/>
<source>Mined</source>
<translation>Madenden çıkarılan</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="400"/>
<source>(n/a)</source>
<translation>(mevcut değil)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="599"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Muamele durumu. Doğrulama sayısını görüntülemek için imleci bu alanda tutunuz.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="601"/>
<source>Date and time that the transaction was received.</source>
<translation>Muamelenin alındığı tarih ve zaman.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="603"/>
<source>Type of transaction.</source>
<translation>Muamele türü.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="605"/>
<source>Destination address of transaction.</source>
<translation>Muamelenin alıcı adresi.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="607"/>
<source>Amount removed from or added to balance.</source>
<translation>Bakiyeden alınan ya da bakiyeye eklenen miktar.</translation>
</message>
</context>
<context>
<name>TransactionView</name><|fim▁hole|> <message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Hepsi</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>Bugün</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>Bu hafta</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>Bu ay</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>Geçen ay</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>Bu sene</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Aralık...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Şununla alınan</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>Kendinize</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Oluşturulan</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Other</source>
<translation>Diğer</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="85"/>
<source>Enter address or label to search</source>
<translation>Aranacak adres ya da etiket giriniz</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="92"/>
<source>Min amount</source>
<translation>Asgari miktar</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Copy amount</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="129"/>
<source>Edit label</source>
<translation>Etiketi düzenle</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="130"/>
<source>Show transaction details</source>
<translation>Muamele detaylarını göster</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="270"/>
<source>Export Transaction Data</source>
<translation>Muamele verilerini dışa aktar</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="271"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="279"/>
<source>Confirmed</source>
<translation>Doğrulandı</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="280"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="284"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="285"/>
<source>ID</source>
<translation>Kimlik</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="289"/>
<source>Error exporting</source>
<translation>Dışa aktarımda hata oluştu</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="289"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="384"/>
<source>Range:</source>
<translation>Aralık:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="392"/>
<source>to</source>
<translation>ilâ</translation>
</message>
</context>
<context>
<name>VerifyMessageDialog</name>
<message>
<location filename="../forms/verifymessagedialog.ui" line="14"/>
<source>Verify Signed Message</source>
<translation>İmzalı mesajı kontrol et</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="20"/>
<source>Enter the message and signature below (be careful to correctly copy newlines, spaces, tabs and other invisible characters) to obtain the FlorijnCoin address used to sign the message.</source>
<translation>Mesajı imzalamak için kullanılan FlorijnCoin adresini elde etmek için mesaj ve imzayı aşağıda giriniz (yani satırlar, boşluklar ve sekmeler gibi görünmeyen karakterleri doğru şekilde kopyalamaya dikkat ediniz).</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="62"/>
<source>Verify a message and obtain the FlorijnCoin address used to sign the message</source>
<translation>Mesajı kontrol et ve imzalamak için kullanılan FlorijnCoin adresini elde et</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="65"/>
<source>&Verify Message</source>
<translation>Mesajı &kontrol et</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="79"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Şu anda seçili olan adresi panoya kopyalar</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="82"/>
<source>&Copy Address</source>
<translation>Adresi &kopyala</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="93"/>
<source>Reset all verify message fields</source>
<translation>Tüm mesaj kontrolü alanlarını sıfırla</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="96"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="28"/>
<source>Enter FlorijnCoin signature</source>
<translation>FlorijnCoin imzası gir</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="29"/>
<source>Click "Verify Message" to obtain address</source>
<translation>Adresi elde etmek için "Mesajı kontrol et" düğmesini tıkayınız</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="55"/>
<location filename="../verifymessagedialog.cpp" line="62"/>
<source>Invalid Signature</source>
<translation>Geçersiz imza</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="55"/>
<source>The signature could not be decoded. Please check the signature and try again.</source>
<translation>İmzanın kodu çözülemedi. İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="62"/>
<source>The signature did not match the message digest. Please check the signature and try again.</source>
<translation>İmza mesajın hash değeri eşleşmedi. İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="72"/>
<source>Address not found in address book.</source>
<translation>Bu adres, adres defterinde bulunamadı.</translation>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="72"/>
<source>Address found in address book: %1</source>
<translation>Adres defterinde bu adres bulundu: %1</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="158"/>
<source>Sending...</source>
<translation>Gönderiliyor...</translation>
</message>
</context>
<context>
<name>WindowOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="313"/>
<source>Window</source>
<translation>Pencere</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="316"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>İşlem çubuğu yerine sistem çekmecesine &küçült</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="317"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Küçültüldükten sonra sadece çekmece ikonu gösterir</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="320"/>
<source>M&inimize on close</source>
<translation>Kapatma sırasında k&üçült</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="321"/>
<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>Pencere kapatıldığında uygulamadan çıkmak yerine uygulamayı küçültür. Bu seçenek etkinleştirildiğinde, uygulama sadece menüden çıkış seçildiğinde kapanacaktır.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>FlorijnCoin version</source>
<translation>FlorijnCoin sürümü</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Send command to -server or bitcoind</source>
<translation>-server ya da bitcoind'ye komut gönder</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<source>List commands</source>
<translation>Komutları listele</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>Get help for a command</source>
<translation>Bir komut için yardım al</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="49"/>
<source>Options:</source>
<translation>Seçenekler:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>Yapılandırma dosyası belirt (varsayılan: bitcoin.conf)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>Pid dosyası belirt (varsayılan: bitcoind.pid)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Generate coins</source>
<translation>Madenî para (FlorijnCoin) oluştur</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Don't generate coins</source>
<translation>FlorijnCoin oluşturmasını devre dışı bırak</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="54"/>
<source>Specify data directory</source>
<translation>Veri dizinini belirt</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="55"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Veritabanı önbellek boyutunu megabayt olarak belirt (varsayılan: 25)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Diskteki veritabanı kütüğü boyutunu megabayt olarak belirt (varsayılan: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>Bağlantı zaman aşım süresini milisaniye olarak belirt</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Bağlantılar için dinlenecek <port> (varsayılan: 8333 ya da testnet: 18333)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Eşler ile en çok <n> adet bağlantı kur (varsayılan: 125)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>Connect only to the specified node</source>
<translation>Sadece belirtilen düğüme bağlan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Eş adresleri elde etmek için bir düğüme bağlan ve ardından bağlantıyı kes</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="68"/>
<source>Specify your own public address</source>
<translation>Kendi genel adresinizi tanımlayın</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="69"/>
<source>Only connect to nodes in network <net> (IPv4 or IPv6)</source>
<translation>Sadece <net> şebekesindeki düğümlere bağlan (IPv4 ya da IPv6)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Try to discover public IP address (default: 1)</source>
<translation>Genel IP adresini keşfetmeye çalış (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Belirtilen adresle ilişiklendir. IPv6 için [makine]:port simgelemini kullanınız</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="75"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Aksaklık gösteren eşlerle bağlantıyı kesme sınırı (varsayılan: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aksaklık gösteren eşlerle yeni bağlantıları engelleme süresi, saniye olarak (varsayılan: 86400)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="79"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Her bağlantı için alım tamponu, <n>*1000 bayt (varsayılan: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="80"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Her bağlantı için yollama tamponu, <n>*1000 bayt (varsayılan: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="83"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Blok ve adres veri tabanlarını ayır. Kapatma süresini arttırır (varsayılan: 0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="86"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Konut satırı ve JSON-RPC komutlarını kabul et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="87"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Arka planda daemon (servis) olarak çalış ve komutları kabul et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="88"/>
<source>Use the test network</source>
<translation>Deneme şebekesini kullan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="89"/>
<source>Output extra debugging information</source>
<translation>İlâve hata ayıklama verisi çıkar</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="90"/>
<source>Prepend debug output with timestamp</source>
<translation>Hata ayıklama çıktısına tarih ön ekleri ilâve et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="91"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trace/hata ayıklama verilerini debug.log dosyası yerine konsola gönder</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="92"/>
<source>Send trace/debug info to debugger</source>
<translation>Hata ayıklayıcıya -debugger- trace/hata ayıklama verileri gönder</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="93"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için kullanıcı ismi</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="94"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için parola</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="95"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332)</source>
<translation>JSON-RPC bağlantıları için dinlenecek <port> (varsayılan: 8332)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="96"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Belirtilen İP adresinden JSON-RPC bağlantılarını kabul et</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="97"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Şu <ip> adresinde (varsayılan: 127.0.0.1) çalışan düğüme komut yolla</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="98"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>En iyi blok değiştiğinde komutu çalıştır (cmd için %s blok hash değeri ile değiştirilecektir)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="101"/>
<source>Upgrade wallet to latest format</source>
<translation>Cüzdanı en yeni biçime güncelle</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="102"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Anahtar alan boyutunu <n> değerine ayarla (varsayılan: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="103"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blok zincirini eksik cüzdan muameleleri için tekrar tara</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="104"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Başlangıçta ne kadar blokun denetleneceği (varsayılan: 2500, 0 = tümü)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="105"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Blok kontrolünün derinliği (0 ilâ 6, varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="106"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Harici blk000?.dat dosyasından blokları içe aktarır</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="108"/>
<source>
SSL options: (see the FlorijnCoin Wiki for SSL setup instructions)</source>
<translation>
SSL seçenekleri: (SSL kurulum bilgisi için FlorijnCoin vikisine bakınız)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="111"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için OpenSSL (https) kullan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="112"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Sunucu sertifika dosyası (varsayılan: server.cert)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="113"/>
<source>Server private key (default: server.pem)</source>
<translation>Sunucu özel anahtarı (varsayılan: server.pem)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="114"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Kabul edilebilir şifreler (varsayılan: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="145"/>
<source>Warning: Disk space is low</source>
<translation>Uyarı: Disk alanı düşük</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="107"/>
<source>This help message</source>
<translation>Bu yardım mesajı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="121"/>
<source>Cannot obtain a lock on data directory %s. FlorijnCoin is probably already running.</source>
<translation>%s veri dizininde kilit elde edilemedi. FlorijnCoin muhtemelen hâlihazırda çalışmaktadır.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="48"/>
<source>FlorijnCoin</source>
<translation>FlorijnCoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. (bind şu hatayı iletti: %d, %s)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="58"/>
<source>Connect through socks proxy</source>
<translation>Socks vekil sunucusu vasıtasıyla bağlan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="59"/>
<source>Select the version of socks proxy to use (4 or 5, 5 is default)</source>
<translation>Kullanılacak socks vekil sunucu sürümünü seç (4 veya 5, ki 5 varsayılan değerdir)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="60"/>
<source>Do not use proxy for connections to network <net> (IPv4 or IPv6)</source>
<translation><net> şebekesi ile bağlantılarda vekil sunucu kullanma (IPv4 ya da IPv6)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="61"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>-addnode, -seednode ve -connect için DNS aramalarına izin ver</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Pass DNS requests to (SOCKS5) proxy</source>
<translation>DNS isteklerini (SOCKS5) vekil sunucusuna devret</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="142"/>
<source>Loading addresses...</source>
<translation>Adresler yükleniyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="132"/>
<source>Error loading blkindex.dat</source>
<translation>blkindex.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="134"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: bozuk cüzdan</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="135"/>
<source>Error loading wallet.dat: Wallet requires newer version of FlorijnCoin</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: cüzdanın daha yeni bir FlorijnCoin sürümüne ihtiyacı var</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="136"/>
<source>Wallet needed to be rewritten: restart FlorijnCoin to complete</source>
<translation>Cüzdanın tekrar yazılması gerekiyordu: işlemi tamamlamak için FlorijnCoin'i yeniden başlatınız</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="137"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="124"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Geçersiz -proxy adresi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="125"/>
<source>Unknown network specified in -noproxy: '%s'</source>
<translation>-noproxy'de bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="127"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet için bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="126"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Bilinmeyen bir -socks vekil sürümü talep edildi: %i</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="128"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="129"/>
<source>Not listening on any port</source>
<translation>Hiçbir port dinlenmiyor</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="130"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="117"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<miktar> için geçersiz miktar: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="143"/>
<source>Error: could not start node</source>
<translation>Hata: düğüm başlatılamadı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Hata: Cüzdan kilitli, muamele oluşturulamadı </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<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>Hata: Muamelenin miktarı, karmaşıklığı ya da yakın geçmişte alınan fonların kullanılması nedeniyle bu muamele en az %s tutarında ücret gerektirmektedir </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="35"/>
<source>Error: Transaction creation failed </source>
<translation>Hata: Muamele oluşturması başarısız oldu </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Sending...</source>
<translation>Gönderiliyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<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>Hata: Muamele reddedildi. Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="41"/>
<source>Invalid amount</source>
<translation>Geçersiz miktar</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Insufficient funds</source>
<translation>Yetersiz bakiye</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="131"/>
<source>Loading block index...</source>
<translation>Blok indeksi yükleniyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Bağlanılacak düğüm ekle ve bağlantıyı zinde tutmaya çalış</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Unable to bind to %s on this computer. FlorijnCoin is probably already running.</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. FlorijnCoin muhtemelen hâlihazırda çalışmaktadır.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Eşleri Internet Relay Chat vasıtasıyla bul (varsayılan: 0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Accept connections from outside (default: 1)</source>
<translation>Dışarıdan gelen bağlantıları kabul et (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="74"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Eşleri DNS araması vasıtasıyla bul (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Use Universal Plug and Play to map the listening port (default: 1)</source>
<translation>Dinlenecek portu haritalamak için Universal Plug and Play kullan (varsayılan: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="82"/>
<source>Use Universal Plug and Play to map the listening port (default: 0)</source>
<translation>Dinlenecek portu haritalamak için Universal Plug and Play kullan (varsayılan: 0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="85"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Yolladığınız muameleler için eklenecek KB başı ücret</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="118"/>
<source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source>
<translation>Uyarı: -paytxfee çok yüksek bir değere ayarlanmış. Bu, muamele gönderirseniz ödeyeceğiniz muamele ücretidir.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="133"/>
<source>Loading wallet...</source>
<translation>Cüzdan yükleniyor...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="138"/>
<source>Cannot downgrade wallet</source>
<translation>Cüzdan eski biçime geri alınamaz</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="139"/>
<source>Cannot initialize keypool</source>
<translation>Keypool başlatılamadı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="140"/>
<source>Cannot write default address</source>
<translation>Varsayılan adres yazılamadı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="141"/>
<source>Rescanning...</source>
<translation>Yeniden tarama...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="144"/>
<source>Done loading</source>
<translation>Yükleme tamamlandı</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>To use the %s option</source>
<translation>%s seçeneğini kullanmak için</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="9"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
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>%s, şu yapılandırma dosyasında rpc parolası belirtmeniz gerekir:
%s
Aşağıdaki rastgele oluşturulan parolayı kullanmanız tavsiye edilir:
rpcuser=bitcoinrpc
rpcpassword=%s
(bu parolayı hatırlamanız gerekli değildir)
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>An error occured while setting up the RPC port %i for listening: %s</source>
<translation>%i RPC portunun dinleme için kurulması sırasında bir hata meydana geldi: %s</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>rpcpassword=<parola> şu yapılandırma dosyasında belirtilmelidir:
%s
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong FlorijnCoin will not work properly.</source>
<translation>Uyarı: Lütfen bilgisayarınızın tarih ve saatinin doğru olup olmadığını kontrol ediniz. Saatiniz doğru değilse FlorijnCoin gerektiği gibi çalışamaz.</translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>build.js<|end_file_name|><|fim▁begin|>/**
* download webdriver
*/
var path = require('path');
var fs = require('fs');<|fim▁hole|>var Decompress = require('decompress');
var fse = require('fs-extra');
var debug = require('debug')('browser');
var chromeVersion = '2.20';
var phantomVersion = '1.9.7';
var basePath = 'https://npm.taobao.org/mirrors/';
var driversDest = path.resolve(__dirname, './driver');
/**
* 下载对应平台的 driver
*/
function downloadDrivers() {
var driversConfig = {
darwin: [
{name: 'phantomjs-darwin', url: 'phantomjs/phantomjs-' + phantomVersion + '-macosx.zip'},
{name: 'chromedriver-darwin', url: 'chromedriver/' + chromeVersion + '/chromedriver_mac32.zip'}
],
win32: [
{name: 'chromedriver.exe', url: 'chromedriver/' + chromeVersion + '/chromedriver_win32.zip'},
{name: 'phantomjs.exe', url: 'phantomjs/phantomjs-' + phantomVersion + '-windows.zip'}
],
linux: [
{name: 'phantomjs-linux', url: 'phantomjs/phantomjs-' + phantomVersion + '-linux-x86_64.tar.bz2'}
]
};
var driverConfig = driversConfig[process.platform];
var count = 0;
console.log('load: download webDrivers...');
if (fs.existsSync(driversDest)) {
rimraf.sync(driversDest);
}
fs.mkdirSync(driversDest);
driverConfig.forEach(function(item) {
var download = new Download({
mode: '777'
// 取不出 tar
// extract: true
});
debug('download', item);
download
.get(basePath + item.url)
// .rename(item.name)
.dest(path.resolve(__dirname, './driver/'))
.run(function(err, files) {
if (err) {
throw new Error('Download drivers error, please reinstall ' + err.message);
}
var downloadFilePath = files[0].path;
var compressDir = path.resolve(driversDest, './' + item.name + '-dir');
debug('下载完一个文件:', downloadFilePath, '开始压缩:');
new Decompress({mode: '777'})
.src(downloadFilePath)
.dest(compressDir)
.use(Decompress.zip({strip: 1}))
.run(function(err) {
if (err) {
throw err;
}
debug('压缩完一个文件');
var type = /phantom/.test(item.name) ? 'phantomjs' : 'chromedriver';
reworkDest(downloadFilePath, compressDir, type);
debug('更改文件权限');
fs.chmodSync(path.resolve(driversDest, item.name), '777');
count ++;
if (count >= driverConfig.length) {
console.log('Download drivers successfully.');
}
});
});
});
}
/**
* 解压之后对文件夹重新整理
*/
function reworkDest(downloadFilePath, compressDir, type) {
// 清理下载的压缩文件
fse.removeSync(downloadFilePath);
var binName = type + (process.platform === 'win32' ? '.exe' : '-' + process.platform);
var binSrcPath = path.resolve(compressDir, type === 'phantomjs' ? './bin/phantomjs' : './chromedriver');
var binDestPath = path.resolve(driversDest, binName);
debug('复制 bin 文件:', binSrcPath, binDestPath);
fse.copySync(binSrcPath, binDestPath);
debug('移除源的文件夹');
fse.removeSync(compressDir);
}
downloadDrivers();<|fim▁end|> | var rimraf = require('rimraf');
var Download = require('download'); |
<|file_name|>products.client.controller.test.js<|end_file_name|><|fim▁begin|>'use strict';
(function() {
// ProductAppliers Controller Spec
describe('ProductAppliersController', function() {
// Initialize global variables
var ProductAppliersController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the ProductAppliers controller.<|fim▁hole|> ProductAppliersController = $controller('ProductAppliersController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one productApplier object fetched from XHR', inject(function(ProductAppliers) {
// Create sample productApplier using the ProductAppliers service
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productAppliers array that includes the new productApplier
var sampleProductAppliers = [sampleProductApplier];
// Set GET response
$httpBackend.expectGET('productAppliers').respond(sampleProductAppliers);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.productAppliers).toEqualData(sampleProductAppliers);
}));
it('$scope.findOne() should create an array with one productApplier object fetched from XHR using a productApplierId URL parameter', inject(function(ProductAppliers) {
// Define a sample productApplier object
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Set the URL parameter
$stateParams.productApplierId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/productAppliers\/([0-9a-fA-F]{24})$/).respond(sampleProductApplier);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.productApplier).toEqualData(sampleProductApplier);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(ProductAppliers) {
// Create a sample productApplier object
var sampleProductApplierPostData = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productApplier response
var sampleProductApplierResponse = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Fixture mock form input values
scope.title = 'An ProductApplier about MEAN';
scope.content = 'MEAN rocks!';
// Set POST response
$httpBackend.expectPOST('productAppliers', sampleProductApplierPostData).respond(sampleProductApplierResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// Test URL redirection after the productApplier was created
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierResponse._id);
}));
it('$scope.update() should update a valid productApplier', inject(function(ProductAppliers) {
// Define a sample productApplier put data
var sampleProductApplierPutData = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN Rocks!'
});
// Mock productApplier in scope
scope.productApplier = sampleProductApplierPutData;
// Set PUT response
$httpBackend.expectPUT(/productAppliers\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid productApplierId and remove the productApplier from the scope', inject(function(ProductAppliers) {
// Create new productApplier object
var sampleProductApplier = new ProductAppliers({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new productAppliers array and include the productApplier
scope.productAppliers = [sampleProductApplier];
// Set expected DELETE response
$httpBackend.expectDELETE(/productAppliers\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleProductApplier);
$httpBackend.flush();
// Test array after successful delete
expect(scope.productAppliers.length).toBe(0);
}));
});
}());<|fim▁end|> | |
<|file_name|>hashmap.go<|end_file_name|><|fim▁begin|>package datastruct
import (
"strings"
"github.com/xyproto/algernon/lua/convert"
"github.com/xyproto/gopher-lua"
"github.com/xyproto/pinterface"
)
// Identifier for the Hash class in Lua
const lHashClass = "HASH"
// Get the first argument, "self", and cast it from userdata to a hash map.
func checkHash(L *lua.LState) pinterface.IHashMap {
ud := L.CheckUserData(1)
if hash, ok := ud.Value.(pinterface.IHashMap); ok {
return hash
}
L.ArgError(1, "hash map expected")
return nil
}
// Create a new hash map.
// id is the name of the hash map.
// dbindex is the Redis database index (typically 0).
func newHashMap(L *lua.LState, creator pinterface.ICreator, id string) (*lua.LUserData, error) {
// Create a new hash map
hash, err := creator.NewHashMap(id)
if err != nil {
return nil, err
}
// Create a new userdata struct
ud := L.NewUserData()
ud.Value = hash
L.SetMetatable(ud, L.GetTypeMetatable(lHashClass))
return ud, nil
}
// String representation
// Returns all keys in the hash map as a comma separated string
// tostring(hash) -> string
func hashToString(L *lua.LState) int {
hash := checkHash(L) // arg 1
all, err := hash.All()
if err != nil {
L.Push(lua.LString(""))
return 1 // Number of returned values
}
L.Push(lua.LString(strings.Join(all, ", ")))
return 1 // Number of returned values
}
// For a given element id (for instance a user id), set a key (for instance "password") and a value.
// Returns true if successful.
// hash:set(string, string, string) -> bool
func hashSet(L *lua.LState) int {
hash := checkHash(L) // arg 1
elementid := L.CheckString(2)
key := L.CheckString(3)
value := L.ToString(4)
L.Push(lua.LBool(nil == hash.Set(elementid, key, value)))
return 1 // Number of returned values
}
// For a given element id (for instance a user id), and a key (for instance "password"), return a value.
// Returns a value only if they key was found and if there were no errors.
// hash:get(string, string) -> string
func hashGet(L *lua.LState) int {
hash := checkHash(L) // arg 1
elementid := L.CheckString(2)
key := L.CheckString(3)
retval, err := hash.Get(elementid, key)
if err != nil {
retval = ""
}
L.Push(lua.LString(retval))
return 1 // Number of returned values
}
// For a given element id (for instance a user id), and a key (for instance "password"), check if it exists in the hash map.
// Returns true only if it exists and there were no errors.
// hash:has(string, string) -> bool
func hashHas(L *lua.LState) int {
hash := checkHash(L) // arg 1
elementid := L.CheckString(2)
key := L.CheckString(3)
b, err := hash.Has(elementid, key)
if err != nil {
b = false
}
L.Push(lua.LBool(b))
return 1 // Number of returned values
}<|fim▁hole|>func hashExists(L *lua.LState) int {
hash := checkHash(L) // arg 1
elementid := L.CheckString(2)
b, err := hash.Exists(elementid)
if err != nil {
b = false
}
L.Push(lua.LBool(b))
return 1 // Number of returned values
}
// Get all keys of the hash map
// hash::getall() -> table
func hashAll(L *lua.LState) int {
hash := checkHash(L) // arg 1
all, err := hash.All()
if err != nil {
// Return an empty table
L.Push(L.NewTable())
return 1 // Number of returned values
}
L.Push(convert.Strings2table(L, all))
return 1 // Number of returned values
}
// Get all subkeys of the hash map
// hash::keys() -> table
func hashKeys(L *lua.LState) int {
hash := checkHash(L) // arg 1
elementid := L.CheckString(2)
keys, err := hash.Keys(elementid)
if err != nil {
// Return an empty table
L.Push(L.NewTable())
return 1 // Number of returned values
}
L.Push(convert.Strings2table(L, keys))
return 1 // Number of returned values
}
// Remove a key for an entry in a hash map (for instance the email field for a user)
// Returns true if successful
// hash:delkey(string, string) -> bool
func hashDelKey(L *lua.LState) int {
hash := checkHash(L) // arg 1
elementid := L.CheckString(2)
key := L.CheckString(3)
L.Push(lua.LBool(nil == hash.DelKey(elementid, key)))
return 1 // Number of returned values
}
// Remove an element (for instance a user)
// Returns true if successful
// hash:del(string) -> bool
func hashDel(L *lua.LState) int {
hash := checkHash(L) // arg 1
elementid := L.CheckString(2)
L.Push(lua.LBool(nil == hash.Del(elementid)))
return 1 // Number of returned values
}
// Remove the hash map itself. Returns true if successful.
// hash:remove() -> bool
func hashRemove(L *lua.LState) int {
hash := checkHash(L) // arg 1
L.Push(lua.LBool(nil == hash.Remove()))
return 1 // Number of returned values
}
// Clear the hash map. Returns true if successful.
// hash:clear() -> bool
func hashClear(L *lua.LState) int {
hash := checkHash(L) // arg 1
L.Push(lua.LBool(nil == hash.Clear()))
return 1 // Number of returned values
}
// The hash map methods that are to be registered
var hashMethods = map[string]lua.LGFunction{
"__tostring": hashToString,
"set": hashSet,
"get": hashGet,
"has": hashHas,
"exists": hashExists,
"getall": hashAll,
"keys": hashKeys,
"delkey": hashDelKey,
"del": hashDel,
"remove": hashRemove,
"clear": hashClear,
}
// LoadHash makes functions related to HTTP requests and responses available to Lua scripts
func LoadHash(L *lua.LState, creator pinterface.ICreator) {
// Register the hash map class and the methods that belongs with it.
mt := L.NewTypeMetatable(lHashClass)
mt.RawSetH(lua.LString("__index"), mt)
L.SetFuncs(mt, hashMethods)
// The constructor for new hash maps takes a name and an optional redis db index
L.SetGlobal("HashMap", L.NewFunction(func(L *lua.LState) int {
name := L.CheckString(1)
// Check if the optional argument is given
if L.GetTop() == 2 {
localDBIndex := L.ToInt(2)
// Set the DB index, if possible
switch rh := creator.(type) {
case pinterface.IRedisCreator:
rh.SelectDatabase(localDBIndex)
}
}
// Create a new hash map in Lua
userdata, err := newHashMap(L, creator, name)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
L.Push(lua.LNumber(1))
return 3 // Number of returned values
}
// Return the hash map object
L.Push(userdata)
return 1 // Number of returned values
}))
}<|fim▁end|> |
// For a given element id (for instance a user id), check if it exists in the hash map.
// Returns true only if it exists and there were no errors.
// hash:exists(string) -> bool |
<|file_name|>generate_blink_resource_map.py<|end_file_name|><|fim▁begin|># Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from string import Template
import optparse
import os
import sys
try:
grit_module_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'tools', 'grit')
sys.path.insert(0, grit_module_path)
from grit.format import data_pack as DataPack
except ImportError, e:
print 'ImportError: ', e
sys.exit(-1)
def is_ascii(s):<|fim▁hole|> return all(ord(c) < 128 for c in s)
header_template = \
"""// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MOJO_SERVICES_HTML_VIEWER_BLINK_RESOURCE_MAP_H_
#define MOJO_SERVICES_HTML_VIEWER_BLINK_RESOURCE_MAP_H_
#include <map>
namespace html_viewer {
class BlinkResourceMap {
public:
BlinkResourceMap();
const char* GetResource(int id, int* length);
private:
struct ResourceEntry {
const char* data;
int length;
ResourceEntry()
: data(nullptr)
, length(0) {
}
ResourceEntry(const char* data, int length)
: data(data)
, length(length) {
}
};
typedef std::map<int, ResourceEntry> ResourceMap;
ResourceMap resources_;
};
} // namespace html_viewer
#endif // MOJO_SERVICES_HTML_VIEWER_BLINK_RESOURCE_MAP_H_"""
cpp_template = \
"""// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "$header_file_name"
#include "base/macros.h"
namespace html_viewer {
$definitions
BlinkResourceMap::BlinkResourceMap()
{
$map_initializer
}
const char* BlinkResourceMap::GetResource(int id, int* length)
{
ResourceMap::iterator it = resources_.find(id);
if (it == resources_.end()) {
*length = 0;
return nullptr;
}
*length = it->second.length;
return it->second.data;
}
} // namespace html_viewer"""
def main():
parser = optparse.OptionParser(
usage='Usage: %prog --pak-file PAK_FILE --header HEADER --cpp CPP\n')
parser.add_option('-i', '--pak-file', action='store', dest='pak_file',
help='The .pak file to be extracted.')
parser.add_option('', '--header', action='store', dest='header_file',
help='Header file to be generated.')
parser.add_option('', '--cpp', action='store', dest='cpp_file',
help='C++ file to be generated.')
(options, _) = parser.parse_args()
if (not options.pak_file or not options.header_file or not options.cpp_file):
parser.print_help()
sys.exit(-1)
header_file = open(options.header_file, 'w+')
cpp_file = open(options.cpp_file, 'w+')
pak_contents = DataPack.ReadDataPack(options.pak_file)
resourceIds = []
header_contents = dict()
cpp_contents = dict()
definitions = []
for (resId, data) in pak_contents.resources.iteritems():
if not is_ascii(data):
continue
resourceIds.append(resId)
hex_values = ['0x{0:02x}'.format(ord(char)) for char in data]
f = lambda A, n=12: [A[i:i+n] for i in range(0, len(A), n)]
hex_values_string = ',\n '.join(', '.join(x) for x in f(hex_values))
cpp_definition = \
'const char kResource%s[%d] = {\n %s \n};' % \
(str(resId), len(hex_values), hex_values_string)
definitions.append(cpp_definition)
header_file_contents = Template(header_template).substitute(header_contents)
header_file.write(header_file_contents)
header_file.close()
map_initializer = []
for resId in resourceIds:
insert_statement = \
'resources_.insert(std::pair<int, ResourceEntry>(\n' \
' %s, ResourceEntry(kResource%s, arraysize(kResource%s))));'
map_initializer.append( \
insert_statement % (str(resId), str(resId), str(resId)))
cpp_contents['definitions']= '\n'.join(definitions)
cpp_contents['header_file_name'] = os.path.basename(options.header_file)
cpp_contents['map_initializer'] = '\n '.join(map_initializer)
cpp_file_contents = Template(cpp_template).substitute(cpp_contents)
cpp_file.write(cpp_file_contents)
cpp_file.close()
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>opening.rs<|end_file_name|><|fim▁begin|>use std::io::prelude::*;
use std::path::Path;
use std::fs::File;
use std::io::Result;
use bitboard::Board;
use bitboard::Move;
use bitboard::Turn;
///
///Opening book file format:
///(16 bytes: hash table array size (n))
///n * (20 bytes: (1 byte used)(16 bytes: board position, normalized)(1 byte: white best move)(1 byte: black best move))
///
struct OpeningNode {
hash_val_1 : u32,
hash_val_2 : u32,<|fim▁hole|> white_minimax : i16,
best_alt_move : u16,
alt_score : i16,
flags : u16,
}
pub struct Opening {
file : File,
}
impl Opening {
pub fn new(filename : String) -> Result<Opening> {
let open_file = File::open(&filename)?;
Ok(Opening {
file : open_file,
})
}
pub fn get_move(&mut self, bb : Board, t : Turn) -> Result<Move> {
Ok(Move::null())
}
}<|fim▁end|> | black_minimax : i16, |
<|file_name|>fileServingSpec.js<|end_file_name|><|fim▁begin|>const frisby = require('frisby')
const config = require('config')
const URL = 'http://localhost:3000'
let blueprint
for (const product of config.get('products')) {
if (product.fileForRetrieveBlueprintChallenge) {
blueprint = product.fileForRetrieveBlueprintChallenge
break
}
}
describe('Server', () => {
it('GET responds with index.html when visiting application URL', done => {
frisby.get(URL)
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', 'dist/juice-shop.min.js')
.done(done)
})
it('GET responds with index.html when visiting application URL with any path', done => {
frisby.get(URL + '/whatever')
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', 'dist/juice-shop.min.js')
.done(done)
})
it('GET a restricted file directly from file system path on server via Directory Traversal attack loads index.html instead', done => {
frisby.get(URL + '/public/images/../../ftp/eastere.gg')
.expect('status', 200)
.expect('bodyContains', '<meta name="description" content="An intentionally insecure JavaScript Web Application">')
.done(done)
})
it('GET a restricted file directly from file system path on server via URL-encoded Directory Traversal attack loads index.html instead', done => {
frisby.get(URL + '/public/images/%2e%2e%2f%2e%2e%2fftp/eastere.gg')
.expect('status', 200)
.expect('bodyContains', '<meta name="description" content="An intentionally insecure JavaScript Web Application">')
.done(done)
})
})
describe('/public/images/tracking', () => {
it('GET tracking image for "Score Board" page access challenge', done => {
frisby.get(URL + '/public/images/tracking/scoreboard.png')
.expect('status', 200)
.expect('header', 'content-type', 'image/png')
.done(done)
})
it('GET tracking image for "Administration" page access challenge', done => {
frisby.get(URL + '/public/images/tracking/administration.png')
.expect('status', 200)
.expect('header', 'content-type', 'image/png')
.done(done)
})
it('GET tracking background image for "Geocities Theme" challenge', done => {
frisby.get(URL + '/public/images/tracking/microfab.gif')
.expect('status', 200)
.expect('header', 'content-type', 'image/gif')
.done(done)
})
})
describe('/encryptionkeys', () => {
it('GET serves a directory listing', done => {
frisby.get(URL + '/encryptionkeys')
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', '<title>listing directory /encryptionkeys</title>')
.done(done)
})
it('GET a non-existing file in will return a 404 error', done => {
frisby.get(URL + '/encryptionkeys/doesnotexist.md')
.expect('status', 404)
.done(done)
})
it('GET the Premium Content AES key', done => {
frisby.get(URL + '/encryptionkeys/premium.key')
.expect('status', 200)
.done(done)
})
it('GET a key file whose name contains a "/" fails with a 403 error', done => {
frisby.fetch(URL + '/encryptionkeys/%2fetc%2fos-release%2500.md', {}, { urlEncode: false })
.expect('status', 403)
.expect('bodyContains', 'Error: File names cannot contain forward slashes!')
.done(done)
})
})
describe('Hidden URL', () => {
it('GET the second easter egg by visiting the Base64>ROT13-decrypted URL', done => {
frisby.get(URL + '/the/devs/are/so/funny/they/hid/an/easter/egg/within/the/easter/egg')
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', '<title>Welcome to Planet Orangeuze</title>')
.done(done)
})
it('GET the premium content by visiting the ROT5>Base64>z85>ROT5-decrypted URL', done => {
frisby.get(URL + '/this/page/is/hidden/behind/an/incredibly/high/paywall/that/could/only/be/unlocked/by/sending/1btc/to/us')
.expect('status', 200)
.expect('header', 'content-type', 'image/gif')
.done(done)
})
it('GET Geocities theme CSS is accessible directly from file system path', done => {
frisby.get(URL + '/css/geo-bootstrap/swatch/bootstrap.css')
.expect('status', 200)
.expect('bodyContains', 'Designed and built with all the love in the world @twitter by @mdo and @fat.')
.done(done)
})
it('GET Klingon translation file for "Extra Language" challenge', done => {
frisby.get(URL + '/i18n/tlh_AA.json')
.expect('status', 200)
.expect('header', 'content-type', /application\/json/)
.done(done)
})
it('GET blueprint file for "Retrieve Blueprint" challenge', done => {
frisby.get(URL + '/public/images/products/' + blueprint)
.expect('status', 200)
.done(done)
})<|fim▁hole|>})<|fim▁end|> | |
<|file_name|>ConflictType.js<|end_file_name|><|fim▁begin|>"use strict";
(function (ConflictType) {
ConflictType[ConflictType["IndividualAttendeeConflict"] = 0] = "IndividualAttendeeConflict";
ConflictType[ConflictType["GroupConflict"] = 1] = "GroupConflict";
ConflictType[ConflictType["GroupTooBigConflict"] = 2] = "GroupTooBigConflict";<|fim▁hole|><|fim▁end|> | ConflictType[ConflictType["UnknownAttendeeConflict"] = 3] = "UnknownAttendeeConflict";
})(exports.ConflictType || (exports.ConflictType = {}));
var ConflictType = exports.ConflictType; |
<|file_name|>test_vmhmm.py<|end_file_name|><|fim▁begin|>from __future__ import print_function, division
import random
from itertools import permutations
import numpy as np
from scipy.stats.distributions import vonmises
import pickle
import tempfile
from sklearn.pipeline import Pipeline
from msmbuilder.example_datasets import AlanineDipeptide
from msmbuilder.featurizer import DihedralFeaturizer
from msmbuilder.hmm import VonMisesHMM
def test_code_works():
# creates a 4-state HMM on the ALA2 data. Nothing fancy, just makes
# sure the code runs without erroring out
trajectories = AlanineDipeptide().get_cached().trajectories
topology = trajectories[0].topology
indices = topology.select('symbol C or symbol O or symbol N')
featurizer = DihedralFeaturizer(['phi', 'psi'], trajectories[0][0])
sequences = featurizer.transform(trajectories)
hmm = VonMisesHMM(n_states=4, n_init=1)
hmm.fit(sequences)
assert len(hmm.timescales_ == 3)
assert np.any(hmm.timescales_ > 50)
def circwrap(x):
"""Wrap an array on (-pi, pi)"""<|fim▁hole|>def create_timeseries(means, kappas, transmat):
"""Construct a random timeseries based on a specified Markov model."""
numStates = len(means)
state = random.randint(0, numStates - 1)
cdf = np.cumsum(transmat, 1)
numFrames = 1000
X = np.empty((numFrames, 1))
for i in range(numFrames):
rand = random.random()
state = (cdf[state] > rand).argmax()
X[i, 0] = circwrap(vonmises.rvs(kappas[state], means[state]))
return X
def validate_timeseries(means, kappas, transmat, model, meantol,
kappatol, transmattol):
"""Test our model matches the one used to create the timeseries."""
numStates = len(means)
assert len(model.means_) == numStates
assert (model.transmat_ >= 0.0).all()
assert (model.transmat_ <= 1.0).all()
totalProbability = sum(model.transmat_.T)
assert (abs(totalProbability - 1.0) < 1e-5).all()
# The states may have come out in a different order,
# so we need to test all possible permutations.
for order in permutations(range(len(means))):
match = True
for i in range(numStates):
if abs(circwrap(means[i] - model.means_[order[i]])) > meantol:
match = False
break
if abs(kappas[i] - model.kappas_[order[i]]) > kappatol:
match = False
break
for j in range(numStates):
diff = transmat[i, j] - model.transmat_[order[i], order[j]]
if abs(diff) > transmattol:
match = False
break
if match:
# It matches.
return
# No permutation matched.
assert False
def test_2_state():
transmat = np.array([[0.7, 0.3], [0.4, 0.6]])
means = np.array([[0.0], [2.0]])
kappas = np.array([[4.0], [8.0]])
X = [create_timeseries(means, kappas, transmat) for i in range(10)]
# For each value of various options,
# create a 2 state HMM and see if it is correct.
for reversible_type in ('mle', 'transpose'):
model = VonMisesHMM(n_states=2, reversible_type=reversible_type,
thresh=1e-4, n_iter=30)
model.fit(X)
validate_timeseries(means, kappas, transmat, model, 0.1, 0.5, 0.05)
assert abs(model.fit_logprob_[-1] - model.score(X)) < 0.5
def test_3_state():
transmat = np.array([[0.2, 0.3, 0.5], [0.4, 0.4, 0.2], [0.8, 0.2, 0.0]])
means = np.array([[0.0], [2.0], [4.0]])
kappas = np.array([[8.0], [8.0], [6.0]])
X = [create_timeseries(means, kappas, transmat) for i in range(20)]
# For each value of various options,
# create a 3 state HMM and see if it is correct.
for reversible_type in ('mle', 'transpose'):
model = VonMisesHMM(n_states=3, reversible_type=reversible_type,
thresh=1e-4, n_iter=30)
model.fit(X)
validate_timeseries(means, kappas, transmat, model, 0.1, 0.5, 0.1)
assert abs(model.fit_logprob_[-1] - model.score(X)) < 0.5
def test_pipeline():
trajs = AlanineDipeptide().get_cached().trajectories
p = Pipeline([
('diheds', DihedralFeaturizer(['phi', 'psi'], sincos=False)),
('hmm', VonMisesHMM(n_states=4))
])
predict = p.fit_predict(trajs)
p.named_steps['hmm'].summarize()
def test_pickle():
"""Test pickling an HMM"""
trajectories = AlanineDipeptide().get_cached().trajectories
topology = trajectories[0].topology
indices = topology.select('symbol C or symbol O or symbol N')
featurizer = DihedralFeaturizer(['phi', 'psi'], trajectories[0][0])
sequences = featurizer.transform(trajectories)
hmm = VonMisesHMM(n_states=4, n_init=1)
hmm.fit(sequences)
logprob, hidden = hmm.predict(sequences)
with tempfile.TemporaryFile() as savefile:
pickle.dump(hmm, savefile)
savefile.seek(0, 0)
hmm2 = pickle.load(savefile)
logprob2, hidden2 = hmm2.predict(sequences)
assert(logprob == logprob2)<|fim▁end|> | return x - 2 * np.pi * np.floor(x / (2 * np.pi) + 0.5)
|
<|file_name|>resource.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from superdesk.resource import Resource
class FormattersResource(Resource):
"""Formatters schema"""
endpoint_name = 'formatters'
resource_methods = ['GET', 'POST']
item_methods = []
resource_title = endpoint_name
schema = {
'article_id': {
'type': 'string',
'required': True
},
'formatter_name': {
'type': 'string',
'required': True<|fim▁hole|> }
privileges = {'POST': 'archive'}<|fim▁end|> | } |
<|file_name|>JailedPlayer.java<|end_file_name|><|fim▁begin|>package net.simpvp.Jail;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.bukkit.Location;
/**
* Class representing the stored information about a jailed player
*/
public class JailedPlayer {
public UUID uuid;
public String playername;
public String reason;
public String jailer;
public Location location;
public int jailed_time;
public boolean to_be_released;
public boolean online;
public JailedPlayer(UUID uuid, String playername, String reason, String jailer, Location location, int jailed_time, boolean to_be_released, boolean online) {
this.uuid = uuid;
this.playername = playername;
this.reason = reason;
this.jailer = jailer;
this.location = location;
this.jailed_time = jailed_time;
this.to_be_released = to_be_released;
this.online = online;
}
public void add() {<|fim▁hole|> SQLite.insert_player_info(this);
}
public int get_to_be_released() {
int ret = 0;
if (this.to_be_released)
ret ^= 1;
if (!this.online)
ret ^= 2;
return ret;
}
/**
* Returns a text description of this jailed player.
*/
public String get_info() {
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, H:m:s");
String msg = this.playername + " (" + this.uuid + ")"
+ " was jailed on " + sdf.format(new Date(this.jailed_time * 1000L))
+ " by " + this.jailer
+ " for" + this.reason + ".";
if (this.to_be_released) {
msg += "\nThis player is set to be released";
}
return msg;
}
}<|fim▁end|> | Jail.jailed_players.add(this.uuid);
}
public void insert() { |
<|file_name|>day22.rs<|end_file_name|><|fim▁begin|>extern crate dotenv;
extern crate lettre;
extern crate uuid;
use std::env;
use lettre::email::{EmailBuilder, SendableEmail};
use lettre::transport::EmailTransport;
use lettre::transport::smtp;
struct Report {
contents: String,
recipient: String,
}
impl SendableEmail for Report {
fn from_address(&self) -> String {
"[email protected]".to_string()
}
<|fim▁hole|> fn to_addresses(&self) -> Vec<String> {
vec![self.recipient.clone()]
}
fn message(&self) -> String {
format!("\nHere's the report you asked for:\n\n{}", self.contents)
}
fn message_id(&self) -> String {
uuid::Uuid::new_v4().simple().to_string()
}
}
fn main() {
println!("24 Days of Rust vol. 2 - lettre");
dotenv::dotenv().ok();
let email = EmailBuilder::new()
.from("[email protected]")
.to("[email protected]")
.subject("Hello Rust!")
.body("Hello Rust!")
.build()
.expect("Failed to build email message");
println!("{:?}", email);
let mut transport = smtp::SmtpTransportBuilder::localhost()
.expect("Failed to create transport")
.build();
println!("{:?}", transport.send(email.clone()));
let mut transport = smtp::SmtpTransportBuilder::new(("smtp.gmail.com", smtp::SUBMISSION_PORT))
.expect("Failed to create transport")
.credentials(&env::var("GMAIL_USERNAME").unwrap_or("user".to_string())[..],
&env::var("GMAIL_PASSWORD").unwrap_or("password".to_string())[..])
.build();
println!("{:?}", transport.send(email));
let report = Report {
contents: "Some very important report".to_string(),
// recipient: "[email protected]".to_string(),
recipient: "[email protected]".to_string(),
};
println!("{:?}", transport.send(report));
}<|fim▁end|> | |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate nickel;
use std::io::net::ip::Ipv4Addr;
use nickel::{ Nickel, Request, Response, HttpRouter };
fn main() {
let mut server = Nickel::new();
fn a_handler (_request: &Request, response: &mut Response) {
<|fim▁hole|> response.send("hello world");
}
server.get("/hello", a_handler);
server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
}<|fim▁end|> | |
<|file_name|>app.component.ts<|end_file_name|><|fim▁begin|>import { Component, ViewChild, ElementRef } from '@angular/core';
import { jqxButtonGroupComponent } from '../../../../../jqwidgets-ts/angular_jqxbuttongroup';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myButtonGroup') myButtonGroup: jqxButtonGroupComponent;
@ViewChild('myLog') myLog: ElementRef;
myDefaultModeButtonChecked(): void {
this.myButtonGroup.mode('default');
};
myRadioModeButtonChecked(): void {
this.myButtonGroup.mode('radio');
};
myCheckBoxModeButtonChecked(): void {<|fim▁hole|> };
groupOnBtnClick(event: any): void {
let clickedButton = event.args.button;
this.myLog.nativeElement.innerHTML = `Clicked: ${clickedButton[0].id}`;
}
}<|fim▁end|> | this.myButtonGroup.mode('checkbox'); |
<|file_name|>check_button.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Create widgets with a discrete toggle button
use glib::translate::ToGlibPtr;
use ffi;
/// CheckButton — Create widgets with a discrete toggle button
struct_Widget!(CheckButton);
impl CheckButton {
pub fn new() -> Option<CheckButton> {
let tmp_pointer = unsafe { ffi::gtk_check_button_new() };
check_pointer!(tmp_pointer, CheckButton)
}
pub fn new_with_label(label: &str) -> Option<CheckButton> {
let tmp_pointer = unsafe {
ffi::gtk_check_button_new_with_label(label.to_glib_none().0)
};<|fim▁hole|> let tmp_pointer = unsafe {
ffi::gtk_check_button_new_with_mnemonic(mnemonic.to_glib_none().0)
};
check_pointer!(tmp_pointer, CheckButton)
}
}
impl_drop!(CheckButton);
impl_TraitWidget!(CheckButton);
impl ::ContainerTrait for CheckButton {}
impl ::ButtonTrait for CheckButton {}
impl ::ToggleButtonTrait for CheckButton {}<|fim▁end|> | check_pointer!(tmp_pointer, CheckButton)
}
pub fn new_with_mnemonic(mnemonic: &str) -> Option<CheckButton> { |
<|file_name|>lib_dalek_config_TEST.js<|end_file_name|><|fim▁begin|>'use strict';
var expect = require('chai').expect;
var Config = require('../lib/dalek/config.js');
describe('dalek-internal-config', function () {
it('should exist', function () {
expect(Config).to.be.ok;
});
it('can be initialized', function () {
var config = new Config({}, {tests: []}, {});
expect(config).to.be.ok;
});
it('can get a value', function () {
var config = new Config({foo: 'bar'}, {tests: []}, {});
expect(config.get('foo')).to.equal('bar');
});
it('can read & parse a yaml file', function () {
var config = new Config({}, {tests: []}, {});
var fileContents = config.readyml(__dirname + '/mock/Dalekfile.yml');
expect(fileContents).to.include.keys('browsers');
expect(fileContents.browsers).to.be.an('array');
expect(fileContents.browsers[0]).to.be.an('object');
expect(fileContents.browsers[0]).to.include.keys('chrome');
expect(fileContents.browsers[0].chrome).to.include.keys('port');
expect(fileContents.browsers[0].chrome.port).to.equal(6000);
});
it('can read & parse a json file', function () {
var config = new Config({}, {tests: []}, {});
var fileContents = config.readjson(__dirname + '/mock/Dalekfile.json');
expect(fileContents).to.include.keys('browsers');
expect(fileContents.browsers).to.be.an('array');
expect(fileContents.browsers[0]).to.be.an('object');
expect(fileContents.browsers[0]).to.include.keys('chrome');
expect(fileContents.browsers[0].chrome).to.include.keys('port');
expect(fileContents.browsers[0].chrome.port).to.equal(6000);
});
it('can read & parse a json5 file', function () {
var config = new Config({}, {tests: []}, {});
var fileContents = config.readjson5(__dirname + '/mock/Dalekfile.json5');
expect(fileContents).to.include.keys('browsers');
expect(fileContents.browsers).to.be.an('array');
expect(fileContents.browsers[0]).to.be.an('object');
expect(fileContents.browsers[0]).to.include.keys('chrome');
expect(fileContents.browsers[0].chrome).to.include.keys('port');
expect(fileContents.browsers[0].chrome.port).to.equal(6000);
});
<|fim▁hole|> expect(fileContents).to.include.keys('browsers');
expect(fileContents.browsers).to.be.an('array');
expect(fileContents.browsers[0]).to.be.an('object');
expect(fileContents.browsers[0]).to.include.keys('chrome');
expect(fileContents.browsers[0].chrome).to.include.keys('port');
expect(fileContents.browsers[0].chrome.port).to.equal(6000);
});
it('can check the avilability of a config file', function () {
var config = new Config({}, {tests: []}, {});
var path = __dirname + '/mock/Dalekfile.coffee';
expect(config.checkAvailabilityOfConfigFile(path)).to.equal(path);
});
it('can verify a reporter', function () {
var config = new Config({}, {tests: []}, {});
var reporter = {
isReporter: function () {
return true;
}
};
var reporters = ['foobar'];
expect(config.verifyReporters(reporters, reporter)[0]).to.equal(reporters[0]);
});
it('can verify a driver', function () {
var config = new Config({}, {tests: []}, {});
var driver = {
isDriver: function () {
return true;
}
};
var drivers = ['foobar'];
expect(config.verifyDrivers(drivers, driver)[0]).to.equal(drivers[0]);
});
it('can return the previous filename if the _checkFile iterator foudn a file', function () {
var config = new Config({}, {tests: []}, {});
expect(config._checkFile('foobarbaz', '', '', '')).to.equal('foobarbaz');
});
it('can check the existance of default config files', function () {
var config = new Config({}, {tests: []}, {});
config.defaultFilename = __dirname + '/mock/Dalekfile';
expect(config._checkFile('js', 'coffee', 0, ['js', 'coffee'])).to.equal(__dirname + '/mock/Dalekfile.js');
});
it('can check the existance of default config files (1st in row doesnt exist, snd. does)', function () {
var config = new Config({}, {tests: []}, {});
config.defaultFilename = __dirname + '/mock/Dalekfile';
expect(config._checkFile('txt', 'coffee', 0, ['txt', 'coffee'])).to.equal(__dirname + '/mock/Dalekfile.coffee');
});
});<|fim▁end|> | it('can read & parse a js file', function () {
var config = new Config({}, {tests: []}, {});
var fileContents = config.readjs(__dirname + '/mock/Dalekfile.js'); |
<|file_name|>mofgpr.rs<|end_file_name|><|fim▁begin|>#[doc = "Register `MOFGPR` reader"]
pub struct R(crate::R<MOFGPR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<MOFGPR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<MOFGPR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<MOFGPR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `MOFGPR` writer"]
pub struct W(crate::W<MOFGPR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<MOFGPR_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<MOFGPR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<MOFGPR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `BOT` reader - Bottom Pointer"]<|fim▁hole|>pub struct BOT_R(crate::FieldReader<u8, u8>);
impl BOT_R {
pub(crate) fn new(bits: u8) -> Self {
BOT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BOT_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `BOT` writer - Bottom Pointer"]
pub struct BOT_W<'a> {
w: &'a mut W,
}
impl<'a> BOT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff);
self.w
}
}
#[doc = "Field `TOP` reader - Top Pointer"]
pub struct TOP_R(crate::FieldReader<u8, u8>);
impl TOP_R {
pub(crate) fn new(bits: u8) -> Self {
TOP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for TOP_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TOP` writer - Top Pointer"]
pub struct TOP_W<'a> {
w: &'a mut W,
}
impl<'a> TOP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8);
self.w
}
}
#[doc = "Field `CUR` reader - Current Object Pointer"]
pub struct CUR_R(crate::FieldReader<u8, u8>);
impl CUR_R {
pub(crate) fn new(bits: u8) -> Self {
CUR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CUR_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CUR` writer - Current Object Pointer"]
pub struct CUR_W<'a> {
w: &'a mut W,
}
impl<'a> CUR_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 16)) | ((value as u32 & 0xff) << 16);
self.w
}
}
#[doc = "Field `SEL` reader - Object Select Pointer"]
pub struct SEL_R(crate::FieldReader<u8, u8>);
impl SEL_R {
pub(crate) fn new(bits: u8) -> Self {
SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SEL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SEL` writer - Object Select Pointer"]
pub struct SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 24)) | ((value as u32 & 0xff) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Bottom Pointer"]
#[inline(always)]
pub fn bot(&self) -> BOT_R {
BOT_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - Top Pointer"]
#[inline(always)]
pub fn top(&self) -> TOP_R {
TOP_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - Current Object Pointer"]
#[inline(always)]
pub fn cur(&self) -> CUR_R {
CUR_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - Object Select Pointer"]
#[inline(always)]
pub fn sel(&self) -> SEL_R {
SEL_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Bottom Pointer"]
#[inline(always)]
pub fn bot(&mut self) -> BOT_W {
BOT_W { w: self }
}
#[doc = "Bits 8:15 - Top Pointer"]
#[inline(always)]
pub fn top(&mut self) -> TOP_W {
TOP_W { w: self }
}
#[doc = "Bits 16:23 - Current Object Pointer"]
#[inline(always)]
pub fn cur(&mut self) -> CUR_W {
CUR_W { w: self }
}
#[doc = "Bits 24:31 - Object Select Pointer"]
#[inline(always)]
pub fn sel(&mut self) -> SEL_W {
SEL_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 = "Message Object FIFO/Gateway Pointer 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 [mofgpr](index.html) module"]
pub struct MOFGPR_SPEC;
impl crate::RegisterSpec for MOFGPR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [mofgpr::R](R) reader structure"]
impl crate::Readable for MOFGPR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [mofgpr::W](W) writer structure"]
impl crate::Writable for MOFGPR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets MOFGPR to value 0"]
impl crate::Resettable for MOFGPR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}<|fim▁end|> | |
<|file_name|>Box.uni.driver.js<|end_file_name|><|fim▁begin|>import { baseUniDriverFactory } from '../../test/utils/unidriver';<|fim▁hole|>export const boxDriverFactory = base => {
return {
...baseUniDriverFactory(base),
};
};<|fim▁end|> | |
<|file_name|>gen.rs<|end_file_name|><|fim▁begin|>// This file is @generated by syn-internal-codegen.
// It is not intended for manual editing.
use super::{Lite, RefCast};
use std::fmt::{self, Debug, Display};
impl Debug for Lite<syn::Abi> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Abi");
if let Some(val) = &_val.name {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::LitStr);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("name", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::AngleBracketedGenericArguments> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("AngleBracketedGenericArguments");
if let Some(val) = &_val.colon2_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon2_token", Print::ref_cast(val));
}
if !_val.args.is_empty() {
formatter.field("args", Lite(&_val.args));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Arm> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Arm");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
if let Some(val) = &_val.guard {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::If, Box<syn::Expr>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("guard", Print::ref_cast(val));
}
formatter.field("body", Lite(&_val.body));
if let Some(val) = &_val.comma {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Comma);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("comma", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::AttrStyle> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::AttrStyle::Outer => formatter.write_str("Outer"),
syn::AttrStyle::Inner(_val) => {
formatter.write_str("Inner")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::Attribute> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Attribute");
formatter.field("style", Lite(&_val.style));
formatter.field("path", Lite(&_val.path));
formatter.field("tokens", Lite(&_val.tokens));
formatter.finish()
}
}
impl Debug for Lite<syn::BareFnArg> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("BareFnArg");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.name {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((proc_macro2::Ident, syn::token::Colon));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.0), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("name", Print::ref_cast(val));
}
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::BinOp> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::BinOp::Add(_val) => {
formatter.write_str("Add")?;
Ok(())
}
syn::BinOp::Sub(_val) => {
formatter.write_str("Sub")?;
Ok(())
}
syn::BinOp::Mul(_val) => {
formatter.write_str("Mul")?;
Ok(())
}
syn::BinOp::Div(_val) => {
formatter.write_str("Div")?;
Ok(())
}
syn::BinOp::Rem(_val) => {
formatter.write_str("Rem")?;
Ok(())
}
syn::BinOp::And(_val) => {
formatter.write_str("And")?;
Ok(())
}
syn::BinOp::Or(_val) => {
formatter.write_str("Or")?;
Ok(())
}
syn::BinOp::BitXor(_val) => {
formatter.write_str("BitXor")?;
Ok(())
}
syn::BinOp::BitAnd(_val) => {
formatter.write_str("BitAnd")?;
Ok(())
}
syn::BinOp::BitOr(_val) => {
formatter.write_str("BitOr")?;
Ok(())
}
syn::BinOp::Shl(_val) => {
formatter.write_str("Shl")?;
Ok(())
}
syn::BinOp::Shr(_val) => {
formatter.write_str("Shr")?;
Ok(())
}
syn::BinOp::Eq(_val) => {
formatter.write_str("Eq")?;
Ok(())
}
syn::BinOp::Lt(_val) => {
formatter.write_str("Lt")?;
Ok(())
}
syn::BinOp::Le(_val) => {
formatter.write_str("Le")?;
Ok(())
}
syn::BinOp::Ne(_val) => {
formatter.write_str("Ne")?;
Ok(())
}
syn::BinOp::Ge(_val) => {
formatter.write_str("Ge")?;
Ok(())
}
syn::BinOp::Gt(_val) => {
formatter.write_str("Gt")?;
Ok(())
}
syn::BinOp::AddEq(_val) => {
formatter.write_str("AddEq")?;
Ok(())
}
syn::BinOp::SubEq(_val) => {
formatter.write_str("SubEq")?;
Ok(())
}
syn::BinOp::MulEq(_val) => {
formatter.write_str("MulEq")?;
Ok(())
}
syn::BinOp::DivEq(_val) => {
formatter.write_str("DivEq")?;
Ok(())
}
syn::BinOp::RemEq(_val) => {
formatter.write_str("RemEq")?;
Ok(())
}
syn::BinOp::BitXorEq(_val) => {
formatter.write_str("BitXorEq")?;
Ok(())
}
syn::BinOp::BitAndEq(_val) => {
formatter.write_str("BitAndEq")?;
Ok(())
}
syn::BinOp::BitOrEq(_val) => {
formatter.write_str("BitOrEq")?;
Ok(())
}
syn::BinOp::ShlEq(_val) => {
formatter.write_str("ShlEq")?;
Ok(())
}
syn::BinOp::ShrEq(_val) => {
formatter.write_str("ShrEq")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::Binding> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Binding");
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::Block> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Block");
if !_val.stmts.is_empty() {
formatter.field("stmts", Lite(&_val.stmts));
}
formatter.finish()
}
}
impl Debug for Lite<syn::BoundLifetimes> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("BoundLifetimes");
if !_val.lifetimes.is_empty() {
formatter.field("lifetimes", Lite(&_val.lifetimes));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ConstParam> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ConstParam");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
if let Some(val) = &_val.eq_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Eq);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("eq_token", Print::ref_cast(val));
}
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Expr);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Constraint> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Constraint");
formatter.field("ident", Lite(&_val.ident));
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Data> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Data::Struct(_val) => {
let mut formatter = formatter.debug_struct("Data::Struct");
formatter.field("fields", Lite(&_val.fields));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::Data::Enum(_val) => {
let mut formatter = formatter.debug_struct("Data::Enum");
if !_val.variants.is_empty() {
formatter.field("variants", Lite(&_val.variants));
}
formatter.finish()
}
syn::Data::Union(_val) => {
let mut formatter = formatter.debug_struct("Data::Union");
formatter.field("fields", Lite(&_val.fields));
formatter.finish()
}
}
}
}
impl Debug for Lite<syn::DataEnum> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("DataEnum");
if !_val.variants.is_empty() {
formatter.field("variants", Lite(&_val.variants));
}
formatter.finish()
}
}
impl Debug for Lite<syn::DataStruct> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("DataStruct");
formatter.field("fields", Lite(&_val.fields));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::DataUnion> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("DataUnion");
formatter.field("fields", Lite(&_val.fields));
formatter.finish()
}
}
impl Debug for Lite<syn::DeriveInput> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("DeriveInput");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("data", Lite(&_val.data));
formatter.finish()
}
}
impl Debug for Lite<syn::Expr> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Expr::Array(_val) => {
let mut formatter = formatter.debug_struct("Expr::Array");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
syn::Expr::Assign(_val) => {
let mut formatter = formatter.debug_struct("Expr::Assign");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("left", Lite(&_val.left));
formatter.field("right", Lite(&_val.right));
formatter.finish()
}
syn::Expr::AssignOp(_val) => {
let mut formatter = formatter.debug_struct("Expr::AssignOp");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("left", Lite(&_val.left));
formatter.field("op", Lite(&_val.op));
formatter.field("right", Lite(&_val.right));
formatter.finish()
}
syn::Expr::Async(_val) => {
let mut formatter = formatter.debug_struct("Expr::Async");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.capture {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Move);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("capture", Print::ref_cast(val));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
syn::Expr::Await(_val) => {
let mut formatter = formatter.debug_struct("Expr::Await");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("base", Lite(&_val.base));
formatter.finish()
}
syn::Expr::Binary(_val) => {
let mut formatter = formatter.debug_struct("Expr::Binary");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("left", Lite(&_val.left));
formatter.field("op", Lite(&_val.op));
formatter.field("right", Lite(&_val.right));
formatter.finish()
}
syn::Expr::Block(_val) => {
let mut formatter = formatter.debug_struct("Expr::Block");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
syn::Expr::Box(_val) => {
let mut formatter = formatter.debug_struct("Expr::Box");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Expr::Break(_val) => {
let mut formatter = formatter.debug_struct("Expr::Break");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Lifetime);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
if let Some(val) = &_val.expr {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("expr", Print::ref_cast(val));
}
formatter.finish()
}
syn::Expr::Call(_val) => {
let mut formatter = formatter.debug_struct("Expr::Call");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("func", Lite(&_val.func));
if !_val.args.is_empty() {
formatter.field("args", Lite(&_val.args));
}
formatter.finish()
}
syn::Expr::Cast(_val) => {
let mut formatter = formatter.debug_struct("Expr::Cast");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
syn::Expr::Closure(_val) => {
let mut formatter = formatter.debug_struct("Expr::Closure");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.asyncness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Async);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("asyncness", Print::ref_cast(val));
}
if let Some(val) = &_val.movability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Static);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("movability", Print::ref_cast(val));
}
if let Some(val) = &_val.capture {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Move);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("capture", Print::ref_cast(val));
}
if !_val.inputs.is_empty() {
formatter.field("inputs", Lite(&_val.inputs));
}
formatter.field("output", Lite(&_val.output));
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
syn::Expr::Continue(_val) => {
let mut formatter = formatter.debug_struct("Expr::Continue");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Lifetime);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.finish()
}
syn::Expr::Field(_val) => {
let mut formatter = formatter.debug_struct("Expr::Field");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("base", Lite(&_val.base));
formatter.field("member", Lite(&_val.member));
formatter.finish()
}
syn::Expr::ForLoop(_val) => {
let mut formatter = formatter.debug_struct("Expr::ForLoop");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("pat", Lite(&_val.pat));
formatter.field("expr", Lite(&_val.expr));
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
syn::Expr::Group(_val) => {
let mut formatter = formatter.debug_struct("Expr::Group");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Expr::If(_val) => {
let mut formatter = formatter.debug_struct("Expr::If");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("cond", Lite(&_val.cond));
formatter.field("then_branch", Lite(&_val.then_branch));
if let Some(val) = &_val.else_branch {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Else, Box<syn::Expr>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("else_branch", Print::ref_cast(val));
}
formatter.finish()
}
syn::Expr::Index(_val) => {
let mut formatter = formatter.debug_struct("Expr::Index");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("index", Lite(&_val.index));
formatter.finish()
}
syn::Expr::Let(_val) => {
let mut formatter = formatter.debug_struct("Expr::Let");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Expr::Lit(_val) => {
let mut formatter = formatter.debug_struct("Expr::Lit");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("lit", Lite(&_val.lit));
formatter.finish()
}
syn::Expr::Loop(_val) => {
let mut formatter = formatter.debug_struct("Expr::Loop");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
syn::Expr::Macro(_val) => {
let mut formatter = formatter.debug_struct("Expr::Macro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
formatter.finish()
}
syn::Expr::Match(_val) => {
let mut formatter = formatter.debug_struct("Expr::Match");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
if !_val.arms.is_empty() {
formatter.field("arms", Lite(&_val.arms));
}
formatter.finish()
}
syn::Expr::MethodCall(_val) => {
let mut formatter = formatter.debug_struct("Expr::MethodCall");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("receiver", Lite(&_val.receiver));
formatter.field("method", Lite(&_val.method));
if let Some(val) = &_val.turbofish {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::MethodTurbofish);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("turbofish", Print::ref_cast(val));
}
if !_val.args.is_empty() {
formatter.field("args", Lite(&_val.args));
}
formatter.finish()
}
syn::Expr::Paren(_val) => {
let mut formatter = formatter.debug_struct("Expr::Paren");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Expr::Path(_val) => {
let mut formatter = formatter.debug_struct("Expr::Path");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.qself {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::QSelf);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("qself", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
syn::Expr::Range(_val) => {
let mut formatter = formatter.debug_struct("Expr::Range");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.from {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("from", Print::ref_cast(val));
}
formatter.field("limits", Lite(&_val.limits));
if let Some(val) = &_val.to {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("to", Print::ref_cast(val));
}
formatter.finish()
}
syn::Expr::Reference(_val) => {
let mut formatter = formatter.debug_struct("Expr::Reference");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Expr::Repeat(_val) => {
let mut formatter = formatter.debug_struct("Expr::Repeat");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("len", Lite(&_val.len));
formatter.finish()
}
syn::Expr::Return(_val) => {
let mut formatter = formatter.debug_struct("Expr::Return");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.expr {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("expr", Print::ref_cast(val));
}
formatter.finish()
}
syn::Expr::Struct(_val) => {
let mut formatter = formatter.debug_struct("Expr::Struct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("path", Lite(&_val.path));
if !_val.fields.is_empty() {
formatter.field("fields", Lite(&_val.fields));
}
if let Some(val) = &_val.dot2_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Dot2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("dot2_token", Print::ref_cast(val));
}
if let Some(val) = &_val.rest {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("rest", Print::ref_cast(val));
}
formatter.finish()
}
syn::Expr::Try(_val) => {
let mut formatter = formatter.debug_struct("Expr::Try");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Expr::TryBlock(_val) => {
let mut formatter = formatter.debug_struct("Expr::TryBlock");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
syn::Expr::Tuple(_val) => {
let mut formatter = formatter.debug_struct("Expr::Tuple");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
syn::Expr::Type(_val) => {
let mut formatter = formatter.debug_struct("Expr::Type");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
syn::Expr::Unary(_val) => {
let mut formatter = formatter.debug_struct("Expr::Unary");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("op", Lite(&_val.op));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Expr::Unsafe(_val) => {
let mut formatter = formatter.debug_struct("Expr::Unsafe");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
syn::Expr::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
syn::Expr::While(_val) => {
let mut formatter = formatter.debug_struct("Expr::While");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("cond", Lite(&_val.cond));
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
syn::Expr::Yield(_val) => {
let mut formatter = formatter.debug_struct("Expr::Yield");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.expr {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("expr", Print::ref_cast(val));
}
formatter.finish()
}
_ => unreachable!(),
}
}
}
impl Debug for Lite<syn::ExprArray> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprArray");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprAssign> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprAssign");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("left", Lite(&_val.left));
formatter.field("right", Lite(&_val.right));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprAssignOp> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprAssignOp");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("left", Lite(&_val.left));
formatter.field("op", Lite(&_val.op));
formatter.field("right", Lite(&_val.right));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprAsync> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprAsync");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.capture {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Move);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("capture", Print::ref_cast(val));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprAwait> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprAwait");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("base", Lite(&_val.base));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprBinary> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprBinary");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("left", Lite(&_val.left));
formatter.field("op", Lite(&_val.op));
formatter.field("right", Lite(&_val.right));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprBlock> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprBlock");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprBox> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprBox");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprBreak> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprBreak");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Lifetime);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
if let Some(val) = &_val.expr {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("expr", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprCall> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprCall");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("func", Lite(&_val.func));
if !_val.args.is_empty() {
formatter.field("args", Lite(&_val.args));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprCast> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprCast");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprClosure> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprClosure");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.asyncness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Async);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("asyncness", Print::ref_cast(val));
}
if let Some(val) = &_val.movability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Static);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("movability", Print::ref_cast(val));
}
if let Some(val) = &_val.capture {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Move);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("capture", Print::ref_cast(val));
}
if !_val.inputs.is_empty() {
formatter.field("inputs", Lite(&_val.inputs));
}
formatter.field("output", Lite(&_val.output));
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprContinue> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprContinue");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Lifetime);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprField> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprField");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("base", Lite(&_val.base));
formatter.field("member", Lite(&_val.member));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprForLoop> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprForLoop");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("pat", Lite(&_val.pat));
formatter.field("expr", Lite(&_val.expr));
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprGroup> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprGroup");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprIf> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprIf");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("cond", Lite(&_val.cond));
formatter.field("then_branch", Lite(&_val.then_branch));
if let Some(val) = &_val.else_branch {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Else, Box<syn::Expr>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("else_branch", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprIndex> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprIndex");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("index", Lite(&_val.index));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprLet> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprLet");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprLit> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprLit");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("lit", Lite(&_val.lit));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprLoop> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprLoop");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprMacro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprMacro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprMatch> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprMatch");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
if !_val.arms.is_empty() {
formatter.field("arms", Lite(&_val.arms));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprMethodCall> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprMethodCall");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("receiver", Lite(&_val.receiver));
formatter.field("method", Lite(&_val.method));
if let Some(val) = &_val.turbofish {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::MethodTurbofish);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("turbofish", Print::ref_cast(val));
}
if !_val.args.is_empty() {
formatter.field("args", Lite(&_val.args));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprParen> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprParen");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprPath> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprPath");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.qself {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::QSelf);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("qself", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprRange> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprRange");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.from {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("from", Print::ref_cast(val));
}
formatter.field("limits", Lite(&_val.limits));
if let Some(val) = &_val.to {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("to", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprReference> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprReference");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprRepeat> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprRepeat");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("len", Lite(&_val.len));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprReturn> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprReturn");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.expr {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("expr", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprStruct> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprStruct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("path", Lite(&_val.path));
if !_val.fields.is_empty() {
formatter.field("fields", Lite(&_val.fields));
}
if let Some(val) = &_val.dot2_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Dot2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("dot2_token", Print::ref_cast(val));
}
if let Some(val) = &_val.rest {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("rest", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprTry> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprTry");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprTryBlock> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprTryBlock");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprTuple> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprTuple");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ExprType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprType");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprUnary> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprUnary");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("op", Lite(&_val.op));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprUnsafe> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprUnsafe");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprWhile> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprWhile");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.label {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Label);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("label", Print::ref_cast(val));
}
formatter.field("cond", Lite(&_val.cond));
formatter.field("body", Lite(&_val.body));
formatter.finish()
}
}
impl Debug for Lite<syn::ExprYield> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ExprYield");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.expr {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Box<syn::Expr>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("expr", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Field> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Field");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.ident {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(proc_macro2::Ident);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("ident", Print::ref_cast(val));
}
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::FieldPat> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("FieldPat");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("member", Lite(&_val.member));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
formatter.field("pat", Lite(&_val.pat));
formatter.finish()
}
}
impl Debug for Lite<syn::FieldValue> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("FieldValue");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("member", Lite(&_val.member));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::Fields> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Fields::Named(_val) => {
let mut formatter = formatter.debug_struct("Fields::Named");
if !_val.named.is_empty() {
formatter.field("named", Lite(&_val.named));
}
formatter.finish()
}
syn::Fields::Unnamed(_val) => {
let mut formatter = formatter.debug_struct("Fields::Unnamed");
if !_val.unnamed.is_empty() {
formatter.field("unnamed", Lite(&_val.unnamed));
}
formatter.finish()
}
syn::Fields::Unit => formatter.write_str("Unit"),
}
}
}
impl Debug for Lite<syn::FieldsNamed> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("FieldsNamed");
if !_val.named.is_empty() {
formatter.field("named", Lite(&_val.named));
}
formatter.finish()
}
}
impl Debug for Lite<syn::FieldsUnnamed> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("FieldsUnnamed");
if !_val.unnamed.is_empty() {
formatter.field("unnamed", Lite(&_val.unnamed));
}
formatter.finish()
}
}
impl Debug for Lite<syn::File> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("File");
if let Some(val) = &_val.shebang {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(String);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("shebang", Print::ref_cast(val));
}
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
}
impl Debug for Lite<syn::FnArg> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::FnArg::Receiver(_val) => {
formatter.write_str("Receiver")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::FnArg::Typed(_val) => {
formatter.write_str("Typed")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::ForeignItem> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::ForeignItem::Fn(_val) => {
let mut formatter = formatter.debug_struct("ForeignItem::Fn");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("sig", Lite(&_val.sig));
formatter.finish()
}
syn::ForeignItem::Static(_val) => {
let mut formatter = formatter.debug_struct("ForeignItem::Static");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
syn::ForeignItem::Type(_val) => {
let mut formatter = formatter.debug_struct("ForeignItem::Type");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));<|fim▁hole|> let mut formatter = formatter.debug_struct("ForeignItem::Macro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::ForeignItem::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
_ => unreachable!(),
}
}
}
impl Debug for Lite<syn::ForeignItemFn> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ForeignItemFn");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("sig", Lite(&_val.sig));
formatter.finish()
}
}
impl Debug for Lite<syn::ForeignItemMacro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ForeignItemMacro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ForeignItemStatic> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ForeignItemStatic");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::ForeignItemType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ForeignItemType");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.finish()
}
}
impl Debug for Lite<syn::GenericArgument> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::GenericArgument::Lifetime(_val) => {
formatter.write_str("Lifetime")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::GenericArgument::Type(_val) => {
formatter.write_str("Type")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::GenericArgument::Binding(_val) => {
formatter.write_str("Binding")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::GenericArgument::Constraint(_val) => {
formatter.write_str("Constraint")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::GenericArgument::Const(_val) => {
formatter.write_str("Const")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::GenericMethodArgument> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::GenericMethodArgument::Type(_val) => {
formatter.write_str("Type")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::GenericMethodArgument::Const(_val) => {
formatter.write_str("Const")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::GenericParam> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::GenericParam::Type(_val) => {
formatter.write_str("Type")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::GenericParam::Lifetime(_val) => {
formatter.write_str("Lifetime")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::GenericParam::Const(_val) => {
formatter.write_str("Const")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::Generics> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Generics");
if let Some(val) = &_val.lt_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Lt);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("lt_token", Print::ref_cast(val));
}
if !_val.params.is_empty() {
formatter.field("params", Lite(&_val.params));
}
if let Some(val) = &_val.gt_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Gt);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("gt_token", Print::ref_cast(val));
}
if let Some(val) = &_val.where_clause {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::WhereClause);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("where_clause", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ImplItem> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::ImplItem::Const(_val) => {
let mut formatter = formatter.debug_struct("ImplItem::Const");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::ImplItem::Method(_val) => {
let mut formatter = formatter.debug_struct("ImplItem::Method");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
formatter.field("sig", Lite(&_val.sig));
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
syn::ImplItem::Type(_val) => {
let mut formatter = formatter.debug_struct("ImplItem::Type");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
syn::ImplItem::Macro(_val) => {
let mut formatter = formatter.debug_struct("ImplItem::Macro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::ImplItem::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
_ => unreachable!(),
}
}
}
impl Debug for Lite<syn::ImplItemConst> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ImplItemConst");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ImplItemMacro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ImplItemMacro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ImplItemMethod> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ImplItemMethod");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
formatter.field("sig", Lite(&_val.sig));
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
}
impl Debug for Lite<syn::ImplItemType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ImplItemType");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::Index> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Index");
formatter.field("index", Lite(&_val.index));
formatter.finish()
}
}
impl Debug for Lite<syn::Item> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Item::Const(_val) => {
let mut formatter = formatter.debug_struct("Item::Const");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Item::Enum(_val) => {
let mut formatter = formatter.debug_struct("Item::Enum");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if !_val.variants.is_empty() {
formatter.field("variants", Lite(&_val.variants));
}
formatter.finish()
}
syn::Item::ExternCrate(_val) => {
let mut formatter = formatter.debug_struct("Item::ExternCrate");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
if let Some(val) = &_val.rename {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::As, proc_macro2::Ident));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("rename", Print::ref_cast(val));
}
formatter.finish()
}
syn::Item::Fn(_val) => {
let mut formatter = formatter.debug_struct("Item::Fn");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("sig", Lite(&_val.sig));
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
syn::Item::ForeignMod(_val) => {
let mut formatter = formatter.debug_struct("Item::ForeignMod");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("abi", Lite(&_val.abi));
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
syn::Item::Impl(_val) => {
let mut formatter = formatter.debug_struct("Item::Impl");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
if let Some(val) = &_val.unsafety {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Unsafe);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("unsafety", Print::ref_cast(val));
}
formatter.field("generics", Lite(&_val.generics));
if let Some(val) = &_val.trait_ {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((Option<syn::token::Bang>, syn::Path, syn::token::For));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(
&(
{
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Option<syn::token::Bang>);
impl Debug for Print {
fn fmt(
&self,
formatter: &mut fmt::Formatter,
) -> fmt::Result
{
match &self.0 {
Some(_val) => {
formatter.write_str("Some")?;
Ok(())
}
None => formatter.write_str("None"),
}
}
}
Print::ref_cast(&_val.0)
},
Lite(&_val.1),
),
formatter,
)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("trait_", Print::ref_cast(val));
}
formatter.field("self_ty", Lite(&_val.self_ty));
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
syn::Item::Macro(_val) => {
let mut formatter = formatter.debug_struct("Item::Macro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.ident {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(proc_macro2::Ident);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("ident", Print::ref_cast(val));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::Item::Macro2(_val) => {
let mut formatter = formatter.debug_struct("Item::Macro2");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("rules", Lite(&_val.rules));
formatter.finish()
}
syn::Item::Mod(_val) => {
let mut formatter = formatter.debug_struct("Item::Mod");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
if let Some(val) = &_val.content {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Brace, Vec<syn::Item>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("content", Print::ref_cast(val));
}
if let Some(val) = &_val.semi {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi", Print::ref_cast(val));
}
formatter.finish()
}
syn::Item::Static(_val) => {
let mut formatter = formatter.debug_struct("Item::Static");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Item::Struct(_val) => {
let mut formatter = formatter.debug_struct("Item::Struct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("fields", Lite(&_val.fields));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::Item::Trait(_val) => {
let mut formatter = formatter.debug_struct("Item::Trait");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.unsafety {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Unsafe);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("unsafety", Print::ref_cast(val));
}
if let Some(val) = &_val.auto_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Auto);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("auto_token", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
if !_val.supertraits.is_empty() {
formatter.field("supertraits", Lite(&_val.supertraits));
}
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
syn::Item::TraitAlias(_val) => {
let mut formatter = formatter.debug_struct("Item::TraitAlias");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
syn::Item::Type(_val) => {
let mut formatter = formatter.debug_struct("Item::Type");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
syn::Item::Union(_val) => {
let mut formatter = formatter.debug_struct("Item::Union");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("fields", Lite(&_val.fields));
formatter.finish()
}
syn::Item::Use(_val) => {
let mut formatter = formatter.debug_struct("Item::Use");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.leading_colon {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("leading_colon", Print::ref_cast(val));
}
formatter.field("tree", Lite(&_val.tree));
formatter.finish()
}
syn::Item::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
_ => unreachable!(),
}
}
}
impl Debug for Lite<syn::ItemConst> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemConst");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ItemEnum> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemEnum");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if !_val.variants.is_empty() {
formatter.field("variants", Lite(&_val.variants));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemExternCrate> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemExternCrate");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
if let Some(val) = &_val.rename {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::As, proc_macro2::Ident));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("rename", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemFn> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemFn");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("sig", Lite(&_val.sig));
formatter.field("block", Lite(&_val.block));
formatter.finish()
}
}
impl Debug for Lite<syn::ItemForeignMod> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemForeignMod");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("abi", Lite(&_val.abi));
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemImpl> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemImpl");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.defaultness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Default);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("defaultness", Print::ref_cast(val));
}
if let Some(val) = &_val.unsafety {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Unsafe);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("unsafety", Print::ref_cast(val));
}
formatter.field("generics", Lite(&_val.generics));
if let Some(val) = &_val.trait_ {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((Option<syn::token::Bang>, syn::Path, syn::token::For));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(
&(
{
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Option<syn::token::Bang>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
Some(_val) => {
formatter.write_str("Some")?;
Ok(())
}
None => formatter.write_str("None"),
}
}
}
Print::ref_cast(&_val.0)
},
Lite(&_val.1),
),
formatter,
)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("trait_", Print::ref_cast(val));
}
formatter.field("self_ty", Lite(&_val.self_ty));
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemMacro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemMacro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.ident {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(proc_macro2::Ident);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("ident", Print::ref_cast(val));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemMacro2> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemMacro2");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("rules", Lite(&_val.rules));
formatter.finish()
}
}
impl Debug for Lite<syn::ItemMod> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemMod");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
if let Some(val) = &_val.content {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Brace, Vec<syn::Item>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("content", Print::ref_cast(val));
}
if let Some(val) = &_val.semi {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemStatic> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemStatic");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::ItemStruct> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemStruct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("fields", Lite(&_val.fields));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemTrait> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemTrait");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.unsafety {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Unsafe);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("unsafety", Print::ref_cast(val));
}
if let Some(val) = &_val.auto_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Auto);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("auto_token", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
if !_val.supertraits.is_empty() {
formatter.field("supertraits", Lite(&_val.supertraits));
}
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemTraitAlias> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemTraitAlias");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ItemType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemType");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::ItemUnion> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemUnion");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
formatter.field("fields", Lite(&_val.fields));
formatter.finish()
}
}
impl Debug for Lite<syn::ItemUse> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ItemUse");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("vis", Lite(&_val.vis));
if let Some(val) = &_val.leading_colon {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("leading_colon", Print::ref_cast(val));
}
formatter.field("tree", Lite(&_val.tree));
formatter.finish()
}
}
impl Debug for Lite<syn::Label> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Label");
formatter.field("name", Lite(&_val.name));
formatter.finish()
}
}
impl Debug for Lite<syn::Lifetime> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Lifetime");
formatter.field("ident", Lite(&_val.ident));
formatter.finish()
}
}
impl Debug for Lite<syn::LifetimeDef> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("LifetimeDef");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("lifetime", Lite(&_val.lifetime));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Lit> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Lit::Str(_val) => {
write!(formatter, "{:?}", _val.value())
}
syn::Lit::ByteStr(_val) => {
write!(formatter, "{:?}", _val.value())
}
syn::Lit::Byte(_val) => {
write!(formatter, "{:?}", _val.value())
}
syn::Lit::Char(_val) => {
write!(formatter, "{:?}", _val.value())
}
syn::Lit::Int(_val) => {
write!(formatter, "{}", _val)
}
syn::Lit::Float(_val) => {
write!(formatter, "{}", _val)
}
syn::Lit::Bool(_val) => {
let mut formatter = formatter.debug_struct("Lit::Bool");
formatter.field("value", Lite(&_val.value));
formatter.finish()
}
syn::Lit::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::LitBool> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("LitBool");
formatter.field("value", Lite(&_val.value));
formatter.finish()
}
}
impl Debug for Lite<syn::LitByte> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
write!(formatter, "{:?}", _val.value())
}
}
impl Debug for Lite<syn::LitByteStr> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
write!(formatter, "{:?}", _val.value())
}
}
impl Debug for Lite<syn::LitChar> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
write!(formatter, "{:?}", _val.value())
}
}
impl Debug for Lite<syn::LitFloat> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
write!(formatter, "{}", _val)
}
}
impl Debug for Lite<syn::LitInt> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
write!(formatter, "{}", _val)
}
}
impl Debug for Lite<syn::LitStr> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
write!(formatter, "{:?}", _val.value())
}
}
impl Debug for Lite<syn::Local> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Local");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
if let Some(val) = &_val.init {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Eq, Box<syn::Expr>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("init", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Macro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Macro");
formatter.field("path", Lite(&_val.path));
formatter.field("delimiter", Lite(&_val.delimiter));
formatter.field("tokens", Lite(&_val.tokens));
formatter.finish()
}
}
impl Debug for Lite<syn::MacroDelimiter> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::MacroDelimiter::Paren(_val) => {
formatter.write_str("Paren")?;
Ok(())
}
syn::MacroDelimiter::Brace(_val) => {
formatter.write_str("Brace")?;
Ok(())
}
syn::MacroDelimiter::Bracket(_val) => {
formatter.write_str("Bracket")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::Member> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Member::Named(_val) => {
formatter.write_str("Named")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::Member::Unnamed(_val) => {
formatter.write_str("Unnamed")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::Meta> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Meta::Path(_val) => {
formatter.write_str("Path")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::Meta::List(_val) => {
let mut formatter = formatter.debug_struct("Meta::List");
formatter.field("path", Lite(&_val.path));
if !_val.nested.is_empty() {
formatter.field("nested", Lite(&_val.nested));
}
formatter.finish()
}
syn::Meta::NameValue(_val) => {
let mut formatter = formatter.debug_struct("Meta::NameValue");
formatter.field("path", Lite(&_val.path));
formatter.field("lit", Lite(&_val.lit));
formatter.finish()
}
}
}
}
impl Debug for Lite<syn::MetaList> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("MetaList");
formatter.field("path", Lite(&_val.path));
if !_val.nested.is_empty() {
formatter.field("nested", Lite(&_val.nested));
}
formatter.finish()
}
}
impl Debug for Lite<syn::MetaNameValue> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("MetaNameValue");
formatter.field("path", Lite(&_val.path));
formatter.field("lit", Lite(&_val.lit));
formatter.finish()
}
}
impl Debug for Lite<syn::MethodTurbofish> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("MethodTurbofish");
if !_val.args.is_empty() {
formatter.field("args", Lite(&_val.args));
}
formatter.finish()
}
}
impl Debug for Lite<syn::NestedMeta> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::NestedMeta::Meta(_val) => {
formatter.write_str("Meta")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::NestedMeta::Lit(_val) => {
formatter.write_str("Lit")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::ParenthesizedGenericArguments> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("ParenthesizedGenericArguments");
if !_val.inputs.is_empty() {
formatter.field("inputs", Lite(&_val.inputs));
}
formatter.field("output", Lite(&_val.output));
formatter.finish()
}
}
impl Debug for Lite<syn::Pat> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Pat::Box(_val) => {
let mut formatter = formatter.debug_struct("Pat::Box");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
formatter.finish()
}
syn::Pat::Ident(_val) => {
let mut formatter = formatter.debug_struct("Pat::Ident");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.by_ref {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Ref);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("by_ref", Print::ref_cast(val));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
if let Some(val) = &_val.subpat {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::At, Box<syn::Pat>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("subpat", Print::ref_cast(val));
}
formatter.finish()
}
syn::Pat::Lit(_val) => {
let mut formatter = formatter.debug_struct("Pat::Lit");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
syn::Pat::Macro(_val) => {
let mut formatter = formatter.debug_struct("Pat::Macro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
formatter.finish()
}
syn::Pat::Or(_val) => {
let mut formatter = formatter.debug_struct("Pat::Or");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.leading_vert {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Or);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("leading_vert", Print::ref_cast(val));
}
if !_val.cases.is_empty() {
formatter.field("cases", Lite(&_val.cases));
}
formatter.finish()
}
syn::Pat::Path(_val) => {
let mut formatter = formatter.debug_struct("Pat::Path");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.qself {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::QSelf);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("qself", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
syn::Pat::Range(_val) => {
let mut formatter = formatter.debug_struct("Pat::Range");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("lo", Lite(&_val.lo));
formatter.field("limits", Lite(&_val.limits));
formatter.field("hi", Lite(&_val.hi));
formatter.finish()
}
syn::Pat::Reference(_val) => {
let mut formatter = formatter.debug_struct("Pat::Reference");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("pat", Lite(&_val.pat));
formatter.finish()
}
syn::Pat::Rest(_val) => {
let mut formatter = formatter.debug_struct("Pat::Rest");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.finish()
}
syn::Pat::Slice(_val) => {
let mut formatter = formatter.debug_struct("Pat::Slice");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
syn::Pat::Struct(_val) => {
let mut formatter = formatter.debug_struct("Pat::Struct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("path", Lite(&_val.path));
if !_val.fields.is_empty() {
formatter.field("fields", Lite(&_val.fields));
}
if let Some(val) = &_val.dot2_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Dot2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("dot2_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::Pat::Tuple(_val) => {
let mut formatter = formatter.debug_struct("Pat::Tuple");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
syn::Pat::TupleStruct(_val) => {
let mut formatter = formatter.debug_struct("Pat::TupleStruct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("path", Lite(&_val.path));
formatter.field("pat", Lite(&_val.pat));
formatter.finish()
}
syn::Pat::Type(_val) => {
let mut formatter = formatter.debug_struct("Pat::Type");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
syn::Pat::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
syn::Pat::Wild(_val) => {
let mut formatter = formatter.debug_struct("Pat::Wild");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.finish()
}
_ => unreachable!(),
}
}
}
impl Debug for Lite<syn::PatBox> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatBox");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
formatter.finish()
}
}
impl Debug for Lite<syn::PatIdent> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatIdent");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.by_ref {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Ref);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("by_ref", Print::ref_cast(val));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
if let Some(val) = &_val.subpat {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::At, Box<syn::Pat>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("subpat", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PatLit> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatLit");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("expr", Lite(&_val.expr));
formatter.finish()
}
}
impl Debug for Lite<syn::PatMacro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatMacro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
formatter.finish()
}
}
impl Debug for Lite<syn::PatOr> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatOr");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.leading_vert {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Or);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("leading_vert", Print::ref_cast(val));
}
if !_val.cases.is_empty() {
formatter.field("cases", Lite(&_val.cases));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PatPath> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatPath");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.qself {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::QSelf);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("qself", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
}
impl Debug for Lite<syn::PatRange> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatRange");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("lo", Lite(&_val.lo));
formatter.field("limits", Lite(&_val.limits));
formatter.field("hi", Lite(&_val.hi));
formatter.finish()
}
}
impl Debug for Lite<syn::PatReference> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatReference");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("pat", Lite(&_val.pat));
formatter.finish()
}
}
impl Debug for Lite<syn::PatRest> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatRest");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PatSlice> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatSlice");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PatStruct> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatStruct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("path", Lite(&_val.path));
if !_val.fields.is_empty() {
formatter.field("fields", Lite(&_val.fields));
}
if let Some(val) = &_val.dot2_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Dot2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("dot2_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PatTuple> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatTuple");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PatTupleStruct> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatTupleStruct");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("path", Lite(&_val.path));
formatter.field("pat", Lite(&_val.pat));
formatter.finish()
}
}
impl Debug for Lite<syn::PatType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatType");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("pat", Lite(&_val.pat));
formatter.field("ty", Lite(&_val.ty));
formatter.finish()
}
}
impl Debug for Lite<syn::PatWild> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PatWild");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Path> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Path");
if let Some(val) = &_val.leading_colon {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("leading_colon", Print::ref_cast(val));
}
if !_val.segments.is_empty() {
formatter.field("segments", Lite(&_val.segments));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PathArguments> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::PathArguments::None => formatter.write_str("None"),
syn::PathArguments::AngleBracketed(_val) => {
let mut formatter = formatter.debug_struct("PathArguments::AngleBracketed");
if let Some(val) = &_val.colon2_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon2);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon2_token", Print::ref_cast(val));
}
if !_val.args.is_empty() {
formatter.field("args", Lite(&_val.args));
}
formatter.finish()
}
syn::PathArguments::Parenthesized(_val) => {
let mut formatter = formatter.debug_struct("PathArguments::Parenthesized");
if !_val.inputs.is_empty() {
formatter.field("inputs", Lite(&_val.inputs));
}
formatter.field("output", Lite(&_val.output));
formatter.finish()
}
}
}
}
impl Debug for Lite<syn::PathSegment> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PathSegment");
formatter.field("ident", Lite(&_val.ident));
formatter.field("arguments", Lite(&_val.arguments));
formatter.finish()
}
}
impl Debug for Lite<syn::PredicateEq> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PredicateEq");
formatter.field("lhs_ty", Lite(&_val.lhs_ty));
formatter.field("rhs_ty", Lite(&_val.rhs_ty));
formatter.finish()
}
}
impl Debug for Lite<syn::PredicateLifetime> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PredicateLifetime");
formatter.field("lifetime", Lite(&_val.lifetime));
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
}
impl Debug for Lite<syn::PredicateType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("PredicateType");
if let Some(val) = &_val.lifetimes {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::BoundLifetimes);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("lifetimes", Print::ref_cast(val));
}
formatter.field("bounded_ty", Lite(&_val.bounded_ty));
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
}
impl Debug for Lite<syn::QSelf> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("QSelf");
formatter.field("ty", Lite(&_val.ty));
formatter.field("position", Lite(&_val.position));
if let Some(val) = &_val.as_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::As);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("as_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::RangeLimits> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::RangeLimits::HalfOpen(_val) => {
formatter.write_str("HalfOpen")?;
Ok(())
}
syn::RangeLimits::Closed(_val) => {
formatter.write_str("Closed")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::Receiver> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Receiver");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
if let Some(val) = &_val.reference {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::And, Option<syn::Lifetime>));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(
{
#[derive(RefCast)]
#[repr(transparent)]
struct Print(Option<syn::Lifetime>);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
Some(_val) => {
formatter.write_str("Some")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
None => formatter.write_str("None"),
}
}
}
Print::ref_cast(&_val.1)
},
formatter,
)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("reference", Print::ref_cast(val));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::ReturnType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::ReturnType::Default => formatter.write_str("Default"),
syn::ReturnType::Type(_v0, _v1) => {
let mut formatter = formatter.debug_tuple("Type");
formatter.field(Lite(_v1));
formatter.finish()
}
}
}
}
impl Debug for Lite<syn::Signature> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Signature");
if let Some(val) = &_val.constness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Const);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("constness", Print::ref_cast(val));
}
if let Some(val) = &_val.asyncness {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Async);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("asyncness", Print::ref_cast(val));
}
if let Some(val) = &_val.unsafety {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Unsafe);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("unsafety", Print::ref_cast(val));
}
if let Some(val) = &_val.abi {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Abi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("abi", Print::ref_cast(val));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if !_val.inputs.is_empty() {
formatter.field("inputs", Lite(&_val.inputs));
}
if let Some(val) = &_val.variadic {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Variadic);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("variadic", Print::ref_cast(val));
}
formatter.field("output", Lite(&_val.output));
formatter.finish()
}
}
impl Debug for Lite<syn::Stmt> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Stmt::Local(_val) => {
formatter.write_str("Local")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::Stmt::Item(_val) => {
formatter.write_str("Item")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::Stmt::Expr(_val) => {
formatter.write_str("Expr")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::Stmt::Semi(_v0, _v1) => {
let mut formatter = formatter.debug_tuple("Semi");
formatter.field(Lite(_v0));
formatter.finish()
}
}
}
}
impl Debug for Lite<syn::TraitBound> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TraitBound");
if let Some(val) = &_val.paren_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Paren);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("paren_token", Print::ref_cast(val));
}
formatter.field("modifier", Lite(&_val.modifier));
if let Some(val) = &_val.lifetimes {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::BoundLifetimes);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("lifetimes", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
}
impl Debug for Lite<syn::TraitBoundModifier> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::TraitBoundModifier::None => formatter.write_str("None"),
syn::TraitBoundModifier::Maybe(_val) => {
formatter.write_str("Maybe")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::TraitItem> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::TraitItem::Const(_val) => {
let mut formatter = formatter.debug_struct("TraitItem::Const");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Eq, syn::Expr));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
formatter.finish()
}
syn::TraitItem::Method(_val) => {
let mut formatter = formatter.debug_struct("TraitItem::Method");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("sig", Lite(&_val.sig));
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Block);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::TraitItem::Type(_val) => {
let mut formatter = formatter.debug_struct("TraitItem::Type");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Eq, syn::Type));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
formatter.finish()
}
syn::TraitItem::Macro(_val) => {
let mut formatter = formatter.debug_struct("TraitItem::Macro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
syn::TraitItem::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
_ => unreachable!(),
}
}
}
impl Debug for Lite<syn::TraitItemConst> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TraitItemConst");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("ty", Lite(&_val.ty));
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Eq, syn::Expr));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::TraitItemMacro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TraitItemMacro");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("mac", Lite(&_val.mac));
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::TraitItemMethod> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TraitItemMethod");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("sig", Lite(&_val.sig));
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Block);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
if let Some(val) = &_val.semi_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Semi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("semi_token", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::TraitItemType> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TraitItemType");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("generics", Lite(&_val.generics));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Eq, syn::Type));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Type> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Type::Array(_val) => {
let mut formatter = formatter.debug_struct("Type::Array");
formatter.field("elem", Lite(&_val.elem));
formatter.field("len", Lite(&_val.len));
formatter.finish()
}
syn::Type::BareFn(_val) => {
let mut formatter = formatter.debug_struct("Type::BareFn");
if let Some(val) = &_val.lifetimes {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::BoundLifetimes);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("lifetimes", Print::ref_cast(val));
}
if let Some(val) = &_val.unsafety {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Unsafe);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("unsafety", Print::ref_cast(val));
}
if let Some(val) = &_val.abi {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Abi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("abi", Print::ref_cast(val));
}
if !_val.inputs.is_empty() {
formatter.field("inputs", Lite(&_val.inputs));
}
if let Some(val) = &_val.variadic {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Variadic);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("variadic", Print::ref_cast(val));
}
formatter.field("output", Lite(&_val.output));
formatter.finish()
}
syn::Type::Group(_val) => {
let mut formatter = formatter.debug_struct("Type::Group");
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
syn::Type::ImplTrait(_val) => {
let mut formatter = formatter.debug_struct("Type::ImplTrait");
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
syn::Type::Infer(_val) => {
let mut formatter = formatter.debug_struct("Type::Infer");
formatter.finish()
}
syn::Type::Macro(_val) => {
let mut formatter = formatter.debug_struct("Type::Macro");
formatter.field("mac", Lite(&_val.mac));
formatter.finish()
}
syn::Type::Never(_val) => {
let mut formatter = formatter.debug_struct("Type::Never");
formatter.finish()
}
syn::Type::Paren(_val) => {
let mut formatter = formatter.debug_struct("Type::Paren");
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
syn::Type::Path(_val) => {
let mut formatter = formatter.debug_struct("Type::Path");
if let Some(val) = &_val.qself {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::QSelf);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("qself", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
syn::Type::Ptr(_val) => {
let mut formatter = formatter.debug_struct("Type::Ptr");
if let Some(val) = &_val.const_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Const);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("const_token", Print::ref_cast(val));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
syn::Type::Reference(_val) => {
let mut formatter = formatter.debug_struct("Type::Reference");
if let Some(val) = &_val.lifetime {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Lifetime);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("lifetime", Print::ref_cast(val));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
syn::Type::Slice(_val) => {
let mut formatter = formatter.debug_struct("Type::Slice");
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
syn::Type::TraitObject(_val) => {
let mut formatter = formatter.debug_struct("Type::TraitObject");
if let Some(val) = &_val.dyn_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Dyn);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("dyn_token", Print::ref_cast(val));
}
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
syn::Type::Tuple(_val) => {
let mut formatter = formatter.debug_struct("Type::Tuple");
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
syn::Type::Verbatim(_val) => {
formatter.write_str("Verbatim")?;
formatter.write_str("(`")?;
Display::fmt(_val, formatter)?;
formatter.write_str("`)")?;
Ok(())
}
_ => unreachable!(),
}
}
}
impl Debug for Lite<syn::TypeArray> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeArray");
formatter.field("elem", Lite(&_val.elem));
formatter.field("len", Lite(&_val.len));
formatter.finish()
}
}
impl Debug for Lite<syn::TypeBareFn> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeBareFn");
if let Some(val) = &_val.lifetimes {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::BoundLifetimes);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("lifetimes", Print::ref_cast(val));
}
if let Some(val) = &_val.unsafety {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Unsafe);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("unsafety", Print::ref_cast(val));
}
if let Some(val) = &_val.abi {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Abi);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("abi", Print::ref_cast(val));
}
if !_val.inputs.is_empty() {
formatter.field("inputs", Lite(&_val.inputs));
}
if let Some(val) = &_val.variadic {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Variadic);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("variadic", Print::ref_cast(val));
}
formatter.field("output", Lite(&_val.output));
formatter.finish()
}
}
impl Debug for Lite<syn::TypeGroup> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeGroup");
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
}
impl Debug for Lite<syn::TypeImplTrait> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeImplTrait");
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
}
impl Debug for Lite<syn::TypeInfer> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeInfer");
formatter.finish()
}
}
impl Debug for Lite<syn::TypeMacro> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeMacro");
formatter.field("mac", Lite(&_val.mac));
formatter.finish()
}
}
impl Debug for Lite<syn::TypeNever> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeNever");
formatter.finish()
}
}
impl Debug for Lite<syn::TypeParam> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeParam");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("ident", Lite(&_val.ident));
if let Some(val) = &_val.colon_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Colon);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("colon_token", Print::ref_cast(val));
}
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
if let Some(val) = &_val.eq_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Eq);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("eq_token", Print::ref_cast(val));
}
if let Some(val) = &_val.default {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Type);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("default", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::TypeParamBound> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::TypeParamBound::Trait(_val) => {
formatter.write_str("Trait")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::TypeParamBound::Lifetime(_val) => {
formatter.write_str("Lifetime")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::TypeParen> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeParen");
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
}
impl Debug for Lite<syn::TypePath> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypePath");
if let Some(val) = &_val.qself {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::QSelf);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("qself", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
}
impl Debug for Lite<syn::TypePtr> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypePtr");
if let Some(val) = &_val.const_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Const);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("const_token", Print::ref_cast(val));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
}
impl Debug for Lite<syn::TypeReference> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeReference");
if let Some(val) = &_val.lifetime {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::Lifetime);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("lifetime", Print::ref_cast(val));
}
if let Some(val) = &_val.mutability {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Mut);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("mutability", Print::ref_cast(val));
}
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
}
impl Debug for Lite<syn::TypeSlice> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeSlice");
formatter.field("elem", Lite(&_val.elem));
formatter.finish()
}
}
impl Debug for Lite<syn::TypeTraitObject> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeTraitObject");
if let Some(val) = &_val.dyn_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::Dyn);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("dyn_token", Print::ref_cast(val));
}
if !_val.bounds.is_empty() {
formatter.field("bounds", Lite(&_val.bounds));
}
formatter.finish()
}
}
impl Debug for Lite<syn::TypeTuple> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("TypeTuple");
if !_val.elems.is_empty() {
formatter.field("elems", Lite(&_val.elems));
}
formatter.finish()
}
}
impl Debug for Lite<syn::UnOp> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::UnOp::Deref(_val) => {
formatter.write_str("Deref")?;
Ok(())
}
syn::UnOp::Not(_val) => {
formatter.write_str("Not")?;
Ok(())
}
syn::UnOp::Neg(_val) => {
formatter.write_str("Neg")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::UseGlob> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("UseGlob");
formatter.finish()
}
}
impl Debug for Lite<syn::UseGroup> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("UseGroup");
if !_val.items.is_empty() {
formatter.field("items", Lite(&_val.items));
}
formatter.finish()
}
}
impl Debug for Lite<syn::UseName> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("UseName");
formatter.field("ident", Lite(&_val.ident));
formatter.finish()
}
}
impl Debug for Lite<syn::UsePath> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("UsePath");
formatter.field("ident", Lite(&_val.ident));
formatter.field("tree", Lite(&_val.tree));
formatter.finish()
}
}
impl Debug for Lite<syn::UseRename> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("UseRename");
formatter.field("ident", Lite(&_val.ident));
formatter.field("rename", Lite(&_val.rename));
formatter.finish()
}
}
impl Debug for Lite<syn::UseTree> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::UseTree::Path(_val) => {
formatter.write_str("Path")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::UseTree::Name(_val) => {
formatter.write_str("Name")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::UseTree::Rename(_val) => {
formatter.write_str("Rename")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::UseTree::Glob(_val) => {
formatter.write_str("Glob")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::UseTree::Group(_val) => {
formatter.write_str("Group")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}
impl Debug for Lite<syn::Variadic> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Variadic");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.finish()
}
}
impl Debug for Lite<syn::Variant> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("Variant");
if !_val.attrs.is_empty() {
formatter.field("attrs", Lite(&_val.attrs));
}
formatter.field("ident", Lite(&_val.ident));
formatter.field("fields", Lite(&_val.fields));
if let Some(val) = &_val.discriminant {
#[derive(RefCast)]
#[repr(transparent)]
struct Print((syn::token::Eq, syn::Expr));
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
let _val = &self.0;
formatter.write_str("(")?;
Debug::fmt(Lite(&_val.1), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
formatter.field("discriminant", Print::ref_cast(val));
}
formatter.finish()
}
}
impl Debug for Lite<syn::VisCrate> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("VisCrate");
formatter.finish()
}
}
impl Debug for Lite<syn::VisPublic> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("VisPublic");
formatter.finish()
}
}
impl Debug for Lite<syn::VisRestricted> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("VisRestricted");
if let Some(val) = &_val.in_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::In);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("in_token", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
}
impl Debug for Lite<syn::Visibility> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::Visibility::Public(_val) => {
let mut formatter = formatter.debug_struct("Visibility::Public");
formatter.finish()
}
syn::Visibility::Crate(_val) => {
let mut formatter = formatter.debug_struct("Visibility::Crate");
formatter.finish()
}
syn::Visibility::Restricted(_val) => {
let mut formatter = formatter.debug_struct("Visibility::Restricted");
if let Some(val) = &_val.in_token {
#[derive(RefCast)]
#[repr(transparent)]
struct Print(syn::token::In);
impl Debug for Print {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Some")?;
Ok(())
}
}
formatter.field("in_token", Print::ref_cast(val));
}
formatter.field("path", Lite(&_val.path));
formatter.finish()
}
syn::Visibility::Inherited => formatter.write_str("Inherited"),
}
}
}
impl Debug for Lite<syn::WhereClause> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
let mut formatter = formatter.debug_struct("WhereClause");
if !_val.predicates.is_empty() {
formatter.field("predicates", Lite(&_val.predicates));
}
formatter.finish()
}
}
impl Debug for Lite<syn::WherePredicate> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let _val = &self.value;
match _val {
syn::WherePredicate::Type(_val) => {
formatter.write_str("Type")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::WherePredicate::Lifetime(_val) => {
formatter.write_str("Lifetime")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
syn::WherePredicate::Eq(_val) => {
formatter.write_str("Eq")?;
formatter.write_str("(")?;
Debug::fmt(Lite(_val), formatter)?;
formatter.write_str(")")?;
Ok(())
}
}
}
}<|fim▁end|> | formatter.finish()
}
syn::ForeignItem::Macro(_val) => { |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Resolves identifiers to decide if they are macros, terminals, or
//! nonterminals. Rewrites the parse tree accordingly.
use super::{NormResult, NormError};
use grammar::parse_tree::*;
use intern::{InternedString};
use collections::{map, Map};
#[cfg(test)]
mod test;
pub fn resolve(mut grammar: Grammar) -> NormResult<Grammar> {
try!(resolve_in_place(&mut grammar));
Ok(grammar)
}
fn resolve_in_place(grammar: &mut Grammar) -> NormResult<()> {
let globals = {
let nonterminal_identifiers =
grammar.items
.iter()
.filter_map(|item| item.as_nonterminal())
.map(|nt| (nt.span, nt.name.0, Def::Nonterminal(nt.args.len())));
let terminal_identifiers =
grammar.items
.iter()
.filter_map(|item| item.as_extern_token())
.flat_map(|extern_token| extern_token.enum_token.as_ref())
.flat_map(|enum_token| &enum_token.conversions)
.filter_map(|conversion| match conversion.from {
TerminalString::Literal(..) => None,
TerminalString::Bare(id) => Some((conversion.span, id, Def::Terminal)),
});
let all_identifiers =
nonterminal_identifiers.chain(terminal_identifiers);
let mut identifiers = map();
for (span, id, def) in all_identifiers {
if let Some(old_def) = identifiers.insert(id, def) {
let description = def.description();
let old_description = old_def.description();
if description == old_description {
return_err!(
span,
"two {}s declared with the name `{}`",
description, id);
} else {
return_err!(
span,
"{} and {} both declared with the name `{}`",
description, old_description, id);
}
}
}
ScopeChain { previous: None, identifiers: identifiers }
};
let validator = Validator {
globals: globals,
};
validator.validate(grammar)
}
struct Validator {
globals: ScopeChain<'static>,
}
#[derive(Copy, Clone, Debug)]
enum Def {
Terminal,
Nonterminal(usize), // argument is the number of macro arguments
MacroArg,
}
#[derive(Debug)]
struct ScopeChain<'scope> {
previous: Option<&'scope ScopeChain<'scope>>,
identifiers: Map<InternedString, Def>,
}
impl Def {
fn description(&self) -> &'static str {
match *self {
Def::Terminal => "terminal",
Def::Nonterminal(0) => "nonterminal",
Def::Nonterminal(_) => "macro",
Def::MacroArg => "macro argument",
}
}
}
impl Validator {
fn validate(&self, grammar: &mut Grammar) -> NormResult<()> {
for item in &mut grammar.items {
match *item {
GrammarItem::Use(..) => { }
GrammarItem::InternToken(..) => {}
GrammarItem::ExternToken(..) => {}
GrammarItem::Nonterminal(ref mut data) => {
let identifiers = try!(self.validate_macro_args(data.span, &data.args));
let locals = ScopeChain {
previous: Some(&self.globals),
identifiers: identifiers,
};
for alternative in &mut data.alternatives {
try!(self.validate_alternative(&locals, alternative));
}
}
}
}
Ok(())
}
fn validate_macro_args(&self,
span: Span,
args: &[NonterminalString])
-> NormResult<Map<InternedString, Def>> {
for (index, arg) in args.iter().enumerate() {
if args[..index].contains(&arg) {
return_err!(span, "multiple macro arguments declared with the name `{}`", arg);
}
}
Ok(args.iter().map(|&nt| (nt.0, Def::MacroArg)).collect())
}
fn validate_alternative(&self,
scope: &ScopeChain,
alternative: &mut Alternative)
-> NormResult<()> {
if let Some(ref condition) = alternative.condition {
let def = try!(self.validate_id(scope, condition.span, condition.lhs.0));
match def {
Def::MacroArg => { /* OK */ }
_ => {
return_err!(condition.span,
"only macro arguments can be used in conditions, \
not {}s like `{}`",
def.description(), condition.lhs);
}
}
}
try!(self.validate_expr(scope, &mut alternative.expr));
Ok(())
}
fn validate_expr(&self,
scope: &ScopeChain,
expr: &mut ExprSymbol)
-> NormResult<()> {
for symbol in &mut expr.symbols {
try!(self.validate_symbol(scope, symbol));
}
Ok(())
}
fn validate_symbol(&self,
scope: &ScopeChain,
symbol: &mut Symbol)
-> NormResult<()> {
match symbol.kind {
SymbolKind::Expr(ref mut expr) => {
try!(self.validate_expr(scope, expr));
}
SymbolKind::AmbiguousId(name) => {
try!(self.rewrite_ambiguous_id(scope, name, symbol));
}
SymbolKind::Terminal(_) => {
/* see postvalidate! */
}
SymbolKind::Nonterminal(id) => {
// in normal operation, the parser never produces Nonterminal(_) entries,
// but during testing we do produce nonterminal entries
let def = try!(self.validate_id(scope, symbol.span, id.0));
match def {
Def::Nonterminal(0) |
Def::MacroArg => {
// OK
}
Def::Terminal |
Def::Nonterminal(_) => {
return_err!(symbol.span, "`{}` is a {}, not a nonterminal",
def.description(), id);
}
}
}
SymbolKind::Macro(ref mut msym) => {
debug_assert!(msym.args.len() > 0);
let def = try!(self.validate_id(scope, symbol.span, msym.name.0));
match def {
Def::Nonterminal(0) |
Def::Terminal |
Def::MacroArg => {
return_err!(symbol.span, "`{}` is a {}, not a macro",
def.description(), msym.name)
}
Def::Nonterminal(arity) => {
if arity != msym.args.len() {
return_err!(symbol.span,
"wrong number of arguments to `{}`: \
expected {}, found {}",
msym.name, arity, msym.args.len());
}
}
}
for arg in &mut msym.args {
try!(self.validate_symbol(scope, arg));
}
}
SymbolKind::Repeat(ref mut repeat) => {
try!(self.validate_symbol(scope, &mut repeat.symbol));
}
SymbolKind::Choose(ref mut sym) | SymbolKind::Name(_, ref mut sym) => {
try!(self.validate_symbol(scope, sym));
}
SymbolKind::Lookahead | SymbolKind::Lookbehind => {
}
}
Ok(())
}
fn rewrite_ambiguous_id(&self,
scope: &ScopeChain,
id: InternedString,
symbol: &mut Symbol)
-> NormResult<()> {
symbol.kind = match try!(self.validate_id(scope, symbol.span, id)) {<|fim▁hole|> };
Ok(())
}
fn validate_id(&self,
scope: &ScopeChain,
span: Span,
id: InternedString)
-> NormResult<Def> {
match scope.def(id) {
Some(def) => Ok(def),
None => return_err!(span, "no definition found for `{}`", id)
}
}
}
impl<'scope> ScopeChain<'scope> {
fn def(&self, id: InternedString) -> Option<Def> {
self.identifiers.get(&id)
.cloned()
.or_else(|| self.previous.and_then(|s| s.def(id)))
}
}<|fim▁end|> | Def::MacroArg |
Def::Nonterminal(0) => SymbolKind::Nonterminal(NonterminalString(id)),
Def::Terminal => SymbolKind::Terminal(TerminalString::Bare(id)),
Def::Nonterminal(_) => return_err!(symbol.span, "`{}` is a macro", id), |
<|file_name|>required.spec.ts<|end_file_name|><|fim▁begin|>import { FormControl } from '../../form-control';
import { RequiredValidator } from './required';
describe('Required validator', () => {
let formControl: FormControl<any>;
beforeEach(() => {
formControl = new FormControl<any>(
[RequiredValidator()]
);
});
it('if value is undefined, it should be invalid', () => {
formControl.validate();
expect(formControl.valid).toBe(false);
});
it('if value is empty array, it should be invalid', () => {
formControl.value = [];
formControl.validate();
expect(formControl.valid).toBe(false);
});
it('is value is empty string, it should be invalid', () => {
formControl.value = '';
formControl.validate();
expect(formControl.valid).toBe(false);
});
it('if value is 0, it should be valid', () => {
formControl.value = 0;
<|fim▁hole|> formControl.validate();
expect(formControl.valid).toBe(true);
});
it('if value is set, it should be valid', () => {
formControl.value = 'test';
formControl.validate();
expect(formControl.valid).toBe(true);
});
});<|fim▁end|> | |
<|file_name|>lexer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
from fsm import parse_automaton, accept
import re
__author__ = 'Roland'
import sys
keywords = ['float', 'char', 'print', 'input', 'break', 'continue', 'return', 'def', 'if', 'elif',
'else', 'while', 'or', 'and', 'not']
operators = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '/', '%']
separators = ['[', ']', '(', ')', ',', ':']
codif = ['var', 'const', '\n', 'indent', 'dedent'] + keywords + operators + separators
<|fim▁hole|>
def error(line_nr, msg):
"""
Show an error message `msg` found at line number `line_nr`
"""
print("Lexical error at line %d: %s" % (line_nr, msg))
def value_or_none(tree):
"""
Helper function to return string, even if given a tree, string or None
"""
if tree is None:
return 'None'
else:
if type(tree) == str:
return tree
return str(tree.value)
class binary_tree(object):
"""
Binary search tree. It remembers the order in which elements were added.
"""
def __init__(self, value):
"""
Constructor
"""
self.value = value
if self.value:
self.elements = [value]
else:
self.elements = []
self.left = None
self.right = None
def add(self, value):
"""
Add `value` to the tree to the correct place
"""
if self.value is None:
self.value = value
elif value < self.value:
if self.left:
self.left.add(value)
else:
self.left = binary_tree(value)
else:
if self.right:
self.right.add(value)
else:
self.right = binary_tree(value)
def __contains__(self, value):
"""
Search for `value` in the tree.
"""
if value == self.value:
return True
return (self.left and value in self.left) or (self.right and value in self.right)
def index(self, value):
"""
Return the parent and sibling node of `value`. Return None if it is not found,
and (None, None) for root node.
"""
if self.value == value:
return (None, None)
if self.right and value == self.right.value:
return self.value, self.left
if self.left and value == self.left.value:
return self.value, self.right
if self.left and value in self.left:
return self.left.index(value)
if self.right and value in self.right:
return self.right.index(value)
def __str__(self):
"""
String representation of the tree, using a table with parent and sibling relations.
"""
s = ""
for i, element in enumerate(self.elements):
parent, sibling = self.index(element)
s += (str(i) + " | " + str(element) + " | " + value_or_none(parent) + " | " + value_or_none(sibling) + "\n")
return s
def get_poz(atom, ts):
"""
Get the position of `atom` in the tree `ts`, and insert it if it's not in the tree.
"""
if atom not in ts:
ts.add(atom)
ts.elements.append(atom)
parent, sibling = ts.index(atom)
return ts.elements.index(atom)
var_lang = ["i a-z s B",
"i A-Z s B",
"s a-z s F",
"s A-z s F",
"s 0-9 s F",
"s [ t",
"t 0-9 f",
"f 0-9 f",
"f ] l F"]
var_aut = parse_automaton(var_lang)
num_lang = ["i 0 s B",
"i 1-9 t B",
"s . n",
"t 0-9 f", "t . n", "f 0-9 f", "f . n", "n 0-9 n F"]
num_aut = parse_automaton(num_lang)
def lexer(program):
"""
Function to do the actual lexing.
"""
ts_const = binary_tree(None)
ts_ident = binary_tree(None)
fip = []
indentation = [0]
for i, line in enumerate(program.splitlines()):
indent_level = len(line) - len(line.lstrip())
if indent_level != indentation[-1]:
if indent_level > indentation[-1]:
indentation.append(indent_level)
fip.append((codif.index('indent'), 0))
else:
while len(indentation) and indentation[-1] != indent_level:
fip.append((codif.index('dedent'), 0))
indentation.pop()
if len(indentation) == 0:
error(i, "incorrect indentation")
in_string = ""
for atom in re.split("( |=|<|>|==|>=|<=|!=|\+|-|\*|/|%|\[|\]|\(|\)|,|:)", line):
if len(atom.strip()) == 0 and not in_string:
continue
if '"' in atom:
if in_string:
in_string += atom
if re.search('[^ "a-zA-Z0-9]', in_string):
error(i, " invalid character in string constant")
continue
fip.append((1, get_poz(in_string, ts_const)))
in_string = ""
continue
else:
in_string = atom
continue
if in_string:
in_string += atom
continue
if atom in keywords or atom in operators or atom in separators:
fip.append((codif.index(atom), 0))
else:
if accept(*var_aut, string=atom) == True:
fip.append((0, get_poz(atom, ts_ident)))
elif accept(*num_aut, string=atom) == True:
fip.append((1, get_poz(atom, ts_const)))
else:
error(i, " unidentified expression " + atom)
if in_string:
error(i, " unterminated string constant ")
fip.append((codif.index('\n'), 0))
return fip, ts_const, ts_ident
if __name__ == "__main__":
if len(sys.argv) == 1:
print("You must give file to analyze as argument")
file = sys.argv[1]
f = open(file, "rb")
fip, ts_const, ts_ident = lexer(f.read())
print(fip)
print(ts_const)
print(ts_ident)<|fim▁end|> | |
<|file_name|>search.js<|end_file_name|><|fim▁begin|>// Search script generated by doxygen
// Copyright (C) 2009 by Dimitri van Heesch.
// The code in this file is loosly based on main.js, part of Natural Docs,
// which is Copyright (C) 2003-2008 Greg Valure
// Natural Docs is licensed under the GPL.
var indexSectionsWithContent =
{
0: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111001111000100001110010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
1: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
2: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
3: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100001101000000000100010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
4: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000110000100000100001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
5: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001011000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "files",
3: "functions",
4: "variables",
5: "defines"
};
function convertToId(search)
{
var result = '';
for (i=0;i<search.length;i++)
{
var c = search.charAt(i);
var cn = c.charCodeAt(0);
if (c.match(/[a-z0-9]/))
{
result+=c;
}
else if (cn<16)
{
result+="_0"+cn.toString(16);
}
else
{
result+="_"+cn.toString(16);
}
}
return result;
}
function getXPos(item)
{
var x = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
x += item.offsetLeft;
item = item.offsetParent;
}
}
return x;
}
function getYPos(item)
{
var y = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
y += item.offsetTop;
item = item.offsetParent;
}
}
return y;
}
/* A class handling everything associated with the search panel.
Parameters:
name - The name of the global variable that will be
storing this instance. Is needed to be able to set timeouts.
resultPath - path to use for external files
*/
function SearchBox(name, resultsPath, inFrame, label)
{
if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); }
// ---------- Instance variables
this.name = name;
this.resultsPath = resultsPath;
this.keyTimeout = 0;
this.keyTimeoutLength = 500;
this.closeSelectionTimeout = 300;
this.lastSearchValue = "";
this.lastResultsPage = "";
this.hideTimeout = 0;
this.searchIndex = 0;
this.searchActive = false;
this.insideFrame = inFrame;
this.searchLabel = label;
// ----------- DOM Elements
this.DOMSearchField = function()
{ return document.getElementById("MSearchField"); }
this.DOMSearchSelect = function()
{ return document.getElementById("MSearchSelect"); }
this.DOMSearchSelectWindow = function()
{ return document.getElementById("MSearchSelectWindow"); }
this.DOMPopupSearchResults = function()
{ return document.getElementById("MSearchResults"); }
this.DOMPopupSearchResultsWindow = function()
{ return document.getElementById("MSearchResultsWindow"); }
this.DOMSearchClose = function()
{ return document.getElementById("MSearchClose"); }
this.DOMSearchBox = function()
{ return document.getElementById("MSearchBox"); }
// ------------ Event Handlers
// Called when focus is added or removed from the search field.
this.OnSearchFieldFocus = function(isActive)
{<|fim▁hole|> this.Activate(isActive);
}
this.OnSearchSelectShow = function()
{
var searchSelectWindow = this.DOMSearchSelectWindow();
var searchField = this.DOMSearchSelect();
if (this.insideFrame)
{
var left = getXPos(searchField);
var top = getYPos(searchField);
left += searchField.offsetWidth + 6;
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
left -= searchSelectWindow.offsetWidth;
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
else
{
var left = getXPos(searchField);
var top = getYPos(searchField);
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
// stop selection hide timer
if (this.hideTimeout)
{
clearTimeout(this.hideTimeout);
this.hideTimeout=0;
}
return false; // to avoid "image drag" default event
}
this.OnSearchSelectHide = function()
{
this.hideTimeout = setTimeout(this.name +".CloseSelectionWindow()",
this.closeSelectionTimeout);
}
// Called when the content of the search field is changed.
this.OnSearchFieldChange = function(evt)
{
if (this.keyTimeout) // kill running timer
{
clearTimeout(this.keyTimeout);
this.keyTimeout = 0;
}
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 || e.keyCode==13)
{
if (e.shiftKey==1)
{
this.OnSearchSelectShow();
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
child.focus();
return;
}
}
return;
}
else if (window.frames.MSearchResults.searchResults)
{
var elem = window.frames.MSearchResults.searchResults.NavNext(0);
if (elem) elem.focus();
}
}
else if (e.keyCode==27) // Escape out of the search field
{
this.DOMSearchField().blur();
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
this.Activate(false);
return;
}
// strip whitespaces
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue != this.lastSearchValue) // search value has changed
{
if (searchValue != "") // non-empty search
{
// set timer for search update
this.keyTimeout = setTimeout(this.name + '.Search()',
this.keyTimeoutLength);
}
else // empty search field
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
}
}
}
this.SelectItemCount = function(id)
{
var count=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
count++;
}
}
return count;
}
this.SelectItemSet = function(id)
{
var i,j=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
var node = child.firstChild;
if (j==id)
{
node.innerHTML='•';
}
else
{
node.innerHTML=' ';
}
j++;
}
}
}
// Called when an search filter selection is made.
// set item with index id as the active item
this.OnSelectItem = function(id)
{
this.searchIndex = id;
this.SelectItemSet(id);
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue!="" && this.searchActive) // something was found -> do a search
{
this.Search();
}
}
this.OnSearchSelectKey = function(evt)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down
{
this.searchIndex++;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==38 && this.searchIndex>0) // Up
{
this.searchIndex--;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==13 || e.keyCode==27)
{
this.OnSelectItem(this.searchIndex);
this.CloseSelectionWindow();
this.DOMSearchField().focus();
}
return false;
}
// --------- Actions
// Closes the results window.
this.CloseResultsWindow = function()
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.Activate(false);
}
this.CloseSelectionWindow = function()
{
this.DOMSearchSelectWindow().style.display = 'none';
}
// Performs a search.
this.Search = function()
{
this.keyTimeout = 0;
// strip leading whitespace
var searchValue = this.DOMSearchField().value.replace(/^ +/, "");
var code = searchValue.toLowerCase().charCodeAt(0);
var hexCode;
if (code<16)
{
hexCode="0"+code.toString(16);
}
else
{
hexCode=code.toString(16);
}
var resultsPage;
var resultsPageWithSearch;
var hasResultsPage;
if (indexSectionsWithContent[this.searchIndex].charAt(code) == '1')
{
resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html';
resultsPageWithSearch = resultsPage+'?'+escape(searchValue);
hasResultsPage = true;
}
else // nothing available for this search term
{
resultsPage = this.resultsPath + '/nomatches.html';
resultsPageWithSearch = resultsPage;
hasResultsPage = false;
}
window.frames.MSearchResults.location = resultsPageWithSearch;
var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow();
if (domPopupSearchResultsWindow.style.display!='block')
{
var domSearchBox = this.DOMSearchBox();
this.DOMSearchClose().style.display = 'inline';
if (this.insideFrame)
{
var domPopupSearchResults = this.DOMPopupSearchResults();
domPopupSearchResultsWindow.style.position = 'relative';
domPopupSearchResultsWindow.style.display = 'block';
var width = document.body.clientWidth - 8; // the -8 is for IE :-(
domPopupSearchResultsWindow.style.width = width + 'px';
domPopupSearchResults.style.width = width + 'px';
}
else
{
var domPopupSearchResults = this.DOMPopupSearchResults();
var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth;
var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1;
domPopupSearchResultsWindow.style.display = 'block';
left -= domPopupSearchResults.offsetWidth;
domPopupSearchResultsWindow.style.top = top + 'px';
domPopupSearchResultsWindow.style.left = left + 'px';
}
}
this.lastSearchValue = searchValue;
this.lastResultsPage = resultsPage;
}
// -------- Activation Functions
// Activates or deactivates the search panel, resetting things to
// their default values if necessary.
this.Activate = function(isActive)
{
if (isActive || // open it
this.DOMPopupSearchResultsWindow().style.display == 'block'
)
{
this.DOMSearchBox().className = 'MSearchBoxActive';
var searchField = this.DOMSearchField();
if (searchField.value == this.searchLabel) // clear "Search" term upon entry
{
searchField.value = '';
this.searchActive = true;
}
}
else if (!isActive) // directly remove the panel
{
this.DOMSearchBox().className = 'MSearchBoxInactive';
this.DOMSearchField().value = this.searchLabel;
this.searchActive = false;
this.lastSearchValue = ''
this.lastResultsPage = '';
}
}
}
// -----------------------------------------------------------------------
// The class that handles everything on the search results page.
function SearchResults(name)
{
// The number of matches from the last run of <Search()>.
this.lastMatchCount = 0;
this.lastKey = 0;
this.repeatOn = false;
// Toggles the visibility of the passed element ID.
this.FindChildElement = function(id)
{
var parentElement = document.getElementById(id);
var element = parentElement.firstChild;
while (element && element!=parentElement)
{
if (element.nodeName == 'DIV' && element.className == 'SRChildren')
{
return element;
}
if (element.nodeName == 'DIV' && element.hasChildNodes())
{
element = element.firstChild;
}
else if (element.nextSibling)
{
element = element.nextSibling;
}
else
{
do
{
element = element.parentNode;
}
while (element && element!=parentElement && !element.nextSibling);
if (element && element!=parentElement)
{
element = element.nextSibling;
}
}
}
}
this.Toggle = function(id)
{
var element = this.FindChildElement(id);
if (element)
{
if (element.style.display == 'block')
{
element.style.display = 'none';
}
else
{
element.style.display = 'block';
}
}
}
// Searches for the passed string. If there is no parameter,
// it takes it from the URL query.
//
// Always returns true, since other documents may try to call it
// and that may or may not be possible.
this.Search = function(search)
{
if (!search) // get search word from URL
{
search = window.location.search;
search = search.substring(1); // Remove the leading '?'
search = unescape(search);
}
search = search.replace(/^ +/, ""); // strip leading spaces
search = search.replace(/ +$/, ""); // strip trailing spaces
search = search.toLowerCase();
search = convertToId(search);
var resultRows = document.getElementsByTagName("div");
var matches = 0;
var i = 0;
while (i < resultRows.length)
{
var row = resultRows.item(i);
if (row.className == "SRResult")
{
var rowMatchName = row.id.toLowerCase();
rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_'
if (search.length<=rowMatchName.length &&
rowMatchName.substr(0, search.length)==search)
{
row.style.display = 'block';
matches++;
}
else
{
row.style.display = 'none';
}
}
i++;
}
document.getElementById("Searching").style.display='none';
if (matches == 0) // no results
{
document.getElementById("NoMatches").style.display='block';
}
else // at least one result
{
document.getElementById("NoMatches").style.display='none';
}
this.lastMatchCount = matches;
return true;
}
// return the first item with index index or higher that is visible
this.NavNext = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index++;
}
return focusItem;
}
this.NavPrev = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index--;
}
return focusItem;
}
this.ProcessKeys = function(e)
{
if (e.type == "keydown")
{
this.repeatOn = false;
this.lastKey = e.keyCode;
}
else if (e.type == "keypress")
{
if (!this.repeatOn)
{
if (this.lastKey) this.repeatOn = true;
return false; // ignore first keypress after keydown
}
}
else if (e.type == "keyup")
{
this.lastKey = 0;
this.repeatOn = false;
}
return this.lastKey!=0;
}
this.Nav = function(evt,itemIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
var newIndex = itemIndex-1;
var focusItem = this.NavPrev(newIndex);
if (focusItem)
{
var child = this.FindChildElement(focusItem.parentNode.parentNode.id);
if (child && child.style.display == 'block') // children visible
{
var n=0;
var tmpElem;
while (1) // search for last child
{
tmpElem = document.getElementById('Item'+newIndex+'_c'+n);
if (tmpElem)
{
focusItem = tmpElem;
}
else // found it!
{
break;
}
n++;
}
}
}
if (focusItem)
{
focusItem.focus();
}
else // return focus to search field
{
parent.document.getElementById("MSearchField").focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = itemIndex+1;
var focusItem;
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem && elem.style.display == 'block') // children visible
{
focusItem = document.getElementById('Item'+itemIndex+'_c0');
}
if (!focusItem) focusItem = this.NavNext(newIndex);
if (focusItem) focusItem.focus();
}
else if (this.lastKey==39) // Right
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'block';
}
else if (this.lastKey==37) // Left
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'none';
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
this.NavChild = function(evt,itemIndex,childIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
if (childIndex>0)
{
var newIndex = childIndex-1;
document.getElementById('Item'+itemIndex+'_c'+newIndex).focus();
}
else // already at first child, jump to parent
{
document.getElementById('Item'+itemIndex).focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = childIndex+1;
var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex);
if (!elem) // last child, jump to parent next parent
{
elem = this.NavNext(itemIndex+1);
}
if (elem)
{
elem.focus();
}
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
}
function setKeyActions(elem,action)
{
elem.setAttribute('onkeydown',action);
elem.setAttribute('onkeypress',action);
elem.setAttribute('onkeyup',action);
}
function setClassAttr(elem,attr)
{
elem.setAttribute('class',attr);
elem.setAttribute('className',attr);
}
function createResults()
{
var results = document.getElementById("SRResults");
for (var e=0; e<searchData.length; e++)
{
var id = searchData[e][0];
var srResult = document.createElement('div');
srResult.setAttribute('id','SR_'+id);
setClassAttr(srResult,'SRResult');
var srEntry = document.createElement('div');
setClassAttr(srEntry,'SREntry');
var srLink = document.createElement('a');
srLink.setAttribute('id','Item'+e);
setKeyActions(srLink,'return searchResults.Nav(event,'+e+')');
setClassAttr(srLink,'SRSymbol');
srLink.innerHTML = searchData[e][1][0];
srEntry.appendChild(srLink);
if (searchData[e][1].length==2) // single result
{
srLink.setAttribute('href',searchData[e][1][1][0]);
if (searchData[e][1][1][1])
{
srLink.setAttribute('target','_parent');
}
var srScope = document.createElement('span');
setClassAttr(srScope,'SRScope');
srScope.innerHTML = searchData[e][1][1][2];
srEntry.appendChild(srScope);
}
else // multiple results
{
srLink.setAttribute('href','javascript:searchResults.Toggle("SR_'+id+'")');
var srChildren = document.createElement('div');
setClassAttr(srChildren,'SRChildren');
for (var c=0; c<searchData[e][1].length-1; c++)
{
var srChild = document.createElement('a');
srChild.setAttribute('id','Item'+e+'_c'+c);
setKeyActions(srChild,'return searchResults.NavChild(event,'+e+','+c+')');
setClassAttr(srChild,'SRScope');
srChild.setAttribute('href',searchData[e][1][c+1][0]);
if (searchData[e][1][c+1][1])
{
srChild.setAttribute('target','_parent');
}
srChild.innerHTML = searchData[e][1][c+1][2];
srChildren.appendChild(srChild);
}
srEntry.appendChild(srChildren);
}
srResult.appendChild(srEntry);
results.appendChild(srResult);
}
}<|fim▁end|> | |
<|file_name|>functional_tests.py<|end_file_name|><|fim▁begin|>from selenium import webdriver
from django.test import LiveServerTestCase, TestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import datetime
from planner.models import Participation, Event, Occurrence, EventType, Role
from django.contrib.auth.models import User
import pytz
import time
tz = pytz.timezone("Europe/Stockholm")
def event(date):
e = Event.objects.create(title="TestEvent", event_type=EventType.objects.get(name="Gudstjänst"))
e.event = Occurrence.objects.create(start_time = tz.localize(date))
Participation.objects.create(user = User.objects.get(pk=2), event = e, attending = "true", role = Role.objects.get(name = "Mötesledare"))
Participation.objects.create(user = User.objects.get(pk=3), event = e, attending = "null", role = Role.objects.get(name = "Textläsare"))
e.save()
def login(browser):
browser.find_element_by_id('id_username').send_keys("admin")
browser.find_element_by_id('id_password').send_keys("1234")
browser.find_element_by_id('id_submit').click()
class BasicTest(StaticLiveServerTestCase):
fixtures = ["fixture1.json"]
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_login(self):
self.browser.get(self.live_server_url)
assert "Planering" in self.browser.title
login(self.browser)
menu = self.browser.find_element_by_id('main-menu').text
assert 'Nytt evenemang' in menu
assert 'Tabellvy' in menu
def test_event_is_displayed(self):
event(datetime.datetime.now() + datetime.timedelta(days = 17))
self.browser.get(self.live_server_url)
login(self.browser)
t = self.browser.find_element_by_id("table-scroll").text
time.sleep(10)
print(t)
assert 'Testevenemang' in t<|fim▁hole|><|fim▁end|> |
if __name__ == '__main__':
unittest.main() |
<|file_name|>compiler.ts<|end_file_name|><|fim▁begin|>import {Binding, resolveForwardRef, Injectable, Inject} from 'angular2/src/core/di';
import {DEFAULT_PIPES_TOKEN} from 'angular2/src/core/pipes';
import {
Type,
isBlank,
isType,
isPresent,
normalizeBlank,
stringify,
isArray,
isPromise
} from 'angular2/src/core/facade/lang';
import {BaseException} from 'angular2/src/core/facade/exceptions';
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
import {ListWrapper, Map, MapWrapper} from 'angular2/src/core/facade/collection';
import {DirectiveResolver} from './directive_resolver';
import {AppProtoView, AppProtoViewMergeMapping} from './view';
import {ProtoViewRef} from './view_ref';
import {DirectiveBinding} from './element_injector';
import {ViewResolver} from './view_resolver';
import {PipeResolver} from './pipe_resolver';
import {ViewMetadata} from 'angular2/src/core/metadata';
import {ComponentUrlMapper} from './component_url_mapper';
import {ProtoViewFactory} from './proto_view_factory';
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
import {AppRootUrl} from 'angular2/src/core/services/app_root_url';
import {ElementBinder} from './element_binder';
import {wtfStartTimeRange, wtfEndTimeRange} from '../profile/profile';
import {PipeBinding} from '../pipes/pipe_binding';
import {
RenderDirectiveMetadata,
ViewDefinition,
RenderCompiler,
ViewType,
RenderProtoViewMergeMapping,
RenderProtoViewRef
} from 'angular2/src/core/render/api';
/**
* Cache that stores the AppProtoView of the template of a component.
* Used to prevent duplicate work and resolve cyclic dependencies.
*/
@Injectable()
export class CompilerCache {
_cache = new Map<Type, AppProtoView>();
_hostCache = new Map<Type, AppProtoView>();
set(component: Type, protoView: AppProtoView): void { this._cache.set(component, protoView); }
get(component: Type): AppProtoView {
var result = this._cache.get(component);
return normalizeBlank(result);
}
setHost(component: Type, protoView: AppProtoView): void {
this._hostCache.set(component, protoView);
}
getHost(component: Type): AppProtoView {
var result = this._hostCache.get(component);
return normalizeBlank(result);
}
clear(): void {
this._cache.clear();
this._hostCache.clear();
}
}
/*
* ## URL Resolution
*
* ```
* var appRootUrl: AppRootUrl = ...;
* var componentUrlMapper: ComponentUrlMapper = ...;
* var urlResolver: UrlResolver = ...;
*
* var componentType: Type = ...;
* var componentAnnotation: ComponentAnnotation = ...;
* var viewAnnotation: ViewAnnotation = ...;
*
* // Resolving a URL
*
* var url = viewAnnotation.templateUrl;
* var componentUrl = componentUrlMapper.getUrl(componentType);
* var componentResolvedUrl = urlResolver.resolve(appRootUrl.value, componentUrl);
* var templateResolvedUrl = urlResolver.resolve(componentResolvedUrl, url);
* ```
*/
/**
* Low-level service for compiling {@link Component}s into {@link ProtoViewRef ProtoViews}s, which
* can later be used to create and render a Component instance.
*
* Most applications should instead use higher-level {@link DynamicComponentLoader} service, which
* both compiles and instantiates a Component.
*/
@Injectable()
export class Compiler {
private _compiling = new Map<Type, Promise<AppProtoView>>();
private _appUrl: string;
private _defaultPipes: Type[];
/**
* @private
*/
constructor(private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver,
@Inject(DEFAULT_PIPES_TOKEN) _defaultPipes: Type[],
private _compilerCache: CompilerCache, private _viewResolver: ViewResolver,
private _componentUrlMapper: ComponentUrlMapper, private _urlResolver: UrlResolver,
private _render: RenderCompiler, private _protoViewFactory: ProtoViewFactory,
appUrl: AppRootUrl) {
this._defaultPipes = _defaultPipes;
this._appUrl = appUrl.value;
}
private _bindDirective(directiveTypeOrBinding): DirectiveBinding {
if (directiveTypeOrBinding instanceof DirectiveBinding) {
return directiveTypeOrBinding;
} else if (directiveTypeOrBinding instanceof Binding) {
let annotation = this._directiveResolver.resolve(directiveTypeOrBinding.token);
return DirectiveBinding.createFromBinding(directiveTypeOrBinding, annotation);
} else {
let annotation = this._directiveResolver.resolve(directiveTypeOrBinding);
return DirectiveBinding.createFromType(directiveTypeOrBinding, annotation);
}
}
private _bindPipe(typeOrBinding): PipeBinding {
let meta = this._pipeResolver.resolve(typeOrBinding);
return PipeBinding.createFromType(typeOrBinding, meta);
}
/**
* Compiles a {@link Component} and returns a promise for this component's {@link ProtoViewRef}.
*
* Returns `ProtoViewRef` that can be later used to instantiate a component via
* {@link ViewContainerRef#createHostView} or {@link AppViewManager#createHostViewInContainer}.
*/
compileInHost(componentType: Type): Promise<ProtoViewRef> {
var r = wtfStartTimeRange('Compiler#compile()', stringify(componentType));
var hostAppProtoView = this._compilerCache.getHost(componentType);
var hostPvPromise;
if (isPresent(hostAppProtoView)) {
hostPvPromise = PromiseWrapper.resolve(hostAppProtoView);
} else {
var componentBinding: DirectiveBinding = this._bindDirective(componentType);
Compiler._assertTypeIsComponent(componentBinding);
var directiveMetadata = componentBinding.metadata;
hostPvPromise = this._render.compileHost(directiveMetadata)
.then((hostRenderPv) => {
var protoViews = this._protoViewFactory.createAppProtoViews(
componentBinding, hostRenderPv, [componentBinding], []);
return this._compileNestedProtoViews(protoViews, componentType,
new Map<Type, AppProtoView>());
})
.then((appProtoView) => {
this._compilerCache.setHost(componentType, appProtoView);
return appProtoView;
});
}
return hostPvPromise.then((hostAppProtoView) => {
wtfEndTimeRange(r);
return hostAppProtoView.ref;
});
}
private _compile(componentBinding: DirectiveBinding,
componentPath: Map<Type, AppProtoView>): Promise<AppProtoView>|
AppProtoView {
var component = <Type>componentBinding.key.token;
var protoView = this._compilerCache.get(component);
if (isPresent(protoView)) {
// The component has already been compiled into an AppProtoView,
// returns a plain AppProtoView, not wrapped inside of a Promise, for performance reasons.
return protoView;
}
var resultPromise = this._compiling.get(component);
if (isPresent(resultPromise)) {
// The component is already being compiled, attach to the existing Promise
// instead of re-compiling the component.
// It happens when a template references a component multiple times.
return resultPromise;
}
var view = this._viewResolver.resolve(component);
var directives = this._flattenDirectives(view);
for (var i = 0; i < directives.length; i++) {
if (!Compiler._isValidDirective(directives[i])) {
throw new BaseException(
`Unexpected directive value '${stringify(directives[i])}' on the View of component '${stringify(component)}'`);
}
}
var boundDirectives = this._removeDuplicatedDirectives(
directives.map(directive => this._bindDirective(directive)));
var pipes = this._flattenPipes(view);
var boundPipes = pipes.map(pipe => this._bindPipe(pipe));
var renderTemplate = this._buildRenderTemplate(component, view, boundDirectives);
resultPromise =
this._render.compile(renderTemplate)
.then((renderPv) => {
var protoViews = this._protoViewFactory.createAppProtoViews(
componentBinding, renderPv, boundDirectives, boundPipes);
return this._compileNestedProtoViews(protoViews, component, componentPath);
})
.then((appProtoView) => {
this._compilerCache.set(component, appProtoView);
MapWrapper.delete(this._compiling, component);
return appProtoView;
});
this._compiling.set(component, resultPromise);
return resultPromise;
}
private _removeDuplicatedDirectives(directives: DirectiveBinding[]): DirectiveBinding[] {
var directivesMap = new Map<number, DirectiveBinding>();
directives.forEach((dirBinding) => { directivesMap.set(dirBinding.key.id, dirBinding); });
return MapWrapper.values(directivesMap);
}
private _compileNestedProtoViews(appProtoViews: AppProtoView[], componentType: Type,
componentPath: Map<Type, AppProtoView>): Promise<AppProtoView> {
var nestedPVPromises = [];
componentPath = MapWrapper.clone(componentPath);
if (appProtoViews[0].type === ViewType.COMPONENT) {
componentPath.set(componentType, appProtoViews[0]);
}
appProtoViews.forEach(appProtoView => {
this._collectComponentElementBinders(appProtoView)
.forEach((elementBinder: ElementBinder) => {
var nestedComponent = elementBinder.componentDirective;
var nestedComponentType = <Type>nestedComponent.key.token;
var elementBinderDone =
(nestedPv: AppProtoView) => { elementBinder.nestedProtoView = nestedPv; };
if (componentPath.has(nestedComponentType)) {
// cycle...
if (appProtoView.isEmbeddedFragment) {
throw new BaseException(
`<ng-content> is used within the recursive path of ${stringify(nestedComponentType)}`);
} else if (appProtoView.type === ViewType.COMPONENT) {
throw new BaseException(
`Unconditional component cycle in ${stringify(nestedComponentType)}`);
} else {
elementBinderDone(componentPath.get(nestedComponentType));
}
} else {
var nestedCall = this._compile(nestedComponent, componentPath);
if (isPromise(nestedCall)) {
nestedPVPromises.push((<Promise<AppProtoView>>nestedCall).then(elementBinderDone));
} else {
elementBinderDone(<AppProtoView>nestedCall);
}
}
});
});
return PromiseWrapper.all(nestedPVPromises)
.then(_ => PromiseWrapper.all(
appProtoViews.map(appProtoView => this._mergeProtoView(appProtoView))))
.then(_ => appProtoViews[0]);
}
private _mergeProtoView(appProtoView: AppProtoView): Promise<any> {
if (appProtoView.type !== ViewType.HOST && appProtoView.type !== ViewType.EMBEDDED) {
return null;
}
return this._render.mergeProtoViewsRecursively(this._collectMergeRenderProtoViews(appProtoView))
.then((mergeResult: RenderProtoViewMergeMapping) => {
appProtoView.mergeMapping = new AppProtoViewMergeMapping(mergeResult);
});
}
private _collectMergeRenderProtoViews(appProtoView:
AppProtoView): Array<RenderProtoViewRef | any[]> {
var result = [appProtoView.render];
for (var i = 0; i < appProtoView.elementBinders.length; i++) {
var binder = appProtoView.elementBinders[i];
if (isPresent(binder.nestedProtoView)) {<|fim▁hole|> (binder.hasEmbeddedProtoView() && binder.nestedProtoView.isEmbeddedFragment)) {
result.push(this._collectMergeRenderProtoViews(binder.nestedProtoView));
} else {
result.push(null);
}
}
}
return result;
}
private _collectComponentElementBinders(appProtoView: AppProtoView): ElementBinder[] {
var componentElementBinders = [];
appProtoView.elementBinders.forEach((elementBinder) => {
if (isPresent(elementBinder.componentDirective)) {
componentElementBinders.push(elementBinder);
}
});
return componentElementBinders;
}
private _buildRenderTemplate(component, view, directives): ViewDefinition {
var componentUrl =
this._urlResolver.resolve(this._appUrl, this._componentUrlMapper.getUrl(component));
var templateAbsUrl = null;
var styleAbsUrls = null;
if (isPresent(view.templateUrl) && view.templateUrl.trim().length > 0) {
templateAbsUrl = this._urlResolver.resolve(componentUrl, view.templateUrl);
} else if (isPresent(view.template)) {
// Note: If we have an inline template, we also need to send
// the url for the component to the render so that it
// is able to resolve urls in stylesheets.
templateAbsUrl = componentUrl;
}
if (isPresent(view.styleUrls)) {
styleAbsUrls =
ListWrapper.map(view.styleUrls, url => this._urlResolver.resolve(componentUrl, url));
}
return new ViewDefinition({
componentId: stringify(component),
templateAbsUrl: templateAbsUrl, template: view.template,
styleAbsUrls: styleAbsUrls,
styles: view.styles,
directives: ListWrapper.map(directives, directiveBinding => directiveBinding.metadata),
encapsulation: view.encapsulation
});
}
private _flattenPipes(view: ViewMetadata): any[] {
if (isBlank(view.pipes)) return this._defaultPipes;
var pipes = ListWrapper.clone(this._defaultPipes);
this._flattenList(view.pipes, pipes);
return pipes;
}
private _flattenDirectives(view: ViewMetadata): Type[] {
if (isBlank(view.directives)) return [];
var directives = [];
this._flattenList(view.directives, directives);
return directives;
}
private _flattenList(tree: any[], out: Array<Type | Binding | any[]>): void {
for (var i = 0; i < tree.length; i++) {
var item = resolveForwardRef(tree[i]);
if (isArray(item)) {
this._flattenList(item, out);
} else {
out.push(item);
}
}
}
private static _isValidDirective(value: Type | Binding): boolean {
return isPresent(value) && (value instanceof Type || value instanceof Binding);
}
private static _assertTypeIsComponent(directiveBinding: DirectiveBinding): void {
if (directiveBinding.metadata.type !== RenderDirectiveMetadata.COMPONENT_TYPE) {
throw new BaseException(
`Could not load '${stringify(directiveBinding.key.token)}' because it is not a component.`);
}
}
}<|fim▁end|> | if (binder.hasStaticComponent() || |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import datetime
import requests
from django.test import TestCase
from wikidata import wikidata
from person.models import Person
from person.util import parse_name_surname_initials, parse_surname_comma_surname_prefix
class TestFindName(TestCase):
@classmethod
def setUpTestData(cls):
cls.p1 = Person.objects.create(forename='Jan Peter', surname='Balkenende', initials='J.P.')
cls.p2 = Person.objects.create(forename='Jan', surname='Balkenende', initials='J.')
cls.p3 = Person.objects.create(forename='Jan', surname='Balkenende', surname_prefix='van', initials='J.')
cls.p4 = Person.objects.create(forename='Jan Peter', surname='Balkenende', surname_prefix='van', initials='J.P.')
cls.p5 = Person.objects.create(forename='Fatma', surname='Koşer Kaya', surname_prefix='', initials='F.')
cls.p6 = Person.objects.create(forename='Jan Peter', surname='Balkenende', initials='')
cls.p7 = Person.objects.create(forename='', surname='van Raak', initials='')
cls.p8 = Person.objects.create(forename='', surname='Grapperhaus', initials='F.B.J.')
cls.p9 = Person.objects.create(forename='Ferdinand', surname='Grapperhaus', initials='F.B.J.')
def test_find_by_fullname(self):
p_found = Person.find_by_fullname('Jan Peter Balkenende')
self.assertEqual(self.p1, p_found)
p_found = Person.find_by_fullname('Jan Balkenende')
self.assertEqual(self.p2, p_found)
p_found = Person.find_by_fullname('Jan van Balkenende')
self.assertEqual(self.p3, p_found)
p_found = Person.find_by_fullname('Jan Peter van Balkenende')
self.assertEqual(self.p4, p_found)
p_found = Person.find_by_fullname('Jan Jaap van Balkenende')
self.assertEqual(None, p_found)
p_found = Person.find_by_fullname('van Raak')
self.assertEqual(self.p7, p_found)
def test_find_by_surname_initials(self):
p_found = Person.find_surname_initials('Balkenende', 'J.P.')
self.assertEqual(p_found, self.p1)
p_found = Person.find_surname_initials('Balkenende', 'J.')
self.assertEqual(p_found, self.p2)
p_found = Person.find_surname_initials('Balkenende', '')
self.assertEqual(p_found, None)
p_found = Person.find_surname_initials('van der Steur', 'J.P.')
self.assertEqual(p_found, None)
p_found = Person.find_surname_initials('Koşer Kaya', 'F.')
self.assertEqual(p_found, self.p5)
def test_find_surname_multiple(self):
p_found = Person.find_surname_initials('Grapperhaus', 'F.B.J.')
self.assertEqual(p_found, self.p9)
class TestNamePrefix(TestCase):
def test_find_name_prefix(self):
name = 'Ard van der Steur'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'van der')
name = 'Ard van derSteur'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'van')
name = 'Ard van de Steur'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'van de')
name = 'Ard van Steur'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'van')
name = 'Gerard \'t Hooft'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, '\'t')
name = 'Jan Peter Balkenende'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, '')
name = 'Boris van der Ham'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'van der')
name = 'van der Ham'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'van der')
name = 'van derHam'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'van')
name = 'von Martels'
prefix, pos = Person.find_prefix(name)
self.assertEqual(prefix, 'von')
def test_parse_surname_surname_prefix(self):
surname_expected = 'Ham'
surname_prefix_expected = 'van der'
surname, surname_prefix = parse_surname_comma_surname_prefix('Ham, van der')
self.assertEqual(surname, surname_expected)
self.assertEqual(surname_prefix, surname_prefix_expected)
class TestCreatePerson(TestCase):
def test_create_person(self):
forename = 'Mark'
surname = 'Rutte'
person = Person.objects.create(forename=forename, surname=surname)
self.assertEqual(Person.objects.count(), 1)
self.assertTrue(Person.person_exists(forename, surname))
person.update_info(language='nl')
person.save()
self.assertEqual(person.wikidata_id, 'Q57792')
self.assertEqual(person.wikimedia_image_name.split('.')[1], 'jpg')
response = requests.get(person.wikimedia_image_url, timeout=60)
self.assertEqual(response.status_code, 200)
self.assertEqual(person.birthdate, datetime.date(1967, 2, 14))<|fim▁hole|>
class TestWikidataNameParts(TestCase):
def test_fatma_koser_kaya(self):
wikidata_id = 'Q467610' # Fatma Koşer Kaya
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Fatma')
self.assertEqual(surname, 'Koşer Kaya')
self.assertEqual(surname_prefix, '')
def test_jan_peter_balkenende(self):
wikidata_id = 'Q133386'
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Jan Peter')
self.assertEqual(surname, 'Balkenende')
self.assertEqual(surname_prefix, '')
def test_jan_kees_de_jager(self):
wikidata_id = 'Q1666631'
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Jan Kees')
self.assertEqual(surname, 'Jager')
self.assertEqual(surname_prefix, 'de')
def test_sjoerd_sjoerdsma(self):
wikidata_id = 'Q516335'
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Sjoerd')
self.assertEqual(surname, 'Sjoerdsma')
self.assertEqual(surname_prefix, '')
def test_sybrand_van_haersma_buma(self):
wikidata_id = 'Q377266'
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Sybrand')
self.assertEqual(surname, 'Haersma Buma')
self.assertEqual(surname_prefix, 'van')
def test_chantal_nijkerken_de_haan(self):
wikidata_id = 'Q19830701'
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Chantal')
self.assertEqual(surname, 'Nijkerken-de Haan')
def test_leendert_de_lange(self):
wikidata_id = 'Q19839084'
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Leendert')
self.assertEqual(surname_prefix, 'de')
self.assertEqual(surname, 'Lange')
def test_melanie_schultz_van_hagen(self):
wikidata_id = 'Q435886'
wikidata_item = wikidata.WikidataItem(wikidata_id)
fullname = wikidata_item.get_label()
forename, surname, surname_prefix = Person.get_name_parts(fullname, wikidata_item)
self.assertEqual(forename, 'Melanie')
self.assertEqual(surname_prefix, '')
self.assertEqual(surname, 'Schultz van Haegen')
class TestParseName(TestCase):
""" Tests name parsing """
initials_expected = 'P.A.'
surname_expected = 'Dijkstra'
def check_result(self, initials, surname):
self.assertEqual(initials, self.initials_expected)
self.assertEqual(surname, self.surname_expected)
def test_initials_surname(self):
name = 'P.A. Dijkstra'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
def test_initials_surname_forname(self):
name = 'P.A. (Pia) Dijkstra'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
name = 'P.A. (Pia)Dijkstra'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
def test_surname_initials(self):
name = 'Dijkstra, P.A.'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
name = 'Dijkstra,P.A.'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
name = 'Dijkstra P.A.'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
name = 'Dijkstra P.A. (Pia)'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
name = 'Dijkstra, (Pia) P.A.'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
def test_surname_initials_forname(self):
name = 'Dijkstra, P.A.(Pia)'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
name = 'Dijkstra, P.A. (Pia)'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
name = 'Dijkstra,P.A.(Pia)'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.check_result(initials, surname)
def test_surname_prefix(self):
name = 'van Dijkstra, P.A.(Pia)'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.assertEqual(surname_prefix, 'van')
self.check_result(initials, surname)
name = 'Dijkstra van, P.A. (Pia)'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.assertEqual(surname_prefix, 'van')
self.check_result(initials, surname)
name = 'van Dijkstra,P.A.(Pia)'
initials, surname, surname_prefix = parse_name_surname_initials(name)
self.assertEqual(surname_prefix, 'van')
self.check_result(initials, surname)
# TODO BR: fix and enable
# def test_initials_multicharacter(self):
# name = 'A.Th.B. Bijleveld-Schouten'
# initials, surname, surname_prefix = parse_name_surname_initials(name)
# self.assertEqual(initials, 'A.Th.B.')<|fim▁end|> | self.assertEqual(person.slug, 'mark-rutte') |
<|file_name|>test_format.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Test output formatting for Series/DataFrame, including to_string & reprs
"""
from __future__ import print_function
from datetime import datetime
import itertools
from operator import methodcaller
import os
import re
import sys
import textwrap
import warnings
import dateutil
import numpy as np
import pytest
import pytz
import pandas.compat as compat
from pandas.compat import (
PY3, StringIO, is_platform_32bit, is_platform_windows, lrange, lzip, range,
u, zip)
import pandas as pd
from pandas import (
DataFrame, Index, MultiIndex, NaT, Series, Timestamp, date_range, read_csv)
from pandas.core.config import (
get_option, option_context, reset_option, set_option)
import pandas.util.testing as tm
import pandas.io.formats.format as fmt
import pandas.io.formats.printing as printing
from pandas.io.formats.terminal import get_terminal_size
use_32bit_repr = is_platform_windows() or is_platform_32bit()
_frame = DataFrame(tm.getSeriesData())
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))
return pth
def has_info_repr(df):
r = repr(df)
c1 = r.split('\n')[0].startswith("<class")
c2 = r.split('\n')[0].startswith(r"<class") # _repr_html_
return c1 or c2
def has_non_verbose_info_repr(df):
has_info = has_info_repr(df)
r = repr(df)
# 1. <class>
# 2. Index
# 3. Columns
# 4. dtype
# 5. memory usage
# 6. trailing newline
nv = len(r.split('\n')) == 6
return has_info and nv
def has_horizontally_truncated_repr(df):
try: # Check header row
fst_line = np.array(repr(df).splitlines()[0].split())
cand_col = np.where(fst_line == '...')[0][0]
except IndexError:
return False
# Make sure each row has this ... in the same place
r = repr(df)
for ix, l in enumerate(r.splitlines()):
if not r.split()[cand_col] == '...':
return False
return True
def has_vertically_truncated_repr(df):
r = repr(df)
only_dot_row = False
for row in r.splitlines():
if re.match(r'^[\.\ ]+$', row):
only_dot_row = True
return only_dot_row
def has_truncated_repr(df):
return has_horizontally_truncated_repr(
df) or has_vertically_truncated_repr(df)
def has_doubly_truncated_repr(df):
return has_horizontally_truncated_repr(
df) and has_vertically_truncated_repr(df)
def has_expanded_repr(df):
r = repr(df)
for line in r.split('\n'):
if line.endswith('\\'):
return True
return False
class TestDataFrameFormatting(object):
def setup_method(self, method):
self.warn_filters = warnings.filters
warnings.filterwarnings('ignore', category=FutureWarning,
module=".*format")
self.frame = _frame.copy()
def teardown_method(self, method):
warnings.filters = self.warn_filters
def test_repr_embedded_ndarray(self):
arr = np.empty(10, dtype=[('err', object)])
for i in range(len(arr)):
arr['err'][i] = np.random.randn(i)
df = DataFrame(arr)
repr(df['err'])
repr(df)
df.to_string()
def test_eng_float_formatter(self):
self.frame.loc[5] = 0
fmt.set_eng_float_format()
repr(self.frame)
fmt.set_eng_float_format(use_eng_prefix=True)
repr(self.frame)
fmt.set_eng_float_format(accuracy=0)
repr(self.frame)
tm.reset_display_options()
def test_show_null_counts(self):
df = DataFrame(1, columns=range(10), index=range(10))
df.iloc[1, 1] = np.nan
def check(null_counts, result):
buf = StringIO()
df.info(buf=buf, null_counts=null_counts)
assert ('non-null' in buf.getvalue()) is result
with option_context('display.max_info_rows', 20,
'display.max_info_columns', 20):
check(None, True)
check(True, True)
check(False, False)
with option_context('display.max_info_rows', 5,
'display.max_info_columns', 5):
check(None, False)
check(True, False)
check(False, False)
def test_repr_tuples(self):
buf = StringIO()
df = DataFrame({'tups': lzip(range(10), range(10))})
repr(df)
df.to_string(col_space=10, buf=buf)
def test_repr_truncation(self):
max_len = 20
with option_context("display.max_colwidth", max_len):
df = DataFrame({'A': np.random.randn(10),
'B': [tm.rands(np.random.randint(
max_len - 1, max_len + 1)) for i in range(10)
]})
r = repr(df)
r = r[r.find('\n') + 1:]
adj = fmt._get_adjustment()
for line, value in lzip(r.split('\n'), df['B']):
if adj.len(value) + 1 > max_len:
assert '...' in line
else:
assert '...' not in line
with option_context("display.max_colwidth", 999999):
assert '...' not in repr(df)
with option_context("display.max_colwidth", max_len + 2):
assert '...' not in repr(df)
def test_repr_chop_threshold(self):
df = DataFrame([[0.1, 0.5], [0.5, -0.1]])
pd.reset_option("display.chop_threshold") # default None
assert repr(df) == ' 0 1\n0 0.1 0.5\n1 0.5 -0.1'
with option_context("display.chop_threshold", 0.2):
assert repr(df) == ' 0 1\n0 0.0 0.5\n1 0.5 0.0'
with option_context("display.chop_threshold", 0.6):
assert repr(df) == ' 0 1\n0 0.0 0.0\n1 0.0 0.0'
with option_context("display.chop_threshold", None):
assert repr(df) == ' 0 1\n0 0.1 0.5\n1 0.5 -0.1'
def test_repr_chop_threshold_column_below(self):
# GH 6839: validation case
df = pd.DataFrame([[10, 20, 30, 40],
[8e-10, -1e-11, 2e-9, -2e-11]]).T
with option_context("display.chop_threshold", 0):
assert repr(df) == (' 0 1\n'
'0 10.0 8.000000e-10\n'
'1 20.0 -1.000000e-11\n'
'2 30.0 2.000000e-09\n'
'3 40.0 -2.000000e-11')
with option_context("display.chop_threshold", 1e-8):
assert repr(df) == (' 0 1\n'
'0 10.0 0.000000e+00\n'
'1 20.0 0.000000e+00\n'
'2 30.0 0.000000e+00\n'
'3 40.0 0.000000e+00')
with option_context("display.chop_threshold", 5e-11):
assert repr(df) == (' 0 1\n'
'0 10.0 8.000000e-10\n'
'1 20.0 0.000000e+00\n'
'2 30.0 2.000000e-09\n'
'3 40.0 0.000000e+00')
def test_repr_obeys_max_seq_limit(self):
with option_context("display.max_seq_items", 2000):
assert len(printing.pprint_thing(lrange(1000))) > 1000
with option_context("display.max_seq_items", 5):
assert len(printing.pprint_thing(lrange(1000))) < 100
def test_repr_set(self):
assert printing.pprint_thing({1}) == '{1}'
def test_repr_is_valid_construction_code(self):
# for the case of Index, where the repr is traditional rather then
# stylized
idx = Index(['a', 'b'])
res = eval("pd." + repr(idx))
tm.assert_series_equal(Series(res), Series(idx))
def test_repr_should_return_str(self):
# https://docs.python.org/3/reference/datamodel.html#object.__repr__
# "...The return value must be a string object."
# (str on py2.x, str (unicode) on py3)
data = [8, 5, 3, 5]
index1 = [u("\u03c3"), u("\u03c4"), u("\u03c5"), u("\u03c6")]
cols = [u("\u03c8")]
df = DataFrame(data, columns=cols, index=index1)
assert type(df.__repr__()) == str # both py2 / 3
def test_repr_no_backslash(self):
with option_context('mode.sim_interactive', True):
df = DataFrame(np.random.randn(10, 4))
assert '\\' not in repr(df)
def test_expand_frame_repr(self):
df_small = DataFrame('hello', [0], [0])
df_wide = DataFrame('hello', [0], lrange(10))
df_tall = DataFrame('hello', lrange(30), lrange(5))
with option_context('mode.sim_interactive', True):
with option_context('display.max_columns', 10, 'display.width', 20,
'display.max_rows', 20,
'display.show_dimensions', True):
with option_context('display.expand_frame_repr', True):
assert not has_truncated_repr(df_small)
assert not has_expanded_repr(df_small)
assert not has_truncated_repr(df_wide)
assert has_expanded_repr(df_wide)
assert has_vertically_truncated_repr(df_tall)
assert has_expanded_repr(df_tall)
with option_context('display.expand_frame_repr', False):
assert not has_truncated_repr(df_small)
assert not has_expanded_repr(df_small)
assert not has_horizontally_truncated_repr(df_wide)
assert not has_expanded_repr(df_wide)
assert has_vertically_truncated_repr(df_tall)
assert not has_expanded_repr(df_tall)
def test_repr_non_interactive(self):
# in non interactive mode, there can be no dependency on the
# result of terminal auto size detection
df = DataFrame('hello', lrange(1000), lrange(5))
with option_context('mode.sim_interactive', False, 'display.width', 0,
'display.max_rows', 5000):
assert not has_truncated_repr(df)
assert not has_expanded_repr(df)
def test_repr_truncates_terminal_size(self, monkeypatch):
# see gh-21180
terminal_size = (118, 96)
monkeypatch.setattr('pandas.io.formats.console.get_terminal_size',
lambda: terminal_size)
monkeypatch.setattr('pandas.io.formats.format.get_terminal_size',
lambda: terminal_size)
index = range(5)
columns = pd.MultiIndex.from_tuples([
('This is a long title with > 37 chars.', 'cat'),
('This is a loooooonger title with > 43 chars.', 'dog'),
])
df = pd.DataFrame(1, index=index, columns=columns)
result = repr(df)
h1, h2 = result.split('\n')[:2]
assert 'long' in h1
assert 'loooooonger' in h1
assert 'cat' in h2
assert 'dog' in h2
# regular columns
df2 = pd.DataFrame({"A" * 41: [1, 2], 'B' * 41: [1, 2]})
result = repr(df2)
assert df2.columns[0] in result.split('\n')[0]
def test_repr_truncates_terminal_size_full(self, monkeypatch):
# GH 22984 ensure entire window is filled
terminal_size = (80, 24)
df = pd.DataFrame(np.random.rand(1, 7))
monkeypatch.setattr('pandas.io.formats.console.get_terminal_size',
lambda: terminal_size)
monkeypatch.setattr('pandas.io.formats.format.get_terminal_size',
lambda: terminal_size)
assert "..." not in str(df)
def test_repr_truncation_column_size(self):
# dataframe with last column very wide -> check it is not used to
# determine size of truncation (...) column
df = pd.DataFrame({'a': [108480, 30830], 'b': [12345, 12345],
'c': [12345, 12345], 'd': [12345, 12345],
'e': ['a' * 50] * 2})
assert "..." in str(df)
assert " ... " not in str(df)
def test_repr_max_columns_max_rows(self):
term_width, term_height = get_terminal_size()
if term_width < 10 or term_height < 10:
pytest.skip("terminal size too small, "
"{0} x {1}".format(term_width, term_height))
def mkframe(n):
index = ['{i:05d}'.format(i=i) for i in range(n)]
return DataFrame(0, index, index)
df6 = mkframe(6)
df10 = mkframe(10)
with option_context('mode.sim_interactive', True):
with option_context('display.width', term_width * 2):
with option_context('display.max_rows', 5,
'display.max_columns', 5):
assert not has_expanded_repr(mkframe(4))
assert not has_expanded_repr(mkframe(5))
assert not has_expanded_repr(df6)
assert has_doubly_truncated_repr(df6)
with option_context('display.max_rows', 20,
'display.max_columns', 10):
# Out off max_columns boundary, but no extending
# since not exceeding width
assert not has_expanded_repr(df6)
assert not has_truncated_repr(df6)
with option_context('display.max_rows', 9,
'display.max_columns', 10):
# out vertical bounds can not result in exanded repr
assert not has_expanded_repr(df10)
assert has_vertically_truncated_repr(df10)
# width=None in terminal, auto detection
with option_context('display.max_columns', 100, 'display.max_rows',
term_width * 20, 'display.width', None):
df = mkframe((term_width // 7) - 2)
assert not has_expanded_repr(df)
df = mkframe((term_width // 7) + 2)
printing.pprint_thing(df._repr_fits_horizontal_())
assert has_expanded_repr(df)
def test_str_max_colwidth(self):
# GH 7856
df = pd.DataFrame([{'a': 'foo',
'b': 'bar',
'c': 'uncomfortably long line with lots of stuff',
'd': 1}, {'a': 'foo',
'b': 'bar',
'c': 'stuff',
'd': 1}])
df.set_index(['a', 'b', 'c'])
assert str(df) == (
' a b c d\n'
'0 foo bar uncomfortably long line with lots of stuff 1\n'
'1 foo bar stuff 1')
with option_context('max_colwidth', 20):
assert str(df) == (' a b c d\n'
'0 foo bar uncomfortably lo... 1\n'
'1 foo bar stuff 1')
def test_auto_detect(self):
term_width, term_height = get_terminal_size()
fac = 1.05 # Arbitrary large factor to exceed term width
cols = range(int(term_width * fac))
index = range(10)
df = DataFrame(index=index, columns=cols)
with option_context('mode.sim_interactive', True):
with option_context('max_rows', None):
with option_context('max_columns', None):
# Wrap around with None
assert has_expanded_repr(df)
with option_context('max_rows', 0):
with option_context('max_columns', 0):
# Truncate with auto detection.
assert has_horizontally_truncated_repr(df)
index = range(int(term_height * fac))
df = DataFrame(index=index, columns=cols)
with option_context('max_rows', 0):
with option_context('max_columns', None):
# Wrap around with None
assert has_expanded_repr(df)
# Truncate vertically
assert has_vertically_truncated_repr(df)
with option_context('max_rows', None):
with option_context('max_columns', 0):
assert has_horizontally_truncated_repr(df)
def test_to_string_repr_unicode(self):
buf = StringIO()
unicode_values = [u('\u03c3')] * 10
unicode_values = np.array(unicode_values, dtype=object)
df = DataFrame({'unicode': unicode_values})
df.to_string(col_space=10, buf=buf)
# it works!
repr(df)
idx = Index(['abc', u('\u03c3a'), 'aegdvg'])
ser = Series(np.random.randn(len(idx)), idx)
rs = repr(ser).split('\n')
line_len = len(rs[0])
for line in rs[1:]:
try:
line = line.decode(get_option("display.encoding"))
except AttributeError:
pass
if not line.startswith('dtype:'):
assert len(line) == line_len
# it works even if sys.stdin in None
_stdin = sys.stdin
try:
sys.stdin = None
repr(df)
finally:
sys.stdin = _stdin
def test_to_string_unicode_columns(self):
df = DataFrame({u('\u03c3'): np.arange(10.)})
buf = StringIO()
df.to_string(buf=buf)
buf.getvalue()
buf = StringIO()
df.info(buf=buf)
buf.getvalue()
result = self.frame.to_string()
assert isinstance(result, compat.text_type)
def test_to_string_utf8_columns(self):
n = u("\u05d0").encode('utf-8')
with option_context('display.max_rows', 1):
df = DataFrame([1, 2], columns=[n])
repr(df)
def test_to_string_unicode_two(self):
dm = DataFrame({u('c/\u03c3'): []})
buf = StringIO()
dm.to_string(buf)
def test_to_string_unicode_three(self):
dm = DataFrame(['\xc2'])
buf = StringIO()
dm.to_string(buf)
def test_to_string_with_formatters(self):
df = DataFrame({'int': [1, 2, 3],
'float': [1.0, 2.0, 3.0],
'object': [(1, 2), True, False]},
columns=['int', 'float', 'object'])
formatters = [('int', lambda x: '0x{x:x}'.format(x=x)),
('float', lambda x: '[{x: 4.1f}]'.format(x=x)),
('object', lambda x: '-{x!s}-'.format(x=x))]
result = df.to_string(formatters=dict(formatters))
result2 = df.to_string(formatters=lzip(*formatters)[1])
assert result == (' int float object\n'
'0 0x1 [ 1.0] -(1, 2)-\n'
'1 0x2 [ 2.0] -True-\n'
'2 0x3 [ 3.0] -False-')
assert result == result2
def test_to_string_with_datetime64_monthformatter(self):
months = [datetime(2016, 1, 1), datetime(2016, 2, 2)]
x = DataFrame({'months': months})
def format_func(x):
return x.strftime('%Y-%m')
result = x.to_string(formatters={'months': format_func})
expected = 'months\n0 2016-01\n1 2016-02'
assert result.strip() == expected
def test_to_string_with_datetime64_hourformatter(self):
x = DataFrame({'hod': pd.to_datetime(['10:10:10.100', '12:12:12.120'],
format='%H:%M:%S.%f')})
def format_func(x):
return x.strftime('%H:%M')
result = x.to_string(formatters={'hod': format_func})
expected = 'hod\n0 10:10\n1 12:12'
assert result.strip() == expected
def test_to_string_with_formatters_unicode(self):
df = DataFrame({u('c/\u03c3'): [1, 2, 3]})
result = df.to_string(
formatters={u('c/\u03c3'): lambda x: '{x}'.format(x=x)})
assert result == u(' c/\u03c3\n') + '0 1\n1 2\n2 3'
def test_east_asian_unicode_false(self):
if PY3:
_rep = repr
else:
_rep = unicode # noqa
# not alighned properly because of east asian width
# mid col
df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'],
'b': [1, 222, 33333, 4]},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" a b\na あ 1\n"
u"bb いいい 222\nc う 33333\n"
u"ddd ええええええ 4")
assert _rep(df) == expected
# last col
df = DataFrame({'a': [1, 222, 33333, 4],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" a b\na 1 あ\n"
u"bb 222 いいい\nc 33333 う\n"
u"ddd 4 ええええええ")
assert _rep(df) == expected
# all col
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" a b\na あああああ あ\n"
u"bb い いいい\nc う う\n"
u"ddd えええ ええええええ")
assert _rep(df) == expected
# column name
df = DataFrame({'b': [u'あ', u'いいい', u'う', u'ええええええ'],
u'あああああ': [1, 222, 33333, 4]},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" b あああああ\na あ 1\n"
u"bb いいい 222\nc う 33333\n"
u"ddd ええええええ 4")
assert _rep(df) == expected
# index
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=[u'あああ', u'いいいいいい', u'うう', u'え'])
expected = (u" a b\nあああ あああああ あ\n"
u"いいいいいい い いいい\nうう う う\n"
u"え えええ ええええええ")
assert _rep(df) == expected
# index name
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=pd.Index([u'あ', u'い', u'うう', u'え'],
name=u'おおおお'))
expected = (u" a b\n"
u"おおおお \n"
u"あ あああああ あ\n"
u"い い いいい\n"
u"うう う う\n"
u"え えええ ええええええ")
assert _rep(df) == expected
# all
df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'],
u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']},
index=pd.Index([u'あ', u'いいい', u'うう', u'え'],
name=u'お'))
expected = (u" あああ いいいいい\n"
u"お \n"
u"あ あああ あ\n"
u"いいい い いいい\n"
u"うう う う\n"
u"え えええええ ええ")
assert _rep(df) == expected
# MultiIndex
idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), (
u'おおお', u'かかかか'), (u'き', u'くく')])
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=idx)
expected = (u" a b\n"
u"あ いい あああああ あ\n"
u"う え い いいい\n"
u"おおお かかかか う う\n"
u"き くく えええ ええええええ")
assert _rep(df) == expected
# truncate
with option_context('display.max_rows', 3, 'display.max_columns', 3):
df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ'],
'c': [u'お', u'か', u'ききき', u'くくくくくく'],
u'ああああ': [u'さ', u'し', u'す', u'せ']},
columns=['a', 'b', 'c', u'ああああ'])
expected = (u" a ... ああああ\n0 あああああ ... さ\n"
u".. ... ... ...\n3 えええ ... せ\n"
u"\n[4 rows x 4 columns]")
assert _rep(df) == expected
df.index = [u'あああ', u'いいいい', u'う', 'aaa']
expected = (u" a ... ああああ\nあああ あああああ ... さ\n"
u".. ... ... ...\naaa えええ ... せ\n"
u"\n[4 rows x 4 columns]")
assert _rep(df) == expected
def test_east_asian_unicode_true(self):
if PY3:
_rep = repr
else:
_rep = unicode # noqa
# Emable Unicode option -----------------------------------------
with option_context('display.unicode.east_asian_width', True):
# mid col
df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'],
'b': [1, 222, 33333, 4]},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" a b\na あ 1\n"
u"bb いいい 222\nc う 33333\n"
u"ddd ええええええ 4")
assert _rep(df) == expected
# last col
df = DataFrame({'a': [1, 222, 33333, 4],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" a b\na 1 あ\n"
u"bb 222 いいい\nc 33333 う\n"
u"ddd 4 ええええええ")
assert _rep(df) == expected
# all col
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" a b\n"
u"a あああああ あ\n"
u"bb い いいい\n"
u"c う う\n"
u"ddd えええ ええええええ")
assert _rep(df) == expected
# column name
df = DataFrame({'b': [u'あ', u'いいい', u'う', u'ええええええ'],
u'あああああ': [1, 222, 33333, 4]},
index=['a', 'bb', 'c', 'ddd'])
expected = (u" b あああああ\n"
u"a あ 1\n"
u"bb いいい 222\n"
u"c う 33333\n"
u"ddd ええええええ 4")
assert _rep(df) == expected
# index
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=[u'あああ', u'いいいいいい', u'うう', u'え'])
expected = (u" a b\n"
u"あああ あああああ あ\n"
u"いいいいいい い いいい\n"
u"うう う う\n"
u"え えええ ええええええ")
assert _rep(df) == expected
# index name
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=pd.Index([u'あ', u'い', u'うう', u'え'],
name=u'おおおお'))
expected = (u" a b\n"
u"おおおお \n"
u"あ あああああ あ\n"
u"い い いいい\n"
u"うう う う\n"
u"え えええ ええええええ")
assert _rep(df) == expected
# all
df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'],
u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']},
index=pd.Index([u'あ', u'いいい', u'うう', u'え'],
name=u'お'))
expected = (u" あああ いいいいい\n"
u"お \n"
u"あ あああ あ\n"
u"いいい い いいい\n"
u"うう う う\n"
u"え えええええ ええ")
assert _rep(df) == expected
# MultiIndex
idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), (
u'おおお', u'かかかか'), (u'き', u'くく')])
df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ']},
index=idx)
expected = (u" a b\n"
u"あ いい あああああ あ\n"
u"う え い いいい\n"
u"おおお かかかか う う\n"
u"き くく えええ ええええええ")
assert _rep(df) == expected
# truncate
with option_context('display.max_rows', 3, 'display.max_columns',
3):
df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
'b': [u'あ', u'いいい', u'う', u'ええええええ'],
'c': [u'お', u'か', u'ききき', u'くくくくくく'],
u'ああああ': [u'さ', u'し', u'す', u'せ']},
columns=['a', 'b', 'c', u'ああああ'])
expected = (u" a ... ああああ\n"
u"0 あああああ ... さ\n"
u".. ... ... ...\n"
u"3 えええ ... せ\n"
u"\n[4 rows x 4 columns]")
assert _rep(df) == expected
df.index = [u'あああ', u'いいいい', u'う', 'aaa']
expected = (u" a ... ああああ\n"
u"あああ あああああ ... さ\n"
u"... ... ... ...\n"
u"aaa えええ ... せ\n"
u"\n[4 rows x 4 columns]")
assert _rep(df) == expected
# ambiguous unicode
df = DataFrame({'b': [u'あ', u'いいい', u'¡¡', u'ええええええ'],
u'あああああ': [1, 222, 33333, 4]},
index=['a', 'bb', 'c', '¡¡¡'])
expected = (u" b あああああ\n"
u"a あ 1\n"
u"bb いいい 222\n"
u"c ¡¡ 33333\n"
u"¡¡¡ ええええええ 4")
assert _rep(df) == expected
def test_to_string_buffer_all_unicode(self):
buf = StringIO()
empty = DataFrame({u('c/\u03c3'): Series()})
nonempty = DataFrame({u('c/\u03c3'): Series([1, 2, 3])})
print(empty, file=buf)
print(nonempty, file=buf)
# this should work
buf.getvalue()
def test_to_string_with_col_space(self):
df = DataFrame(np.random.random(size=(1, 3)))
c10 = len(df.to_string(col_space=10).split("\n")[1])
c20 = len(df.to_string(col_space=20).split("\n")[1])
c30 = len(df.to_string(col_space=30).split("\n")[1])
assert c10 < c20 < c30
# GH 8230
# col_space wasn't being applied with header=False
with_header = df.to_string(col_space=20)
with_header_row1 = with_header.splitlines()[1]
no_header = df.to_string(col_space=20, header=False)
assert len(with_header_row1) == len(no_header)
def test_to_string_truncate_indices(self):
for index in [tm.makeStringIndex, tm.makeUnicodeIndex, tm.makeIntIndex,
tm.makeDateIndex, tm.makePeriodIndex]:
for column in [tm.makeStringIndex]:
for h in [10, 20]:
for w in [10, 20]:
with option_context("display.expand_frame_repr",
False):
df = DataFrame(index=index(h), columns=column(w))
with option_context("display.max_rows", 15):
if h == 20:
assert has_vertically_truncated_repr(df)
else:
assert not has_vertically_truncated_repr(
df)
with option_context("display.max_columns", 15):
if w == 20:
assert has_horizontally_truncated_repr(df)
else:
assert not (
has_horizontally_truncated_repr(df))
with option_context("display.max_rows", 15,
"display.max_columns", 15):
if h == 20 and w == 20:
assert has_doubly_truncated_repr(df)
else:
assert not has_doubly_truncated_repr(
df)
def test_to_string_truncate_multilevel(self):
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
df = DataFrame(index=arrays, columns=arrays)
with option_context("display.max_rows", 7, "display.max_columns", 7):
assert has_doubly_truncated_repr(df)
def test_truncate_with_different_dtypes(self):
# 11594, 12045
# when truncated the dtypes of the splits can differ
# 11594
import datetime
s = Series([datetime.datetime(2012, 1, 1)] * 10 +
[datetime.datetime(1012, 1, 2)] + [
datetime.datetime(2012, 1, 3)] * 10)
with pd.option_context('display.max_rows', 8):
result = str(s)
assert 'object' in result
# 12045
df = DataFrame({'text': ['some words'] + [None] * 9})
with pd.option_context('display.max_rows', 8,
'display.max_columns', 3):
result = str(df)
assert 'None' in result
assert 'NaN' not in result
def test_datetimelike_frame(self):
# GH 12211
df = DataFrame(
{'date': [pd.Timestamp('20130101').tz_localize('UTC')] +
[pd.NaT] * 5})
with option_context("display.max_rows", 5):
result = str(df)
assert '2013-01-01 00:00:00+00:00' in result
assert 'NaT' in result
assert '...' in result
assert '[6 rows x 1 columns]' in result
dts = [pd.Timestamp('2011-01-01', tz='US/Eastern')] * 5 + [pd.NaT] * 5
df = pd.DataFrame({"dt": dts,
"x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
with option_context('display.max_rows', 5):
expected = (' dt x\n'
'0 2011-01-01 00:00:00-05:00 1\n'
'1 2011-01-01 00:00:00-05:00 2\n'
'.. ... ..\n'
'8 NaT 9\n'
'9 NaT 10\n\n'
'[10 rows x 2 columns]')
assert repr(df) == expected
dts = [pd.NaT] * 5 + [pd.Timestamp('2011-01-01', tz='US/Eastern')] * 5
df = pd.DataFrame({"dt": dts,
"x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
with option_context('display.max_rows', 5):
expected = (' dt x\n'
'0 NaT 1\n'
'1 NaT 2\n'
'.. ... ..\n'
'8 2011-01-01 00:00:00-05:00 9\n'
'9 2011-01-01 00:00:00-05:00 10\n\n'
'[10 rows x 2 columns]')
assert repr(df) == expected
dts = ([pd.Timestamp('2011-01-01', tz='Asia/Tokyo')] * 5 +
[pd.Timestamp('2011-01-01', tz='US/Eastern')] * 5)
df = pd.DataFrame({"dt": dts,
"x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
with option_context('display.max_rows', 5):
expected = (' dt x\n'
'0 2011-01-01 00:00:00+09:00 1\n'
'1 2011-01-01 00:00:00+09:00 2\n'
'.. ... ..\n'
'8 2011-01-01 00:00:00-05:00 9\n'
'9 2011-01-01 00:00:00-05:00 10\n\n'
'[10 rows x 2 columns]')
assert repr(df) == expected
@pytest.mark.parametrize('start_date', [
'2017-01-01 23:59:59.999999999',
'2017-01-01 23:59:59.99999999',
'2017-01-01 23:59:59.9999999',
'2017-01-01 23:59:59.999999',
'2017-01-01 23:59:59.99999',
'2017-01-01 23:59:59.9999',
])
def test_datetimeindex_highprecision(self, start_date):
# GH19030
# Check that high-precision time values for the end of day are
# included in repr for DatetimeIndex
df = DataFrame({'A': date_range(start=start_date,
freq='D', periods=5)})
result = str(df)
assert start_date in result
dti = date_range(start=start_date,
freq='D', periods=5)
df = DataFrame({'A': range(5)}, index=dti)
result = str(df.index)
assert start_date in result
def test_nonunicode_nonascii_alignment(self):
df = DataFrame([["aa\xc3\xa4\xc3\xa4", 1], ["bbbb", 2]])
rep_str = df.to_string()
lines = rep_str.split('\n')
assert len(lines[1]) == len(lines[2])
def test_unicode_problem_decoding_as_ascii(self):
dm = DataFrame({u('c/\u03c3'): Series({'test': np.nan})})
compat.text_type(dm.to_string())
def test_string_repr_encoding(self, datapath):
filepath = datapath('io', 'parser', 'data', 'unicode_series.csv')
df = pd.read_csv(filepath, header=None, encoding='latin1')
repr(df)
repr(df[1])
def test_repr_corner(self):
# representing infs poses no problems
df = DataFrame({'foo': [-np.inf, np.inf]})
repr(df)
def test_frame_info_encoding(self):
index = ['\'Til There Was You (1997)',
'ldum klaka (Cold Fever) (1994)']
fmt.set_option('display.max_rows', 1)
df = DataFrame(columns=['a', 'b', 'c'], index=index)
repr(df)
repr(df.T)
fmt.set_option('display.max_rows', 200)
def test_pprint_thing(self):
from pandas.io.formats.printing import pprint_thing as pp_t
if PY3:
pytest.skip("doesn't work on Python 3")
assert pp_t('a') == u('a')
assert pp_t(u('a')) == u('a')
assert pp_t(None) == 'None'
assert pp_t(u('\u05d0'), quote_strings=True) == u("u'\u05d0'")
assert pp_t(u('\u05d0'), quote_strings=False) == u('\u05d0')
assert (pp_t((u('\u05d0'), u('\u05d1')), quote_strings=True) ==
u("(u'\u05d0', u'\u05d1')"))
assert (pp_t((u('\u05d0'), (u('\u05d1'), u('\u05d2'))),
quote_strings=True) == u("(u'\u05d0', "
"(u'\u05d1', u'\u05d2'))"))
assert (pp_t(('foo', u('\u05d0'), (u('\u05d0'), u('\u05d0'))),
quote_strings=True) == u("(u'foo', u'\u05d0', "
"(u'\u05d0', u'\u05d0'))"))
# gh-2038: escape embedded tabs in string
assert "\t" not in pp_t("a\tb", escape_chars=("\t", ))
def test_wide_repr(self):
with option_context('mode.sim_interactive', True,
'display.show_dimensions', True,
'display.max_columns', 20):
max_cols = get_option('display.max_columns')
df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1)))
set_option('display.expand_frame_repr', False)
rep_str = repr(df)
assert "10 rows x {c} columns".format(c=max_cols - 1) in rep_str
set_option('display.expand_frame_repr', True)
wide_repr = repr(df)
assert rep_str != wide_repr
with option_context('display.width', 120):
wider_repr = repr(df)
assert len(wider_repr) < len(wide_repr)
reset_option('display.expand_frame_repr')
def test_wide_repr_wide_columns(self):
with option_context('mode.sim_interactive', True,
'display.max_columns', 20):
df = DataFrame(np.random.randn(5, 3),
columns=['a' * 90, 'b' * 90, 'c' * 90])
rep_str = repr(df)
assert len(rep_str.splitlines()) == 20
def test_wide_repr_named(self):
with option_context('mode.sim_interactive', True,
'display.max_columns', 20):
max_cols = get_option('display.max_columns')
df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1)))
df.index.name = 'DataFrame Index'
set_option('display.expand_frame_repr', False)
rep_str = repr(df)
set_option('display.expand_frame_repr', True)
wide_repr = repr(df)
assert rep_str != wide_repr
with option_context('display.width', 150):
wider_repr = repr(df)
assert len(wider_repr) < len(wide_repr)
for line in wide_repr.splitlines()[1::13]:
assert 'DataFrame Index' in line
reset_option('display.expand_frame_repr')
def test_wide_repr_multiindex(self):
with option_context('mode.sim_interactive', True,
'display.max_columns', 20):
midx = MultiIndex.from_arrays(tm.rands_array(5, size=(2, 10)))
max_cols = get_option('display.max_columns')
df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1)),
index=midx)
df.index.names = ['Level 0', 'Level 1']
set_option('display.expand_frame_repr', False)
rep_str = repr(df)
set_option('display.expand_frame_repr', True)
wide_repr = repr(df)
assert rep_str != wide_repr
with option_context('display.width', 150):
wider_repr = repr(df)
assert len(wider_repr) < len(wide_repr)
for line in wide_repr.splitlines()[1::13]:
assert 'Level 0 Level 1' in line
reset_option('display.expand_frame_repr')
def test_wide_repr_multiindex_cols(self):
with option_context('mode.sim_interactive', True,
'display.max_columns', 20):
max_cols = get_option('display.max_columns')
midx = MultiIndex.from_arrays(tm.rands_array(5, size=(2, 10)))
mcols = MultiIndex.from_arrays(
tm.rands_array(3, size=(2, max_cols - 1)))
df = DataFrame(tm.rands_array(25, (10, max_cols - 1)),
index=midx, columns=mcols)
df.index.names = ['Level 0', 'Level 1']
set_option('display.expand_frame_repr', False)
rep_str = repr(df)
set_option('display.expand_frame_repr', True)
wide_repr = repr(df)
assert rep_str != wide_repr
with option_context('display.width', 150, 'display.max_columns', 20):
wider_repr = repr(df)
assert len(wider_repr) < len(wide_repr)
reset_option('display.expand_frame_repr')
def test_wide_repr_unicode(self):
with option_context('mode.sim_interactive', True,
'display.max_columns', 20):
max_cols = 20
df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1)))
set_option('display.expand_frame_repr', False)
rep_str = repr(df)
set_option('display.expand_frame_repr', True)
wide_repr = repr(df)
assert rep_str != wide_repr
with option_context('display.width', 150):
wider_repr = repr(df)
assert len(wider_repr) < len(wide_repr)
reset_option('display.expand_frame_repr')
def test_wide_repr_wide_long_columns(self):
with option_context('mode.sim_interactive', True):
df = DataFrame({'a': ['a' * 30, 'b' * 30],
'b': ['c' * 70, 'd' * 80]})
result = repr(df)
assert 'ccccc' in result
assert 'ddddd' in result
def test_long_series(self):
n = 1000
s = Series(
np.random.randint(-50, 50, n),
index=['s{x:04d}'.format(x=x) for x in range(n)], dtype='int64')
import re
str_rep = str(s)
nmatches = len(re.findall('dtype', str_rep))
assert nmatches == 1
def test_index_with_nan(self):
# GH 2850
df = DataFrame({'id1': {0: '1a3',
1: '9h4'},
'id2': {0: np.nan,
1: 'd67'},
'id3': {0: '78d',
1: '79d'},
'value': {0: 123,
1: 64}})
# multi-index
y = df.set_index(['id1', 'id2', 'id3'])
result = y.to_string()
expected = u(
' value\nid1 id2 id3 \n'
'1a3 NaN 78d 123\n9h4 d67 79d 64')
assert result == expected
# index
y = df.set_index('id2')
result = y.to_string()
expected = u(
' id1 id3 value\nid2 \n'
'NaN 1a3 78d 123\nd67 9h4 79d 64')
assert result == expected
# with append (this failed in 0.12)
y = df.set_index(['id1', 'id2']).set_index('id3', append=True)
result = y.to_string()
expected = u(
' value\nid1 id2 id3 \n'
'1a3 NaN 78d 123\n9h4 d67 79d 64')
assert result == expected
# all-nan in mi
df2 = df.copy()
df2.loc[:, 'id2'] = np.nan
y = df2.set_index('id2')
result = y.to_string()
expected = u(
' id1 id3 value\nid2 \n'
'NaN 1a3 78d 123\nNaN 9h4 79d 64')
assert result == expected
# partial nan in mi
df2 = df.copy()
df2.loc[:, 'id2'] = np.nan
y = df2.set_index(['id2', 'id3'])
result = y.to_string()
expected = u(
' id1 value\nid2 id3 \n'
'NaN 78d 1a3 123\n 79d 9h4 64')
assert result == expected
df = DataFrame({'id1': {0: np.nan,
1: '9h4'},
'id2': {0: np.nan,
1: 'd67'},
'id3': {0: np.nan,
1: '79d'},
'value': {0: 123,
1: 64}})
y = df.set_index(['id1', 'id2', 'id3'])
result = y.to_string()
expected = u(
' value\nid1 id2 id3 \n'
'NaN NaN NaN 123\n9h4 d67 79d 64')
assert result == expected
def test_to_string(self):
# big mixed
biggie = DataFrame({'A': np.random.randn(200),
'B': tm.makeStringIndex(200)},
index=lrange(200))
biggie.loc[:20, 'A'] = np.nan
biggie.loc[:20, 'B'] = np.nan
s = biggie.to_string()
buf = StringIO()
retval = biggie.to_string(buf=buf)
assert retval is None
assert buf.getvalue() == s
assert isinstance(s, compat.string_types)
# print in right order
result = biggie.to_string(columns=['B', 'A'], col_space=17,
float_format='%.5f'.__mod__)
lines = result.split('\n')
header = lines[0].strip().split()
joined = '\n'.join(re.sub(r'\s+', ' ', x).strip() for x in lines[1:])
recons = read_csv(StringIO(joined), names=header,
header=None, sep=' ')
tm.assert_series_equal(recons['B'], biggie['B'])
assert recons['A'].count() == biggie['A'].count()
assert (np.abs(recons['A'].dropna() -
biggie['A'].dropna()) < 0.1).all()
# expected = ['B', 'A']
# assert header == expected
result = biggie.to_string(columns=['A'], col_space=17)
header = result.split('\n')[0].strip().split()
expected = ['A']
assert header == expected
biggie.to_string(columns=['B', 'A'],
formatters={'A': lambda x: '{x:.1f}'.format(x=x)})
biggie.to_string(columns=['B', 'A'], float_format=str)
biggie.to_string(columns=['B', 'A'], col_space=12, float_format=str)
frame = DataFrame(index=np.arange(200))
frame.to_string()
def test_to_string_no_header(self):
df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df_s = df.to_string(header=False)
expected = "0 1 4\n1 2 5\n2 3 6"
assert df_s == expected
def test_to_string_specified_header(self):
df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df_s = df.to_string(header=['X', 'Y'])
expected = ' X Y\n0 1 4\n1 2 5\n2 3 6'
assert df_s == expected
with pytest.raises(ValueError):
df.to_string(header=['X'])
def test_to_string_no_index(self):
# GH 16839, GH 13032
df = DataFrame({'x': [11, 22], 'y': [33, -44], 'z': ['AAA', ' ']})
df_s = df.to_string(index=False)
# Leading space is expected for positive numbers.
expected = (" x y z\n"
" 11 33 AAA\n"
" 22 -44 ")
assert df_s == expected
df_s = df[['y', 'x', 'z']].to_string(index=False)
expected = (" y x z\n"
" 33 11 AAA\n"
"-44 22 ")
assert df_s == expected
def test_to_string_line_width_no_index(self):
# GH 13998, GH 22505
df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df_s = df.to_string(line_width=1, index=False)
expected = " x \\\n 1 \n 2 \n 3 \n\n y \n 4 \n 5 \n 6 "
assert df_s == expected
df = DataFrame({'x': [11, 22, 33], 'y': [4, 5, 6]})
df_s = df.to_string(line_width=1, index=False)
expected = " x \\\n 11 \n 22 \n 33 \n\n y \n 4 \n 5 \n 6 "
assert df_s == expected
df = DataFrame({'x': [11, 22, -33], 'y': [4, 5, -6]})
df_s = df.to_string(line_width=1, index=False)
expected = " x \\\n 11 \n 22 \n-33 \n\n y \n 4 \n 5 \n-6 "
assert df_s == expected
def test_to_string_float_formatting(self):
tm.reset_display_options()
fmt.set_option('display.precision', 5, 'display.column_space', 12,
'display.notebook_repr_html', False)
df = DataFrame({'x': [0, 0.25, 3456.000, 12e+45, 1.64e+6, 1.7e+8,
1.253456, np.pi, -1e6]})
df_s = df.to_string()
if _three_digit_exp():
expected = (' x\n0 0.00000e+000\n1 2.50000e-001\n'
'2 3.45600e+003\n3 1.20000e+046\n4 1.64000e+006\n'
'5 1.70000e+008\n6 1.25346e+000\n7 3.14159e+000\n'
'8 -1.00000e+006')
else:
expected = (' x\n0 0.00000e+00\n1 2.50000e-01\n'
'2 3.45600e+03\n3 1.20000e+46\n4 1.64000e+06\n'
'5 1.70000e+08\n6 1.25346e+00\n7 3.14159e+00\n'
'8 -1.00000e+06')
assert df_s == expected
df = DataFrame({'x': [3234, 0.253]})
df_s = df.to_string()
expected = (' x\n' '0 3234.000\n' '1 0.253')
assert df_s == expected
tm.reset_display_options()
assert get_option("display.precision") == 6
df = DataFrame({'x': [1e9, 0.2512]})
df_s = df.to_string()
if _three_digit_exp():
expected = (' x\n'
'0 1.000000e+009\n'
'1 2.512000e-001')
else:
expected = (' x\n'
'0 1.000000e+09\n'
'1 2.512000e-01')
assert df_s == expected
def test_to_string_float_format_no_fixed_width(self):
# GH 21625
df = DataFrame({'x': [0.19999]})
expected = ' x\n0 0.200'
assert df.to_string(float_format='%.3f') == expected
# GH 22270
df = DataFrame({'x': [100.0]})
expected = ' x\n0 100'
assert df.to_string(float_format='%.0f') == expected
def test_to_string_small_float_values(self):
df = DataFrame({'a': [1.5, 1e-17, -5.5e-7]})
result = df.to_string()
# sadness per above
if '{x:.4g}'.format(x=1.7e8) == '1.7e+008':
expected = (' a\n'
'0 1.500000e+000\n'
'1 1.000000e-017\n'
'2 -5.500000e-007')
else:
expected = (' a\n'
'0 1.500000e+00\n'
'1 1.000000e-17\n'
'2 -5.500000e-07')
assert result == expected
# but not all exactly zero
df = df * 0
result = df.to_string()
expected = (' 0\n' '0 0\n' '1 0\n' '2 -0')
def test_to_string_float_index(self):
index = Index([1.5, 2, 3, 4, 5])
df = DataFrame(lrange(5), index=index)
result = df.to_string()
expected = (' 0\n'
'1.5 0\n'
'2.0 1\n'
'3.0 2\n'
'4.0 3\n'
'5.0 4')
assert result == expected
def test_to_string_ascii_error(self):
data = [('0 ', u(' .gitignore '), u(' 5 '),
' \xe2\x80\xa2\xe2\x80\xa2\xe2\x80'
'\xa2\xe2\x80\xa2\xe2\x80\xa2')]
df = DataFrame(data)
# it works!
repr(df)
def test_to_string_int_formatting(self):
df = DataFrame({'x': [-15, 20, 25, -35]})
assert issubclass(df['x'].dtype.type, np.integer)
output = df.to_string()
expected = (' x\n' '0 -15\n' '1 20\n' '2 25\n' '3 -35')
assert output == expected
def test_to_string_index_formatter(self):
df = DataFrame([lrange(5), lrange(5, 10), lrange(10, 15)])
rs = df.to_string(formatters={'__index__': lambda x: 'abc' [x]})
xp = """\
0 1 2 3 4
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14\
"""
assert rs == xp
def test_to_string_left_justify_cols(self):
tm.reset_display_options()
df = DataFrame({'x': [3234, 0.253]})
df_s = df.to_string(justify='left')
expected = (' x \n' '0 3234.000\n' '1 0.253')
assert df_s == expected
def test_to_string_format_na(self):
tm.reset_display_options()
df = DataFrame({'A': [np.nan, -1, -2.1234, 3, 4],
'B': [np.nan, 'foo', 'foooo', 'fooooo', 'bar']})
result = df.to_string()
expected = (' A B\n'
'0 NaN NaN\n'
'1 -1.0000 foo\n'
'2 -2.1234 foooo\n'
'3 3.0000 fooooo\n'
'4 4.0000 bar')
assert result == expected
df = DataFrame({'A': [np.nan, -1., -2., 3., 4.],
'B': [np.nan, 'foo', 'foooo', 'fooooo', 'bar']})
result = df.to_string()
expected = (' A B\n'
'0 NaN NaN\n'
'1 -1.0 foo\n'
'2 -2.0 foooo\n'
'3 3.0 fooooo\n'
'4 4.0 bar')
assert result == expected
def test_to_string_format_inf(self):
# Issue #24861
tm.reset_display_options()
df = DataFrame({
'A': [-np.inf, np.inf, -1, -2.1234, 3, 4],
'B': [-np.inf, np.inf, 'foo', 'foooo', 'fooooo', 'bar']
})
result = df.to_string()
expected = (' A B\n'
'0 -inf -inf\n'
'1 inf inf\n'
'2 -1.0000 foo\n'
'3 -2.1234 foooo\n'
'4 3.0000 fooooo\n'
'5 4.0000 bar')
assert result == expected
df = DataFrame({
'A': [-np.inf, np.inf, -1., -2., 3., 4.],
'B': [-np.inf, np.inf, 'foo', 'foooo', 'fooooo', 'bar']
})
result = df.to_string()
expected = (' A B\n'
'0 -inf -inf\n'
'1 inf inf\n'
'2 -1.0 foo\n'
'3 -2.0 foooo\n'
'4 3.0 fooooo\n'
'5 4.0 bar')
assert result == expected
def test_to_string_decimal(self):
# Issue #23614
df = DataFrame({'A': [6.0, 3.1, 2.2]})
expected = ' A\n0 6,0\n1 3,1\n2 2,2'
assert df.to_string(decimal=',') == expected
def test_to_string_line_width(self):
df = DataFrame(123, lrange(10, 15), lrange(30))
s = df.to_string(line_width=80)
assert max(len(l) for l in s.split('\n')) == 80
def test_show_dimensions(self):
df = DataFrame(123, lrange(10, 15), lrange(30))
with option_context('display.max_rows', 10, 'display.max_columns', 40,
'display.width', 500, 'display.expand_frame_repr',
'info', 'display.show_dimensions', True):
assert '5 rows' in str(df)
assert '5 rows' in df._repr_html_()
with option_context('display.max_rows', 10, 'display.max_columns', 40,
'display.width', 500, 'display.expand_frame_repr',
'info', 'display.show_dimensions', False):
assert '5 rows' not in str(df)
assert '5 rows' not in df._repr_html_()
with option_context('display.max_rows', 2, 'display.max_columns', 2,
'display.width', 500, 'display.expand_frame_repr',
'info', 'display.show_dimensions', 'truncate'):
assert '5 rows' in str(df)
assert '5 rows' in df._repr_html_()
with option_context('display.max_rows', 10, 'display.max_columns', 40,
'display.width', 500, 'display.expand_frame_repr',
'info', 'display.show_dimensions', 'truncate'):
assert '5 rows' not in str(df)
assert '5 rows' not in df._repr_html_()
def test_repr_html(self):
self.frame._repr_html_()
fmt.set_option('display.max_rows', 1, 'display.max_columns', 1)
self.frame._repr_html_()
fmt.set_option('display.notebook_repr_html', False)
self.frame._repr_html_()
tm.reset_display_options()
df = DataFrame([[1, 2], [3, 4]])
fmt.set_option('display.show_dimensions', True)
assert '2 rows' in df._repr_html_()
fmt.set_option('display.show_dimensions', False)
assert '2 rows' not in df._repr_html_()
tm.reset_display_options()
def test_repr_html_mathjax(self):
df = DataFrame([[1, 2], [3, 4]])
assert 'tex2jax_ignore' not in df._repr_html_()
with pd.option_context('display.html.use_mathjax', False):
assert 'tex2jax_ignore' in df._repr_html_()
def test_repr_html_wide(self):
max_cols = 20
df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1)))
with option_context('display.max_rows', 60, 'display.max_columns', 20):
assert "..." not in df._repr_html_()
wide_df = DataFrame(tm.rands_array(25, size=(10, max_cols + 1)))
with option_context('display.max_rows', 60, 'display.max_columns', 20):
assert "..." in wide_df._repr_html_()
def test_repr_html_wide_multiindex_cols(self):
max_cols = 20
mcols = MultiIndex.from_product([np.arange(max_cols // 2),
['foo', 'bar']],
names=['first', 'second'])
df = DataFrame(tm.rands_array(25, size=(10, len(mcols))),
columns=mcols)
reg_repr = df._repr_html_()
assert '...' not in reg_repr
mcols = MultiIndex.from_product((np.arange(1 + (max_cols // 2)),
['foo', 'bar']),
names=['first', 'second'])
df = DataFrame(tm.rands_array(25, size=(10, len(mcols))),
columns=mcols)
with option_context('display.max_rows', 60, 'display.max_columns', 20):
assert '...' in df._repr_html_()
def test_repr_html_long(self):
with option_context('display.max_rows', 60):
max_rows = get_option('display.max_rows')
h = max_rows - 1
df = DataFrame({'A': np.arange(1, 1 + h),
'B': np.arange(41, 41 + h)})
reg_repr = df._repr_html_()
assert '..' not in reg_repr
assert str(41 + max_rows // 2) in reg_repr
h = max_rows + 1
df = DataFrame({'A': np.arange(1, 1 + h),
'B': np.arange(41, 41 + h)})
long_repr = df._repr_html_()
assert '..' in long_repr
assert str(41 + max_rows // 2) not in long_repr
assert u('{h} rows ').format(h=h) in long_repr
assert u('2 columns') in long_repr
def test_repr_html_float(self):
with option_context('display.max_rows', 60):
max_rows = get_option('display.max_rows')
h = max_rows - 1
df = DataFrame({'idx': np.linspace(-10, 10, h),
'A': np.arange(1, 1 + h),
'B': np.arange(41, 41 + h)}).set_index('idx')
reg_repr = df._repr_html_()
assert '..' not in reg_repr
assert '<td>{val}</td>'.format(val=str(40 + h)) in reg_repr
h = max_rows + 1
df = DataFrame({'idx': np.linspace(-10, 10, h),
'A': np.arange(1, 1 + h),<|fim▁hole|> long_repr = df._repr_html_()
assert '..' in long_repr
assert '<td>{val}</td>'.format(val='31') not in long_repr
assert u('{h} rows ').format(h=h) in long_repr
assert u('2 columns') in long_repr
def test_repr_html_long_multiindex(self):
max_rows = 60
max_L1 = max_rows // 2
tuples = list(itertools.product(np.arange(max_L1), ['foo', 'bar']))
idx = MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = DataFrame(np.random.randn(max_L1 * 2, 2), index=idx,
columns=['A', 'B'])
with option_context('display.max_rows', 60, 'display.max_columns', 20):
reg_repr = df._repr_html_()
assert '...' not in reg_repr
tuples = list(itertools.product(np.arange(max_L1 + 1), ['foo', 'bar']))
idx = MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = DataFrame(np.random.randn((max_L1 + 1) * 2, 2), index=idx,
columns=['A', 'B'])
long_repr = df._repr_html_()
assert '...' in long_repr
def test_repr_html_long_and_wide(self):
max_cols = 20
max_rows = 60
h, w = max_rows - 1, max_cols - 1
df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
with option_context('display.max_rows', 60, 'display.max_columns', 20):
assert '...' not in df._repr_html_()
h, w = max_rows + 1, max_cols + 1
df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
with option_context('display.max_rows', 60, 'display.max_columns', 20):
assert '...' in df._repr_html_()
def test_info_repr(self):
# GH#21746 For tests inside a terminal (i.e. not CI) we need to detect
# the terminal size to ensure that we try to print something "too big"
term_width, term_height = get_terminal_size()
max_rows = 60
max_cols = 20 + (max(term_width, 80) - 80) // 4
# Long
h, w = max_rows + 1, max_cols - 1
df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
assert has_vertically_truncated_repr(df)
with option_context('display.large_repr', 'info'):
assert has_info_repr(df)
# Wide
h, w = max_rows - 1, max_cols + 1
df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
assert has_horizontally_truncated_repr(df)
with option_context('display.large_repr', 'info',
'display.max_columns', max_cols):
assert has_info_repr(df)
def test_info_repr_max_cols(self):
# GH #6939
df = DataFrame(np.random.randn(10, 5))
with option_context('display.large_repr', 'info',
'display.max_columns', 1,
'display.max_info_columns', 4):
assert has_non_verbose_info_repr(df)
with option_context('display.large_repr', 'info',
'display.max_columns', 1,
'display.max_info_columns', 5):
assert not has_non_verbose_info_repr(df)
# test verbose overrides
# fmt.set_option('display.max_info_columns', 4) # exceeded
def test_info_repr_html(self):
max_rows = 60
max_cols = 20
# Long
h, w = max_rows + 1, max_cols - 1
df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
assert r'<class' not in df._repr_html_()
with option_context('display.large_repr', 'info'):
assert r'<class' in df._repr_html_()
# Wide
h, w = max_rows - 1, max_cols + 1
df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
assert '<class' not in df._repr_html_()
with option_context('display.large_repr', 'info',
'display.max_columns', max_cols):
assert '<class' in df._repr_html_()
def test_fake_qtconsole_repr_html(self):
def get_ipython():
return {'config': {'KernelApp':
{'parent_appname': 'ipython-qtconsole'}}}
repstr = self.frame._repr_html_()
assert repstr is not None
fmt.set_option('display.max_rows', 5, 'display.max_columns', 2)
repstr = self.frame._repr_html_()
assert 'class' in repstr # info fallback
tm.reset_display_options()
def test_pprint_pathological_object(self):
"""
If the test fails, it at least won't hang.
"""
class A(object):
def __getitem__(self, key):
return 3 # obviously simplified
df = DataFrame([A()])
repr(df) # just don't die
def test_float_trim_zeros(self):
vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10,
2.03954217305e+10, 5.59897817305e+10]
skip = True
for line in repr(DataFrame({'A': vals})).split('\n')[:-2]:
if line.startswith('dtype:'):
continue
if _three_digit_exp():
assert ('+010' in line) or skip
else:
assert ('+10' in line) or skip
skip = False
def test_dict_entries(self):
df = DataFrame({'A': [{'a': 1, 'b': 2}]})
val = df.to_string()
assert "'a': 1" in val
assert "'b': 2" in val
def test_period(self):
# GH 12615
df = pd.DataFrame({'A': pd.period_range('2013-01',
periods=4, freq='M'),
'B': [pd.Period('2011-01', freq='M'),
pd.Period('2011-02-01', freq='D'),
pd.Period('2011-03-01 09:00', freq='H'),
pd.Period('2011-04', freq='M')],
'C': list('abcd')})
exp = (" A B C\n"
"0 2013-01 2011-01 a\n"
"1 2013-02 2011-02-01 b\n"
"2 2013-03 2011-03-01 09:00 c\n"
"3 2013-04 2011-04 d")
assert str(df) == exp
def gen_series_formatting():
s1 = pd.Series(['a'] * 100)
s2 = pd.Series(['ab'] * 100)
s3 = pd.Series(['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef'])
s4 = s3[::-1]
test_sers = {'onel': s1, 'twol': s2, 'asc': s3, 'desc': s4}
return test_sers
class TestSeriesFormatting(object):
def setup_method(self, method):
self.ts = tm.makeTimeSeries()
def test_repr_unicode(self):
s = Series([u('\u03c3')] * 10)
repr(s)
a = Series([u("\u05d0")] * 1000)
a.name = 'title1'
repr(a)
def test_to_string(self):
buf = StringIO()
s = self.ts.to_string()
retval = self.ts.to_string(buf=buf)
assert retval is None
assert buf.getvalue().strip() == s
# pass float_format
format = '%.4f'.__mod__
result = self.ts.to_string(float_format=format)
result = [x.split()[1] for x in result.split('\n')[:-1]]
expected = [format(x) for x in self.ts]
assert result == expected
# empty string
result = self.ts[:0].to_string()
assert result == 'Series([], Freq: B)'
result = self.ts[:0].to_string(length=0)
assert result == 'Series([], Freq: B)'
# name and length
cp = self.ts.copy()
cp.name = 'foo'
result = cp.to_string(length=True, name=True, dtype=True)
last_line = result.split('\n')[-1].strip()
assert last_line == ("Freq: B, Name: foo, "
"Length: {cp}, dtype: float64".format(cp=len(cp)))
def test_freq_name_separation(self):
s = Series(np.random.randn(10),
index=date_range('1/1/2000', periods=10), name=0)
result = repr(s)
assert 'Freq: D, Name: 0' in result
def test_to_string_mixed(self):
s = Series(['foo', np.nan, -1.23, 4.56])
result = s.to_string()
expected = (u('0 foo\n') + u('1 NaN\n') + u('2 -1.23\n') +
u('3 4.56'))
assert result == expected
# but don't count NAs as floats
s = Series(['foo', np.nan, 'bar', 'baz'])
result = s.to_string()
expected = (u('0 foo\n') + '1 NaN\n' + '2 bar\n' + '3 baz')
assert result == expected
s = Series(['foo', 5, 'bar', 'baz'])
result = s.to_string()
expected = (u('0 foo\n') + '1 5\n' + '2 bar\n' + '3 baz')
assert result == expected
def test_to_string_float_na_spacing(self):
s = Series([0., 1.5678, 2., -3., 4.])
s[::2] = np.nan
result = s.to_string()
expected = (u('0 NaN\n') + '1 1.5678\n' + '2 NaN\n' +
'3 -3.0000\n' + '4 NaN')
assert result == expected
def test_to_string_without_index(self):
# GH 11729 Test index=False option
s = Series([1, 2, 3, 4])
result = s.to_string(index=False)
expected = (u(' 1\n') + ' 2\n' + ' 3\n' + ' 4')
assert result == expected
def test_unicode_name_in_footer(self):
s = Series([1, 2], name=u('\u05e2\u05d1\u05e8\u05d9\u05ea'))
sf = fmt.SeriesFormatter(s, name=u('\u05e2\u05d1\u05e8\u05d9\u05ea'))
sf._get_footer() # should not raise exception
def test_east_asian_unicode_series(self):
if PY3:
_rep = repr
else:
_rep = unicode # noqa
# not aligned properly because of east asian width
# unicode index
s = Series(['a', 'bb', 'CCC', 'D'],
index=[u'あ', u'いい', u'ううう', u'ええええ'])
expected = (u"あ a\nいい bb\nううう CCC\n"
u"ええええ D\ndtype: object")
assert _rep(s) == expected
# unicode values
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
index=['a', 'bb', 'c', 'ddd'])
expected = (u"a あ\nbb いい\nc ううう\n"
u"ddd ええええ\ndtype: object")
assert _rep(s) == expected
# both
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
index=[u'ああ', u'いいいい', u'う', u'えええ'])
expected = (u"ああ あ\nいいいい いい\nう ううう\n"
u"えええ ええええ\ndtype: object")
assert _rep(s) == expected
# unicode footer
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
index=[u'ああ', u'いいいい', u'う', u'えええ'],
name=u'おおおおおおお')
expected = (u"ああ あ\nいいいい いい\nう ううう\n"
u"えええ ええええ\nName: おおおおおおお, dtype: object")
assert _rep(s) == expected
# MultiIndex
idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), (
u'おおお', u'かかかか'), (u'き', u'くく')])
s = Series([1, 22, 3333, 44444], index=idx)
expected = (u"あ いい 1\n"
u"う え 22\n"
u"おおお かかかか 3333\n"
u"き くく 44444\ndtype: int64")
assert _rep(s) == expected
# object dtype, shorter than unicode repr
s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ'])
expected = (u"1 1\nAB 22\nNaN 3333\n"
u"あああ 44444\ndtype: int64")
assert _rep(s) == expected
# object dtype, longer than unicode repr
s = Series([1, 22, 3333, 44444],
index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ'])
expected = (u"1 1\n"
u"AB 22\n"
u"2011-01-01 00:00:00 3333\n"
u"あああ 44444\ndtype: int64")
assert _rep(s) == expected
# truncate
with option_context('display.max_rows', 3):
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
name=u'おおおおおおお')
expected = (u"0 あ\n ... \n"
u"3 ええええ\n"
u"Name: おおおおおおお, Length: 4, dtype: object")
assert _rep(s) == expected
s.index = [u'ああ', u'いいいい', u'う', u'えええ']
expected = (u"ああ あ\n ... \n"
u"えええ ええええ\n"
u"Name: おおおおおおお, Length: 4, dtype: object")
assert _rep(s) == expected
# Emable Unicode option -----------------------------------------
with option_context('display.unicode.east_asian_width', True):
# unicode index
s = Series(['a', 'bb', 'CCC', 'D'],
index=[u'あ', u'いい', u'ううう', u'ええええ'])
expected = (u"あ a\nいい bb\nううう CCC\n"
u"ええええ D\ndtype: object")
assert _rep(s) == expected
# unicode values
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
index=['a', 'bb', 'c', 'ddd'])
expected = (u"a あ\nbb いい\nc ううう\n"
u"ddd ええええ\ndtype: object")
assert _rep(s) == expected
# both
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
index=[u'ああ', u'いいいい', u'う', u'えええ'])
expected = (u"ああ あ\n"
u"いいいい いい\n"
u"う ううう\n"
u"えええ ええええ\ndtype: object")
assert _rep(s) == expected
# unicode footer
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
index=[u'ああ', u'いいいい', u'う', u'えええ'],
name=u'おおおおおおお')
expected = (u"ああ あ\n"
u"いいいい いい\n"
u"う ううう\n"
u"えええ ええええ\n"
u"Name: おおおおおおお, dtype: object")
assert _rep(s) == expected
# MultiIndex
idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), (
u'おおお', u'かかかか'), (u'き', u'くく')])
s = Series([1, 22, 3333, 44444], index=idx)
expected = (u"あ いい 1\n"
u"う え 22\n"
u"おおお かかかか 3333\n"
u"き くく 44444\n"
u"dtype: int64")
assert _rep(s) == expected
# object dtype, shorter than unicode repr
s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ'])
expected = (u"1 1\nAB 22\nNaN 3333\n"
u"あああ 44444\ndtype: int64")
assert _rep(s) == expected
# object dtype, longer than unicode repr
s = Series([1, 22, 3333, 44444],
index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ'])
expected = (u"1 1\n"
u"AB 22\n"
u"2011-01-01 00:00:00 3333\n"
u"あああ 44444\ndtype: int64")
assert _rep(s) == expected
# truncate
with option_context('display.max_rows', 3):
s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
name=u'おおおおおおお')
expected = (u"0 あ\n ... \n"
u"3 ええええ\n"
u"Name: おおおおおおお, Length: 4, dtype: object")
assert _rep(s) == expected
s.index = [u'ああ', u'いいいい', u'う', u'えええ']
expected = (u"ああ あ\n"
u" ... \n"
u"えええ ええええ\n"
u"Name: おおおおおおお, Length: 4, dtype: object")
assert _rep(s) == expected
# ambiguous unicode
s = Series([u'¡¡', u'い¡¡', u'ううう', u'ええええ'],
index=[u'ああ', u'¡¡¡¡いい', u'¡¡', u'えええ'])
expected = (u"ああ ¡¡\n"
u"¡¡¡¡いい い¡¡\n"
u"¡¡ ううう\n"
u"えええ ええええ\ndtype: object")
assert _rep(s) == expected
def test_float_trim_zeros(self):
vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10,
2.03954217305e+10, 5.59897817305e+10]
for line in repr(Series(vals)).split('\n'):
if line.startswith('dtype:'):
continue
if _three_digit_exp():
assert '+010' in line
else:
assert '+10' in line
def test_datetimeindex(self):
index = date_range('20130102', periods=6)
s = Series(1, index=index)
result = s.to_string()
assert '2013-01-02' in result
# nat in index
s2 = Series(2, index=[Timestamp('20130111'), NaT])
s = s2.append(s)
result = s.to_string()
assert 'NaT' in result
# nat in summary
result = str(s2.index)
assert 'NaT' in result
@pytest.mark.parametrize('start_date', [
'2017-01-01 23:59:59.999999999',
'2017-01-01 23:59:59.99999999',
'2017-01-01 23:59:59.9999999',
'2017-01-01 23:59:59.999999',
'2017-01-01 23:59:59.99999',
'2017-01-01 23:59:59.9999'
])
def test_datetimeindex_highprecision(self, start_date):
# GH19030
# Check that high-precision time values for the end of day are
# included in repr for DatetimeIndex
s1 = Series(date_range(start=start_date, freq='D', periods=5))
result = str(s1)
assert start_date in result
dti = date_range(start=start_date, freq='D', periods=5)
s2 = Series(3, index=dti)
result = str(s2.index)
assert start_date in result
def test_timedelta64(self):
from datetime import datetime, timedelta
Series(np.array([1100, 20], dtype='timedelta64[ns]')).to_string()
s = Series(date_range('2012-1-1', periods=3, freq='D'))
# GH2146
# adding NaTs
y = s - s.shift(1)
result = y.to_string()
assert '1 days' in result
assert '00:00:00' not in result
assert 'NaT' in result
# with frac seconds
o = Series([datetime(2012, 1, 1, microsecond=150)] * 3)
y = s - o
result = y.to_string()
assert '-1 days +23:59:59.999850' in result
# rounding?
o = Series([datetime(2012, 1, 1, 1)] * 3)
y = s - o
result = y.to_string()
assert '-1 days +23:00:00' in result
assert '1 days 23:00:00' in result
o = Series([datetime(2012, 1, 1, 1, 1)] * 3)
y = s - o
result = y.to_string()
assert '-1 days +22:59:00' in result
assert '1 days 22:59:00' in result
o = Series([datetime(2012, 1, 1, 1, 1, microsecond=150)] * 3)
y = s - o
result = y.to_string()
assert '-1 days +22:58:59.999850' in result
assert '0 days 22:58:59.999850' in result
# neg time
td = timedelta(minutes=5, seconds=3)
s2 = Series(date_range('2012-1-1', periods=3, freq='D')) + td
y = s - s2
result = y.to_string()
assert '-1 days +23:54:57' in result
td = timedelta(microseconds=550)
s2 = Series(date_range('2012-1-1', periods=3, freq='D')) + td
y = s - td
result = y.to_string()
assert '2012-01-01 23:59:59.999450' in result
# no boxing of the actual elements
td = Series(pd.timedelta_range('1 days', periods=3))
result = td.to_string()
assert result == u("0 1 days\n1 2 days\n2 3 days")
def test_mixed_datetime64(self):
df = DataFrame({'A': [1, 2], 'B': ['2012-01-01', '2012-01-02']})
df['B'] = pd.to_datetime(df.B)
result = repr(df.loc[0])
assert '2012-01-01' in result
def test_period(self):
# GH 12615
index = pd.period_range('2013-01', periods=6, freq='M')
s = Series(np.arange(6, dtype='int64'), index=index)
exp = ("2013-01 0\n"
"2013-02 1\n"
"2013-03 2\n"
"2013-04 3\n"
"2013-05 4\n"
"2013-06 5\n"
"Freq: M, dtype: int64")
assert str(s) == exp
s = Series(index)
exp = ("0 2013-01\n"
"1 2013-02\n"
"2 2013-03\n"
"3 2013-04\n"
"4 2013-05\n"
"5 2013-06\n"
"dtype: period[M]")
assert str(s) == exp
# periods with mixed freq
s = Series([pd.Period('2011-01', freq='M'),
pd.Period('2011-02-01', freq='D'),
pd.Period('2011-03-01 09:00', freq='H')])
exp = ("0 2011-01\n1 2011-02-01\n"
"2 2011-03-01 09:00\ndtype: object")
assert str(s) == exp
def test_max_multi_index_display(self):
# GH 7101
# doc example (indexing.rst)
# multi-index
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = Series(np.random.randn(8), index=index)
with option_context("display.max_rows", 10):
assert len(str(s).split('\n')) == 10
with option_context("display.max_rows", 3):
assert len(str(s).split('\n')) == 5
with option_context("display.max_rows", 2):
assert len(str(s).split('\n')) == 5
with option_context("display.max_rows", 1):
assert len(str(s).split('\n')) == 4
with option_context("display.max_rows", 0):
assert len(str(s).split('\n')) == 10
# index
s = Series(np.random.randn(8), None)
with option_context("display.max_rows", 10):
assert len(str(s).split('\n')) == 9
with option_context("display.max_rows", 3):
assert len(str(s).split('\n')) == 4
with option_context("display.max_rows", 2):
assert len(str(s).split('\n')) == 4
with option_context("display.max_rows", 1):
assert len(str(s).split('\n')) == 3
with option_context("display.max_rows", 0):
assert len(str(s).split('\n')) == 9
# Make sure #8532 is fixed
def test_consistent_format(self):
s = pd.Series([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9999, 1, 1] * 10)
with option_context("display.max_rows", 10,
"display.show_dimensions", False):
res = repr(s)
exp = ('0 1.0000\n1 1.0000\n2 1.0000\n3 '
'1.0000\n4 1.0000\n ... \n125 '
'1.0000\n126 1.0000\n127 0.9999\n128 '
'1.0000\n129 1.0000\ndtype: float64')
assert res == exp
def chck_ncols(self, s):
with option_context("display.max_rows", 10):
res = repr(s)
lines = res.split('\n')
lines = [line for line in repr(s).split('\n')
if not re.match(r'[^\.]*\.+', line)][:-1]
ncolsizes = len({len(line.strip()) for line in lines})
assert ncolsizes == 1
def test_format_explicit(self):
test_sers = gen_series_formatting()
with option_context("display.max_rows", 4,
"display.show_dimensions", False):
res = repr(test_sers['onel'])
exp = '0 a\n1 a\n ..\n98 a\n99 a\ndtype: object'
assert exp == res
res = repr(test_sers['twol'])
exp = ('0 ab\n1 ab\n ..\n98 ab\n99 ab\ndtype:'
' object')
assert exp == res
res = repr(test_sers['asc'])
exp = ('0 a\n1 ab\n ... \n4 abcde\n5'
' abcdef\ndtype: object')
assert exp == res
res = repr(test_sers['desc'])
exp = ('5 abcdef\n4 abcde\n ... \n1 ab\n0'
' a\ndtype: object')
assert exp == res
def test_ncols(self):
test_sers = gen_series_formatting()
for s in test_sers.values():
self.chck_ncols(s)
def test_max_rows_eq_one(self):
s = Series(range(10), dtype='int64')
with option_context("display.max_rows", 1):
strrepr = repr(s).split('\n')
exp1 = ['0', '0']
res1 = strrepr[0].split()
assert exp1 == res1
exp2 = ['..']
res2 = strrepr[1].split()
assert exp2 == res2
def test_truncate_ndots(self):
def getndots(s):
return len(re.match(r'[^\.]*(\.*)', s).groups()[0])
s = Series([0, 2, 3, 6])
with option_context("display.max_rows", 2):
strrepr = repr(s).replace('\n', '')
assert getndots(strrepr) == 2
s = Series([0, 100, 200, 400])
with option_context("display.max_rows", 2):
strrepr = repr(s).replace('\n', '')
assert getndots(strrepr) == 3
def test_show_dimensions(self):
# gh-7117
s = Series(range(5))
assert 'Length' not in repr(s)
with option_context("display.max_rows", 4):
assert 'Length' in repr(s)
with option_context("display.show_dimensions", True):
assert 'Length' in repr(s)
with option_context("display.max_rows", 4,
"display.show_dimensions", False):
assert 'Length' not in repr(s)
def test_to_string_name(self):
s = Series(range(100), dtype='int64')
s.name = 'myser'
res = s.to_string(max_rows=2, name=True)
exp = '0 0\n ..\n99 99\nName: myser'
assert res == exp
res = s.to_string(max_rows=2, name=False)
exp = '0 0\n ..\n99 99'
assert res == exp
def test_to_string_dtype(self):
s = Series(range(100), dtype='int64')
res = s.to_string(max_rows=2, dtype=True)
exp = '0 0\n ..\n99 99\ndtype: int64'
assert res == exp
res = s.to_string(max_rows=2, dtype=False)
exp = '0 0\n ..\n99 99'
assert res == exp
def test_to_string_length(self):
s = Series(range(100), dtype='int64')
res = s.to_string(max_rows=2, length=True)
exp = '0 0\n ..\n99 99\nLength: 100'
assert res == exp
def test_to_string_na_rep(self):
s = pd.Series(index=range(100))
res = s.to_string(na_rep='foo', max_rows=2)
exp = '0 foo\n ..\n99 foo'
assert res == exp
def test_to_string_float_format(self):
s = pd.Series(range(10), dtype='float64')
res = s.to_string(float_format=lambda x: '{0:2.1f}'.format(x),
max_rows=2)
exp = '0 0.0\n ..\n9 9.0'
assert res == exp
def test_to_string_header(self):
s = pd.Series(range(10), dtype='int64')
s.index.name = 'foo'
res = s.to_string(header=True, max_rows=2)
exp = 'foo\n0 0\n ..\n9 9'
assert res == exp
res = s.to_string(header=False, max_rows=2)
exp = '0 0\n ..\n9 9'
assert res == exp
def _three_digit_exp():
return '{x:.4g}'.format(x=1.7e8) == '1.7e+008'
class TestFloatArrayFormatter(object):
def test_misc(self):
obj = fmt.FloatArrayFormatter(np.array([], dtype=np.float64))
result = obj.get_result()
assert len(result) == 0
def test_format(self):
obj = fmt.FloatArrayFormatter(np.array([12, 0], dtype=np.float64))
result = obj.get_result()
assert result[0] == " 12.0"
assert result[1] == " 0.0"
def test_output_significant_digits(self):
# Issue #9764
# In case default display precision changes:
with pd.option_context('display.precision', 6):
# DataFrame example from issue #9764
d = pd.DataFrame(
{'col1': [9.999e-8, 1e-7, 1.0001e-7, 2e-7, 4.999e-7, 5e-7,
5.0001e-7, 6e-7, 9.999e-7, 1e-6, 1.0001e-6, 2e-6,
4.999e-6, 5e-6, 5.0001e-6, 6e-6]})
expected_output = {
(0, 6):
' col1\n'
'0 9.999000e-08\n'
'1 1.000000e-07\n'
'2 1.000100e-07\n'
'3 2.000000e-07\n'
'4 4.999000e-07\n'
'5 5.000000e-07',
(1, 6):
' col1\n'
'1 1.000000e-07\n'
'2 1.000100e-07\n'
'3 2.000000e-07\n'
'4 4.999000e-07\n'
'5 5.000000e-07',
(1, 8):
' col1\n'
'1 1.000000e-07\n'
'2 1.000100e-07\n'
'3 2.000000e-07\n'
'4 4.999000e-07\n'
'5 5.000000e-07\n'
'6 5.000100e-07\n'
'7 6.000000e-07',
(8, 16):
' col1\n'
'8 9.999000e-07\n'
'9 1.000000e-06\n'
'10 1.000100e-06\n'
'11 2.000000e-06\n'
'12 4.999000e-06\n'
'13 5.000000e-06\n'
'14 5.000100e-06\n'
'15 6.000000e-06',
(9, 16):
' col1\n'
'9 0.000001\n'
'10 0.000001\n'
'11 0.000002\n'
'12 0.000005\n'
'13 0.000005\n'
'14 0.000005\n'
'15 0.000006'
}
for (start, stop), v in expected_output.items():
assert str(d[start:stop]) == v
def test_too_long(self):
# GH 10451
with pd.option_context('display.precision', 4):
# need both a number > 1e6 and something that normally formats to
# having length > display.precision + 6
df = pd.DataFrame(dict(x=[12345.6789]))
assert str(df) == ' x\n0 12345.6789'
df = pd.DataFrame(dict(x=[2e6]))
assert str(df) == ' x\n0 2000000.0'
df = pd.DataFrame(dict(x=[12345.6789, 2e6]))
assert str(df) == ' x\n0 1.2346e+04\n1 2.0000e+06'
class TestRepr_timedelta64(object):
def test_none(self):
delta_1d = pd.to_timedelta(1, unit='D')
delta_0d = pd.to_timedelta(0, unit='D')
delta_1s = pd.to_timedelta(1, unit='s')
delta_500ms = pd.to_timedelta(500, unit='ms')
drepr = lambda x: x._repr_base()
assert drepr(delta_1d) == "1 days"
assert drepr(-delta_1d) == "-1 days"
assert drepr(delta_0d) == "0 days"
assert drepr(delta_1s) == "0 days 00:00:01"
assert drepr(delta_500ms) == "0 days 00:00:00.500000"
assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"
assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"
assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"
assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"
def test_sub_day(self):
delta_1d = pd.to_timedelta(1, unit='D')
delta_0d = pd.to_timedelta(0, unit='D')
delta_1s = pd.to_timedelta(1, unit='s')
delta_500ms = pd.to_timedelta(500, unit='ms')
drepr = lambda x: x._repr_base(format='sub_day')
assert drepr(delta_1d) == "1 days"
assert drepr(-delta_1d) == "-1 days"
assert drepr(delta_0d) == "00:00:00"
assert drepr(delta_1s) == "00:00:01"
assert drepr(delta_500ms) == "00:00:00.500000"
assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"
assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"
assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"
assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"
def test_long(self):
delta_1d = pd.to_timedelta(1, unit='D')
delta_0d = pd.to_timedelta(0, unit='D')
delta_1s = pd.to_timedelta(1, unit='s')
delta_500ms = pd.to_timedelta(500, unit='ms')
drepr = lambda x: x._repr_base(format='long')
assert drepr(delta_1d) == "1 days 00:00:00"
assert drepr(-delta_1d) == "-1 days +00:00:00"
assert drepr(delta_0d) == "0 days 00:00:00"
assert drepr(delta_1s) == "0 days 00:00:01"
assert drepr(delta_500ms) == "0 days 00:00:00.500000"
assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"
assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"
assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"
assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"
def test_all(self):
delta_1d = pd.to_timedelta(1, unit='D')
delta_0d = pd.to_timedelta(0, unit='D')
delta_1ns = pd.to_timedelta(1, unit='ns')
drepr = lambda x: x._repr_base(format='all')
assert drepr(delta_1d) == "1 days 00:00:00.000000000"
assert drepr(-delta_1d) == "-1 days +00:00:00.000000000"
assert drepr(delta_0d) == "0 days 00:00:00.000000000"
assert drepr(delta_1ns) == "0 days 00:00:00.000000001"
assert drepr(-delta_1d + delta_1ns) == "-1 days +00:00:00.000000001"
class TestTimedelta64Formatter(object):
def test_days(self):
x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D')
result = fmt.Timedelta64Formatter(x, box=True).get_result()
assert result[0].strip() == "'0 days'"
assert result[1].strip() == "'1 days'"
result = fmt.Timedelta64Formatter(x[1:2], box=True).get_result()
assert result[0].strip() == "'1 days'"
result = fmt.Timedelta64Formatter(x, box=False).get_result()
assert result[0].strip() == "0 days"
assert result[1].strip() == "1 days"
result = fmt.Timedelta64Formatter(x[1:2], box=False).get_result()
assert result[0].strip() == "1 days"
def test_days_neg(self):
x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D')
result = fmt.Timedelta64Formatter(-x, box=True).get_result()
assert result[0].strip() == "'0 days'"
assert result[1].strip() == "'-1 days'"
def test_subdays(self):
y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s')
result = fmt.Timedelta64Formatter(y, box=True).get_result()
assert result[0].strip() == "'00:00:00'"
assert result[1].strip() == "'00:00:01'"
def test_subdays_neg(self):
y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s')
result = fmt.Timedelta64Formatter(-y, box=True).get_result()
assert result[0].strip() == "'00:00:00'"
assert result[1].strip() == "'-1 days +23:59:59'"
def test_zero(self):
x = pd.to_timedelta(list(range(1)) + [pd.NaT], unit='D')
result = fmt.Timedelta64Formatter(x, box=True).get_result()
assert result[0].strip() == "'0 days'"
x = pd.to_timedelta(list(range(1)), unit='D')
result = fmt.Timedelta64Formatter(x, box=True).get_result()
assert result[0].strip() == "'0 days'"
class TestDatetime64Formatter(object):
def test_mixed(self):
x = Series([datetime(2013, 1, 1), datetime(2013, 1, 1, 12), pd.NaT])
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "2013-01-01 00:00:00"
assert result[1].strip() == "2013-01-01 12:00:00"
def test_dates(self):
x = Series([datetime(2013, 1, 1), datetime(2013, 1, 2), pd.NaT])
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "2013-01-01"
assert result[1].strip() == "2013-01-02"
def test_date_nanos(self):
x = Series([Timestamp(200)])
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "1970-01-01 00:00:00.000000200"
def test_dates_display(self):
# 10170
# make sure that we are consistently display date formatting
x = Series(date_range('20130101 09:00:00', periods=5, freq='D'))
x.iloc[1] = np.nan
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "2013-01-01 09:00:00"
assert result[1].strip() == "NaT"
assert result[4].strip() == "2013-01-05 09:00:00"
x = Series(date_range('20130101 09:00:00', periods=5, freq='s'))
x.iloc[1] = np.nan
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "2013-01-01 09:00:00"
assert result[1].strip() == "NaT"
assert result[4].strip() == "2013-01-01 09:00:04"
x = Series(date_range('20130101 09:00:00', periods=5, freq='ms'))
x.iloc[1] = np.nan
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "2013-01-01 09:00:00.000"
assert result[1].strip() == "NaT"
assert result[4].strip() == "2013-01-01 09:00:00.004"
x = Series(date_range('20130101 09:00:00', periods=5, freq='us'))
x.iloc[1] = np.nan
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "2013-01-01 09:00:00.000000"
assert result[1].strip() == "NaT"
assert result[4].strip() == "2013-01-01 09:00:00.000004"
x = Series(date_range('20130101 09:00:00', periods=5, freq='N'))
x.iloc[1] = np.nan
result = fmt.Datetime64Formatter(x).get_result()
assert result[0].strip() == "2013-01-01 09:00:00.000000000"
assert result[1].strip() == "NaT"
assert result[4].strip() == "2013-01-01 09:00:00.000000004"
def test_datetime64formatter_yearmonth(self):
x = Series([datetime(2016, 1, 1), datetime(2016, 2, 2)])
def format_func(x):
return x.strftime('%Y-%m')
formatter = fmt.Datetime64Formatter(x, formatter=format_func)
result = formatter.get_result()
assert result == ['2016-01', '2016-02']
def test_datetime64formatter_hoursecond(self):
x = Series(pd.to_datetime(['10:10:10.100', '12:12:12.120'],
format='%H:%M:%S.%f'))
def format_func(x):
return x.strftime('%H:%M')
formatter = fmt.Datetime64Formatter(x, formatter=format_func)
result = formatter.get_result()
assert result == ['10:10', '12:12']
class TestNaTFormatting(object):
def test_repr(self):
assert repr(pd.NaT) == "NaT"
def test_str(self):
assert str(pd.NaT) == "NaT"
class TestDatetimeIndexFormat(object):
def test_datetime(self):
formatted = pd.to_datetime([datetime(2003, 1, 1, 12), pd.NaT]).format()
assert formatted[0] == "2003-01-01 12:00:00"
assert formatted[1] == "NaT"
def test_date(self):
formatted = pd.to_datetime([datetime(2003, 1, 1), pd.NaT]).format()
assert formatted[0] == "2003-01-01"
assert formatted[1] == "NaT"
def test_date_tz(self):
formatted = pd.to_datetime([datetime(2013, 1, 1)], utc=True).format()
assert formatted[0] == "2013-01-01 00:00:00+00:00"
formatted = pd.to_datetime(
[datetime(2013, 1, 1), pd.NaT], utc=True).format()
assert formatted[0] == "2013-01-01 00:00:00+00:00"
def test_date_explicit_date_format(self):
formatted = pd.to_datetime([datetime(2003, 2, 1), pd.NaT]).format(
date_format="%m-%d-%Y", na_rep="UT")
assert formatted[0] == "02-01-2003"
assert formatted[1] == "UT"
class TestDatetimeIndexUnicode(object):
def test_dates(self):
text = str(pd.to_datetime([datetime(2013, 1, 1), datetime(2014, 1, 1)
]))
assert "['2013-01-01'," in text
assert ", '2014-01-01']" in text
def test_mixed(self):
text = str(pd.to_datetime([datetime(2013, 1, 1), datetime(
2014, 1, 1, 12), datetime(2014, 1, 1)]))
assert "'2013-01-01 00:00:00'," in text
assert "'2014-01-01 00:00:00']" in text
class TestStringRepTimestamp(object):
def test_no_tz(self):
dt_date = datetime(2013, 1, 2)
assert str(dt_date) == str(Timestamp(dt_date))
dt_datetime = datetime(2013, 1, 2, 12, 1, 3)
assert str(dt_datetime) == str(Timestamp(dt_datetime))
dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45)
assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))
ts_nanos_only = Timestamp(200)
assert str(ts_nanos_only) == "1970-01-01 00:00:00.000000200"
ts_nanos_micros = Timestamp(1200)
assert str(ts_nanos_micros) == "1970-01-01 00:00:00.000001200"
def test_tz_pytz(self):
dt_date = datetime(2013, 1, 2, tzinfo=pytz.utc)
assert str(dt_date) == str(Timestamp(dt_date))
dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=pytz.utc)
assert str(dt_datetime) == str(Timestamp(dt_datetime))
dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=pytz.utc)
assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))
def test_tz_dateutil(self):
utc = dateutil.tz.tzutc()
dt_date = datetime(2013, 1, 2, tzinfo=utc)
assert str(dt_date) == str(Timestamp(dt_date))
dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=utc)
assert str(dt_datetime) == str(Timestamp(dt_datetime))
dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=utc)
assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))
def test_nat_representations(self):
for f in (str, repr, methodcaller('isoformat')):
assert f(pd.NaT) == 'NaT'
def test_format_percentiles():
result = fmt.format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999])
expected = ['1.999%', '2.001%', '50%', '66.667%', '99.99%']
assert result == expected
result = fmt.format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999])
expected = ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%']
assert result == expected
msg = r"percentiles should all be in the interval \[0,1\]"
with pytest.raises(ValueError, match=msg):
fmt.format_percentiles([0.1, np.nan, 0.5])
with pytest.raises(ValueError, match=msg):
fmt.format_percentiles([-0.001, 0.1, 0.5])
with pytest.raises(ValueError, match=msg):
fmt.format_percentiles([2, 0.1, 0.5])
with pytest.raises(ValueError, match=msg):
fmt.format_percentiles([0.1, 0.5, 'a'])
def test_repr_html_ipython_config(ip):
code = textwrap.dedent("""\
import pandas as pd
df = pd.DataFrame({"A": [1, 2]})
df._repr_html_()
cfg = get_ipython().config
cfg['IPKernelApp']['parent_appname']
df._repr_html_()
""")
result = ip.run_cell(code)
assert not result.error_in_exec<|fim▁end|> | 'B': np.arange(41, 41 + h)}).set_index('idx') |
<|file_name|>ND280Transform_CSVEvtList.py<|end_file_name|><|fim▁begin|>from GangaCore.GPIDev.Schema import *
from GangaCore.GPIDev.Lib.Tasks.common import *
from GangaCore.GPIDev.Lib.Tasks.ITransform import ITransform
from GangaCore.GPIDev.Lib.Job.Job import JobError
from GangaCore.GPIDev.Lib.Registry.JobRegistry import JobRegistrySlice, JobRegistrySliceProxy
from GangaCore.Core.exceptions import ApplicationConfigurationError
from GangaCore.GPIDev.Lib.Tasks.ITransform import ITransform
from GangaCore.GPIDev.Lib.Tasks.TaskLocalCopy import TaskLocalCopy
from GangaCore.Utility.logging import getLogger
from .ND280Unit_CSVEvtList import ND280Unit_CSVEvtList
from GangaND280.ND280Dataset.ND280Dataset import ND280LocalDataset
from GangaND280.ND280Splitter import splitCSVFile
import GangaCore.GPI as GPI
import os
logger = getLogger()
class ND280Transform_CSVEvtList(ITransform):
_schema = Schema(Version(1,0), dict(list(ITransform._schema.datadict.items()) + list({
'nbevents' : SimpleItem(defvalue=-1,doc='The number of events for each unit'),
}.items())))
_category = 'transforms'
_name = 'ND280Transform_CSVEvtList'
_exportmethods = ITransform._exportmethods + [ ]
def __init__(self):
super(ND280Transform_CSVEvtList,self).__init__()
def createUnits(self):
"""Create new units if required given the inputdata"""
# call parent for chaining
super(ND280Transform_CSVEvtList,self).createUnits()
# Look at the application schema and check if there is a csvfile variable
try:
csvfile = self.application.csvfile
except AttributeError:
logger.error('This application doesn\'t contain a csvfile variable. Use another Transform !')
return
subsets = splitCSVFile(self.application.csvfile, self.nbevents)
for s,sub in enumerate(subsets):
# check if this data is being run over by checking all the names listed
ok = False
for unit in self.units:
if unit.subpartid == s:
ok = True
if ok:
continue
# new unit required for this dataset
unit = ND280Unit_CSVEvtList()
unit.name = "Unit %d" % len(self.units)
unit.subpartid = s
unit.eventswanted = sub
unit.inputdata = self.inputdata[0]
self.addUnitToTRF( unit )
def createChainUnit( self, parent_units, use_copy_output = True ):
"""Create a chained unit using the output data from the given units"""
# check all parent units for copy_output
copy_output_ok = True
for parent in parent_units:
if not parent.copy_output:
copy_output_ok = False
# all parent units must be completed so the outputfiles are filled correctly
for parent in parent_units:<|fim▁hole|> if not use_copy_output or not copy_output_ok:
unit = ND280Unit_CSVEvtList()
unit.inputdata = ND280LocalDataset()
for parent in parent_units:
# loop over the output files and add them to the ND280LocalDataset - THIS MIGHT NEED SOME WORK!
job = GPI.jobs(parent.active_job_ids[0])
for f in job.outputfiles:
# should check for different file types and add them as appropriate to the dataset
# self.inputdata (== TaskChainInput).include/exclude_file_mask could help with this
# This will be A LOT easier with Ganga 6.1 as you can easily map outputfiles -> inputfiles!
unit.inputdata.names.append( os.path.join( job.outputdir, f.namePattern ) )
else:
unit = ND280Unit_CSVEvtList()
unit.inputdata = ND280LocalDataset()
for parent in parent_units:
# unit needs to have completed and downloaded before we can get file list
if parent.status != "completed":
return None
# we should be OK so copy all output to the dataset
for f in parent.copy_output.files:
unit.inputdata.names.append( os.path.join( parent.copy_output.local_location, f ) )
return unit<|fim▁end|> | if parent.status != "completed":
return None
|
<|file_name|>position_correction.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
/***************************************************************************
SuroLeveling
A QGIS plugin
todo
-------------------
begin : 2016-02-12
git sha : $Format:%H$
copyright : (C) 2016 by Ondřej Pešek
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, Qt
from PyQt4.QtGui import QAction, QIcon
# Initialize Qt resources from file resources.py
import resources
# Import the code for the DockWidget
#from suro_leveling_dockwidget import PositionCorrectionDockWidget#SuroLevelingDockWidget
from position_correction_dockwidget import PositionCorrectionDockWidget
import os.path
class PositionCorrection:#SuroLeveling:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'SuroLeveling_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&GPS position lag correction')
#print "** INITIALIZING SuroLeveling"
self.pluginIsActive = False
self.dockwidget = None
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('GPS position lag correction', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
self.iface.addToolBarIcon(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/SuroLeveling/icon.png'
self.add_action(
icon_path,
text=self.tr(u'GPS position lag correction'),
callback=self.run,
parent=self.iface.mainWindow())
#--------------------------------------------------------------------------
#def onClosePlugin(self): CAUSE OF ENABLE SECOND OPENING
# """Cleanup necessary items here when plugin dockwidget is closed"""
# print "** CLOSING SuroLeveling"
# disconnects
# self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
# self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
#print "** UNLOAD SuroLeveling"
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&GPS position lag correction'),
action)
self.iface.removeToolBarIcon(action)
#--------------------------------------------------------------------------
def run(self):
"""Run method that loads and starts the plugin"""
if not self.pluginIsActive:
self.pluginIsActive = True
#print "** STARTING SuroLeveling"
# dockwidget may not exist if:
# first run of plugin
# removed on close (see self.onClosePlugin method)
if self.dockwidget == None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = PositionCorrectionDockWidget()#SuroLevelingDockWidget()
<|fim▁hole|>
# show the dockwidget
self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
self.dockwidget.show()
self.pluginIsActive = False<|fim▁end|> | # connect to provide cleanup on closing of dockwidget
# self.dockwidget.closingPlugin.connect(self.onClosePlugin) CAUSE OF ENABLE SECOND OPENING |
<|file_name|>opcode_ins.py<|end_file_name|><|fim▁begin|># This file is part of Androguard.
#
# Copyright (C) 2012, Geoffroy Gueguen <[email protected]>
# 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.
from builtins import range
from builtins import object
import logging
from struct import pack, unpack
import androguard.decompiler.dad.util as util
from androguard.decompiler.dad.instruction import (
ArrayLengthExpression, ArrayLoadExpression, ArrayStoreInstruction,
AssignExpression, BaseClass, BinaryCompExpression, BinaryExpression,
BinaryExpression2Addr, BinaryExpressionLit, CastExpression,
CheckCastExpression, ConditionalExpression, ConditionalZExpression,
Constant, FillArrayExpression, FilledArrayExpression, InstanceExpression,
InstanceInstruction, InvokeInstruction, InvokeDirectInstruction,
InvokeRangeInstruction, InvokeStaticInstruction, MonitorEnterExpression,
MonitorExitExpression, MoveExceptionExpression, MoveExpression,
MoveResultExpression, NewArrayExpression, NewInstance, NopExpression,
ThrowExpression, Variable, ReturnInstruction, StaticExpression,
StaticInstruction, SwitchExpression, ThisParam, UnaryExpression)
logger = logging.getLogger('dad.opcode_ins')
class Op(object):
CMP = 'cmp'
ADD = '+'
SUB = '-'
MUL = '*'
DIV = '/'
MOD = '%'
AND = '&'
OR = '|'
XOR = '^'
EQUAL = '=='
NEQUAL = '!='
GREATER = '>'
LOWER = '<'
GEQUAL = '>='
LEQUAL = '<='
NEG = '-'
NOT = '~'
INTSHL = '<<' # '(%s << ( %s & 0x1f ))'
INTSHR = '>>' # '(%s >> ( %s & 0x1f ))'
LONGSHL = '<<' # '(%s << ( %s & 0x3f ))'
LONGSHR = '>>' # '(%s >> ( %s & 0x3f ))'
def get_variables(vmap, *variables):
res = []
for variable in variables:
res.append(vmap.setdefault(variable, Variable(variable)))
if len(res) == 1:
return res[0]
return res
def assign_const(dest_reg, cst, vmap):
return AssignExpression(get_variables(vmap, dest_reg), cst)
def assign_cmp(val_a, val_b, val_c, cmp_type, vmap):
reg_a, reg_b, reg_c = get_variables(vmap, val_a, val_b, val_c)
exp = BinaryCompExpression(Op.CMP, reg_b, reg_c, cmp_type)
return AssignExpression(reg_a, exp)
def load_array_exp(val_a, val_b, val_c, ar_type, vmap):
reg_a, reg_b, reg_c = get_variables(vmap, val_a, val_b, val_c)
return AssignExpression(reg_a, ArrayLoadExpression(reg_b, reg_c, ar_type))
def store_array_inst(val_a, val_b, val_c, ar_type, vmap):
reg_a, reg_b, reg_c = get_variables(vmap, val_a, val_b, val_c)
return ArrayStoreInstruction(reg_a, reg_b, reg_c, ar_type)
def assign_cast_exp(val_a, val_b, val_op, op_type, vmap):
reg_a, reg_b = get_variables(vmap, val_a, val_b)
return AssignExpression(reg_a, CastExpression(val_op, op_type, reg_b))
def assign_binary_exp(ins, val_op, op_type, vmap):
reg_a, reg_b, reg_c = get_variables(vmap, ins.AA, ins.BB, ins.CC)
return AssignExpression(reg_a, BinaryExpression(val_op, reg_b, reg_c,
op_type))
def assign_binary_2addr_exp(ins, val_op, op_type, vmap):
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
return AssignExpression(reg_a, BinaryExpression2Addr(val_op, reg_a, reg_b,
op_type))
def assign_lit(op_type, val_cst, val_a, val_b, vmap):
cst = Constant(val_cst, 'I')
var_a, var_b = get_variables(vmap, val_a, val_b)
return AssignExpression(var_a, BinaryExpressionLit(op_type, var_b, cst))
# nop
def nop(ins, vmap):
return NopExpression()
# move vA, vB ( 4b, 4b )
def move(ins, vmap):
logger.debug('Move %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
return MoveExpression(reg_a, reg_b)
# move/from16 vAA, vBBBB ( 8b, 16b )
def movefrom16(ins, vmap):
logger.debug('MoveFrom16 %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.AA, ins.BBBB)
return MoveExpression(reg_a, reg_b)
# move/16 vAAAA, vBBBB ( 16b, 16b )
def move16(ins, vmap):
logger.debug('Move16 %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.AAAA, ins.BBBB)
return MoveExpression(reg_a, reg_b)
# move-wide vA, vB ( 4b, 4b )
def movewide(ins, vmap):
logger.debug('MoveWide %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
return MoveExpression(reg_a, reg_b)
# move-wide/from16 vAA, vBBBB ( 8b, 16b )
def movewidefrom16(ins, vmap):
logger.debug('MoveWideFrom16 : %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.AA, ins.BBBB)
return MoveExpression(reg_a, reg_b)
# move-wide/16 vAAAA, vBBBB ( 16b, 16b )
def movewide16(ins, vmap):
logger.debug('MoveWide16 %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.AAAA, ins.BBBB)
return MoveExpression(reg_a, reg_b)
# move-object vA, vB ( 4b, 4b )
def moveobject(ins, vmap):
logger.debug('MoveObject %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
return MoveExpression(reg_a, reg_b)
# move-object/from16 vAA, vBBBB ( 8b, 16b )
def moveobjectfrom16(ins, vmap):
logger.debug('MoveObjectFrom16 : %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.AA, ins.BBBB)
return MoveExpression(reg_a, reg_b)
# move-object/16 vAAAA, vBBBB ( 16b, 16b )
def moveobject16(ins, vmap):
logger.debug('MoveObject16 : %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.AAAA, ins.BBBB)
return MoveExpression(reg_a, reg_b)
# move-result vAA ( 8b )
def moveresult(ins, vmap, ret):
logger.debug('MoveResult : %s', ins.get_output())
return MoveResultExpression(get_variables(vmap, ins.AA), ret)
# move-result-wide vAA ( 8b )
def moveresultwide(ins, vmap, ret):
logger.debug('MoveResultWide : %s', ins.get_output())
return MoveResultExpression(get_variables(vmap, ins.AA), ret)
# move-result-object vAA ( 8b )
def moveresultobject(ins, vmap, ret):
logger.debug('MoveResultObject : %s', ins.get_output())
return MoveResultExpression(get_variables(vmap, ins.AA), ret)
# move-exception vAA ( 8b )
def moveexception(ins, vmap, _type):
logger.debug('MoveException : %s', ins.get_output())
return MoveExceptionExpression(get_variables(vmap, ins.AA), _type)
# return-void
def returnvoid(ins, vmap):
logger.debug('ReturnVoid')
return ReturnInstruction(None)
# return vAA ( 8b )
def return_reg(ins, vmap):
logger.debug('Return : %s', ins.get_output())
return ReturnInstruction(get_variables(vmap, ins.AA))
# return-wide vAA ( 8b )
def returnwide(ins, vmap):
logger.debug('ReturnWide : %s', ins.get_output())
return ReturnInstruction(get_variables(vmap, ins.AA))
# return-object vAA ( 8b )
def returnobject(ins, vmap):
logger.debug('ReturnObject : %s', ins.get_output())
return ReturnInstruction(get_variables(vmap, ins.AA))
# const/4 vA, #+B ( 4b, 4b )
def const4(ins, vmap):
logger.debug('Const4 : %s', ins.get_output())
cst = Constant(ins.B, 'I')
return assign_const(ins.A, cst, vmap)
# const/16 vAA, #+BBBB ( 8b, 16b )
def const16(ins, vmap):
logger.debug('Const16 : %s', ins.get_output())
cst = Constant(ins.BBBB, 'I')
return assign_const(ins.AA, cst, vmap)
# const vAA, #+BBBBBBBB ( 8b, 32b )
def const(ins, vmap):
logger.debug('Const : %s', ins.get_output())
value = unpack("=f", pack("=i", ins.BBBBBBBB))[0]
cst = Constant(value, 'I', ins.BBBBBBBB)
return assign_const(ins.AA, cst, vmap)
# const/high16 vAA, #+BBBB0000 ( 8b, 16b )
def consthigh16(ins, vmap):
logger.debug('ConstHigh16 : %s', ins.get_output())
value = unpack('=f', pack('=i', ins.BBBB << 16))[0]
cst = Constant(value, 'I', ins.BBBB << 16)
return assign_const(ins.AA, cst, vmap)
# const-wide/16 vAA, #+BBBB ( 8b, 16b )
def constwide16(ins, vmap):
logger.debug('ConstWide16 : %s', ins.get_output())
value = unpack('=d', pack('=d', ins.BBBB))[0]
cst = Constant(value, 'J', ins.BBBB)
return assign_const(ins.AA, cst, vmap)
# const-wide/32 vAA, #+BBBBBBBB ( 8b, 32b )
def constwide32(ins, vmap):
logger.debug('ConstWide32 : %s', ins.get_output())
value = unpack('=d', pack('=d', ins.BBBBBBBB))[0]
cst = Constant(value, 'J', ins.BBBBBBBB)
return assign_const(ins.AA, cst, vmap)
# const-wide vAA, #+BBBBBBBBBBBBBBBB ( 8b, 64b )
def constwide(ins, vmap):
logger.debug('ConstWide : %s', ins.get_output())
value = unpack('=d', pack('=q', ins.BBBBBBBBBBBBBBBB))[0]
cst = Constant(value, 'D', ins.BBBBBBBBBBBBBBBB)
return assign_const(ins.AA, cst, vmap)
# const-wide/high16 vAA, #+BBBB000000000000 ( 8b, 16b )
def constwidehigh16(ins, vmap):
logger.debug('ConstWideHigh16 : %s', ins.get_output())
value = unpack('=d', b'\x00\x00\x00\x00\x00\x00' + pack('=h', ins.BBBB))[0]
cst = Constant(value, 'D', ins.BBBB)
return assign_const(ins.AA, cst, vmap)
# const-string vAA ( 8b )
def conststring(ins, vmap):
logger.debug('ConstString : %s', ins.get_output())
cst = Constant(ins.get_raw_string(), 'Ljava/lang/String;')
return assign_const(ins.AA, cst, vmap)
# const-string/jumbo vAA ( 8b )
def conststringjumbo(ins, vmap):
logger.debug('ConstStringJumbo %s', ins.get_output())
cst = Constant(ins.get_raw_string(), 'Ljava/lang/String;')
return assign_const(ins.AA, cst, vmap)
# const-class vAA, type@BBBB ( 8b )
def constclass(ins, vmap):
logger.debug('ConstClass : %s', ins.get_output())
cst = Constant(util.get_type(ins.get_string()),
'Ljava/lang/Class;',
descriptor=ins.get_string())
return assign_const(ins.AA, cst, vmap)
# monitor-enter vAA ( 8b )
def monitorenter(ins, vmap):
logger.debug('MonitorEnter : %s', ins.get_output())
return MonitorEnterExpression(get_variables(vmap, ins.AA))
# monitor-exit vAA ( 8b )
def monitorexit(ins, vmap):
logger.debug('MonitorExit : %s', ins.get_output())
a = get_variables(vmap, ins.AA)
return MonitorExitExpression(a)
# check-cast vAA ( 8b )
def checkcast(ins, vmap):
logger.debug('CheckCast: %s', ins.get_output())
cast_type = util.get_type(ins.get_translated_kind())
cast_var = get_variables(vmap, ins.AA)
cast_expr = CheckCastExpression(cast_var,
cast_type,
descriptor=ins.get_translated_kind())
return AssignExpression(cast_var, cast_expr)
# instance-of vA, vB ( 4b, 4b )
def instanceof(ins, vmap):
logger.debug('InstanceOf : %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
reg_c = BaseClass(util.get_type(ins.get_translated_kind()),
descriptor=ins.get_translated_kind())
exp = BinaryExpression('instanceof', reg_b, reg_c, 'Z')
return AssignExpression(reg_a, exp)
# array-length vA, vB ( 4b, 4b )
def arraylength(ins, vmap):
logger.debug('ArrayLength: %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
return AssignExpression(reg_a, ArrayLengthExpression(reg_b))
# new-instance vAA ( 8b )
def newinstance(ins, vmap):
logger.debug('NewInstance : %s', ins.get_output())
reg_a = get_variables(vmap, ins.AA)
ins_type = ins.cm.get_type(ins.BBBB)
return AssignExpression(reg_a, NewInstance(ins_type))
# new-array vA, vB ( 8b, size )
def newarray(ins, vmap):
logger.debug('NewArray : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
exp = NewArrayExpression(b, ins.cm.get_type(ins.CCCC))
return AssignExpression(a, exp)
# filled-new-array {vD, vE, vF, vG, vA} ( 4b each )
def fillednewarray(ins, vmap, ret):
logger.debug('FilledNewArray : %s', ins.get_output())
c, d, e, f, g = get_variables(vmap, ins.C, ins.D, ins.E, ins.F, ins.G)
array_type = ins.cm.get_type(ins.BBBB)
exp = FilledArrayExpression(ins.A, array_type, [c, d, e, f, g][:ins.A])
return AssignExpression(ret, exp)
# filled-new-array/range {vCCCC..vNNNN} ( 16b )
def fillednewarrayrange(ins, vmap, ret):
logger.debug('FilledNewArrayRange : %s', ins.get_output())
a, c, n = get_variables(vmap, ins.AA, ins.CCCC, ins.NNNN)
array_type = ins.cm.get_type(ins.BBBB)
exp = FilledArrayExpression(a, array_type, [c, n])
return AssignExpression(ret, exp)
# fill-array-data vAA, +BBBBBBBB ( 8b, 32b )
def fillarraydata(ins, vmap, value):
logger.debug('FillArrayData : %s', ins.get_output())
return FillArrayExpression(get_variables(vmap, ins.AA), value)
# fill-array-data-payload vAA, +BBBBBBBB ( 8b, 32b )
def fillarraydatapayload(ins, vmap):
logger.debug('FillArrayDataPayload : %s', ins.get_output())
return FillArrayExpression(None)
# throw vAA ( 8b )
def throw(ins, vmap):
logger.debug('Throw : %s', ins.get_output())
return ThrowExpression(get_variables(vmap, ins.AA))
# goto +AA ( 8b )
def goto(ins, vmap):
return NopExpression()
# goto/16 +AAAA ( 16b )
def goto16(ins, vmap):
return NopExpression()
# goto/32 +AAAAAAAA ( 32b )
def goto32(ins, vmap):
return NopExpression()
# packed-switch vAA, +BBBBBBBB ( reg to test, 32b )
def packedswitch(ins, vmap):
logger.debug('PackedSwitch : %s', ins.get_output())
reg_a = get_variables(vmap, ins.AA)
return SwitchExpression(reg_a, ins.BBBBBBBB)
# sparse-switch vAA, +BBBBBBBB ( reg to test, 32b )
def sparseswitch(ins, vmap):
logger.debug('SparseSwitch : %s', ins.get_output())
reg_a = get_variables(vmap, ins.AA)
return SwitchExpression(reg_a, ins.BBBBBBBB)
# cmpl-float vAA, vBB, vCC ( 8b, 8b, 8b )
def cmplfloat(ins, vmap):
logger.debug('CmpglFloat : %s', ins.get_output())
return assign_cmp(ins.AA, ins.BB, ins.CC, 'F', vmap)
# cmpg-float vAA, vBB, vCC ( 8b, 8b, 8b )
def cmpgfloat(ins, vmap):
logger.debug('CmpgFloat : %s', ins.get_output())
return assign_cmp(ins.AA, ins.BB, ins.CC, 'F', vmap)
# cmpl-double vAA, vBB, vCC ( 8b, 8b, 8b )
def cmpldouble(ins, vmap):
logger.debug('CmplDouble : %s', ins.get_output())
return assign_cmp(ins.AA, ins.BB, ins.CC, 'D', vmap)
# cmpg-double vAA, vBB, vCC ( 8b, 8b, 8b )
def cmpgdouble(ins, vmap):
logger.debug('CmpgDouble : %s', ins.get_output())
return assign_cmp(ins.AA, ins.BB, ins.CC, 'D', vmap)
# cmp-long vAA, vBB, vCC ( 8b, 8b, 8b )
def cmplong(ins, vmap):
logger.debug('CmpLong : %s', ins.get_output())
return assign_cmp(ins.AA, ins.BB, ins.CC, 'J', vmap)
# if-eq vA, vB, +CCCC ( 4b, 4b, 16b )
def ifeq(ins, vmap):
logger.debug('IfEq : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
return ConditionalExpression(Op.EQUAL, a, b)
# if-ne vA, vB, +CCCC ( 4b, 4b, 16b )
def ifne(ins, vmap):
logger.debug('IfNe : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
return ConditionalExpression(Op.NEQUAL, a, b)
# if-lt vA, vB, +CCCC ( 4b, 4b, 16b )
def iflt(ins, vmap):
logger.debug('IfLt : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
return ConditionalExpression(Op.LOWER, a, b)
# if-ge vA, vB, +CCCC ( 4b, 4b, 16b )
def ifge(ins, vmap):
logger.debug('IfGe : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
return ConditionalExpression(Op.GEQUAL, a, b)
# if-gt vA, vB, +CCCC ( 4b, 4b, 16b )
def ifgt(ins, vmap):
logger.debug('IfGt : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
return ConditionalExpression(Op.GREATER, a, b)
# if-le vA, vB, +CCCC ( 4b, 4b, 16b )
def ifle(ins, vmap):
logger.debug('IfLe : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
return ConditionalExpression(Op.LEQUAL, a, b)
# if-eqz vAA, +BBBB ( 8b, 16b )
def ifeqz(ins, vmap):
logger.debug('IfEqz : %s', ins.get_output())
return ConditionalZExpression(Op.EQUAL, get_variables(vmap, ins.AA))
# if-nez vAA, +BBBB ( 8b, 16b )
def ifnez(ins, vmap):
logger.debug('IfNez : %s', ins.get_output())
return ConditionalZExpression(Op.NEQUAL, get_variables(vmap, ins.AA))
# if-ltz vAA, +BBBB ( 8b, 16b )
def ifltz(ins, vmap):
logger.debug('IfLtz : %s', ins.get_output())
return ConditionalZExpression(Op.LOWER, get_variables(vmap, ins.AA))
# if-gez vAA, +BBBB ( 8b, 16b )
def ifgez(ins, vmap):
logger.debug('IfGez : %s', ins.get_output())
return ConditionalZExpression(Op.GEQUAL, get_variables(vmap, ins.AA))
# if-gtz vAA, +BBBB ( 8b, 16b )
def ifgtz(ins, vmap):
logger.debug('IfGtz : %s', ins.get_output())
return ConditionalZExpression(Op.GREATER, get_variables(vmap, ins.AA))
# if-lez vAA, +BBBB (8b, 16b )
def iflez(ins, vmap):
logger.debug('IfLez : %s', ins.get_output())
return ConditionalZExpression(Op.LEQUAL, get_variables(vmap, ins.AA))
# TODO: check type for all aget
# aget vAA, vBB, vCC ( 8b, 8b, 8b )
def aget(ins, vmap):
logger.debug('AGet : %s', ins.get_output())
return load_array_exp(ins.AA, ins.BB, ins.CC, None, vmap)
# aget-wide vAA, vBB, vCC ( 8b, 8b, 8b )
def agetwide(ins, vmap):
logger.debug('AGetWide : %s', ins.get_output())
return load_array_exp(ins.AA, ins.BB, ins.CC, 'W', vmap)
# aget-object vAA, vBB, vCC ( 8b, 8b, 8b )
def agetobject(ins, vmap):
logger.debug('AGetObject : %s', ins.get_output())
return load_array_exp(ins.AA, ins.BB, ins.CC, 'O', vmap)
# aget-boolean vAA, vBB, vCC ( 8b, 8b, 8b )
def agetboolean(ins, vmap):
logger.debug('AGetBoolean : %s', ins.get_output())
return load_array_exp(ins.AA, ins.BB, ins.CC, 'Z', vmap)
# aget-byte vAA, vBB, vCC ( 8b, 8b, 8b )
def agetbyte(ins, vmap):
logger.debug('AGetByte : %s', ins.get_output())
return load_array_exp(ins.AA, ins.BB, ins.CC, 'B', vmap)
# aget-char vAA, vBB, vCC ( 8b, 8b, 8b )
def agetchar(ins, vmap):
logger.debug('AGetChar : %s', ins.get_output())
return load_array_exp(ins.AA, ins.BB, ins.CC, 'C', vmap)
# aget-short vAA, vBB, vCC ( 8b, 8b, 8b )
def agetshort(ins, vmap):
logger.debug('AGetShort : %s', ins.get_output())
return load_array_exp(ins.AA, ins.BB, ins.CC, 'S', vmap)
# aput vAA, vBB, vCC
def aput(ins, vmap):
logger.debug('APut : %s', ins.get_output())
return store_array_inst(ins.AA, ins.BB, ins.CC, None, vmap)
# aput-wide vAA, vBB, vCC ( 8b, 8b, 8b )
def aputwide(ins, vmap):
logger.debug('APutWide : %s', ins.get_output())
return store_array_inst(ins.AA, ins.BB, ins.CC, 'W', vmap)
# aput-object vAA, vBB, vCC ( 8b, 8b, 8b )
def aputobject(ins, vmap):
logger.debug('APutObject : %s', ins.get_output())
return store_array_inst(ins.AA, ins.BB, ins.CC, 'O', vmap)
# aput-boolean vAA, vBB, vCC ( 8b, 8b, 8b )
def aputboolean(ins, vmap):
logger.debug('APutBoolean : %s', ins.get_output())
return store_array_inst(ins.AA, ins.BB, ins.CC, 'Z', vmap)
# aput-byte vAA, vBB, vCC ( 8b, 8b, 8b )
def aputbyte(ins, vmap):
logger.debug('APutByte : %s', ins.get_output())
return store_array_inst(ins.AA, ins.BB, ins.CC, 'B', vmap)
# aput-char vAA, vBB, vCC ( 8b, 8b, 8b )
def aputchar(ins, vmap):
logger.debug('APutChar : %s', ins.get_output())
return store_array_inst(ins.AA, ins.BB, ins.CC, 'C', vmap)
# aput-short vAA, vBB, vCC ( 8b, 8b, 8b )
def aputshort(ins, vmap):
logger.debug('APutShort : %s', ins.get_output())
return store_array_inst(ins.AA, ins.BB, ins.CC, 'S', vmap)
# iget vA, vB ( 4b, 4b )
def iget(ins, vmap):
logger.debug('IGet : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
exp = InstanceExpression(b, klass, ftype, name)
return AssignExpression(a, exp)
# iget-wide vA, vB ( 4b, 4b )
def igetwide(ins, vmap):
logger.debug('IGetWide : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
exp = InstanceExpression(b, klass, ftype, name)
return AssignExpression(a, exp)
# iget-object vA, vB ( 4b, 4b )
def igetobject(ins, vmap):
logger.debug('IGetObject : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
exp = InstanceExpression(b, klass, ftype, name)
return AssignExpression(a, exp)
# iget-boolean vA, vB ( 4b, 4b )
def igetboolean(ins, vmap):
logger.debug('IGetBoolean : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
exp = InstanceExpression(b, klass, ftype, name)
return AssignExpression(a, exp)
# iget-byte vA, vB ( 4b, 4b )
def igetbyte(ins, vmap):
logger.debug('IGetByte : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
exp = InstanceExpression(b, klass, ftype, name)
return AssignExpression(a, exp)
# iget-char vA, vB ( 4b, 4b )
def igetchar(ins, vmap):
logger.debug('IGetChar : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
exp = InstanceExpression(b, klass, ftype, name)
return AssignExpression(a, exp)
# iget-short vA, vB ( 4b, 4b )
def igetshort(ins, vmap):
logger.debug('IGetShort : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
exp = InstanceExpression(b, klass, ftype, name)
return AssignExpression(a, exp)
# iput vA, vB ( 4b, 4b )
def iput(ins, vmap):
logger.debug('IPut %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
return InstanceInstruction(a, b, klass, atype, name)
# iput-wide vA, vB ( 4b, 4b )
def iputwide(ins, vmap):
logger.debug('IPutWide %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
return InstanceInstruction(a, b, klass, atype, name)
# iput-object vA, vB ( 4b, 4b )
def iputobject(ins, vmap):
logger.debug('IPutObject %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
return InstanceInstruction(a, b, klass, atype, name)
# iput-boolean vA, vB ( 4b, 4b )
def iputboolean(ins, vmap):
logger.debug('IPutBoolean %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
return InstanceInstruction(a, b, klass, atype, name)
# iput-byte vA, vB ( 4b, 4b )
def iputbyte(ins, vmap):
logger.debug('IPutByte %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
return InstanceInstruction(a, b, klass, atype, name)
# iput-char vA, vB ( 4b, 4b )
def iputchar(ins, vmap):
logger.debug('IPutChar %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
return InstanceInstruction(a, b, klass, atype, name)
# iput-short vA, vB ( 4b, 4b )
def iputshort(ins, vmap):
logger.debug('IPutShort %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.CCCC)
a, b = get_variables(vmap, ins.A, ins.B)
return InstanceInstruction(a, b, klass, atype, name)
# sget vAA ( 8b )
def sget(ins, vmap):
logger.debug('SGet : %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.BBBB)
exp = StaticExpression(klass, atype, name)
a = get_variables(vmap, ins.AA)
return AssignExpression(a, exp)
# sget-wide vAA ( 8b )
def sgetwide(ins, vmap):
logger.debug('SGetWide : %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.BBBB)
exp = StaticExpression(klass, atype, name)
a = get_variables(vmap, ins.AA)
return AssignExpression(a, exp)
# sget-object vAA ( 8b )
def sgetobject(ins, vmap):
logger.debug('SGetObject : %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.BBBB)
exp = StaticExpression(klass, atype, name)
a = get_variables(vmap, ins.AA)
return AssignExpression(a, exp)
# sget-boolean vAA ( 8b )
def sgetboolean(ins, vmap):
logger.debug('SGetBoolean : %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.BBBB)
exp = StaticExpression(klass, atype, name)
a = get_variables(vmap, ins.AA)
return AssignExpression(a, exp)
# sget-byte vAA ( 8b )
def sgetbyte(ins, vmap):
logger.debug('SGetByte : %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.BBBB)
exp = StaticExpression(klass, atype, name)
a = get_variables(vmap, ins.AA)
return AssignExpression(a, exp)
# sget-char vAA ( 8b )
def sgetchar(ins, vmap):
logger.debug('SGetChar : %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.BBBB)
exp = StaticExpression(klass, atype, name)
a = get_variables(vmap, ins.AA)
return AssignExpression(a, exp)
# sget-short vAA ( 8b )
def sgetshort(ins, vmap):
logger.debug('SGetShort : %s', ins.get_output())
klass, atype, name = ins.cm.get_field(ins.BBBB)
exp = StaticExpression(klass, atype, name)
a = get_variables(vmap, ins.AA)
return AssignExpression(a, exp)
# sput vAA ( 8b )
def sput(ins, vmap):
logger.debug('SPut : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.BBBB)
a = get_variables(vmap, ins.AA)
return StaticInstruction(a, klass, ftype, name)
# sput-wide vAA ( 8b )
def sputwide(ins, vmap):
logger.debug('SPutWide : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.BBBB)
a = get_variables(vmap, ins.AA)
return StaticInstruction(a, klass, ftype, name)
# sput-object vAA ( 8b )
def sputobject(ins, vmap):
logger.debug('SPutObject : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.BBBB)
a = get_variables(vmap, ins.AA)
return StaticInstruction(a, klass, ftype, name)
# sput-boolean vAA ( 8b )
def sputboolean(ins, vmap):
logger.debug('SPutBoolean : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.BBBB)
a = get_variables(vmap, ins.AA)
return StaticInstruction(a, klass, ftype, name)
# sput-wide vAA ( 8b )
def sputbyte(ins, vmap):
logger.debug('SPutByte : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.BBBB)
a = get_variables(vmap, ins.AA)
return StaticInstruction(a, klass, ftype, name)
# sput-char vAA ( 8b )
def sputchar(ins, vmap):
logger.debug('SPutChar : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.BBBB)
a = get_variables(vmap, ins.AA)
return StaticInstruction(a, klass, ftype, name)
# sput-short vAA ( 8b )
def sputshort(ins, vmap):
logger.debug('SPutShort : %s', ins.get_output())
klass, ftype, name = ins.cm.get_field(ins.BBBB)
a = get_variables(vmap, ins.AA)
return StaticInstruction(a, klass, ftype, name)
def get_args(vmap, param_type, largs):
num_param = 0
args = []
if len(param_type) > len(largs):
logger.warning('len(param_type) > len(largs) !')
return args
for type_ in param_type:
param = largs[num_param]
args.append(param)
num_param += util.get_type_size(type_)
if len(param_type) == 1:
return [get_variables(vmap, *args)]
return get_variables(vmap, *args)
# invoke-virtual {vD, vE, vF, vG, vA} ( 4b each )
def invokevirtual(ins, vmap, ret):
logger.debug('InvokeVirtual : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = [ins.D, ins.E, ins.F, ins.G]
args = get_args(vmap, param_type, largs)
c = get_variables(vmap, ins.C)
returned = None if ret_type == 'V' else ret.new()
exp = InvokeInstruction(cls_name, name, c, ret_type, param_type, args,
method.get_triple())
return AssignExpression(returned, exp)
# invoke-super {vD, vE, vF, vG, vA} ( 4b each )
def invokesuper(ins, vmap, ret):
logger.debug('InvokeSuper : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = [ins.D, ins.E, ins.F, ins.G]
args = get_args(vmap, param_type, largs)
superclass = BaseClass('super')
returned = None if ret_type == 'V' else ret.new()
exp = InvokeInstruction(cls_name, name, superclass, ret_type, param_type,
args, method.get_triple())
return AssignExpression(returned, exp)
# invoke-direct {vD, vE, vF, vG, vA} ( 4b each )
def invokedirect(ins, vmap, ret):
logger.debug('InvokeDirect : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = [ins.D, ins.E, ins.F, ins.G]
args = get_args(vmap, param_type, largs)
base = get_variables(vmap, ins.C)
if ret_type == 'V':
if isinstance(base, ThisParam):
returned = None
else:
returned = base
ret.set_to(base)
else:
returned = ret.new()
exp = InvokeDirectInstruction(cls_name, name, base, ret_type, param_type,
args, method.get_triple())
return AssignExpression(returned, exp)
# invoke-static {vD, vE, vF, vG, vA} ( 4b each )
def invokestatic(ins, vmap, ret):
logger.debug('InvokeStatic : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = [ins.C, ins.D, ins.E, ins.F, ins.G]
args = get_args(vmap, param_type, largs)
base = BaseClass(cls_name, descriptor=method.get_class_name())
returned = None if ret_type == 'V' else ret.new()
exp = InvokeStaticInstruction(cls_name, name, base, ret_type, param_type,
args, method.get_triple())
return AssignExpression(returned, exp)
# invoke-interface {vD, vE, vF, vG, vA} ( 4b each )
def invokeinterface(ins, vmap, ret):
logger.debug('InvokeInterface : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = [ins.D, ins.E, ins.F, ins.G]
args = get_args(vmap, param_type, largs)
c = get_variables(vmap, ins.C)
returned = None if ret_type == 'V' else ret.new()
exp = InvokeInstruction(cls_name, name, c, ret_type, param_type, args,
method.get_triple())
return AssignExpression(returned, exp)
# invoke-virtual/range {vCCCC..vNNNN} ( 16b each )
def invokevirtualrange(ins, vmap, ret):
logger.debug('InvokeVirtualRange : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = list(range(ins.CCCC, ins.NNNN + 1))
this_arg = get_variables(vmap, largs[0])
args = get_args(vmap, param_type, largs[1:])
returned = None if ret_type == 'V' else ret.new()
exp = InvokeRangeInstruction(cls_name, name, ret_type, param_type,
[this_arg] + args, method.get_triple())
return AssignExpression(returned, exp)
# invoke-super/range {vCCCC..vNNNN} ( 16b each )
def invokesuperrange(ins, vmap, ret):
logger.debug('InvokeSuperRange : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = list(range(ins.CCCC, ins.NNNN + 1))
args = get_args(vmap, param_type, largs[1:])
base = get_variables(vmap, ins.CCCC)
if ret_type != 'V':
returned = ret.new()
else:
returned = base
ret.set_to(base)
superclass = BaseClass('super')
exp = InvokeRangeInstruction(cls_name, name, ret_type, param_type,
[superclass] + args, method.get_triple())
return AssignExpression(returned, exp)
# invoke-direct/range {vCCCC..vNNNN} ( 16b each )
def invokedirectrange(ins, vmap, ret):
logger.debug('InvokeDirectRange : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = list(range(ins.CCCC, ins.NNNN + 1))
this_arg = get_variables(vmap, largs[0])
args = get_args(vmap, param_type, largs[1:])
base = get_variables(vmap, ins.CCCC)
if ret_type != 'V':
returned = ret.new()
else:
returned = base
ret.set_to(base)
exp = InvokeRangeInstruction(cls_name, name, ret_type, param_type,
[this_arg] + args, method.get_triple())
return AssignExpression(returned, exp)
# invoke-static/range {vCCCC..vNNNN} ( 16b each )
def invokestaticrange(ins, vmap, ret):
logger.debug('InvokeStaticRange : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = list(range(ins.CCCC, ins.NNNN + 1))
args = get_args(vmap, param_type, largs)
base = BaseClass(cls_name, descriptor=method.get_class_name())
returned = None if ret_type == 'V' else ret.new()
exp = InvokeStaticInstruction(cls_name, name, base, ret_type, param_type,
args, method.get_triple())
return AssignExpression(returned, exp)
# invoke-interface/range {vCCCC..vNNNN} ( 16b each )
def invokeinterfacerange(ins, vmap, ret):
logger.debug('InvokeInterfaceRange : %s', ins.get_output())
method = ins.cm.get_method_ref(ins.BBBB)
cls_name = util.get_type(method.get_class_name())
name = method.get_name()
param_type, ret_type = method.get_proto()
param_type = util.get_params_type(param_type)
largs = list(range(ins.CCCC, ins.NNNN + 1))
base_arg = get_variables(vmap, largs[0])
args = get_args(vmap, param_type, largs[1:])
returned = None if ret_type == 'V' else ret.new()
exp = InvokeRangeInstruction(cls_name, name, ret_type, param_type,
[base_arg] + args, method.get_triple())
return AssignExpression(returned, exp)
# neg-int vA, vB ( 4b, 4b )
def negint(ins, vmap):
logger.debug('NegInt : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
exp = UnaryExpression(Op.NEG, b, 'I')
return AssignExpression(a, exp)
# not-int vA, vB ( 4b, 4b )
def notint(ins, vmap):
logger.debug('NotInt : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
exp = UnaryExpression(Op.NOT, b, 'I')
return AssignExpression(a, exp)
# neg-long vA, vB ( 4b, 4b )
def neglong(ins, vmap):
logger.debug('NegLong : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)<|fim▁hole|>
# not-long vA, vB ( 4b, 4b )
def notlong(ins, vmap):
logger.debug('NotLong : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
exp = UnaryExpression(Op.NOT, b, 'J')
return AssignExpression(a, exp)
# neg-float vA, vB ( 4b, 4b )
def negfloat(ins, vmap):
logger.debug('NegFloat : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
exp = UnaryExpression(Op.NEG, b, 'F')
return AssignExpression(a, exp)
# neg-double vA, vB ( 4b, 4b )
def negdouble(ins, vmap):
logger.debug('NegDouble : %s', ins.get_output())
a, b = get_variables(vmap, ins.A, ins.B)
exp = UnaryExpression(Op.NEG, b, 'D')
return AssignExpression(a, exp)
# int-to-long vA, vB ( 4b, 4b )
def inttolong(ins, vmap):
logger.debug('IntToLong : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(long)', 'J', vmap)
# int-to-float vA, vB ( 4b, 4b )
def inttofloat(ins, vmap):
logger.debug('IntToFloat : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(float)', 'F', vmap)
# int-to-double vA, vB ( 4b, 4b )
def inttodouble(ins, vmap):
logger.debug('IntToDouble : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(double)', 'D', vmap)
# long-to-int vA, vB ( 4b, 4b )
def longtoint(ins, vmap):
logger.debug('LongToInt : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(int)', 'I', vmap)
# long-to-float vA, vB ( 4b, 4b )
def longtofloat(ins, vmap):
logger.debug('LongToFloat : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(float)', 'F', vmap)
# long-to-double vA, vB ( 4b, 4b )
def longtodouble(ins, vmap):
logger.debug('LongToDouble : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(double)', 'D', vmap)
# float-to-int vA, vB ( 4b, 4b )
def floattoint(ins, vmap):
logger.debug('FloatToInt : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(int)', 'I', vmap)
# float-to-long vA, vB ( 4b, 4b )
def floattolong(ins, vmap):
logger.debug('FloatToLong : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(long)', 'J', vmap)
# float-to-double vA, vB ( 4b, 4b )
def floattodouble(ins, vmap):
logger.debug('FloatToDouble : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(double)', 'D', vmap)
# double-to-int vA, vB ( 4b, 4b )
def doubletoint(ins, vmap):
logger.debug('DoubleToInt : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(int)', 'I', vmap)
# double-to-long vA, vB ( 4b, 4b )
def doubletolong(ins, vmap):
logger.debug('DoubleToLong : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(long)', 'J', vmap)
# double-to-float vA, vB ( 4b, 4b )
def doubletofloat(ins, vmap):
logger.debug('DoubleToFloat : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(float)', 'F', vmap)
# int-to-byte vA, vB ( 4b, 4b )
def inttobyte(ins, vmap):
logger.debug('IntToByte : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(byte)', 'B', vmap)
# int-to-char vA, vB ( 4b, 4b )
def inttochar(ins, vmap):
logger.debug('IntToChar : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(char)', 'C', vmap)
# int-to-short vA, vB ( 4b, 4b )
def inttoshort(ins, vmap):
logger.debug('IntToShort : %s', ins.get_output())
return assign_cast_exp(ins.A, ins.B, '(short)', 'S', vmap)
# add-int vAA, vBB, vCC ( 8b, 8b, 8b )
def addint(ins, vmap):
logger.debug('AddInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.ADD, 'I', vmap)
# sub-int vAA, vBB, vCC ( 8b, 8b, 8b )
def subint(ins, vmap):
logger.debug('SubInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.SUB, 'I', vmap)
# mul-int vAA, vBB, vCC ( 8b, 8b, 8b )
def mulint(ins, vmap):
logger.debug('MulInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.MUL, 'I', vmap)
# div-int vAA, vBB, vCC ( 8b, 8b, 8b )
def divint(ins, vmap):
logger.debug('DivInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.DIV, 'I', vmap)
# rem-int vAA, vBB, vCC ( 8b, 8b, 8b )
def remint(ins, vmap):
logger.debug('RemInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.MOD, 'I', vmap)
# and-int vAA, vBB, vCC ( 8b, 8b, 8b )
def andint(ins, vmap):
logger.debug('AndInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.AND, 'I', vmap)
# or-int vAA, vBB, vCC ( 8b, 8b, 8b )
def orint(ins, vmap):
logger.debug('OrInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.OR, 'I', vmap)
# xor-int vAA, vBB, vCC ( 8b, 8b, 8b )
def xorint(ins, vmap):
logger.debug('XorInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.XOR, 'I', vmap)
# shl-int vAA, vBB, vCC ( 8b, 8b, 8b )
def shlint(ins, vmap):
logger.debug('ShlInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.INTSHL, 'I', vmap)
# shr-int vAA, vBB, vCC ( 8b, 8b, 8b )
def shrint(ins, vmap):
logger.debug('ShrInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.INTSHR, 'I', vmap)
# ushr-int vAA, vBB, vCC ( 8b, 8b, 8b )
def ushrint(ins, vmap):
logger.debug('UShrInt : %s', ins.get_output())
return assign_binary_exp(ins, Op.INTSHR, 'I', vmap)
# add-long vAA, vBB, vCC ( 8b, 8b, 8b )
def addlong(ins, vmap):
logger.debug('AddLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.ADD, 'J', vmap)
# sub-long vAA, vBB, vCC ( 8b, 8b, 8b )
def sublong(ins, vmap):
logger.debug('SubLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.SUB, 'J', vmap)
# mul-long vAA, vBB, vCC ( 8b, 8b, 8b )
def mullong(ins, vmap):
logger.debug('MulLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.MUL, 'J', vmap)
# div-long vAA, vBB, vCC ( 8b, 8b, 8b )
def divlong(ins, vmap):
logger.debug('DivLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.DIV, 'J', vmap)
# rem-long vAA, vBB, vCC ( 8b, 8b, 8b )
def remlong(ins, vmap):
logger.debug('RemLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.MOD, 'J', vmap)
# and-long vAA, vBB, vCC ( 8b, 8b, 8b )
def andlong(ins, vmap):
logger.debug('AndLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.AND, 'J', vmap)
# or-long vAA, vBB, vCC ( 8b, 8b, 8b )
def orlong(ins, vmap):
logger.debug('OrLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.OR, 'J', vmap)
# xor-long vAA, vBB, vCC ( 8b, 8b, 8b )
def xorlong(ins, vmap):
logger.debug('XorLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.XOR, 'J', vmap)
# shl-long vAA, vBB, vCC ( 8b, 8b, 8b )
def shllong(ins, vmap):
logger.debug('ShlLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.LONGSHL, 'J', vmap)
# shr-long vAA, vBB, vCC ( 8b, 8b, 8b )
def shrlong(ins, vmap):
logger.debug('ShrLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.LONGSHR, 'J', vmap)
# ushr-long vAA, vBB, vCC ( 8b, 8b, 8b )
def ushrlong(ins, vmap):
logger.debug('UShrLong : %s', ins.get_output())
return assign_binary_exp(ins, Op.LONGSHR, 'J', vmap)
# add-float vAA, vBB, vCC ( 8b, 8b, 8b )
def addfloat(ins, vmap):
logger.debug('AddFloat : %s', ins.get_output())
return assign_binary_exp(ins, Op.ADD, 'F', vmap)
# sub-float vAA, vBB, vCC ( 8b, 8b, 8b )
def subfloat(ins, vmap):
logger.debug('SubFloat : %s', ins.get_output())
return assign_binary_exp(ins, Op.SUB, 'F', vmap)
# mul-float vAA, vBB, vCC ( 8b, 8b, 8b )
def mulfloat(ins, vmap):
logger.debug('MulFloat : %s', ins.get_output())
return assign_binary_exp(ins, Op.MUL, 'F', vmap)
# div-float vAA, vBB, vCC ( 8b, 8b, 8b )
def divfloat(ins, vmap):
logger.debug('DivFloat : %s', ins.get_output())
return assign_binary_exp(ins, Op.DIV, 'F', vmap)
# rem-float vAA, vBB, vCC ( 8b, 8b, 8b )
def remfloat(ins, vmap):
logger.debug('RemFloat : %s', ins.get_output())
return assign_binary_exp(ins, Op.MOD, 'F', vmap)
# add-double vAA, vBB, vCC ( 8b, 8b, 8b )
def adddouble(ins, vmap):
logger.debug('AddDouble : %s', ins.get_output())
return assign_binary_exp(ins, Op.ADD, 'D', vmap)
# sub-double vAA, vBB, vCC ( 8b, 8b, 8b )
def subdouble(ins, vmap):
logger.debug('SubDouble : %s', ins.get_output())
return assign_binary_exp(ins, Op.SUB, 'D', vmap)
# mul-double vAA, vBB, vCC ( 8b, 8b, 8b )
def muldouble(ins, vmap):
logger.debug('MulDouble : %s', ins.get_output())
return assign_binary_exp(ins, Op.MUL, 'D', vmap)
# div-double vAA, vBB, vCC ( 8b, 8b, 8b )
def divdouble(ins, vmap):
logger.debug('DivDouble : %s', ins.get_output())
return assign_binary_exp(ins, Op.DIV, 'D', vmap)
# rem-double vAA, vBB, vCC ( 8b, 8b, 8b )
def remdouble(ins, vmap):
logger.debug('RemDouble : %s', ins.get_output())
return assign_binary_exp(ins, Op.MOD, 'D', vmap)
# add-int/2addr vA, vB ( 4b, 4b )
def addint2addr(ins, vmap):
logger.debug('AddInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.ADD, 'I', vmap)
# sub-int/2addr vA, vB ( 4b, 4b )
def subint2addr(ins, vmap):
logger.debug('SubInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.SUB, 'I', vmap)
# mul-int/2addr vA, vB ( 4b, 4b )
def mulint2addr(ins, vmap):
logger.debug('MulInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MUL, 'I', vmap)
# div-int/2addr vA, vB ( 4b, 4b )
def divint2addr(ins, vmap):
logger.debug('DivInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.DIV, 'I', vmap)
# rem-int/2addr vA, vB ( 4b, 4b )
def remint2addr(ins, vmap):
logger.debug('RemInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MOD, 'I', vmap)
# and-int/2addr vA, vB ( 4b, 4b )
def andint2addr(ins, vmap):
logger.debug('AndInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.AND, 'I', vmap)
# or-int/2addr vA, vB ( 4b, 4b )
def orint2addr(ins, vmap):
logger.debug('OrInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.OR, 'I', vmap)
# xor-int/2addr vA, vB ( 4b, 4b )
def xorint2addr(ins, vmap):
logger.debug('XorInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.XOR, 'I', vmap)
# shl-int/2addr vA, vB ( 4b, 4b )
def shlint2addr(ins, vmap):
logger.debug('ShlInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.INTSHL, 'I', vmap)
# shr-int/2addr vA, vB ( 4b, 4b )
def shrint2addr(ins, vmap):
logger.debug('ShrInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.INTSHR, 'I', vmap)
# ushr-int/2addr vA, vB ( 4b, 4b )
def ushrint2addr(ins, vmap):
logger.debug('UShrInt2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.INTSHR, 'I', vmap)
# add-long/2addr vA, vB ( 4b, 4b )
def addlong2addr(ins, vmap):
logger.debug('AddLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.ADD, 'J', vmap)
# sub-long/2addr vA, vB ( 4b, 4b )
def sublong2addr(ins, vmap):
logger.debug('SubLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.SUB, 'J', vmap)
# mul-long/2addr vA, vB ( 4b, 4b )
def mullong2addr(ins, vmap):
logger.debug('MulLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MUL, 'J', vmap)
# div-long/2addr vA, vB ( 4b, 4b )
def divlong2addr(ins, vmap):
logger.debug('DivLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.DIV, 'J', vmap)
# rem-long/2addr vA, vB ( 4b, 4b )
def remlong2addr(ins, vmap):
logger.debug('RemLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MOD, 'J', vmap)
# and-long/2addr vA, vB ( 4b, 4b )
def andlong2addr(ins, vmap):
logger.debug('AndLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.AND, 'J', vmap)
# or-long/2addr vA, vB ( 4b, 4b )
def orlong2addr(ins, vmap):
logger.debug('OrLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.OR, 'J', vmap)
# xor-long/2addr vA, vB ( 4b, 4b )
def xorlong2addr(ins, vmap):
logger.debug('XorLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.XOR, 'J', vmap)
# shl-long/2addr vA, vB ( 4b, 4b )
def shllong2addr(ins, vmap):
logger.debug('ShlLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.LONGSHL, 'J', vmap)
# shr-long/2addr vA, vB ( 4b, 4b )
def shrlong2addr(ins, vmap):
logger.debug('ShrLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.LONGSHR, 'J', vmap)
# ushr-long/2addr vA, vB ( 4b, 4b )
def ushrlong2addr(ins, vmap):
logger.debug('UShrLong2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.LONGSHR, 'J', vmap)
# add-float/2addr vA, vB ( 4b, 4b )
def addfloat2addr(ins, vmap):
logger.debug('AddFloat2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.ADD, 'F', vmap)
# sub-float/2addr vA, vB ( 4b, 4b )
def subfloat2addr(ins, vmap):
logger.debug('SubFloat2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.SUB, 'F', vmap)
# mul-float/2addr vA, vB ( 4b, 4b )
def mulfloat2addr(ins, vmap):
logger.debug('MulFloat2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MUL, 'F', vmap)
# div-float/2addr vA, vB ( 4b, 4b )
def divfloat2addr(ins, vmap):
logger.debug('DivFloat2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.DIV, 'F', vmap)
# rem-float/2addr vA, vB ( 4b, 4b )
def remfloat2addr(ins, vmap):
logger.debug('RemFloat2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MOD, 'F', vmap)
# add-double/2addr vA, vB ( 4b, 4b )
def adddouble2addr(ins, vmap):
logger.debug('AddDouble2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.ADD, 'D', vmap)
# sub-double/2addr vA, vB ( 4b, 4b )
def subdouble2addr(ins, vmap):
logger.debug('subDouble2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.SUB, 'D', vmap)
# mul-double/2addr vA, vB ( 4b, 4b )
def muldouble2addr(ins, vmap):
logger.debug('MulDouble2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MUL, 'D', vmap)
# div-double/2addr vA, vB ( 4b, 4b )
def divdouble2addr(ins, vmap):
logger.debug('DivDouble2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.DIV, 'D', vmap)
# rem-double/2addr vA, vB ( 4b, 4b )
def remdouble2addr(ins, vmap):
logger.debug('RemDouble2Addr : %s', ins.get_output())
return assign_binary_2addr_exp(ins, Op.MOD, 'D', vmap)
# add-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b )
def addintlit16(ins, vmap):
logger.debug('AddIntLit16 : %s', ins.get_output())
return assign_lit(Op.ADD, ins.CCCC, ins.A, ins.B, vmap)
# rsub-int vA, vB, #+CCCC ( 4b, 4b, 16b )
def rsubint(ins, vmap):
logger.debug('RSubInt : %s', ins.get_output())
var_a, var_b = get_variables(vmap, ins.A, ins.B)
cst = Constant(ins.CCCC, 'I')
return AssignExpression(var_a, BinaryExpressionLit(Op.SUB, cst, var_b))
# mul-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b )
def mulintlit16(ins, vmap):
logger.debug('MulIntLit16 : %s', ins.get_output())
return assign_lit(Op.MUL, ins.CCCC, ins.A, ins.B, vmap)
# div-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b )
def divintlit16(ins, vmap):
logger.debug('DivIntLit16 : %s', ins.get_output())
return assign_lit(Op.DIV, ins.CCCC, ins.A, ins.B, vmap)
# rem-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b )
def remintlit16(ins, vmap):
logger.debug('RemIntLit16 : %s', ins.get_output())
return assign_lit(Op.MOD, ins.CCCC, ins.A, ins.B, vmap)
# and-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b )
def andintlit16(ins, vmap):
logger.debug('AndIntLit16 : %s', ins.get_output())
return assign_lit(Op.AND, ins.CCCC, ins.A, ins.B, vmap)
# or-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b )
def orintlit16(ins, vmap):
logger.debug('OrIntLit16 : %s', ins.get_output())
return assign_lit(Op.OR, ins.CCCC, ins.A, ins.B, vmap)
# xor-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b )
def xorintlit16(ins, vmap):
logger.debug('XorIntLit16 : %s', ins.get_output())
return assign_lit(Op.XOR, ins.CCCC, ins.A, ins.B, vmap)
# add-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def addintlit8(ins, vmap):
logger.debug('AddIntLit8 : %s', ins.get_output())
literal, op = [(ins.CC, Op.ADD), (-ins.CC, Op.SUB)][ins.CC < 0]
return assign_lit(op, literal, ins.AA, ins.BB, vmap)
# rsub-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def rsubintlit8(ins, vmap):
logger.debug('RSubIntLit8 : %s', ins.get_output())
var_a, var_b = get_variables(vmap, ins.AA, ins.BB)
cst = Constant(ins.CC, 'I')
return AssignExpression(var_a, BinaryExpressionLit(Op.SUB, cst, var_b))
# mul-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def mulintlit8(ins, vmap):
logger.debug('MulIntLit8 : %s', ins.get_output())
return assign_lit(Op.MUL, ins.CC, ins.AA, ins.BB, vmap)
# div-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def divintlit8(ins, vmap):
logger.debug('DivIntLit8 : %s', ins.get_output())
return assign_lit(Op.DIV, ins.CC, ins.AA, ins.BB, vmap)
# rem-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def remintlit8(ins, vmap):
logger.debug('RemIntLit8 : %s', ins.get_output())
return assign_lit(Op.MOD, ins.CC, ins.AA, ins.BB, vmap)
# and-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def andintlit8(ins, vmap):
logger.debug('AndIntLit8 : %s', ins.get_output())
return assign_lit(Op.AND, ins.CC, ins.AA, ins.BB, vmap)
# or-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def orintlit8(ins, vmap):
logger.debug('OrIntLit8 : %s', ins.get_output())
return assign_lit(Op.OR, ins.CC, ins.AA, ins.BB, vmap)
# xor-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def xorintlit8(ins, vmap):
logger.debug('XorIntLit8 : %s', ins.get_output())
return assign_lit(Op.XOR, ins.CC, ins.AA, ins.BB, vmap)
# shl-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def shlintlit8(ins, vmap):
logger.debug('ShlIntLit8 : %s', ins.get_output())
return assign_lit(Op.INTSHL, ins.CC, ins.AA, ins.BB, vmap)
# shr-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def shrintlit8(ins, vmap):
logger.debug('ShrIntLit8 : %s', ins.get_output())
return assign_lit(Op.INTSHR, ins.CC, ins.AA, ins.BB, vmap)
# ushr-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b )
def ushrintlit8(ins, vmap):
logger.debug('UShrIntLit8 : %s', ins.get_output())
return assign_lit(Op.INTSHR, ins.CC, ins.AA, ins.BB, vmap)
INSTRUCTION_SET = [
# 0x00
nop, # nop
move, # move
movefrom16, # move/from16
move16, # move/16
movewide, # move-wide
movewidefrom16, # move-wide/from16
movewide16, # move-wide/16
moveobject, # move-object
moveobjectfrom16, # move-object/from16
moveobject16, # move-object/16
moveresult, # move-result
moveresultwide, # move-result-wide
moveresultobject, # move-result-object
moveexception, # move-exception
returnvoid, # return-void
return_reg, # return
# 0x10
returnwide, # return-wide
returnobject, # return-object
const4, # const/4
const16, # const/16
const, # const
consthigh16, # const/high16
constwide16, # const-wide/16
constwide32, # const-wide/32
constwide, # const-wide
constwidehigh16, # const-wide/high16
conststring, # const-string
conststringjumbo, # const-string/jumbo
constclass, # const-class
monitorenter, # monitor-enter
monitorexit, # monitor-exit
checkcast, # check-cast
# 0x20
instanceof, # instance-of
arraylength, # array-length
newinstance, # new-instance
newarray, # new-array
fillednewarray, # filled-new-array
fillednewarrayrange, # filled-new-array/range
fillarraydata, # fill-array-data
throw, # throw
goto, # goto
goto16, # goto/16
goto32, # goto/32
packedswitch, # packed-switch
sparseswitch, # sparse-switch
cmplfloat, # cmpl-float
cmpgfloat, # cmpg-float
cmpldouble, # cmpl-double
# 0x30
cmpgdouble, # cmpg-double
cmplong, # cmp-long
ifeq, # if-eq
ifne, # if-ne
iflt, # if-lt
ifge, # if-ge
ifgt, # if-gt
ifle, # if-le
ifeqz, # if-eqz
ifnez, # if-nez
ifltz, # if-ltz
ifgez, # if-gez
ifgtz, # if-gtz
iflez, # if-l
nop, # unused
nop, # unused
# 0x40
nop, # unused
nop, # unused
nop, # unused
nop, # unused
aget, # aget
agetwide, # aget-wide
agetobject, # aget-object
agetboolean, # aget-boolean
agetbyte, # aget-byte
agetchar, # aget-char
agetshort, # aget-short
aput, # aput
aputwide, # aput-wide
aputobject, # aput-object
aputboolean, # aput-boolean
aputbyte, # aput-byte
# 0x50
aputchar, # aput-char
aputshort, # aput-short
iget, # iget
igetwide, # iget-wide
igetobject, # iget-object
igetboolean, # iget-boolean
igetbyte, # iget-byte
igetchar, # iget-char
igetshort, # iget-short
iput, # iput
iputwide, # iput-wide
iputobject, # iput-object
iputboolean, # iput-boolean
iputbyte, # iput-byte
iputchar, # iput-char
iputshort, # iput-short
# 0x60
sget, # sget
sgetwide, # sget-wide
sgetobject, # sget-object
sgetboolean, # sget-boolean
sgetbyte, # sget-byte
sgetchar, # sget-char
sgetshort, # sget-short
sput, # sput
sputwide, # sput-wide
sputobject, # sput-object
sputboolean, # sput-boolean
sputbyte, # sput-byte
sputchar, # sput-char
sputshort, # sput-short
invokevirtual, # invoke-virtual
invokesuper, # invoke-super
# 0x70
invokedirect, # invoke-direct
invokestatic, # invoke-static
invokeinterface, # invoke-interface
nop, # unused
invokevirtualrange, # invoke-virtual/range
invokesuperrange, # invoke-super/range
invokedirectrange, # invoke-direct/range
invokestaticrange, # invoke-static/range
invokeinterfacerange, # invoke-interface/range
nop, # unused
nop, # unused
negint, # neg-int
notint, # not-int
neglong, # neg-long
notlong, # not-long
negfloat, # neg-float
# 0x80
negdouble, # neg-double
inttolong, # int-to-long
inttofloat, # int-to-float
inttodouble, # int-to-double
longtoint, # long-to-int
longtofloat, # long-to-float
longtodouble, # long-to-double
floattoint, # float-to-int
floattolong, # float-to-long
floattodouble, # float-to-double
doubletoint, # double-to-int
doubletolong, # double-to-long
doubletofloat, # double-to-float
inttobyte, # int-to-byte
inttochar, # int-to-char
inttoshort, # int-to-short
# 0x90
addint, # add-int
subint, # sub-int
mulint, # mul-int
divint, # div-int
remint, # rem-int
andint, # and-int
orint, # or-int
xorint, # xor-int
shlint, # shl-int
shrint, # shr-int
ushrint, # ushr-int
addlong, # add-long
sublong, # sub-long
mullong, # mul-long
divlong, # div-long
remlong, # rem-long
# 0xa0
andlong, # and-long
orlong, # or-long
xorlong, # xor-long
shllong, # shl-long
shrlong, # shr-long
ushrlong, # ushr-long
addfloat, # add-float
subfloat, # sub-float
mulfloat, # mul-float
divfloat, # div-float
remfloat, # rem-float
adddouble, # add-double
subdouble, # sub-double
muldouble, # mul-double
divdouble, # div-double
remdouble, # rem-double
# 0xb0
addint2addr, # add-int/2addr
subint2addr, # sub-int/2addr
mulint2addr, # mul-int/2addr
divint2addr, # div-int/2addr
remint2addr, # rem-int/2addr
andint2addr, # and-int/2addr
orint2addr, # or-int/2addr
xorint2addr, # xor-int/2addr
shlint2addr, # shl-int/2addr
shrint2addr, # shr-int/2addr
ushrint2addr, # ushr-int/2addr
addlong2addr, # add-long/2addr
sublong2addr, # sub-long/2addr
mullong2addr, # mul-long/2addr
divlong2addr, # div-long/2addr
remlong2addr, # rem-long/2addr
# 0xc0
andlong2addr, # and-long/2addr
orlong2addr, # or-long/2addr
xorlong2addr, # xor-long/2addr
shllong2addr, # shl-long/2addr
shrlong2addr, # shr-long/2addr
ushrlong2addr, # ushr-long/2addr
addfloat2addr, # add-float/2addr
subfloat2addr, # sub-float/2addr
mulfloat2addr, # mul-float/2addr
divfloat2addr, # div-float/2addr
remfloat2addr, # rem-float/2addr
adddouble2addr, # add-double/2addr
subdouble2addr, # sub-double/2addr
muldouble2addr, # mul-double/2addr
divdouble2addr, # div-double/2addr
remdouble2addr, # rem-double/2addr
# 0xd0
addintlit16, # add-int/lit16
rsubint, # rsub-int
mulintlit16, # mul-int/lit16
divintlit16, # div-int/lit16
remintlit16, # rem-int/lit16
andintlit16, # and-int/lit16
orintlit16, # or-int/lit16
xorintlit16, # xor-int/lit16
addintlit8, # add-int/lit8
rsubintlit8, # rsub-int/lit8
mulintlit8, # mul-int/lit8
divintlit8, # div-int/lit8
remintlit8, # rem-int/lit8
andintlit8, # and-int/lit8
orintlit8, # or-int/lit8
xorintlit8, # xor-int/lit8
# 0xe0
shlintlit8, # shl-int/lit8
shrintlit8, # shr-int/lit8
ushrintlit8, # ushr-int/lit8
]<|fim▁end|> | exp = UnaryExpression(Op.NEG, b, 'J')
return AssignExpression(a, exp)
|
<|file_name|>franken.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# FRANKEN CIPHER
# WRITTEN FOR ACADEMIC PURPOSES
#
# AUTHORED BY: Dan C and [email protected]
#
# THIS SCRIPT IS WRITTEN TO DEMONSTRATE A UNIQUE ENCRYPTION ALGORITHM THAT IS INSPIRED BY A NUMBER
# OF EXISTING ALGORITHMS.
# THE SCRIPT IS WRITTEN ENTIRELY FOR ACADEMIC PURPOSES. NO WARRANTY OR GUARANTEES ARE
# OFFERED BY THE AUTHORS IN RELATION TO THE USE OF THIS SCRIPT.
#
# Usage: franken.py <"-v" (verbose)> <"-d" (decrypt)> <"-k" (key phrase)> <"-m" (string to encrypt/decrypt)>
#
# indentation: TABS!
import sys
import getopt
import collections
import binascii
import hashlib
import itertools
# GLOBALS
# define -v and -d as false (-d defaults to encrypt mode)
verbose_opt = False
decrypt_opt = False
key_phrase = '' # clear text key phrase
key_hashed = '' # hashed key phrase
clear_text = '' # starting message input
pigpen_message = '' # message after pigpen stage
encrypted_message = '' # the encrypted message
decrypted_message = '' # the decrypted message
# GLOBALS
# pigpen dictionaries
pigpen_A = {'A':'ETL', 'B':'ETM', 'C':'ETR', 'D':'EML', 'E':'EMM', 'F':'EMR', 'G':'EBL', 'H':'EBM', 'I':'EBR', 'J':'DTL',
'K':'DTM', 'L':'DTR', 'M':'DML', 'N':'DMM', 'O':'DMR', 'P':'DBL', 'Q':'DBM', 'R':'DBR', 'S':'EXT', 'T':'EXL', 'U':'EXR',
'V':'EXB', 'W':'DXT', 'X':'DXL', 'Y':'DXR', 'Z':'DXB', ' ':'EPS', '.':'EPF', ',':'EPC', '!':'EPE', '?':'EPQ', '"':'EPD',
'@':'EPA','0':'NTL', '1':'NTM', '2':'NTR', '3':'NML', '4':'NMM', '5':'NMR', '6':'NBL', '7':'NBM', '8':'NBR','9':'NXT'}
pigpen_B = {'C':'ETL', 'D':'ETM', 'A':'ETR', 'B':'EML', 'G':'EMM', 'H':'EMR', 'E':'EBL', 'F':'EBM', 'K':'EBR', 'L':'DTL',
'I':'DTM', 'J':'DTR', 'O':'DML', 'P':'DMM', 'M':'DMR', 'N':'DBL', 'S':'DBM', 'T':'DBR', 'Q':'EXT', 'R':'EXL', 'W':'EXR',
'X':'EXB', 'U':'DXT', 'V':'DXL', ' ':'DXR', ',':'DXB', 'Y':'EPS', '!':'EPF', 'Z':'EPC', '.':'EPE', '@':'EPQ', '0':'EPD',
'?':'EPA','"':'NTL', '3':'NTM', '4':'NTR', '1':'NML', '2':'NMM', '7':'NMR', '8':'NBL', '9':'NBM', '5':'NBR', '6':'NXT'}
pigpen_C = {'K':'ETL', 'L':'ETM', 'M':'ETR', 'N':'EML', 'O':'EMM', 'P':'EMR', 'Q':'EBL', 'R':'EBM', 'S':'EBR', 'U':'DTL',
'V':'DTM', 'W':'DTR', 'X':'DML', 'Y':'DMM', 'Z':'DMR', ' ':'DBL', '.':'DBM', ',':'DBR', '!':'EXT', '"':'EXL', '?':'EXR',
'@':'EXB', '0':'DXT', '1':'DXL', '2':'DXR', '3':'DXB', '4':'EPS', '5':'EPF', '6':'EPC', '7':'EPE', '8':'EPQ', '9':'EPD',
'A':'EPA','B':'NTL', 'C':'NTM', 'D':'NTR', 'E':'NML', 'F':'NMM', 'G':'NMR', 'H':'NBL', 'I':'NBM', 'J':'NBR','T':'NXT'}
# creates hashes of the key phrase inputted by the user
# in order for it to be used as a key
# the clear text key phrase string is retained
def keyGenerate():
global key_hashed
# create the hashes of the key phrase string
md5_hash = hashlib.md5(key_phrase.encode())
sha256_hash = hashlib.sha256(key_phrase.encode())
sha512_hash = hashlib.sha512(key_phrase.encode())
# concatenate the hash digests into one key
key_hashed = md5_hash.hexdigest() + sha256_hash.hexdigest() + sha512_hash.hexdigest()
# hash the entire key (so far) one more time and concatenate to make 1024bit key
key_hashed_hash = hashlib.md5(key_hashed.encode())
key_hashed += key_hashed_hash.hexdigest()
# vebose mode if verbose option is set
if verbose_opt:
print("[KEY GENERATION]: The key phrase is: \"" + key_phrase + "\"")
print("[KEY GENERATION]: \"" + key_phrase + "\" is independantly hashed 3 times using MD5, SHA256 and SHA512")
print("[KEY GENERATION]: The 3 hashes are concatenated with 1 more md5 hash, resulting in the 1024bit key:")
print("[KEY GENERATION]: \"" + key_hashed + "\"\n")
return
# selects the appropriate pigpen dictionary based on summing all of the ascii
# values in the key phrase and modulating the sum of the integers by 3 in order to retrieve
# one of 3 values. Returns the appropriate dictionary
def selectDict():
# sum ASCII value of each character in the clear text key phrase
ascii_total = 0
for x in key_phrase:
ascii_total += ord(x)
# modulo 3 ascii_total to find 0-3 result to select pigpen dict
if ascii_total % 3 == 0:
pigpen_dict = pigpen_A
elif ascii_total % 3 == 1:
pigpen_dict = pigpen_B
elif ascii_total % 3 == 2:
pigpen_dict = pigpen_C
# return the dictionary
return pigpen_dict
# convert message into pigpen alphabet. compare each letter to dict key.
# first makes all chars uppercase and ignores some punctuation.
# itterates through pigpen dict to find value based on clear message char as key
def pigpenForward():
global pigpen_message
# convert clear message to uppercase
message = clear_text.upper()
# itterate through dict looking for chars
for letter in message:
if letter in selectDict():
pigpen_message += selectDict().get(letter)
# verbose mode if verbose option is set
if verbose_opt:
print("[ENCRYPTION - Phase 1]: The clear text is:")
print("[ENCRYPTION - Phase 1]: \"" + clear_text + "\"")
print("[ENCRYPTION - Phase 1]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)")
print("[ENCRYPTION - Phase 1]: The clear text is converted into pigpen cipher text using the selected dictionary:")
print("[ENCRYPTION - Phase 1]: \"" + pigpen_message + "\"\n")
return
# reverses the pigpen process. takes a pigpen string and converts it back to clear text
# first creates a list of each 3 values from the inputted string (each element has 3 chars)
# then compares those elements to the pigpen dictionary to create the decrypted string
def pigpenBackward():
global decrypted_message
# convert encrypted message (int array) back to a single ascii string
message = ''
try:
for i in decrypted_message:
message += chr(i)
except:
print("[ERROR]: Incorrect key. Cannot decrypt.")
usageText()
# retrieve each 3 chars (one pigpen value) and form a list
message_list = [message[i:i+3] for i in range(0, len(message), 3)]
# zero out decrypted message string in order to store pigpen deciphered characters
decrypted_message = ''
# itterate through list elements and compare against pigpen dict
# to find correct key (clear text letter) and create decrypted string
for element in message_list:
for key, value in selectDict().iteritems():
if value == element:
decrypted_message += key
# verbose mode if verbose option is set
if verbose_opt:
print("[DECRYPTION - Phase 3]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)")<|fim▁hole|> print("[DECRYPTION - Phase 3]: The values of the pigpen cipher text are looked up in the selected dictionary")
print("[DECRYPTION - Phase 3]: The pigpen cipher text is converted back into clear text:\n")
print("[DECRYPTION - COMPLETE]: \"" + decrypted_message + "\"\n")
return
# XORs an int value derived from the hashed key to each ascii int value of the message.
# The key value is looked up by using the value stored in that key array position to reference
# the array position that value points to. That value is then XOR'ed with the corresponding value of the message
# this occurs three times. Inspired by DES key sub key generation and RC4
def keyConfusion(message):
# create array of base10 ints from ascii values of chars in hashed key
key = []
for x in key_hashed:
key.append(ord(x))
# create a variable for cycling through the key array (in case the message is longer than key)
key_cycle = itertools.cycle(key)
# loop through the key and XOR the resultant value with the corresponding value in the message
for i in range(len(message)):
# find the value pointed to by the value of each element of the key (for each value in the message array)
key_pointer = key_cycle.next() % 128 # get the next key byte. mod 128 because 128 bytes in 1024bits
key_byte = key[key_pointer]
# XOR message byte with current key_byte
message[i] = message[i] ^ key_byte
# XOR message byte with the key byte pointed to by previous key byte value
key_byte = key[(key_byte % 128)]
message[i] = message[i] ^ key_byte
# once again XOR message byte with the next key byte pointed to by previous key byte value
key_byte = key[(key_byte % 128)]
message[i] = message[i] ^ key_byte
# verbose mode if verbose option is set
if verbose_opt:
# are we decrypting or encrypting?
if decrypt_opt:
en_or_de = "[DECRYPTION - Phase 2]: "
en_or_de_text = " pigpen cipher text:"
else:
en_or_de = "[ENCRYPTION - Phase 2]: "
en_or_de_text = " partially encrypted string:"
# print the appropriate output for encrypting or decrypting
print(en_or_de + "Each byte of the pigpen cipher is then XOR'ed against 3 bytes of the key")
print(en_or_de + "The key byte is XOR'ed against the byte of the message and then used to select the")
print(en_or_de + "position in the key array of the next key byte value. This occurs three times.")
print(en_or_de + "Resulting in the" + en_or_de_text)
print(en_or_de + "\"" + message + "\"\n")
return message
# xors the hashed key against the pigpenned message
# each character in the message is xor'ed against each character
# in the hashed key, resulting in the encrypted message
def xorForward():
global encrypted_message
# convert key and message into ints for xoring
message = bytearray(pigpen_message)
key = bytearray(key_hashed)
# send pigpen message off for permution
message = keyConfusion(message)
# iterate over message and xor each character against each value in the key
for x in range(len(message)):
for y in range(len(key)):
xored = key[y] ^ message[x]
message[x] = xored
# store hex value of encrypted string in global variable
encrypted_message = binascii.hexlify(bytearray(message))
# verbose mode is verbose option is set
if verbose_opt:
print("[ENCRYPTION - Phase 3]: The partially encrypted cipher text and key are converted into a byte arrays")
print("[ENCRYPTION - Phase 3]: Each byte of the message is XOR'ed against each byte of the key")
print("[ENCRYPTION - Phase 3]: Resulting in the cipher text hex string:\n")
print("[ENCRYPTION - COMPLETE]: \"" + encrypted_message + "\"\n")
return
# the reverse of the encrypt function, whereby the supplied key is reversed
# and xored against the encrypted message. The message is first unhexlified
# to facilitate xoring
def xorBackward():
global decrypted_message
# create byte array for key and to store decrypted message
reverse_key = key_hashed[::-1]
key = bytearray(reverse_key)
# try to convert the encrypted message from hex to int, error if incorrect string
try:
message = bytearray(binascii.unhexlify(clear_text))
except:
print("[ERROR]: Incorrect string. Cannot decrypt.")
usageText()
# iterate over the encrypted message and xor each value against each value in the key
for x in range(len(message)):
for y in range(len(key)):
xored = key[y] ^ message[x]
message[x] = xored
# verbose mode is verbose option is set
if verbose_opt:
print("[DECRYPTION - Phase 1]: The cipher text is:")
print("[DECRYPTION - Phase 1]: \"" + clear_text + "\"")
print("[DECRYPTION - Phase 1]: The cipher text and key are converted into a byte arrays")
print("[DECRYPTION - Phase 1]: The key is reversed in order to reverse this stage of XOR'ing")
print("[DECRYPTION - Phase 1]: Each byte of the cipher text is XOR'ed against each byte of the key")
print("[DECRYPTION - Phase 1]: Resulting in the partially decrypted string:")
print("[DECRYPTION - Phase 1]: \"" + message + "\"\n")
# send decrypted array off for permutation (reverse encrypted XOR'ing)
decrypted_message = keyConfusion(message)
return
# text to be displayed on incorrect user input
def usageText():
print("\n[USAGE]: franken.py -v (verbose) -d (decrypt) --keyphrase (-k) <phrase> --message (-m) <message to encrypt>")
print("[USAGE]: -v and -d arguments are optional. --keyphrase(-k) and --message(-m) are required")
print("\n[EXAMPLE]: python franken.py -v --keyphrase \"super secret\" --message \"This is a super secret message\"\n")
print("[!] As with any cipher, your message is only as secure as your key phrase.")
print("[!] REMEMBER: The more complicated your key phrase, the stronger your encrypted message will be!\n")
sys.exit(2)
# USER INPUT HANDLING
# check that arguments have been supplied
if len(sys.argv) < 2:
usageText()
# define the arguments and necessity.
try:
opts, args = getopt.getopt(sys.argv[1:], 'vdk:m:', ["verbose", "decrypt", "keyphrase=", "message="])
except getopt.GetoptError:
usageText()
# check for presence of args and assign values
for opt, arg in opts:
if opt == '-v':
verbose_opt = True
if opt == '-d':
decrypt_opt = True
if opt in ('-k', '--keyphrase'):
key_phrase = arg
if opt in ('-m', '--message'):
clear_text = arg
# Check that a keyphrase and message has been set
if not key_phrase or not clear_text:
usageText()
print(
'''
__ _
/ _| | |
| |_ _ __ __ _ _ __ | | _____ _ __
| _| '__/ _` | '_ \| |/ / _ \ '_ \
| | | | | (_| | | | | < __/ | | |
|_| |_| \__,_|_| |_|_|\_\___|_| |_|
_ _
__(_)_ __| |_ ___ _ _
/ _| | '_ \ ' \/ -_) '_|
\__|_| .__/_||_\___|_|
|_|
[!] franken.py
An encryption algorithm inspired by a number of existing ciphers.
Created for CC6004 Course Work 1. 2016/17
[@] Dan C and [email protected]
__________________________________________________
'''
)
# are we decrypting or encrypting? defaults to encrypting
# decrypt
if decrypt_opt:
keyGenerate()
xorBackward()
pigpenBackward()
if not verbose_opt:
print("[DECRYPTED]: " + decrypted_message + "\n")
# encrypt
else:
keyGenerate()
pigpenForward()
xorForward()
if not verbose_opt:
print("[ENCRYPTED]: " + encrypted_message + "\n")<|fim▁end|> | |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>import {IconDefinition, IconLookup, IconName, IconPrefix, IconPathData, IconPack } from '@fortawesome/fontawesome-common-types';
export {IconDefinition, IconLookup, IconName, IconPrefix, IconPathData, IconPack } from '@fortawesome/fontawesome-common-types';
export const dom: DOM;
export const library: Library;
export const parse: { transform(transformString: string): Transform };
export const config: Config;
export function noAuto():void;
export function findIconDefinition(iconLookup: IconLookup): IconDefinition;
export function text(content: string, params?: TextParams): Text;
export function counter(content: string | number, params?: CounterParams): Counter;
export function toHtml(content: any): string;
export function toHtml(abstractNodes: AbstractElement): string;
export function layer(
assembler: (
addLayerCallback: (layerToAdd: IconOrText | IconOrText[]) => void
) => void,
params?: LayerParams
): Layer;
export function icon(icon: IconName | IconLookup, params?: IconParams): Icon;
export type IconProp = IconName | [IconPrefix, IconName] | IconLookup;
export type FlipProp = "horizontal" | "vertical" | "both";
export type SizeProp =
| "xs"
| "lg"
| "sm"
| "1x"
| "2x"
| "3x"
| "4x"
| "5x"
| "6x"
| "7x"
| "8x"
| "9x"
| "10x";
export type PullProp = "left" | "right";
export type RotateProp = 90 | 180 | 270;
export type FaSymbol = string | boolean;
export interface Config {
familyPrefix: IconPrefix;
replacementClass: string;
autoReplaceSvg: boolean | 'nest';
autoAddCss: boolean;
autoA11y: boolean;
searchPseudoElements: boolean;
observeMutations: boolean;
keepOriginalSource: boolean;
measurePerformance: boolean;
showMissingIcons: boolean;
}
export interface AbstractElement {
tag: string;
attributes: any;
children?: AbstractElement[];
}
export interface FontawesomeObject {
readonly abstract: AbstractElement[];
readonly html: string[];
readonly node: HTMLCollection;
}
export interface Icon extends FontawesomeObject, IconDefinition {
readonly type: "icon";
}
export interface Text extends FontawesomeObject {
readonly type: "text";
}
export interface Counter extends FontawesomeObject {
readonly type: "counter";
}
export interface Layer extends FontawesomeObject {
readonly type: "layer";
}
type IconOrText = Icon | Text;
export interface Attributes {
[key: string]: number | string;
}
export interface Styles {
[key: string]: string;
}
export interface Transform {
size?: number;
x?: number;
y?: number;
rotate?: number;
flipX?: boolean;
flipY?: boolean;<|fim▁hole|> attributes?: Attributes;
styles?: Styles;
}
export interface CounterParams extends Params {
}
export interface LayerParams {
classes?: string | string[];
}
export interface TextParams extends Params {
transform?: Transform;
}
export interface IconParams extends Params {
transform?: Transform;
symbol?: FaSymbol;
mask?: IconLookup;
}
export interface DOM {
i2svg(params?: { node: Node; callback: () => void }): Promise<void>;
css(): string;
insertCss(): string;
watch(): void;
}
type IconDefinitionOrPack = IconDefinition | IconPack;
export interface Library {
add(...definitions: IconDefinitionOrPack[]): void;
reset(): void;
}<|fim▁end|> | }
export interface Params {
title?: string;
classes?: string | string[]; |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import sys<|fim▁hole|>sys.path.append(os.path.abspath(os.curdir))<|fim▁end|> | import os |
<|file_name|>simd.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.
#![cfg_attr(feature = "cargo-clippy", allow(inline_always))]
use simd_opt;
pub use simdty::{u32x4, u64x4};
pub trait Vector4<T>: Copy {
fn gather(src: &[T], i0: usize, i1: usize, i2: usize, i3: usize) -> Self;
fn from_le(self) -> Self;
fn to_le(self) -> Self;
fn wrapping_add(self, rhs: Self) -> Self;
fn rotate_right_const(self, n: u32) -> Self;
fn shuffle_left_1(self) -> Self;
fn shuffle_left_2(self) -> Self;
fn shuffle_left_3(self) -> Self;
#[inline(always)] fn shuffle_right_1(self) -> Self { self.shuffle_left_3() }
#[inline(always)] fn shuffle_right_2(self) -> Self { self.shuffle_left_2() }
#[inline(always)] fn shuffle_right_3(self) -> Self { self.shuffle_left_1() }
}
macro_rules! impl_vector4 {
($vec:ident, $word:ident) => {
impl Vector4<$word> for $vec {
#[inline(always)]
fn gather(src: &[$word], i0: usize, i1: usize,
i2: usize, i3: usize) -> Self {
$vec::new(src[i0], src[i1], src[i2], src[i3])
}
#[cfg(target_endian = "little")]
#[inline(always)]
fn from_le(self) -> Self { self }
#[cfg(not(target_endian = "little"))]
#[inline(always)]
fn from_le(self) -> Self {
$vec::new($word::from_le(self.0),
$word::from_le(self.1),
$word::from_le(self.2),
$word::from_le(self.3))
}
#[cfg(target_endian = "little")]
#[inline(always)]
fn to_le(self) -> Self { self }
#[cfg(not(target_endian = "little"))]
#[inline(always)]
fn to_le(self) -> Self {
$vec::new(self.0.to_le(),
self.1.to_le(),<|fim▁hole|> #[inline(always)]
fn wrapping_add(self, rhs: Self) -> Self { self + rhs }
#[inline(always)]
fn rotate_right_const(self, n: u32) -> Self {
simd_opt::$vec::rotate_right_const(self, n)
}
#[cfg(feature = "simd")]
#[inline(always)]
fn shuffle_left_1(self) -> Self {
use simdint::simd_shuffle4;
unsafe { simd_shuffle4(self, self, [1, 2, 3, 0]) }
}
#[cfg(not(feature = "simd"))]
#[inline(always)]
fn shuffle_left_1(self) -> Self {
$vec::new(self.1, self.2, self.3, self.0)
}
#[cfg(feature = "simd")]
#[inline(always)]
fn shuffle_left_2(self) -> Self {
use simdint::simd_shuffle4;
unsafe { simd_shuffle4(self, self, [2, 3, 0, 1]) }
}
#[cfg(not(feature = "simd"))]
#[inline(always)]
fn shuffle_left_2(self) -> Self {
$vec::new(self.2, self.3, self.0, self.1)
}
#[cfg(feature = "simd")]
#[inline(always)]
fn shuffle_left_3(self) -> Self {
use simdint::simd_shuffle4;
unsafe { simd_shuffle4(self, self, [3, 0, 1, 2]) }
}
#[cfg(not(feature = "simd"))]
#[inline(always)]
fn shuffle_left_3(self) -> Self {
$vec::new(self.3, self.0, self.1, self.2)
}
}
}
}
impl_vector4!(u32x4, u32);
impl_vector4!(u64x4, u64);<|fim▁end|> | self.2.to_le(),
self.3.to_le())
}
|
<|file_name|>flushLogs.ts<|end_file_name|><|fim▁begin|>import { ClientCommand } from './clientCommand';
import { BaseCommand } from './baseCommand';
module.exports = class FlushLogs extends ClientCommand {
static create(): BaseCommand {
return new FlushLogs();
}
constructor() {
super('Flush Logs', 'flush-logs');
this.async = false;
this.body.args.ui = true;<|fim▁hole|>}<|fim▁end|> | } |
<|file_name|>2.module.js<|end_file_name|><|fim▁begin|>webpackJsonp([2],{
/***/ 16:
/***/ function(module, exports, __webpack_require__) {
/// <reference path="../../typings/tsd.d.ts" />
var ListController = __webpack_require__(17);
// webpack will load the html. Nifty, eh?
__webpack_require__(9);
// webpack will load this scss too!
__webpack_require__(18);
module.exports = angular.module('List', [])
.controller('ListController', ['$scope', ListController]);
//# sourceMappingURL=index.js.map<|fim▁hole|>
/***/ },
/***/ 17:
/***/ function(module, exports) {
var ListController = (function () {
function ListController() {
this.apps = [
{ name: 'Gmail' },
{ name: 'Facebook' },
{ name: 'Twitter' },
{ name: 'LinkedIn' }
];
this.title = 'Applications';
}
return ListController;
})();
module.exports = ListController;
//# sourceMappingURL=list.controller.js.map
/***/ },
/***/ 18:
/***/ function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(19);
if(typeof content === 'string') content = [[module.id, content, '']];
// add the styles to the DOM
var update = __webpack_require__(15)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!./../../../../node_modules/css-loader/index.js!./../../../../node_modules/autoprefixer-loader/index.js!./../../../../node_modules/sass-loader/index.js!./list.scss", function() {
var newContent = require("!!./../../../../node_modules/css-loader/index.js!./../../../../node_modules/autoprefixer-loader/index.js!./../../../../node_modules/sass-loader/index.js!./list.scss");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ },
/***/ 19:
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(14)();
// imports
// module
exports.push([module.id, ".list-item {\n color: blue; }\n", ""]);
// exports
/***/ }
});<|fim▁end|> | |
<|file_name|>notifications-add-interval.js<|end_file_name|><|fim▁begin|>var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
const notUtils = require('./notifications-utils.js');
module.exports = [
function (session) {
session.beginDialog('notifications-common-symbol');
},
function (session, results) {
var pair = results.response;
session.dialogData.symbol = pair;
builder.Prompts.number(session, 'How big should the interval be?');
},
function (session, results) {
session.dialogData.interval = results.response;
builder.Prompts.text(session, "What name would you like to give to this notification?");
},
function (session, results) {
var sub = notUtils.getBaseNotification('interval', session.message.address);
sub.symbol = session.dialogData.symbol;
sub.interval = session.dialogData.interval;
sub.previousprice = 0;
sub.isfirstun = true;
sub.name = results.response;
notUtils.createNotification(sub).then((r) => {<|fim▁hole|> }).catch((e) => {
session.endDialog('Couldn\'t create notification: ' + e);
});
}
];<|fim▁end|> | session.endDialog('Notification created!'); |
<|file_name|>common.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Common client code
#
# Copyright 2016 Markus Zoeller
import os
from launchpadlib.launchpad import Launchpad
def get_project_client(project_name):
cachedir = os.path.expanduser("~/.launchpadlib/cache/")
if not os.path.exists(cachedir):
os.makedirs(cachedir, 0o700)
launchpad = Launchpad.login_anonymously(project_name + '-bugs',
'production', cachedir)
project = launchpad.projects[project_name]
return project
def remove_first_line(invalid_json):
return '\n'.join(invalid_json.split('\n')[1:])
class BugReport(object):
def __init__(self, link, title, age):
self.link = link
self.title = title.encode('ascii', 'replace')
self.age = age
<|fim▁hole|> def __cmp__(self, other):
return cmp(self.age, other.age)<|fim▁end|> | def __str__(self):
data = {'link': self.link, 'title': self.title, 'age': self.age}
return "{link} ({title}) - ({age} days)".format(**data)
|
<|file_name|>spelling.py<|end_file_name|><|fim▁begin|># Copyright 2014 Michal Nowikowski.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Checker for spelling errors in comments and docstrings.
"""
import sys
import tokenize
import string
import re
if sys.version_info[0] >= 3:
maketrans = str.maketrans
else:
maketrans = string.maketrans
from pylint.interfaces import ITokenChecker, IAstroidChecker
from pylint.checkers import BaseTokenChecker
from pylint.checkers.utils import check_messages
try:
import enchant
except ImportError:
enchant = None
if enchant is not None:
br = enchant.Broker()
dicts = br.list_dicts()
dict_choices = [''] + [d[0] for d in dicts]
dicts = ["%s (%s)" % (d[0], d[1].name) for d in dicts]
dicts = ", ".join(dicts)
instr = ""
else:
dicts = "none"
dict_choices = ['']
instr = " To make it working install python-enchant package."
table = maketrans("", "")
class SpellingChecker(BaseTokenChecker):
"""Check spelling in comments and docstrings"""
__implements__ = (ITokenChecker, IAstroidChecker)
name = 'spelling'
msgs = {
'C0401': ('Wrong spelling of a word \'%s\' in a comment:\n%s\n'
'%s\nDid you mean: \'%s\'?',
'wrong-spelling-in-comment',
'Used when a word in comment is not spelled correctly.'),
'C0402': ('Wrong spelling of a word \'%s\' in a docstring:\n%s\n'
'%s\nDid you mean: \'%s\'?',
'wrong-spelling-in-docstring',
'Used when a word in docstring is not spelled correctly.'),
}
options = (('spelling-dict',
{'default' : '', 'type' : 'choice', 'metavar' : '<dict name>',
'choices': dict_choices,
'help' : 'Spelling dictionary name. '
'Available dictionaries: %s.%s' % (dicts, instr)}),
('spelling-ignore-words',
{'default' : '',
'type' : 'string',
'metavar' : '<comma separated words>',
'help' : 'List of comma separated words that '
'should not be checked.'}),
('spelling-private-dict-file',
{'default' : '',
'type' : 'string',
'metavar' : '<path to file>',
'help' : 'A path to a file that contains private '
'dictionary; one word per line.'}),
('spelling-store-unknown-words',
{'default' : 'n', 'type' : 'yn', 'metavar' : '<y_or_n>',
'help' : 'Tells whether to store unknown words to '
'indicated private dictionary in '
'--spelling-private-dict-file option instead of '
'raising a message.'}),
)
def open(self):
self.initialized = False
self.private_dict_file = None<|fim▁hole|> dict_name = self.config.spelling_dict
if not dict_name:
return
self.ignore_list = [w.strip() for w in self.config.spelling_ignore_words.split(",")]
# "param" appears in docstring in param description and
# "pylint" appears in comments in pylint pragmas.
self.ignore_list.extend(["param", "pylint"])
if self.config.spelling_private_dict_file:
self.spelling_dict = enchant.DictWithPWL(
dict_name, self.config.spelling_private_dict_file)
self.private_dict_file = open(
self.config.spelling_private_dict_file, "a")
else:
self.spelling_dict = enchant.Dict(dict_name)
if self.config.spelling_store_unknown_words:
self.unknown_words = set()
# Prepare regex for stripping punctuation signs from text.
# ' and _ are treated in a special way.
puncts = string.punctuation.replace("'", "").replace("_", "")
self.punctuation_regex = re.compile('[%s]' % re.escape(puncts))
self.initialized = True
def close(self):
if self.private_dict_file:
self.private_dict_file.close()
def _check_spelling(self, msgid, line, line_num):
line2 = line.strip()
# Replace ['afadf with afadf (but preserve don't)
line2 = re.sub("'([^a-zA-Z]|$)", " ", line2)
# Replace afadf'] with afadf (but preserve don't)
line2 = re.sub("([^a-zA-Z]|^)'", " ", line2)
# Replace punctuation signs with space e.g. and/or -> and or
line2 = self.punctuation_regex.sub(' ', line2)
words = []
for word in line2.split():
# Skip words with digits.
if len(re.findall(r"\d", word)) > 0:
continue
# Skip words with mixed big and small letters,
# they are probaly class names.
if (len(re.findall("[A-Z]", word)) > 0 and
len(re.findall("[a-z]", word)) > 0 and
len(word) > 2):
continue
# Skip words with _ - they are probably function parameter names.
if word.count('_') > 0:
continue
words.append(word)
# Go through words and check them.
for word in words:
# Skip words from ignore list.
if word in self.ignore_list:
continue
orig_word = word
word = word.lower()
# Strip starting u' from unicode literals and r' from raw strings.
if (word.startswith("u'") or
word.startswith('u"') or
word.startswith("r'") or
word.startswith('r"')) and len(word) > 2:
word = word[2:]
# If it is a known word, then continue.
if self.spelling_dict.check(word):
continue
# Store word to private dict or raise a message.
if self.config.spelling_store_unknown_words:
if word not in self.unknown_words:
self.private_dict_file.write("%s\n" % word)
self.unknown_words.add(word)
else:
# Present up to 4 suggestions.
# TODO: add support for customising this.
suggestions = self.spelling_dict.suggest(word)[:4]
m = re.search(r"(\W|^)(%s)(\W|$)" % word, line.lower())
if m:
# Start position of second group in regex.
col = m.regs[2][0]
else:
col = line.lower().index(word)
indicator = (" " * col) + ("^" * len(word))
self.add_message(msgid, line=line_num,
args=(orig_word, line,
indicator,
"' or '".join(suggestions)))
def process_tokens(self, tokens):
if not self.initialized:
return
# Process tokens and look for comments.
for (tok_type, token, (start_row, _), _, _) in tokens:
if tok_type == tokenize.COMMENT:
self._check_spelling('wrong-spelling-in-comment',
token, start_row)
@check_messages('wrong-spelling-in-docstring')
def visit_module(self, node):
if not self.initialized:
return
self._check_docstring(node)
@check_messages('wrong-spelling-in-docstring')
def visit_class(self, node):
if not self.initialized:
return
self._check_docstring(node)
@check_messages('wrong-spelling-in-docstring')
def visit_function(self, node):
if not self.initialized:
return
self._check_docstring(node)
def _check_docstring(self, node):
"""check the node has any spelling errors"""
docstring = node.doc
if not docstring:
return
start_line = node.lineno + 1
# Go through lines of docstring
for idx, line in enumerate(docstring.splitlines()):
self._check_spelling('wrong-spelling-in-docstring',
line, start_line + idx)
def register(linter):
"""required method to auto register this checker """
linter.register_checker(SpellingChecker(linter))<|fim▁end|> |
if enchant is None:
return |
<|file_name|>serviceworkercontainer.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions;
use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{
ServiceWorkerContainerMethods, Wrap,
};
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::USVString;
use crate::dom::client::Client;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise;
use crate::dom::serviceworker::ServiceWorker;
use crate::script_thread::ScriptThread;
use crate::serviceworkerjob::{Job, JobType};
use dom_struct::dom_struct;
use std::default::Default;
use std::rc::Rc;
#[dom_struct]
pub struct ServiceWorkerContainer {
eventtarget: EventTarget,
controller: MutNullableDom<ServiceWorker>,
client: Dom<Client>,
}
impl ServiceWorkerContainer {
fn new_inherited(client: &Client) -> ServiceWorkerContainer {
ServiceWorkerContainer {
eventtarget: EventTarget::new_inherited(),
controller: Default::default(),
client: Dom::from_ref(client),
}<|fim▁hole|> }
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> {
let client = Client::new(&global.as_window());
let container = ServiceWorkerContainer::new_inherited(&*client);
reflect_dom_object(Box::new(container), global, Wrap)
}
}
impl ServiceWorkerContainerMethods for ServiceWorkerContainer {
// https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute
fn GetController(&self) -> Option<DomRoot<ServiceWorker>> {
self.client.get_controller()
}
#[allow(unrooted_must_root)]
// https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A
// https://w3c.github.io/ServiceWorker/#start-register-algorithm - B
fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> {
// A: Step 1
let promise = Promise::new(&*self.global());
let USVString(ref script_url) = script_url;
let api_base_url = self.global().api_base_url();
// A: Step 3-5
let script_url = match api_base_url.join(script_url) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid script URL".to_owned()));
return promise;
},
};
// B: Step 2
match script_url.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 3
if script_url.path().to_ascii_lowercase().contains("%2f") ||
script_url.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Script URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 4-5
let scope = match options.scope {
Some(ref scope) => {
let &USVString(ref inner_scope) = scope;
match api_base_url.join(inner_scope) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid scope URL".to_owned()));
return promise;
},
}
},
None => script_url.join("./").unwrap(),
};
// B: Step 6
match scope.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 7
if scope.path().to_ascii_lowercase().contains("%2f") ||
scope.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Scope URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 8
let job = Job::create_job(
JobType::Register,
scope,
script_url,
promise.clone(),
&*self.client,
);
ScriptThread::schedule_job(job);
promise
}
}<|fim▁end|> | |
<|file_name|>file_exporter.py<|end_file_name|><|fim▁begin|>import shutil
import os
import errno
class file_exporter:
def __init__(self):
self.error_message = ''
def get_error_message (self):
return self.error_message
def tally_path_segments (self, file):
while (file != ''):
(first, last) = os.path.split (file)
if first == file:
#### we've hit the top of the path, so bail out
break
if first not in self.path_segments:
self.path_segments[first] = 0
self.path_segments[first] += 1
file = first
def get_base_path (self):
self.path_segments = {}
for file in self.files:
self.tally_path_segments (file)
max_path_len = 0
max_path = ''
for segment in self.path_segments:
if self.path_segments[segment] == len (self.files):
if len (segment) > max_path_len:
max_path_len = len (segment)
max_path = segment
#### use join() to append a final separator; this is important when<|fim▁hole|> self.base_path = os.path.join (max_path, '')
def export (self, export_path, files):
self.files = files
self.base_path = ''
print " calculating base path..."
self.get_base_path ()
print " base path : " + self.base_path.encode('utf-8')
for file in self.files:
print " - exporting file '" + file.encode('utf-8') + "'..."
basename = file.replace (self.base_path, '')
export_file = os.path.join (export_path, basename)
print " writing to '" + export_file.encode('utf-8') + "'..."
(first, last) = os.path.split (export_file)
try:
print " making dir '" + first.encode('utf-8') + "'..."
os.makedirs (first.encode ('utf-8'))
except OSError as e:
#### ignore directory already exists
if e.errno == errno.EEXIST:
pass
else:
self.error_message = "Could not copy '" + file.encode('utf-8') + "' to '" + export_file.encode('utf-8') + "': " + e.strerror
return False
print " copying file..."
try:
shutil.copy2(file.encode ('utf-8'), export_file.encode ('utf-8'))
except OSError as e:
self.error_message = "Could not copy '" + file.encode ('utf-8') + "' to '" + export_file.encode ('utf-8') + "': " + e.strerror
return False
return True<|fim▁end|> | #### we strip the base path from the full filenames |
<|file_name|>analyze.js<|end_file_name|><|fim▁begin|>#!/usr/bin/env node
var execSync = require('child_process').execSync;
var fs = require("fs");
var args = process.argv.slice(2);
var guid = args[0];
if (typeof guid === "undefined") {
console.log("provide a guid");
} else {
var fileList = ""+execSync("ls -lh");
var lines = fileList.split("\n");
var count = 0; for (l in lines) { if (lines[l].indexOf(".wav") != -1) { count++; } }
var rep = 0;
console.log("About "+count+" audio files to analyze...");
for (l in lines) { if (lines[l].indexOf(".wav") != -1) {
rep++;
var fileName = lines[l].substr(lines[l].lastIndexOf(".wav")-32,32)+".wav";
var timestamp = lines[l].substr(lines[l].lastIndexOf(".wav")-19,19);
var dateTime = (new Date(timestamp.substr(0,timestamp.indexOf("T"))+"T"+timestamp.substr(1+timestamp.indexOf("T")).replace(/-/g,":"))).toISOString();
var checkInId = lines[l].substr(lines[l].lastIndexOf(".wav")-32,32);
var audioId = lines[l].substr(lines[l].lastIndexOf(".wav")-32,32);
<|fim▁hole|> // +" -data /Users/topher/code/rfcx/worker-analysis/config/input_defaults.properties"
+" --guardian_id "+guid
+" --checkin_id checkin-"+checkInId
+" --audio_id audio-"+audioId
+" --start_time '"+dateTime+"'"
+" --ambient_temp "+40
+" --lat_lng "+"3.6141375,14.2108033"
+" --local"
+" >> /Volumes/rfcx-audio/GuardianAudio/"+guid+"/"+fileName+".txt"
;
console.log(fileName);
execSync(execStr);
} }
}<|fim▁end|> | var execStr = "cd /Users/topher/code/rfcx/worker-analysis && /usr/local/bin/python2.7"
+" /Users/topher/code/rfcx/worker-analysis/analyze.py"
+" --wav_path /Volumes/rfcx-audio/GuardianAudio/"+guid+"/"+fileName |
<|file_name|>groupLayersAlgorithm.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
/***************************************************************************
DsgTools
A QGIS plugin
Brazilian Army Cartographic Production Tools
-------------------
begin : 2019-04-26
git sha : $Format:%H$
copyright : (C) 2019 by Philipe Borba -
Cartographic Engineer @ Brazilian Army
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
from PyQt5.QtCore import QCoreApplication
from qgis.core import (QgsDataSourceUri, QgsExpression, QgsExpressionContext,
QgsExpressionContextUtils, QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingOutputMultipleLayers,
QgsProcessingParameterExpression,
QgsProcessingParameterMultipleLayers,
QgsProcessingParameterNumber,
QgsProcessingParameterString, QgsProject)
from qgis.utils import iface
class GroupLayersAlgorithm(QgsProcessingAlgorithm):
"""
Algorithm to group layers according to primitive, dataset and a category.
INPUT_LAYERS: list of QgsVectorLayer
CATEGORY_TOKEN: token used to split layer name
CATEGORY_TOKEN_INDEX: index of the split list
OUTPUT: list of outputs
"""
INPUT_LAYERS = 'INPUT_LAYERS'
CATEGORY_EXPRESSION = 'CATEGORY_EXPRESSION'
OUTPUT = 'OUTPUT'
def initAlgorithm(self, config):
"""
Parameter setting.
"""
self.addParameter(
QgsProcessingParameterMultipleLayers(
self.INPUT_LAYERS,
self.tr('Input Layers'),
QgsProcessing.TypeVector
)
)
self.addParameter(
QgsProcessingParameterExpression(
self.CATEGORY_EXPRESSION,
self.tr('Expression used to find out the category'),
defaultValue="regexp_substr(@layer_name ,'([^_]+)')"
)
)
self.addOutput(
QgsProcessingOutputMultipleLayers(
self.OUTPUT,
self.tr('Original reorganized layers')
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
inputLyrList = self.parameterAsLayerList(
parameters,
self.INPUT_LAYERS,
context
)
categoryExpression = self.parameterAsExpression(
parameters,
self.CATEGORY_EXPRESSION,
context
)
listSize = len(inputLyrList)
progressStep = 100/listSize if listSize else 0
rootNode = QgsProject.instance().layerTreeRoot()
inputLyrList.sort(key=lambda x: (x.geometryType(), x.name()))
geometryNodeDict = {
0 : self.tr('Point'),
1 : self.tr('Line'),
2 : self.tr('Polygon'),
4 : self.tr('Non spatial')
}
iface.mapCanvas().freeze(True)
for current, lyr in enumerate(inputLyrList):
if feedback.isCanceled():
break
rootDatabaseNode = self.getLayerRootNode(lyr, rootNode)
geometryNode = self.createGroup(
geometryNodeDict[lyr.geometryType()],
rootDatabaseNode
)
categoryNode = self.getLayerCategoryNode(
lyr,
geometryNode,
categoryExpression
)
lyrNode = rootNode.findLayer(lyr.id())
myClone = lyrNode.clone()
categoryNode.addChildNode(myClone)
# not thread safe, must set flag to FlagNoThreading
rootNode.removeChildNode(lyrNode)
feedback.setProgress(current*progressStep)
iface.mapCanvas().freeze(False)
return {self.OUTPUT: [i.id() for i in inputLyrList]}
def getLayerRootNode(self, lyr, rootNode):
"""
Finds the database name of the layer and creates (if not exists)
a node with the found name.
lyr: (QgsVectorLayer)
rootNode: (node item)
"""
uriText = lyr.dataProvider().dataSourceUri()
candidateUri = QgsDataSourceUri(uriText)
rootNodeName = candidateUri.database()
if not rootNodeName:
rootNodeName = self.getRootNodeName(uriText)
#creates database root
return self.createGroup(rootNodeName, rootNode)
def getRootNodeName(self, uriText):
"""
Gets root node name from uri according to provider type.
"""
if 'memory?' in uriText:
rootNodeName = 'memory'
elif 'dbname' in uriText:
rootNodeName = uriText.replace('dbname=', '').split(' ')[0]
elif '|' in uriText:
rootNodeName = os.path.dirname(uriText.split(' ')[0].split('|')[0])
else:
rootNodeName = 'unrecognised_format'
return rootNodeName
def getLayerCategoryNode(self, lyr, rootNode, categoryExpression):
"""
Finds category node based on category expression
and creates it (if not exists a node)
"""
exp = QgsExpression(categoryExpression)
context = QgsExpressionContext()
context.appendScopes(
QgsExpressionContextUtils.globalProjectLayerScopes(lyr)
)
if exp.hasParserError():
raise Exception(exp.parserErrorString())
if exp.hasEvalError():
raise ValueError(exp.evalErrorString())
categoryText = exp.evaluate(context)<|fim▁hole|> Create group with the name groupName and parent rootNode.
"""
groupNode = rootNode.findGroup(groupName)
return groupNode if groupNode else rootNode.addGroup(groupName)
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'grouplayers'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr('Group Layers')
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr('Layer Management Algorithms')
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'DSGTools: Layer Management Algorithms'
def tr(self, string):
"""
Translates input string.
"""
return QCoreApplication.translate('GroupLayersAlgorithm', string)
def createInstance(self):
"""
Creates an instance of this class
"""
return GroupLayersAlgorithm()
def flags(self):
"""
This process is not thread safe due to the fact that removeChildNode
method from QgsLayerTreeGroup is not thread safe.
"""
return super().flags() | QgsProcessingAlgorithm.FlagNoThreading<|fim▁end|> | return self.createGroup(categoryText, rootNode)
def createGroup(self, groupName, rootNode):
""" |
<|file_name|>YQZyppSolverDialogPluginStub.cc<|end_file_name|><|fim▁begin|>/**************************************************************************
Copyright (C) 2000 - 2010 Novell, Inc.
All Rights Reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**************************************************************************/
/*---------------------------------------------------------------------\
| |
| __ __ ____ _____ ____ |
| \ \ / /_ _/ ___|_ _|___ \ |
| \ V / _` \___ \ | | __) | |
| | | (_| |___) || | / __/ |
| |_|\__,_|____/ |_| |_____| |
| |
| core system |
| (c) SuSE Linux AG |
\----------------------------------------------------------------------/<|fim▁hole|>
File: YQZyppSolverDialogPluginStub.cc
Authors: Stefan Schubert <[email protected]>
Textdomain "qt-pkg"
/-*/
#include <qmessagebox.h>
#include "YQZyppSolverDialogPluginStub.h"
#define YUILogComponent "qt-ui"
#include "YUILog.h"
#include "YQi18n.h"
#define PLUGIN_BASE_NAME "qt_zypp_solver_dialog"
using std::endl;
YQZyppSolverDialogPluginStub::YQZyppSolverDialogPluginStub()
: YUIPlugin( PLUGIN_BASE_NAME )
{
if ( success() )
{
yuiMilestone() << "Loaded " << PLUGIN_BASE_NAME
<< " plugin successfully from " << pluginLibFullPath()
<< endl;
}
impl = (YQZyppSolverDialogPluginIf*) locateSymbol("ZYPPDIALOGP");
if ( ! impl )
{
yuiError() << "Plugin " << PLUGIN_BASE_NAME << " does not provide ZYPPP symbol" << endl;
}
}
YQZyppSolverDialogPluginStub::~YQZyppSolverDialogPluginStub()
{
// NOP
}
bool
YQZyppSolverDialogPluginStub::createZyppSolverDialog( const zypp::PoolItem item )
{
if ( ! impl )
{
QMessageBox::information( 0,
_("Missing package") ,
_("Package libqdialogsolver is required for this feature."));
return false;
}
return impl->createZyppSolverDialog( item );
}<|fim▁end|> | |
<|file_name|>mnist_tf_keras.py<|end_file_name|><|fim▁begin|>import tensorflow as tf
import numpy as np
import deep_architect.modules as mo
import deep_architect.hyperparameters as hp
from deep_architect.contrib.misc.search_spaces.tensorflow.common import siso_tfm
D = hp.Discrete # Discrete Hyperparameter
def dense(h_units):
def compile_fn(di, dh): # compile function
Dense = tf.keras.layers.Dense(dh['units'])
def fn(di): # forward function
return {'out': Dense(di['in'])}
return fn
return siso_tfm('Dense', compile_fn, {'units': h_units})
def flatten():
def compile_fn(di, dh):
Flatten = tf.keras.layers.Flatten()
def fn(di):
return {'out': Flatten(di['in'])}
return fn
return siso_tfm('Flatten', compile_fn, {})
def nonlinearity(h_nonlin_name):
def compile_fn(di, dh):
def fn(di):
nonlin_name = dh['nonlin_name']
if nonlin_name == 'relu':
Out = tf.keras.layers.Activation('relu')(di['in'])
elif nonlin_name == 'tanh':
Out = tf.keras.layers.Activation('tanh')(di['in'])
elif nonlin_name == 'elu':
Out = tf.keras.layers.Activation('elu')(di['in'])
else:
raise ValueError
return {"out": Out}
return fn
return siso_tfm('Nonlinearity', compile_fn, {'nonlin_name': h_nonlin_name})
def dropout(h_keep_prob):
def compile_fn(di, dh):
Dropout = tf.keras.layers.Dropout(dh['keep_prob'])
def fn(di):
return {'out': Dropout(di['in'])}
return fn
return siso_tfm('Dropout', compile_fn, {'keep_prob': h_keep_prob})
def batch_normalization():
def compile_fn(di, dh):
bn = tf.keras.layers.BatchNormalization()
def fn(di):
return {'out': bn(di['in'])}
return fn
return siso_tfm('BatchNormalization', compile_fn, {})
def dnn_net_simple(num_classes):
# defining hyperparameter
h_num_hidden = D([64, 128, 256, 512,
1024]) # number of hidden units for dense module
h_nonlin_name = D(['relu', 'tanh',
'elu']) # nonlinearity function names to choose from
h_opt_drop = D(
[0, 1]) # dropout optional hyperparameter; 0 is exclude, 1 is include
h_drop_keep_prob = D([0.25, 0.5,
0.75]) # dropout probability to choose from
h_opt_bn = D([0, 1]) # batch_norm optional hyperparameter
h_perm = D([0, 1]) # order of swapping for permutation
h_num_repeats = D([1, 2]) # 1 is appearing once, 2 is appearing twice
# defining search space topology
model = mo.siso_sequential([
flatten(),
mo.siso_repeat(
lambda: mo.siso_sequential([
dense(h_num_hidden),
nonlinearity(h_nonlin_name),
mo.siso_permutation([
lambda: mo.siso_optional(lambda: dropout(h_drop_keep_prob),
h_opt_drop),
lambda: mo.siso_optional(batch_normalization, h_opt_bn),
], h_perm)
]), h_num_repeats),
dense(D([num_classes]))
])
return model
def dnn_cell(h_num_hidden, h_nonlin_name, h_swap, h_opt_drop, h_opt_bn,
h_drop_keep_prob):
return mo.siso_sequential([
dense(h_num_hidden),
nonlinearity(h_nonlin_name),
mo.siso_permutation([
lambda: mo.siso_optional(lambda: dropout(h_drop_keep_prob),
h_opt_drop),
lambda: mo.siso_optional(batch_normalization, h_opt_bn),
], h_swap)
])
def dnn_net(num_classes):
h_nonlin_name = D(['relu', 'tanh', 'elu'])
h_swap = D([0, 1])
h_opt_drop = D([0, 1])
h_opt_bn = D([0, 1])
return mo.siso_sequential([
flatten(),
mo.siso_repeat(
lambda: dnn_cell(D([64, 128, 256, 512, 1024]),<|fim▁hole|> h_nonlin_name, h_swap, h_opt_drop, h_opt_bn,
D([0.25, 0.5, 0.75])), D([1, 2])),
dense(D([num_classes]))
])
import deep_architect.searchers.random as se
import deep_architect.core as co
def get_search_space(num_classes):
def fn():
co.Scope.reset_default_scope()
inputs, outputs = dnn_net(num_classes)
return inputs, outputs, {}
return fn
class SimpleClassifierEvaluator:
def __init__(self,
train_dataset,
num_classes,
max_num_training_epochs=20,
batch_size=256,
learning_rate=1e-3):
self.train_dataset = train_dataset
self.num_classes = num_classes
self.max_num_training_epochs = max_num_training_epochs
self.learning_rate = learning_rate
self.batch_size = batch_size
self.val_split = 0.1 # 10% of dataset for validation
def evaluate(self, inputs, outputs):
tf.keras.backend.clear_session()
tf.reset_default_graph()
(x_train, y_train) = self.train_dataset
X = tf.keras.layers.Input(x_train[0].shape)
co.forward({inputs['in']: X})
logits = outputs['out'].val
probs = tf.keras.layers.Softmax()(logits)
model = tf.keras.models.Model(inputs=[inputs['in'].val],
outputs=[probs])
optimizer = tf.keras.optimizers.Adam(lr=self.learning_rate)
model.compile(optimizer=optimizer,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.summary()
history = model.fit(x_train,
y_train,
batch_size=self.batch_size,
epochs=self.max_num_training_epochs,
validation_split=self.val_split)
results = {'val_acc': history.history['val_acc'][-1]}
return results
def main():
num_classes = 10
num_samples = 3 # number of architecture to sample
best_val_acc, best_architecture = 0., -1
# load and normalize data
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# defining evaluator and searcher
evaluator = SimpleClassifierEvaluator((x_train, y_train),
num_classes,
max_num_training_epochs=5)
searcher = se.RandomSearcher(get_search_space(num_classes))
for i in xrange(num_samples):
print("Sampling architecture %d" % i)
inputs, outputs, _, searcher_eval_token = searcher.sample()
val_acc = evaluator.evaluate(
inputs,
outputs)['val_acc'] # evaluate and return validation accuracy
print("Finished evaluating architecture %d, validation accuracy is %f" %
(i, val_acc))
if val_acc > best_val_acc:
best_val_acc = val_acc
best_architecture = i
searcher.update(val_acc, searcher_eval_token)
print("Best validation accuracy is %f with architecture %d" %
(best_val_acc, best_architecture))
if __name__ == "__main__":
main()<|fim▁end|> | |
<|file_name|>ImportFatalError.ts<|end_file_name|><|fim▁begin|>import { c } from 'ttag';
export class ImportFatalError extends Error {
error: Error;
constructor(error: Error) {<|fim▁hole|>}<|fim▁end|> | super(c('Error importing calendar').t`An unexpected error occurred. Import must be restarted.`);
this.error = error;
Object.setPrototypeOf(this, ImportFatalError.prototype);
} |
<|file_name|>seriesPicker.js<|end_file_name|><|fim▁begin|>/**
* Piwik - free/libre analytics platform
*
* Series Picker control addition for DataTable visualizations.
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function ($, require) {
/**
* This class creates and manages the Series Picker for certain DataTable visualizations.
*
* To add the series picker to your DataTable visualization, create a SeriesPicker instance
* and after your visualization has been rendered, call the 'init' method.
*
* To customize SeriesPicker placement and behavior, you can bind callbacks to the following
* events before calling 'init':
*
* 'placeSeriesPicker': Triggered after the DOM element for the series picker link is created.
* You must use this event to add the link to the dataTable. YOu can also
* use this event to position the link however you want.
*
* Callback Signature: function () {}
*
* 'seriesPicked': Triggered when the user selects one or more columns/rows.
*
* Callback Signature: function (eventInfo, columns, rows) {}
*
* Events are triggered via jQuery, so you bind callbacks to them like this:
*
* var picker = new SeriesPicker(dataTable);
* $(picker).bind('placeSeriesPicker', function () {
* $(this.domElem).doSomething(...);
* });
*
* @param {dataTable} dataTable The dataTable instance to add a series picker to.
* @constructor
* @deprecated use the piwik-series-picker directive instead
*/
var SeriesPicker = function (dataTable) {
this.domElem = null;
this.dataTableId = dataTable.workingDivId;
// the columns that can be selected
this.selectableColumns = dataTable.props.selectable_columns;
// the rows that can be selected
this.selectableRows = dataTable.props.selectable_rows;
// render the picker?
this.show = !! dataTable.props.show_series_picker
&& (this.selectableColumns || this.selectableRows);
// can multiple rows we selected?
this.multiSelect = !! dataTable.props.allow_multi_select_series_picker;
};
SeriesPicker.prototype = {
/**
* Initializes the series picker by creating the element. Must be called when
* the datatable the picker is being attached to is ready for it to be drawn.
*/
init: function () {
if (!this.show) {
return;
}
<|fim▁hole|> .filter(isItemDisplayed)
.map(function (columnConfig) {
return columnConfig.column;
});
var selectedRows = this.selectableRows
.filter(isItemDisplayed)
.map(function (rowConfig) {
return rowConfig.matcher;
});
// initialize dom element
var seriesPicker = '<piwik-series-picker'
+ ' multiselect="' + (this.multiSelect ? 'true' : 'false') + '"'
+ ' selectable-columns="selectableColumns"'
+ ' selectable-rows="selectableRows"'
+ ' selected-columns="selectedColumns"'
+ ' selected-rows="selectedRows"'
+ ' on-select="selectionChanged(columns, rows)"/>';
this.domElem = $(seriesPicker); // TODO: don't know if this will work without a root scope
$(this).trigger('placeSeriesPicker');
piwikHelper.compileAngularComponents(this.domElem, {
scope: {
selectableColumns: this.selectableColumns,
selectableRows: this.selectableRows,
selectedColumns: selectedColumns,
selectedRows: selectedRows,
selectionChanged: function selectionChanged(columns, rows) {
if (columns.length === 0 && rows.length === 0) {
return;
}
$(self).trigger('seriesPicked', [columns, rows]);
// inform dashboard widget about changed parameters (to be restored on reload)
var UI = require('piwik/UI');
var params = {
columns: columns,
columns_to_display: columns,
rows: rows,
rows_to_display: rows
};
var tableNode = $('#' + this.dataTableId);
UI.DataTable.prototype.notifyWidgetParametersChange(tableNode, params);
}
}
});
function isItemDisplayed(columnOrRowConfig) {
return columnOrRowConfig.displayed;
}
},
/**
* Returns the translation of a metric that can be selected.
*
* @param {String} metric The name of the metric, ie, 'nb_visits' or 'nb_actions'.
* @return {String} The metric translation. If one cannot be found, the metric itself
* is returned.
*/
getMetricTranslation: function (metric) {
for (var i = 0; i !== this.selectableColumns.length; ++i) {
if (this.selectableColumns[i].column === metric) {
return this.selectableColumns[i].translation;
}
}
return metric;
}
};
var exports = require('piwik/DataTableVisualizations/Widgets');
exports.SeriesPicker = SeriesPicker;
})(jQuery, require);<|fim▁end|> | var self = this;
var selectedColumns = this.selectableColumns |
<|file_name|>Handler.js<|end_file_name|><|fim▁begin|>"use strict";
var _ = require("lodash");
var Base = require("./Base");
var User = require("./User");
var UpdateMixin = require("./UpdateMixin");
/**
* Ticket handler model for the client
*
* @namespace models.client
* @class Handler
* @extends models.client.Base
* @uses models.client.UpdateMixin
*/
var Handler = Base.extend({
defaults: function() {
return {
type: "handlers",
createdAt: new Date().toString()
};
},
relationsMap: function() {
return {
handler: User
};
},
url: function() {
if (this.isNew()) return this.parent.url() + "/handlers";
return _.result(this.parent, "url") + "/handlers/" + this.get("handledById");
},
/**
* Return the handler user object
*
* @method getUser
* @return {models.client.User}
*/<|fim▁hole|>});
_.extend(Handler.prototype, UpdateMixin);
module.exports = Handler;<|fim▁end|> | getUser: function(){
return this.rel("handler");
},
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|># Licensed to the StackStorm, Inc ('StackStorm') 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.
import abc
import six
from mongoengine import NotUniqueError
from st2common import log as logging
from st2common.exceptions.db import StackStormDBObjectConflictError
from st2common.models.system.common import ResourceReference
from st2common.transport.reactor import TriggerDispatcher
__all__ = [
'Access',
'ContentPackResource',
'StatusBasedResource'
]
LOG = logging.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class Access(object):
impl = None
publisher = None
dispatcher = None
# ModelAPI class for this resource
api_model_cls = None
# A list of operations for which we should dispatch a trigger
dispatch_trigger_for_operations = []
# Maps model operation name (e.g. create, update, delete) to the trigger reference which is
# used when dispatching a trigger
operation_to_trigger_ref_map = {}
@classmethod
@abc.abstractmethod
def _get_impl(cls):
pass
@classmethod
@abc.abstractmethod
def _get_publisher(cls):
return None
@classmethod
def _get_dispatcher(cls):
"""
Return a dispatcher class which is used for dispatching triggers.
"""
if not cls.dispatcher:
cls.dispatcher = TriggerDispatcher(LOG)
return cls.dispatcher
@classmethod
@abc.abstractmethod
def _get_by_object(cls, object):
return None
@classmethod
def get_by_name(cls, value):
return cls._get_impl().get_by_name(value)
@classmethod
def get_by_id(cls, value):
return cls._get_impl().get_by_id(value)
@classmethod
def get_by_ref(cls, value):
return cls._get_impl().get_by_ref(value)
@classmethod
def get(cls, *args, **kwargs):
return cls._get_impl().get(*args, **kwargs)
@classmethod
def get_all(cls, *args, **kwargs):
return cls._get_impl().get_all(*args, **kwargs)
@classmethod
def count(cls, *args, **kwargs):
return cls._get_impl().count(*args, **kwargs)
@classmethod
def query(cls, *args, **kwargs):
return cls._get_impl().query(*args, **kwargs)
@classmethod
def distinct(cls, *args, **kwargs):
return cls._get_impl().distinct(*args, **kwargs)
@classmethod
def aggregate(cls, *args, **kwargs):
return cls._get_impl().aggregate(*args, **kwargs)
@classmethod
def insert(cls, model_object, publish=True, dispatch_trigger=True,
log_not_unique_error_as_debug=False):
if model_object.id:
raise ValueError('id for object %s was unexpected.' % model_object)
try:
model_object = cls._get_impl().insert(model_object)
except NotUniqueError as e:
if log_not_unique_error_as_debug:
LOG.debug('Conflict while trying to save in DB.', exc_info=True)
else:
LOG.exception('Conflict while trying to save in DB.')
# On a conflict determine the conflicting object and return its id in
# the raised exception.
conflict_object = cls._get_by_object(model_object)
conflict_id = str(conflict_object.id) if conflict_object else None
message = str(e)
raise StackStormDBObjectConflictError(message=message, conflict_id=conflict_id,
model_object=model_object)
# Publish internal event on the message bus
if publish:
try:
cls.publish_create(model_object)
except:
LOG.exception('Publish failed.')
# Dispatch trigger
if dispatch_trigger:
try:
cls.dispatch_create_trigger(model_object)
except:
LOG.exception('Trigger dispatch failed.')
return model_object
@classmethod
def add_or_update(cls, model_object, publish=True, dispatch_trigger=True,
log_not_unique_error_as_debug=False):
pre_persist_id = model_object.id
try:
model_object = cls._get_impl().add_or_update(model_object)
except NotUniqueError as e:
if log_not_unique_error_as_debug:
LOG.debug('Conflict while trying to save in DB.', exc_info=True)
else:
LOG.exception('Conflict while trying to save in DB.')
# On a conflict determine the conflicting object and return its id in
# the raised exception.
conflict_object = cls._get_by_object(model_object)
conflict_id = str(conflict_object.id) if conflict_object else None
message = str(e)
raise StackStormDBObjectConflictError(message=message, conflict_id=conflict_id,
model_object=model_object)
is_update = str(pre_persist_id) == str(model_object.id)
# Publish internal event on the message bus<|fim▁hole|> else:
cls.publish_create(model_object)
except:
LOG.exception('Publish failed.')
# Dispatch trigger
if dispatch_trigger:
try:
if is_update:
cls.dispatch_update_trigger(model_object)
else:
cls.dispatch_create_trigger(model_object)
except:
LOG.exception('Trigger dispatch failed.')
return model_object
@classmethod
def update(cls, model_object, publish=True, dispatch_trigger=True, **kwargs):
"""
Use this method when -
* upsert=False is desired
* special operators like push, push_all are to be used.
"""
cls._get_impl().update(model_object, **kwargs)
# update does not return the object but a flag; likely success/fail but docs
# are not very good on this one so ignoring. Explicitly get the object from
# DB abd return.
model_object = cls.get_by_id(model_object.id)
# Publish internal event on the message bus
if publish:
try:
cls.publish_update(model_object)
except:
LOG.exception('Publish failed.')
# Dispatch trigger
if dispatch_trigger:
try:
cls.dispatch_update_trigger(model_object)
except:
LOG.exception('Trigger dispatch failed.')
return model_object
@classmethod
def delete(cls, model_object, publish=True, dispatch_trigger=True):
persisted_object = cls._get_impl().delete(model_object)
# Publish internal event on the message bus
if publish:
try:
cls.publish_delete(model_object)
except Exception:
LOG.exception('Publish failed.')
# Dispatch trigger
if dispatch_trigger:
try:
cls.dispatch_delete_trigger(model_object)
except Exception:
LOG.exception('Trigger dispatch failed.')
return persisted_object
####################################################
# Internal event bus message publish related methods
####################################################
@classmethod
def publish_create(cls, model_object):
publisher = cls._get_publisher()
if publisher:
publisher.publish_create(model_object)
@classmethod
def publish_update(cls, model_object):
publisher = cls._get_publisher()
if publisher:
publisher.publish_update(model_object)
@classmethod
def publish_delete(cls, model_object):
publisher = cls._get_publisher()
if publisher:
publisher.publish_delete(model_object)
############################################
# Internal trigger dispatch related methods
###########################################
@classmethod
def dispatch_create_trigger(cls, model_object):
"""
Dispatch a resource-specific trigger which indicates a new resource has been created.
"""
return cls._dispatch_operation_trigger(operation='create', model_object=model_object)
@classmethod
def dispatch_update_trigger(cls, model_object):
"""
Dispatch a resource-specific trigger which indicates an existing resource has been updated.
"""
return cls._dispatch_operation_trigger(operation='update', model_object=model_object)
@classmethod
def dispatch_delete_trigger(cls, model_object):
"""
Dispatch a resource-specific trigger which indicates an existing resource has been
deleted.
"""
return cls._dispatch_operation_trigger(operation='delete', model_object=model_object)
@classmethod
def _get_trigger_ref_for_operation(cls, operation):
trigger_ref = cls.operation_to_trigger_ref_map.get(operation, None)
if not trigger_ref:
raise ValueError('Trigger ref not specified for operation: %s' % (operation))
return trigger_ref
@classmethod
def _dispatch_operation_trigger(cls, operation, model_object):
if operation not in cls.dispatch_trigger_for_operations:
return
trigger = cls._get_trigger_ref_for_operation(operation=operation)
object_payload = cls.api_model_cls.from_model(model_object, mask_secrets=True).__json__()
payload = {
'object': object_payload
}
return cls._dispatch_trigger(operation=operation, trigger=trigger, payload=payload)
@classmethod
def _dispatch_trigger(cls, operation, trigger, payload):
if operation not in cls.dispatch_trigger_for_operations:
return
dispatcher = cls._get_dispatcher()
return dispatcher.dispatch(trigger=trigger, payload=payload)
class ContentPackResource(Access):
@classmethod
def get_by_ref(cls, ref):
if not ref:
return None
ref_obj = ResourceReference.from_string_reference(ref=ref)
result = cls.query(name=ref_obj.name,
pack=ref_obj.pack).first()
return result
@classmethod
def _get_by_object(cls, object):
# For an object with a resourcepack pack.name is unique.
name = getattr(object, 'name', '')
pack = getattr(object, 'pack', '')
return cls.get_by_ref(ResourceReference.to_string_reference(pack=pack, name=name))
class StatusBasedResource(Access):
"""Persistence layer for models that needs to publish status to the message queue."""
@classmethod
def publish_status(cls, model_object):
"""Publish the object status to the message queue.
Publish the instance of the model as payload with the status
as routing key to the message queue via the StatePublisher.
:param model_object: An instance of the model.
:type model_object: ``object``
"""
publisher = cls._get_publisher()
if publisher:
publisher.publish_state(model_object, getattr(model_object, 'status', None))<|fim▁end|> | if publish:
try:
if is_update:
cls.publish_update(model_object) |
<|file_name|>mongo_test.go<|end_file_name|><|fim▁begin|>package mongo
import (
"fmt"
"labix.org/v2/mgo"
"testing"<|fim▁hole|>)
var (
taro = &User{Name: "Taro", Age: 20}
hanako = &User{Name: "Hanako", Age: 22}
)
// テストデータを投入
func init() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("droneTest").C("users")
c.DropCollection()
err = c.Insert(taro)
if err != nil {
panic(err)
}
err = c.Insert(hanako)
if err != nil {
panic(err)
}
}
// Find関数をテスト
func TestFind(t *testing.T) {
// User(Nmae="Taro")を抽出
user, err := Find(taro.Name)
if err != nil {
t.Error(err)
}
if user.Name != taro.Name || user.Age != taro.Age {
t.Error(fmt.Sprintf("検索結果が不正です。[期待値: %+v][実際: %+v]", taro, user))
}
// 存在しないUserを抽出
user, err = Find("X")
if err == nil || err.Error() != "not found" {
t.Error("検索結果が不正です。検索結果が存在します。")
}
}<|fim▁end|> | |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import ReactIdSwiper from './ReactIdSwiper';
// Types
export {
ReactIdSwiperProps,<|fim▁hole|> ReactIdSwiperChildren,
SwiperModuleName,
SwiperRefNode
} from './types';
// React-id-swiper
export default ReactIdSwiper;<|fim▁end|> | ReactIdSwiperRenderProps,
SelectableElement,
SwiperInstance,
WrappedElementType, |
<|file_name|>problem-039.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// If p is the perimeter of a right angle triangle with integral length sides,
// {a,b,c}, there are exactly three solutions for p = 120.
//
// {20,48,52}, {24,45,51}, {30,40,50}
//
// For which value of p ≤ 1000, is the number of solutions maximised?
//
#![feature(test)]
extern crate test;
/// Find the number of right triangles with integral sides for a given perimeter<|fim▁hole|> let mut count = 0;
let psq = p*p;
// a^2 + b^2 = c^2, a + b + c = p; substitute c = p - a - b and rearrange
// solutions must satisfy 2p(a+b) = p^2 + ab
// TODO: This can probably be simplified further, but algebra
for a in 1..p {
for b in 1..p {
if 2*p*(a + b) == psq + a*b {
count += 1;
}
}
}
count
}
pub fn solution() -> u32 {
let mut max = 0;
let mut max_p = 0;
for p in 1..1001 {
// Perimeter will always be even
if p % 2 != 0 {
continue;
}
let count = num_triangles(p);
if count > max {
max = count;
max_p = p;
}
}
max_p
}
fn main() {
println!("p = {} has the maximum number of solutions.", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(840, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}<|fim▁end|> | fn num_triangles(p: u32) -> u32 { |
<|file_name|>iplookup.py<|end_file_name|><|fim▁begin|>"""This will perform basic enrichment on a given IP."""
import csv
import json
import mmap
import os
import socket
import urllib
import dns.resolver
import dns.reversename
from geoip import geolite2
from IPy import IP
from joblib import Parallel, delayed
from netaddr import AddrFormatError, IPSet
torcsv = 'Tor_ip_list_ALL.csv'
sfile = 'http://torstatus.blutmagie.de/ip_list_all.php/Tor_ip_list_ALL.csv'
SUBNET = 0
INPUTDICT = {}
SECTOR_CSV = 'sector.csv'
OUTFILE = 'IPLookup-output.csv'
CSVCOLS = '"ip-address","asn","as-name","isp","abuse-1","abuse-2","abuse-3","domain","reverse-dns","type","country","lat","long","tor-node"'
def identify(var):
result = ""
with open(SECTOR_CSV) as f:
root = csv.reader(f)
for i in root:
if i[0] in var:
result = i[1]
return result
def lookup(value):
"""Perform a dns request on the given value."""
try:
answers = dns.resolver.query(value, 'TXT')
for rdata in answers:
for txt_string in rdata.strings:
value = txt_string.replace(" | ", "|")
value = value.replace(" |", "|").split("|")
except (dns.resolver.NXDOMAIN, dns.resolver.NoNameservers):
value = []
return value
def flookup(value, fname, sfile):
"""Look up a value in a file."""
try:
fhandle = open(fname)
except IOError:
sourceFile = urllib.URLopener()
sourceFile.retrieve(
sfile,
fname)
fhandle = open(fname)
search = mmap.mmap(fhandle.fileno(), 0, access=mmap.ACCESS_READ)
if search.find(value) != -1:
return 'true'
else:
return 'false'
def iprange(sample, sub):
"""Identify if the given ip address is in the previous range."""
if sub is not 0:
try:
ipset = IPSet([sub])
if sample in ipset:
return True
except AddrFormatError:
return False
else:
return False
<|fim▁hole|> global SUBNET
global INPUTDICT
var = ''.join(var.split())
if IP(var).iptype() != 'PRIVATE' and IP(var).version() == 4:
if iprange(var, SUBNET) is True:
print
elif INPUTDICT.get("ip-address") == var:
print
else:
try:
socket.inet_aton(var)
except socket.error:
var = socket.gethostbyname(var)
contactlist = []
rvar = '.'.join(reversed(str(var).split(".")))
origin = lookup(rvar + '.origin.asn.shadowserver.org')
SUBNET = origin[1]
try:
contact = lookup(rvar + '.abuse-contacts.abusix.org')
contactlist = str(contact[0]).split(",")
except IndexError:
contactlist = []
contactlist.extend(["-"] * (4 - len(contactlist)))
try:
addr = dns.reversename.from_address(var)
rdns = str(dns.resolver.query(addr, "PTR")[0])
except (dns.resolver.NXDOMAIN, dns.resolver.NoNameservers):
rdns = ""
match = geolite2.lookup(var)
if match is None or match.location is None:
country = ''
location = ["", ""]
else:
country = match.country
location = match.location
tor = flookup(var, torcsv, sfile)
category = identify(origin[4])
if category == "":
category = identify(contactlist[0])
origin.extend(["-"] * (6 - len(origin)))
INPUTDICT = {
'abuse-1': contactlist[0],
'abuse-2': contactlist[1],
'abuse-3': contactlist[2],
'as-name': origin[2],
'asn': origin[0],
'country': country,
'descr': origin[5],
'domain': origin[4],
'ip-address': var,
'lat': location[0],
'long': location[1],
'reverse-dns': rdns,
'tor-node': tor,
'sector': category,
}
else:
INPUTDICT = {
'abuse-1': "", 'abuse-2': "", 'abuse-3': "", 'as-name': "",
'asn': "", 'country': "", 'descr': "", 'domain': "",
'domain-count': "", 'ip-address': var, 'lat': "", 'long': "",
'reverse-dns': "", 'tor-node': "", 'sector': "",
}
INPUTDICT['ip-address'] = var
out = json.dumps(
INPUTDICT,
indent=4,
sort_keys=True,
ensure_ascii=False)
csvout(INPUTDICT)
return out
def batch(inputfile):
"""Handle batch lookups using file based input."""
if os.path.isfile(OUTFILE):
os.remove(OUTFILE)
fhandle = open(OUTFILE, "a")
header = 0
if header == 0:
fhandle.write(str(CSVCOLS) + "\n")
header = 1
fhandle.close()
with open(inputfile) as fhandle:
Parallel(n_jobs=100, verbose=51)(delayed(mainlookup)(i.rstrip('\n'))
for i in fhandle)
def single(lookupvar):
"""Do a single IP lookup."""
result = mainlookup(lookupvar)
return result
def csvout(inputdict):
"""Generate a CSV file from the output inputdict."""
fhandle = open(OUTFILE, "a")
# header = 0
# if header == 0:
# fhandle.write("Boop")
# header = 1
try:
writer = csv.writer(fhandle, quoting=csv.QUOTE_ALL)
writer.writerow((
inputdict['ip-address'],
inputdict['asn'],
inputdict['as-name'],
inputdict['descr'],
inputdict['abuse-1'],
inputdict['abuse-2'],
inputdict['abuse-3'],
inputdict['domain'],
inputdict['reverse-dns'],
inputdict['sector'],
inputdict['country'],
inputdict['lat'],
inputdict['long'],
inputdict['tor-node']))
finally:
fhandle.close()
def main():
import argparse
PARSER = argparse.ArgumentParser()
PARSER.add_argument("-t",
choices=('single', 'batch'),
required="false",
metavar="request-type",
help="Either single or batch request")
PARSER.add_argument("-v",
required="false",
metavar="value",
help="The value of the request")
ARGS = PARSER.parse_args()
if ARGS.t == "single":
print(single(ARGS.v))
elif ARGS.t == "batch":
batch(ARGS.v)
else:
PARSER.print_help()
if __name__ == "__main__":
main()<|fim▁end|> |
def mainlookup(var):
"""Wrap the main lookup and generated the dictionary.""" |
<|file_name|>root_check.cpp<|end_file_name|><|fim▁begin|>/*root_check.c
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/input.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <dirent.h>
#include "common.h"
#include "cutils/properties.h"
#include "cutils/android_reboot.h"
#include "install.h"
#include "minui/minui.h"
#include "minzip/DirUtil.h"
#include "minzip/SysUtil.h"
#include "roots.h"
#include "ui.h"
#include "screen_ui.h"
#include "device.h"
#include "minzip/Zip.h"
#include "root_check.h"
extern "C" {
#include "cr32.h"
#include "md5.h"
}
#define FILENAME_MAX 200
unsigned int key=15;
bool checkResult = true;
static const char *SYSTEM_ROOT = "/system/";
static char* file_to_check[]={ "supersu.apk",
"superroot.apk",
"superuser.apk",
"busybox.apk"};
static char* file_to_pass[]={
"recovery-from-boot.p",
"install-recovery.sh",
"recovery_rootcheck",
"build.prop",
"S_ANDRO_SFL.ini",
"recovery.sig"
};
static const char *IMAGE_LOAD_PATH ="/tmp/rootcheck/";
static const char *TEMP_FILE_IN_RAM="/tmp/system_dencrypt";
static const char *TEMP_IMAGE_IN_RAM="/tmp/image_dencrypt";
static const char *CRC_COUNT_TMP="/tmp/crc_count";
static const char *FILE_COUNT_TMP="/tmp/file_count";
static const char *DYW_DOUB_TMP="/tmp/doub_check";
static const char *FILE_NEW_TMP="/tmp/list_new_file";
struct last_check_file{
int n_newfile;
int n_lostfile;
int n_modifyfile;
int n_rootfile;
int file_number_to_check;
int expect_file_number;
unsigned int file_count_check;
unsigned int crc_count_check;
};
static struct last_check_file*check_file_result;
int root_to_check[MAX_ROOT_TO_CHECK]={0};
extern RecoveryUI* ui;
img_name_t img_array[PART_MAX] = {
#ifdef MTK_ROOT_PRELOADER_CHECK
{"/dev/preloader", "preloader"},
#endif
{"/dev/uboot", "uboot"},
{"/dev/bootimg", "bootimg"},
{"/dev/recovery", "recoveryimg"},
{"/dev/logo", "logo"},
};
img_name_t img_array_gpt[PART_MAX] = {
#ifdef MTK_ROOT_PRELOADER_CHECK
{"/dev/preloader", "preloader"},
#endif
{"/dev/block/platform/mtk-msdc.0/by-name/lk", "uboot"},
{"/dev/block/platform/mtk-msdc.0/by-name/boot", "bootimg"},
{"/dev/block/platform/mtk-msdc.0/by-name/recovery", "recoveryimg"},
{"/dev/block/platform/mtk-msdc.0/by-name/logo", "logo"},
};
img_checksum_t computed_checksum[PART_MAX];
img_checksum_t expected_checksum[PART_MAX];
int check_map[MAX_FILES_IN_SYSTEM/INT_BY_BIT+1];
int check_modify[MAX_FILES_IN_SYSTEM/INT_BY_BIT+1];
static bool is_support_gpt_c(void) {
int fd = open("/dev/block/platform/mtk-msdc.0/by-name/para", O_RDONLY);
if (fd == -1) {
return false;
} else {
close(fd);
return true;
}
}
static void set_bit(int x)
{
check_map[x>>SHIFT]|= 1<<(x&MASK);
}
static void clear_bit(int x)
{
check_map[x>>SHIFT]&= ~(1<<(x&MASK));
}
static int test_bit(int x)
{
return check_map[x>>SHIFT]&(1<<(x&MASK));
}
static void set_bit_m(int x)
{
check_modify[x>>SHIFT]|= 1<<(x&MASK);
}
static void clear_bit_m(int x)
{
check_modify[x>>SHIFT]&= ~(1<<(x&MASK));
}
static int test_bit_m(int x)
{
return check_modify[x>>SHIFT]&(1<<(x&MASK));
}
static int file_crc_check( const char* path, unsigned int* nCS, unsigned char *nMd5)
{
char buf[4*1024];
FILE *fp = 0;
int rRead_count = 0;
int i = 0;
*nCS = 0;
#ifdef MTK_ROOT_ADVANCE_CHECK
MD5_CTX md5;
MD5Init(&md5);
memset(nMd5, 0, MD5_LENGTH);
#endif
struct stat st;
memset(&st,0,sizeof(st));
if ( path == NULL ){
LOGE("file_crc_check-> %s is null", path);
return -1;
}
if(lstat(path,&st)<0)
{
LOGE("\n %s does not exist,lsta fail", path);
return 1;
}
if(S_ISLNK(st.st_mode))
{
printf("%s is a link file,just pass\n", path);
return 0;
}
fp = fopen(path, "r");
if( fp == NULL )
{
LOGE("\nfile_crc_check->path:%s ,fp is null", path);
LOGE("\nfopen fail reason is %s",strerror(errno));
return -1;
}
while(!feof(fp))
{
memset(buf, 0x0, sizeof(buf));
rRead_count = fread(buf, 1, sizeof(buf), fp);
if( rRead_count <=0 )
break;
#ifdef MTK_ROOT_NORMAL_CHECK
*nCS += crc32(*nCS, buf, rRead_count);
#endif
#ifdef MTK_ROOT_ADVANCE_CHECK
MD5Update(&md5,(unsigned char*)buf, rRead_count);
#endif
}
#ifdef MTK_ROOT_ADVANCE_CHECK
MD5Final(&md5, nMd5);
#endif
fclose(fp);
return 0;
}
static int clear_selinux_file(char* path)
{
int found=0;
int ret=0;
FILE *fp_info;
FILE *fp_new;
char buf[512];
char p_name[256];
unsigned char p_md[MD5_LENGTH*2];
char *p_cmp_name;
unsigned int p_size;
int p_number;
struct stat statbuf;
fp_info = fopen(TEMP_FILE_IN_RAM, "r");
if(fp_info)
{
if(fgets(buf, sizeof(buf), fp_info) != NULL)
{
while(fgets(buf, sizeof(buf), fp_info))
{
if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4)
{
//TODO:path[0] will be '\0' sometimes, and it should be '/'
path[0] = '/';
if(strstr(p_name,path)!=NULL)
{
p_cmp_name=strstr(p_name,path);
if(strcmp(p_cmp_name,path)==0)
{
found=1;
clear_bit(p_number);
}
}
}
}
if(found==0)
{
LOGE("found a new file,filename is %s",path);
check_file_result->n_newfile+=1;
if(access(FILE_NEW_TMP,0)==-1)
{
int fd_new=creat(FILE_NEW_TMP,0755);
}
fp_new=fopen(FILE_NEW_TMP, "a");
if(fp_new)
{
fprintf(fp_new,"%s\n",path);
}
else
{
LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno));
return CHECK_ADD_NEW_FILE;
}
checkResult=false;
fclose(fp_info);
fclose(fp_new);
return CHECK_ADD_NEW_FILE;
}
}
}
else
{
LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno));
return CHECK_NO_KEY;
}
fclose(fp_info);
return CHECK_PASS;
}
static int clear_selinux_dir(char const* path)
{
int ret=0;
FILE *fp_info;
FILE *fp_new;
char buf[512];
char p_name[256];
unsigned char p_md[MD5_LENGTH*2];
char *p_cmp_name;
unsigned int p_size;
int p_number;
struct stat statbuf;
fp_info = fopen(TEMP_FILE_IN_RAM, "r");
if(fp_info)
{
if(fgets(buf, sizeof(buf), fp_info) != NULL)
{
while(fgets(buf, sizeof(buf), fp_info))
{
if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4)
{
//TODO:path[0] will be '\0' sometimes, and it should be '/'
//path[0] = '/';
if(strstr(p_name,path)!=NULL)
{
p_cmp_name=strstr(p_name,path);
LOGE("%s file is selinux protected,just pass\n",p_cmp_name);
clear_bit(p_number);
}
else
{
//LOGE("not found %s in orignal file,please check!",path);
continue;
}
}
}
}
}
else
{
LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno));
return CHECK_NO_KEY;
}
fclose(fp_info);
return CHECK_PASS;
}
static int check_reall_file(char* path, int nCS, char* nMd5)
{
int found=0;
int ret=0;
FILE *fp_info;
FILE *fp_new;
char buf[512];
char p_name[256];
unsigned char p_md[MD5_LENGTH*2];
char *p_cmp_name;
unsigned int p_size;
int p_number;
struct stat statbuf;
fp_info = fopen(TEMP_FILE_IN_RAM, "r");
if(fp_info)
{
if(fgets(buf, sizeof(buf), fp_info) != NULL)
{
//while(fgets(buf, sizeof(buf), fp_info)&&!found)
while(fgets(buf, sizeof(buf), fp_info))
{
memset(p_md, '0', sizeof(p_md));
if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4)
{
//TODO: can not get correct p_name from sscanf(), so use below instead
char *p1 = strchr(buf, '\t');
char *p2 = strchr(p1+1, '\t');
if(p1&&p2)
memcpy(p_name, p1+1, p2-p1-1);
//TODO:path[0] will be '\0' sometimes, and it should be '/'
path[0] = '/';
if(strstr(p_name,path)!=NULL)
{
p_cmp_name=strstr(p_name,path);
if(strcmp(p_cmp_name,path)==0)
{
found=1;
int rettmp = 0;
clear_bit(p_number);
#ifdef MTK_ROOT_NORMAL_CHECK
if(p_size==nCS)
{
//printf("%s crc check pass\n",path);
}
else
{
printf("expected crc is %u\n",p_size);
printf("computed crc is %u\n",nCS);
printf("%s is modifyed\n",path);
//fclose(fp_info);
rettmp = CHECK_FILE_NOT_MATCH;
}
#endif
#ifdef MTK_ROOT_ADVANCE_CHECK
if(p_md[1]=='\0')
p_md[1]='0';
hextoi_md5(p_md);
if(memcmp(nMd5, p_md, MD5_LENGTH)==0)
{
//printf("%s md5 check pass\n",path);
}
else
{
#if 1
int i;
for(i=0;i<16;i++)
{
printf("%02x",nMd5[i]);
}
for(i=0;i<16;i++)
{
printf("%02x", p_md[i]);
}
#endif
LOGE("<<ERROR>>\n");
//check_file_result->n_modifyfile+=1;
LOGE("Error:%s has been modified md5",path);
ret=stat(path,&statbuf);
if(ret != 0)
{
LOGE("Error:%s is not exist\n",path);
}
time_t modify=statbuf.st_mtime;
ui->Print("on %s\n", ctime(&modify));
//fclose(fp_info);
//return CHECK_FILE_NOT_MATCH;
rettmp = CHECK_FILE_NOT_MATCH;
}
#endif
if(rettmp){
check_file_result->n_modifyfile+=1;
clear_bit_m(p_number);
fclose(fp_info);
return rettmp;
}
}
}
}
}
if(found==0)
{
LOGE("found a new file,filename is %s",path);
check_file_result->n_newfile+=1;
if(access(FILE_NEW_TMP,0)==-1)
{
int fd_new=creat(FILE_NEW_TMP,0755);
}
fp_new=fopen(FILE_NEW_TMP, "a");
if(fp_new)
{
fprintf(fp_new,"%s\n",path);
}
else
{
LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno));
return CHECK_ADD_NEW_FILE;
}
checkResult=false;
fclose(fp_info);
fclose(fp_new);
return CHECK_ADD_NEW_FILE;
}
}
}
else
{
LOGE("open %s error,error reason is %s\n",TEMP_FILE_IN_RAM,strerror(errno));
return CHECK_NO_KEY;
}
fclose(fp_info);
return CHECK_PASS;
}
static bool dir_check( char const*dir)
{
struct dirent *dp;
DIR *d_fd;
unsigned int nCS = 0;
unsigned char nMd5[MD5_LENGTH];
char newdir[FILENAME_MAX];
int find_pass=0;
if ((d_fd = opendir(dir)) == NULL) {
if(strcmp(dir,"/system/")==0) {
LOGE("open system dir fail,please check!\n");
return false;
} else {
LOGE("%s is selinux protected,this dir just pass!\n",dir);
if(clear_selinux_dir(dir) != 0) {
LOGE("clear selinux dir fail\n");
}
return false;
}
}
while ((dp = readdir(d_fd)) != NULL) {
find_pass = 0;
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0)
continue;
if (dp->d_type == DT_DIR){
memset(newdir, 0, FILENAME_MAX);
strcpy(newdir, dir);
strcat(newdir, dp->d_name);
strcat(newdir, "/");
if(dir_check(newdir) == false){
//closedir(d_fd);
continue;
//return false;
}
}else{
int idx = 0;
int idy = 0;
memset(newdir, 0, FILENAME_MAX);
strcpy(newdir, dir);
strcat(newdir, dp->d_name);
for(; idx < sizeof(file_to_check)/sizeof(char*); idx++){
if(strcmp(dp->d_name, file_to_check[idx]) == 0){
root_to_check[idx]=1;
ui->Print("Dir_check---found a root File: %s\n",dp->d_name);
}
}
for(; idy < sizeof(file_to_pass)/sizeof(char*); idy++){
if(strcmp(dp->d_name, file_to_pass[idy]) == 0){
printf("Dir_check---found a file to pass: %s\n",dp->d_name);
find_pass=1;
break;
}
}
if(find_pass==0)
{
ui->Print("scanning **** %s ****\n",dp->d_name);
if(0 == file_crc_check(newdir, &nCS, nMd5)){
if (check_reall_file(newdir, nCS, (char*)nMd5)!=0)
{
LOGE("Error:%s check fail\n",newdir);
checkResult = false;
}
check_file_result->file_number_to_check++;
}else if(1 == file_crc_check(newdir, &nCS, nMd5)) {
LOGE("%s could be selinux protected\n",newdir);
//closedir(d_fd)
if (clear_selinux_file(newdir)!=0) {
LOGE("Error:%s is a selinux file,clear bit fail\n",newdir);
checkResult = false;
}
check_file_result->file_number_to_check++;
continue;
} else {
LOGE("check %s error\n",newdir);
closedir(d_fd);
return false;
}
}
}
}
closedir(d_fd);
return true;
}
static int load_zip_file()
{
const char *FILE_COUNT_ZIP="file_count";
const char *CRC_COUNT_ZIP="crc_count";
const char *DOUBLE_DYW_CHECK="doub_check";
const char *ZIP_FILE_ROOT="/system/data/recovery_rootcheck";
//const char *ZIP_FILE_ROOT_TEMP="/system/recovery_rootcheck";
ZipArchive zip;
//struct stat statbuf;
int ret;
int err=1;
MemMapping map;
if (sysMapFile(ZIP_FILE_ROOT, &map) != 0) {
LOGE("failed to map file %s\n", ZIP_FILE_ROOT);
return INSTALL_CORRUPT;
}
//ret=stat(ZIP_FILE_ROOT_TEMP,&statbuf);
printf("load zip file from %s\n",ZIP_FILE_ROOT);
err = mzOpenZipArchive(map.addr, map.length, &zip);
if (err != 0)
{
LOGE("Can't open %s\n(%s)\n", ZIP_FILE_ROOT, err != -1 ? strerror(err) : "bad");
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
const ZipEntry* file_count = mzFindZipEntry(&zip,FILE_COUNT_ZIP);
if (file_count== NULL)
{
mzCloseZipArchive(&zip);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
unlink(FILE_COUNT_TMP);
int fd_file = creat(FILE_COUNT_TMP, 0755);
if (fd_file< 0)
{
mzCloseZipArchive(&zip);
LOGE("Can't make %s:%s\n", FILE_COUNT_TMP, strerror(errno));
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
bool ok_file= mzExtractZipEntryToFile(&zip, file_count, fd_file);
close(fd_file);
if (!ok_file)
{
LOGE("Can't copy %s\n", FILE_COUNT_ZIP);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
else
{
printf("%s is ok\n", FILE_COUNT_TMP);
}
const ZipEntry* crc_count =
mzFindZipEntry(&zip,CRC_COUNT_ZIP);
if (crc_count== NULL)
{
mzCloseZipArchive(&zip);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
unlink(CRC_COUNT_TMP);
int fd_crc = creat(CRC_COUNT_TMP, 0755);
if (fd_crc< 0)
{
mzCloseZipArchive(&zip);
LOGE("Can't make %s\n", CRC_COUNT_TMP);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
bool ok_crc = mzExtractZipEntryToFile(&zip, crc_count, fd_crc);
close(fd_crc);
if (!ok_crc)
{
LOGE("Can't copy %s\n", CRC_COUNT_ZIP);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
else
{
printf("%s is ok\n", CRC_COUNT_TMP);
}
const ZipEntry* dcheck_crc =
mzFindZipEntry(&zip,DOUBLE_DYW_CHECK);
if (dcheck_crc== NULL)
{
mzCloseZipArchive(&zip);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
unlink(DYW_DOUB_TMP);
int fd_d = creat(DYW_DOUB_TMP, 0755);
if (fd_d< 0)
{
mzCloseZipArchive(&zip);
LOGE("Can't make %s\n", DYW_DOUB_TMP);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
bool ok_d = mzExtractZipEntryToFile(&zip, dcheck_crc, fd_d);
close(fd_d);
if (!ok_d)
{
LOGE("Can't copy %s\n", DOUBLE_DYW_CHECK);
sysReleaseMap(&map);
return CHECK_NO_KEY;
}
else
{
printf("%s is ok\n", DYW_DOUB_TMP);
}
mzCloseZipArchive(&zip);
sysReleaseMap(&map);
return 0;
}
static char* decrypt_str(char *source,unsigned int key)
{
char buf[FILENAME_MAX]={0};
memset(buf, 0, FILENAME_MAX);
int i;
int j=0;
int len=strlen(source);
if(len%2 != 0)
{
printf("Error,sourcr encrypt filename length is odd");
return NULL;
}
int len2=len/2;
for(i=0;i<len2;i++)
{
char c1=source[j];
char c2=source[j+1];
j=j+2;
c1=c1-65;
c2=c2-65;
char b2=c2*16+c1;
char b1=b2^key;
buf[i]=b1;
}
buf[len2]='\0';
memset(source,0,len);
strcpy(source,buf);
return source;
}
static int load_image_encrypt_file()
{
FILE *fp_info;
FILE *fp_tmp;
char buf[512];
char p_name[512];
char p_img_size[128];
char *p_cmp_name=NULL;
char p_crc[256];
char p_md5[256];
int p_number;
int p_file_number;
fp_info = fopen(CRC_COUNT_TMP, "r");
fp_tmp = fopen(TEMP_IMAGE_IN_RAM,"w+");
if(fp_tmp)
{
if(fp_info)
{
while (fgets(buf, sizeof(buf), fp_info)) {
memset(p_md5, 0, sizeof(p_md5));
if (sscanf(buf,"%s %s %s %s",p_name,p_img_size,p_crc,p_md5) == 4) {
char *p_pname=decrypt_str(p_name,key);
char *p_pcrc=decrypt_str(p_crc,key);
char *p_pmd5=decrypt_str(p_md5,key);
char *p_pimgsize=decrypt_str(p_img_size,key);
unsigned long crc;
crc = strtoul(p_pcrc, (char **)NULL, 10);
unsigned long img_size = strtoul(p_pimgsize, (char **)NULL, 10);
//printf("p_pname %s,p_img_size %d,rcrc %u, p_pmd5 %s\n",p_pname,img_size,rcrc, p_pmd5);
fprintf(fp_tmp,"%s\t%lu\t%lu\t%s\n",p_pname,img_size, crc, p_pmd5);
}
}
}
else
{
ui->Print("fopen error,error reason is %s\n",strerror(errno));
return -1;
}
}
else
{
ui->Print("fopen error,error reason is %s\n",strerror(errno));
return CHECK_NO_KEY;
}
fclose(fp_info);
fclose(fp_tmp);
return 0;
}
static int load_system_encrypt_file()
{
FILE *fp_info;
FILE *fp_tmp;
char buf[512];
char p_name[512];
char *p_cmp_name=NULL;
char p_crc[256];
char p_md5[256];
int p_number;
int p_file_number;
fp_info = fopen(FILE_COUNT_TMP, "r");
fp_tmp = fopen(TEMP_FILE_IN_RAM,"w+");
if(fp_tmp)
{
if(fp_info)
{
if (fgets(buf, sizeof(buf), fp_info) != NULL) {
if (sscanf(buf, "%d %s %d", &p_number,p_name,&p_file_number) == 3) {
fprintf(fp_tmp,"%d\t%s\t%d\n",p_number,p_name,p_file_number);
}
while (fgets(buf, sizeof(buf), fp_info)) {
memset(p_md5, 0, sizeof(p_md5));
if (sscanf(buf, "%d %s %s %s", &p_number,p_name,p_crc,p_md5) == 4) {
char *p_pname=decrypt_str(p_name,key);
char *p_pcrc=decrypt_str(p_crc,key);
char *p_pmd5=decrypt_str(p_md5,key);
unsigned long crc;
crc = strtoul(p_pcrc, (char **)NULL, 10);
//printf("p_pname:%s, crc32:%s %lu %d %d %d\n", p_pname, p_pcrc, crc, sizeof(long), sizeof(long long), sizeof(unsigned int));
fprintf(fp_tmp,"%d\t%s\t%lu\t%s\n",p_number,p_pname,crc, p_pmd5);
}
}
}
}
else
{
ui->Print("fopen error,error reason is %s\n",strerror(errno));
return -1;
}
}
else
{
ui->Print("fopen error,error reason is %s\n",strerror(errno));
return CHECK_NO_KEY;
}
fclose(fp_info);
fclose(fp_tmp);
return 0;
}
static bool image_crc_check( char const*dir)
{
struct dirent *dp;
DIR *d_fd;
unsigned int nCS = 0;
unsigned char nMd5[MD5_LENGTH];
if ((d_fd = opendir(dir)) == NULL) {
LOGE("dir_check-<<<< %s not dir\n",dir);
return false;
}
while ((dp = readdir(d_fd)) != NULL) {
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0)
continue;
if (dp->d_type == DT_DIR){
char newdir[FILENAME_MAX]={0};
memset(newdir, 0, FILENAME_MAX);
strcpy(newdir, dir);
strcat(newdir, dp->d_name);
strcat(newdir, "/");
if(dir_check(newdir) == false){
closedir(d_fd);
return false;
}
}else{
char newdir[FILENAME_MAX];
int idx = 0;
int idy = 0;
memset(newdir, 0, FILENAME_MAX);
strcpy(newdir, dir);
strcat(newdir, dp->d_name);
if(0 == file_crc_check(newdir, &nCS, nMd5)){
#ifdef MTK_ROOT_PRELOADER_CHECK
if(strstr(newdir,"preloader")!=NULL)
{
computed_checksum[PRELOADER].crc32=nCS;
memcpy(computed_checksum[PRELOADER].md5, nMd5, MD5_LENGTH);
}
#endif
if(strstr(newdir,"bootimg")!=NULL)
{
computed_checksum[BOOTIMG].crc32=nCS;
memcpy(computed_checksum[BOOTIMG].md5, nMd5, MD5_LENGTH);
}
if(strstr(newdir,"uboot")!=NULL)
{
computed_checksum[UBOOT].crc32=nCS;
memcpy(computed_checksum[UBOOT].md5, nMd5, MD5_LENGTH);
}
if(strstr(newdir,"recovery")!=NULL)
{
computed_checksum[RECOVERYIMG].crc32=nCS;
memcpy(computed_checksum[RECOVERYIMG].md5, nMd5, MD5_LENGTH);
}
if(strstr(newdir,"logo")!=NULL)
{
computed_checksum[LOGO].crc32=nCS;
memcpy(computed_checksum[LOGO].md5, nMd5, MD5_LENGTH);
}
}else{
printf("%s function fail\n",__func__);
closedir(d_fd);
return false;
}
}
}
closedir(d_fd);
return true;
}
static int list_root_file()
{
int idx=0;
for(;idx<MAX_ROOT_TO_CHECK;idx++)
{
if(root_to_check[idx]==1)
{
check_file_result->n_rootfile+=1;
ui->Print("found a root file,%s\n",file_to_check[idx]);
}
}
return 0;
}
static int list_lost_file(int number)
{
FILE *fp_info;
char buf[512];
char p_name[256];
char p_md[256];
int found=0;
char *p_cmp_name=NULL;
unsigned int p_size;
int p_number;
int idy=0;
fp_info = fopen(TEMP_FILE_IN_RAM, "r");
if(fp_info)
{
if (fgets(buf, sizeof(buf), fp_info) != NULL) {
while (fgets(buf, sizeof(buf), fp_info)) {
if (sscanf(buf, "%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4) {
if(p_number==number)
{
p_cmp_name=strstr(p_name,"/system");
for(; idy < sizeof(file_to_pass)/sizeof(char*); idy++)
{
if(strstr(p_cmp_name, file_to_pass[idy]) != NULL)
{
printf("list lost file---found a file to pass: %s\n",p_cmp_name);
//checkResult=true;
//break;
return 0;
}
}
if(p_cmp_name != NULL)
{
check_file_result->n_lostfile+=1;
ui->Print("Error:%s is lost\n",p_cmp_name);
checkResult=false;
}
else
{
check_file_result->n_lostfile+=1;
ui->Print("Error:%s is lost\n",p_name);
checkResult=false;
}
found=1;
break;
}
}
}
if(!found)
{
LOGE("Error:not found a lost file\n");
fclose(fp_info);
return -1;
}
}
}
else
{
ui->Print("fopen error,error reason is %s\n",strerror(errno));
return -1;
}
fclose(fp_info);
return 0;
}
static int image_copy( const char* path,int loop,const char* tem_name)
{
unsigned int nCS=0;
char *temp_file;
char buf[1024];
int rRead_count = 0;
int idx = 0;
int sum=0;
if (path == NULL ){
LOGE("image_copy-> %s is null", path);
return -1;
}
if (ensure_path_mounted(IMAGE_LOAD_PATH) != 0) {
LOGE("Can't mount %s\n", IMAGE_LOAD_PATH);
return -1;
}
if (mkdir(IMAGE_LOAD_PATH, 0700) != 0) {
if (errno != EEXIST) {
LOGE("Can't mkdir %s (%s)\n", IMAGE_LOAD_PATH, strerror(errno));
return -1;
}
}
struct stat st;
if (stat(IMAGE_LOAD_PATH, &st) != 0) {
LOGE("failed to stat %s (%s)\n", IMAGE_LOAD_PATH, strerror(errno));
return -1;
}
if (!S_ISDIR(st.st_mode)) {
LOGE("%s isn't a directory\n", IMAGE_LOAD_PATH);
return -1;
}
if ((st.st_mode & 0777) != 0700) {
LOGE("%s has perms %o\n", IMAGE_LOAD_PATH, st.st_mode);
return -1;
}
if (st.st_uid != 0) {
LOGE("%s owned by %lu; not root\n", IMAGE_LOAD_PATH, st.st_uid);
return -1;
}
char copy_path[FILENAME_MAX];
memset(copy_path, 0, FILENAME_MAX);
strcpy(copy_path, IMAGE_LOAD_PATH);
strcat(copy_path, "/temp_");
strcat(copy_path, tem_name);
char* buffer = (char*)malloc(1024);
if (buffer == NULL) {
LOGE("Failed to allocate buffer\n");
return -1;
}
size_t read;
FILE* fin = fopen(path, "rb");
if (fin == NULL) {
LOGE("Failed to open %s (%s)\n", path, strerror(errno));
return -1;
}
FILE* fout = fopen(copy_path, "wb");
if (fout == NULL) {
LOGE("Failed to open %s (%s)\n", copy_path, strerror(errno));
return -1;
}
while ((read = fread(buffer, 1, 1024, fin)) > 0) {
sum+=read;
if(sum<loop)
{
if (fwrite(buffer, 1, read, fout) != read) {
LOGE("Short write of %s (%s)\n", copy_path, strerror(errno));
return -1;
}
}
else
{
int read_end=read+loop-sum;
if (fwrite(buffer, 1, read_end, fout) != read_end) {
LOGE("Short write of %s (%s)\n", copy_path, strerror(errno));
return -1;
}
break;
}
}
free(buffer);
if (fclose(fout) != 0) {
LOGE("Failed to close %s (%s)\n", copy_path, strerror(errno));
return -1;
}
if (fclose(fin) != 0) {
LOGE("Failed to close %s (%s)\n", path, strerror(errno));
return -1;
}
return 0;
}
static int list_new_file()
{
FILE *fp_new;
struct stat statbuf;
char buf[256];
if(access(FILE_NEW_TMP,0)==-1)
{
printf("%s is not exist\n",FILE_NEW_TMP);
return 0;
}
fp_new= fopen(FILE_NEW_TMP, "r");
if(fp_new)
{
while (fgets(buf, sizeof(buf), fp_new)) {
ui->Print("Error:%s is new ",buf);
int ret=stat(buf,&statbuf);
/*
if(ret != 0)
{
LOGE("Error:%s is not exist\n",buf);
}
*/
time_t modify=statbuf.st_mtime;
ui->Print("it is created on %s\n", ctime(&modify));
}
}
else
{
LOGE("open %s error,error reason is %s\n",FILE_NEW_TMP,strerror(errno));
return -1;
}
fclose(fp_new);
return 0;
}
static bool remove_check_file(const char *file_name)
{
int ret = 0;
ret = unlink(file_name);
if (ret == 0)
return true;
if (ret < 0 && errno == ENOENT)
return true;
return false;
}
static bool remove_check_dir(const char *dir_name)
{
struct dirent *dp;
DIR *d_fd;
if ((d_fd = opendir(dir_name)) == NULL) {
LOGE("dir_check-<<<< %s not dir\n",dir_name);
return false;
}
while ((dp = readdir(d_fd)) != NULL) {
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name,"lost+found")==0)
continue;
if (dp->d_type == DT_DIR){
char newdir[FILENAME_MAX]={0};
memset(newdir, 0, FILENAME_MAX);
strcpy(newdir, dir_name);
strcat(newdir, dp->d_name);
strcat(newdir, "/");
if(remove_check_dir(newdir) == false){
closedir(d_fd);
return false;
}
}else{
char newdir[FILENAME_MAX];
int idx = 0;
int idy = 0;
memset(newdir, 0, FILENAME_MAX);
strcpy(newdir, dir_name);
strcat(newdir, dp->d_name);
const char* to_remove_file;
to_remove_file=newdir;
if(!remove_check_file(to_remove_file))
{
LOGE("Error:unlink %s fail\n",to_remove_file);
}
}
}
return true;
}
static int get_image_info()
{
FILE *fp_info;
char buf[512];
char p_name[32];
unsigned int p_size;
unsigned int p_c;
unsigned char p_crc[MD5_LENGTH*2];
memset(expected_checksum, 0, sizeof(expected_checksum));
fp_info = fopen(TEMP_IMAGE_IN_RAM, "r");
if(fp_info)
{
while (fgets(buf, sizeof(buf), fp_info)) {
memset(p_crc, 0, sizeof(p_crc));
//Z_DEBUG("%d %s\n", __LINE__, buf);
if (sscanf(buf, "%s %d %u %s", p_name, &p_size, &p_c, p_crc) == 4) {
//Z_DEBUG("%d %s\n", __LINE__, p_crc);
hextoi_md5(p_crc);
#ifdef MTK_ROOT_PRELOADER_CHECK
if (!strcmp(p_name, "preloader.bin")) {
expected_checksum[PRELOADER].size = p_size;
expected_checksum[PRELOADER].crc32 = p_c;
memcpy(expected_checksum[PRELOADER].md5, p_crc, MD5_LENGTH);
}
#endif
if (!strcmp(p_name, "lk.bin")) {
expected_checksum[UBOOT].size = p_size;
expected_checksum[UBOOT].crc32 = p_c;
memcpy(expected_checksum[UBOOT].md5, p_crc, MD5_LENGTH);
}
if (!strcmp(p_name, "boot.img")) {
expected_checksum[BOOTIMG].size = p_size;
expected_checksum[BOOTIMG].crc32 = p_c;
memcpy(expected_checksum[BOOTIMG].md5, p_crc, MD5_LENGTH);
}
if (!strcmp(p_name, "recovery.img")) {
expected_checksum[RECOVERYIMG].size = p_size;
expected_checksum[RECOVERYIMG].crc32 = p_c;
memcpy(expected_checksum[RECOVERYIMG].md5, p_crc, MD5_LENGTH);
}
if (!strcmp(p_name, "logo.bin")) {
expected_checksum[LOGO].size = p_size;
expected_checksum[LOGO].crc32 = p_c;
memcpy(expected_checksum[LOGO].md5, p_crc, MD5_LENGTH);
}
}
}
}
else
{
printf("%s function fail,open error reason is %s\n",__func__,strerror(errno));
return -1;
}
fclose(fp_info);
return 0;
}
static int check_file_number_insystem(int file_number)
{
FILE *fp_info;
char buf[512];
char p_name[128];
int p_number;
int p_pnumber;
fp_info = fopen(TEMP_FILE_IN_RAM, "r");<|fim▁hole|> if (fgets(buf, sizeof(buf), fp_info) != NULL) {
if (sscanf(buf, "%d %s %d", &p_pnumber,p_name, &p_number)== 3) {
printf("p_name:%s,p_number : %d\n",p_name,p_number);
if (!strcmp(p_name, "file_number_in_system_dayu")) {
check_file_result->expect_file_number=p_number;
//printf("func is %s,line is %d,p_number is %d,file_number is %d,n_modfyfile is %d,check_file_result->n_newfile is %d\n",__func__,__LINE__,p_number,file_number,check_file_result->n_modifyfile,check_file_result->n_newfile);
#if 0
if((p_number==file_number)&&(check_file_result->n_lostfile==0)&&(check_file_result->n_newfile==0))
{
ui->Print("\nSystem Dir File Number Check Pass");
fclose(fp_info);
return 0;
}
else
{
printf("%s %d p_number:%d file_number:%d check_file_result->n_lostfile:%d check_file_result->n_newfile:%d\n", __func__, __LINE__, p_number, file_number, check_file_result->n_lostfile, check_file_result->n_newfile);
ui->Print("\nSystem Dir File Number Check Fail\n");
fclose(fp_info);
return CHECK_SYSTEM_FILE_NUM_ERR;
}
#endif
}
}
}
}
else
{
ui->Print("fopen error,error reason is %s\n",strerror(errno));
return 1;
}
fclose(fp_info);
return 0;
}
static void delete_unneed_file()
{
if(!remove_check_file(TEMP_FILE_IN_RAM))
{
LOGE("unlink temp system crc file error\n");
}
if(!remove_check_file(TEMP_IMAGE_IN_RAM))
{
LOGE("unlink temp image crc file error\n");
}
if(!remove_check_file(FILE_NEW_TMP))
{
LOGE("unlink temp new file error\n");
}
if(!remove_check_file(FILE_COUNT_TMP))
{
LOGE("unlink temp new file error\n");
}
if(!remove_check_file(DYW_DOUB_TMP))
{
LOGE("unlink temp new file error\n");
}
if(!remove_check_dir(IMAGE_LOAD_PATH))
{
LOGE("unlink temp image dir error\n");
}
}
static int list_modify_file(int number)
{
FILE *fp_info;
struct stat statbuf;
char buf[512];
char p_name[256];
char p_md[256];
int found=0;
char *p_cmp_name=NULL;
unsigned int p_size;
int p_number;
fp_info = fopen(TEMP_FILE_IN_RAM, "r");
if(fp_info)
{
if (fgets(buf, sizeof(buf), fp_info) != NULL)
{
while (fgets(buf, sizeof(buf), fp_info))
{
if (sscanf(buf,"%d %s %u %s", &p_number,p_name,&p_size,p_md) == 4)
{
if(p_number==number)
{
p_cmp_name=strstr(p_name,"/system");
if(p_cmp_name != NULL)
{
ui->Print("Error:%s has been modified",p_cmp_name);
int ret=stat(p_cmp_name,&statbuf);
if(ret != 0)
{
LOGE("Error:%s is not exist\n",p_cmp_name);
}
time_t modify=statbuf.st_mtime;
ui->Print("on %s\n", ctime(&modify));
}
else
{
ui->Print("Error:%s is modifyed\n",p_name);
}
found=1;
break;
}
}
}
if(!found)
{
LOGE("Error:not found a lost file\n");
fclose(fp_info);
return -1;
}
}
}
else
{
ui->Print("fopen error,error reason is %s\n",strerror(errno));
return -1;
}
fclose(fp_info);
return 0;
}
static int encrypt_file_doub_check()
{
char buf[512];
FILE *fp_info;
unsigned int file_count_crc;
unsigned int crc_count_crc;
unsigned int nCS = 0;
unsigned char nMd5[MD5_LENGTH];
fp_info = fopen(DYW_DOUB_TMP, "r");
if(fp_info)
{
if(fgets(buf, sizeof(buf), fp_info) != NULL)
{
if (sscanf(buf,"%u %u", &file_count_crc,&crc_count_crc) == 2)
{
check_file_result->file_count_check=file_count_crc;
check_file_result->crc_count_check=crc_count_crc;
}
else
{
ui->Print("double check file is error\n");
return CHECK_NO_KEY;
}
}
else
{
ui->Print("double check file is null\n");
return CHECK_NO_KEY;
}
}
else
{
LOGE("open %s error,error reason is %s\n",DYW_DOUB_TMP,strerror(errno));
return CHECK_NO_KEY;
}
if(0 == file_crc_check(FILE_COUNT_TMP, &nCS, nMd5))
{
if(nCS!=check_file_result->file_count_check)
{
ui->Print("file count double check fail\n");
return CHECK_NO_KEY;
}
}
if(0 == file_crc_check(CRC_COUNT_TMP, &nCS, nMd5))
{
if(nCS != check_file_result->crc_count_check)
{
ui->Print("crc count double check fail\n");
return CHECK_NO_KEY;
}
}
return 0;
}
int root_check(){
ui->SetBackground(RecoveryUI::ERASING);
ui->SetProgressType(RecoveryUI::INDETERMINATE);
ui->Print("Now check begins, please wait.....\n");
int per,cper;
#ifdef MTK_ROOT_NORMAL_CHECK
printf("use normal check\n");
#endif
#ifdef MTK_ROOT_ADVANCE_CHECK
printf("use advance check\n");
#endif
check_file_result=(struct last_check_file*)malloc(sizeof(last_check_file));
if(ensure_path_mounted(SYSTEM_ROOT) != 0)
{
ui->Print("--mount System fail \n");
}
memset(check_file_result,0,sizeof(last_check_file));
memset(check_map,0xff,sizeof(check_map));
memset(check_modify,0xff,sizeof(check_modify));
if(load_zip_file())
{
ui->Print("load source zip file fail\n");
return CHECK_NO_KEY;
}
if(load_system_encrypt_file())
{
ui->Print("load system encrypt file fail\n");
return CHECK_NO_KEY;
}
if(load_image_encrypt_file())
{
ui->Print("load partition encrypt file fail\n");
return CHECK_NO_KEY;
}
if(encrypt_file_doub_check())
{
ui->Print("encrypt file double check fail\n");
return CHECK_NO_KEY;
}
if(false == dir_check(SYSTEM_ROOT))
{
checkResult = false;
}
check_file_result->file_number_to_check+=1;
ui->Print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (check_file_number_insystem(check_file_result->file_number_to_check)!=0)
{
checkResult=false;
}
if(list_new_file())
{
LOGE("list new file error\n");
}
if(list_root_file())
{
LOGE("list root file error\n");
}
for(cper=0;cper<check_file_result->file_number_to_check-1;cper++)
{
if(test_bit(cper))
{
//checkResult=false;
list_lost_file(cper);
}
}
for(cper=0;cper<check_file_result->file_number_to_check-1;cper++)
{
if(!test_bit_m(cper))
{
checkResult=false;
list_modify_file(cper);
}
}
if(check_file_result->n_newfile)
{
ui->Print("Error:found %d new files\n",check_file_result->n_newfile);
}
if(check_file_result->n_lostfile)
{
ui->Print("Error:found %d lost files\n",check_file_result->n_lostfile);
}
if(check_file_result->n_modifyfile)
{
ui->Print("Error:found %d modified files\n",check_file_result->n_modifyfile);
}
if(check_file_result->n_rootfile)
{
ui->Print("Error:found %d root files\n",check_file_result->n_rootfile);
}
if(ensure_path_unmounted(SYSTEM_ROOT) != 0)
{
LOGE("root_check function--unmount System fail \n");
}
if(get_image_info())
{
checkResult=false;
}
int i = 0;
if(!is_support_gpt_c())
{
printf("this is not gpt version");
for(i=0;i<PART_MAX;i++)
{
if(0 == image_copy(img_array[i].img_devname,expected_checksum[i].size,img_array[i].img_printname))
{
printf("copy %s done\n", img_array[i].img_printname);
}
else
{
printf("copy %s error\n", img_array[i].img_printname);
checkResult = false;
}
}
}
else
{
printf("this is gpt version");
for(i=0;i<PART_MAX;i++)
{
if(0 == image_copy(img_array_gpt[i].img_devname,expected_checksum[i].size,img_array_gpt[i].img_printname))
{
printf("copy %s done\n", img_array_gpt[i].img_printname);
}
else
{
printf("copy %s error\n", img_array_gpt[i].img_printname);
checkResult = false;
}
}
}
if(false == image_crc_check(IMAGE_LOAD_PATH))
{
checkResult = false;
return CHECK_IMAGE_ERR;
}
for(i=0;i<PART_MAX;i++)
{
#ifdef MTK_ROOT_NORMAL_CHECK
if((expected_checksum[i].crc32==computed_checksum[i].crc32)&&(computed_checksum[i].crc32 != 0))
{
printf("\n%s NORMAL check Pass", img_array[i].img_printname);
}
else
{
if(i==1)
{
checkResult=false;
ui->Print("Error:%s NORMAL check Fail\n",img_array[i].img_printname);
printf("except check sum is %u,compute checksum is %u\n",expected_checksum[i].crc32,computed_checksum[i].crc32);
}
}
#endif
#ifdef MTK_ROOT_ADVANCE_CHECK
if(memcmp(expected_checksum[i].md5, computed_checksum[i].md5, MD5_LENGTH)==0)
{
printf("\n%s ADVANCE check Pass", img_array[i].img_printname);
}
else
{
if(i==1)
{
checkResult=false;
ui->Print("Error:%s ADVANCE check Fail\n", img_array[i].img_printname);
#if 1
char *nMd5 = (char*)expected_checksum[i].md5;
char *p_md = (char*)computed_checksum[i].md5;
int i;
printf("e:");
for(i=0;i<16;i++)
{
printf("%02x",nMd5[i]);
}
printf("\n");
printf("c:");
for(i=0;i<16;i++)
{
printf("%02x", p_md[i]);
}
printf("\n");
#endif
}
}
#endif
}
int m_root_check=0;
for(;m_root_check<MAX_ROOT_TO_CHECK;m_root_check++)
{
root_to_check[m_root_check]=0;
}
delete_unneed_file();
free(check_file_result);
if(checkResult)
{
return CHECK_PASS;
}
else
{
checkResult=true;
return CHECK_FAIL;
}
}<|fim▁end|> | if(fp_info)
{ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.