prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>Domain.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2010 The University of Reading
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:<|fim▁hole|> * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University of Reading, nor the names of the
* authors or contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.ac.rdg.resc.edal.coverage.domain;
import java.util.List;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
/**
* A geospatial/temporal domain: defines the set of points for which a {@link DiscreteCoverage}
* is defined. The domain is comprised of a set of unique domain objects in a
* defined order. The domain therefore has the semantics of both a {@link Set}
* and a {@link List} of domain objects.
* @param <DO> The type of the domain object
* @author Jon
*/
public interface Domain<DO>
{
/**
* Gets the coordinate reference system to which objects in this domain are
* referenced. Returns null if the domain objects cannot be referenced
* to an external coordinate reference system.
* @return the coordinate reference system to which objects in this domain are
* referenced, or null if the domain objects are not externally referenced.
*/
public CoordinateReferenceSystem getCoordinateReferenceSystem();
/**
* Returns the {@link List} of domain objects that comprise this domain.
* @todo There may be issues for large grids if the number of domain objects
* is greater than Integer.MAX_VALUE, as the size of this list will be recorded
* incorrectly. This will only happen for very large domains (e.g. large grids).
*/
public List<DO> getDomainObjects();
/**
* <p>Returns the number of domain objects in the domain.</p>
* <p>This is a long integer because grids can grow very large, beyond the
* range of a 4-byte integer.</p>
*/
public long size();
}<|fim▁end|> | * 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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<|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.
from polyaxon.proxies.schemas.api.base import get_base_config
from polyaxon.proxies.schemas.api.main import get_main_config<|fim▁end|> | |
<|file_name|>cmap.hpp<|end_file_name|><|fim▁begin|>// MIT License
// Copyright (c) 2017 Simon Pettersson
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <stdexcept>
#include <optional>
namespace cmap {
/*
The underlying model for the binary tree
*/
namespace _model {
/*
A map is built like a binary tree as illustrated below.
f1(k)
/ \
/ \
f2(k) f3(k)
/ \
/ \
f4(k) f5(k)
Each subtree f1,f2,f3,f4,f5 is a function which
evaluates a key and returns an `std::optional` with a value if
the key matches a key in that subtree, or `std::nullopt` if there
was no match in that subtree.
To construct the tree we utilize two factory functions
* One called `make_terminal(k,v)` which creates a function that
evaluates a key and returns a std::optional.
* One called `make_branch(left,right)` which creates a branch
node, a function that first evaluates the left subtree, if there
is a match the left subtree is returned. If unsuccessful it
returns the right subtree.
Example: Construct the tree above
const auto f5 = make_terminal(5,15);
const auto f4 = make_terminal(4,14);
const auto f2 = make_terminal(3,13);
const auto f3 = make_branch(f4, f5);
const auto f1 = make_branch(f2, f3);
// Performing a lookup for the value `5` would
// produce the stacktrace
f1(5)
f2(5) -> {false, 13}
f3(5)
f4(5) -> {false, 14}
f5(5) -> {true, 15}
...
-> {true, 15}
In order to easily chain together multiple subtrees there is a
utility function called `merge(node1, ...)` which takes all the
terminal nodes as arguments and automatically creates the branches.
To reproduce the previous example using the merge function one could do
the following.
Example: Construct the same tree using the `merge` function
const auto f5 = make_terminal(5,15);
const auto f4 = make_terminal(4,14);
const auto f2 = make_terminal(3,13);
const auto f1 = merge(f2,f4,f5);
Since the whole model is completely independent of the datatype stored
there is literally no limit to what you can store in the map, as long
as it is copy constructible. That means that you can nest maps and store
complex types.
*/
template<typename K, typename V>
constexpr auto make_terminal(const K key, const V value) {
return [key,value](const auto _key) {
return key == _key ? std::make_optional(value) : std::nullopt;
};
};
constexpr auto make_branch(const auto left, const auto right) {
return [left,right](auto key) -> decltype(left(key)) {
const auto result = left(key);
if(result != std::nullopt) {
return result;
}
return right(key);
};
}
constexpr auto merge(const auto node) {
return node;
}
constexpr auto merge(const auto left, const auto ... rest) {
return make_branch(left, merge(rest...));
}
}
/*
Functional interface
Example:
constexpr auto map = make_map(map(13,43), map(14,44));
constexpr auto fourty_three = lookup(map, 13);
constexpr auto fourty_four = lookup(map, 14);
*/
constexpr auto make_map(const auto ... rest) {
return _model::merge(rest...);
}
constexpr auto map(const auto key, const auto value) {
return _model::make_terminal(key, value);
}
constexpr auto lookup(const auto tree, const auto key) {
const auto result = tree(key);
return result != std::nullopt ? result.value() : throw std::out_of_range("No such key");
}
/*
Class interface
Example:
constexpr auto map = make_lookup(map(13,43), map(14,44));
constexpr auto fourty_three = map[13];<|fim▁hole|>template<typename TLookup>
struct lookup_type {
constexpr lookup_type(const TLookup m) : map{m} {}
constexpr auto operator[](const auto key) const { return lookup(map, key); }
const TLookup map;
};
constexpr auto make_lookup(lookup_type<auto> ... rest) {
return lookup_type{make_map(rest.map...)};
}
constexpr auto make_lookup(const auto ... rest) {
return lookup_type{make_map(rest...)};
}
} // namespace cmap<|fim▁end|> | constexpr auto fourty_four = map[14];
*/
|
<|file_name|>ConnectionPageNetwork.java<|end_file_name|><|fim▁begin|>/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.dialogs.connection;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.connection.DBPDriver;
import org.jkiss.dbeaver.model.net.DBWHandlerConfiguration;
import org.jkiss.dbeaver.registry.DataSourceDescriptor;
import org.jkiss.dbeaver.registry.configurator.UIPropertyConfiguratorDescriptor;
import org.jkiss.dbeaver.registry.configurator.UIPropertyConfiguratorRegistry;
import org.jkiss.dbeaver.registry.network.NetworkHandlerDescriptor;
import org.jkiss.dbeaver.registry.network.NetworkHandlerRegistry;
import org.jkiss.dbeaver.ui.IObjectPropertyConfigurator;
import org.jkiss.dbeaver.ui.UIUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Network handlers edit dialog page
*/
public class ConnectionPageNetwork extends ConnectionWizardPage {
public static final String PAGE_NAME = ConnectionPageNetwork.class.getSimpleName();
private static final Log log = Log.getLog(ConnectionPageNetwork.class);
private TabFolder handlersFolder;
private DataSourceDescriptor prevDataSource;
private static class HandlerBlock {
private final IObjectPropertyConfigurator<DBWHandlerConfiguration> configurator;
private final Composite blockControl;
private final Button useHandlerCheck;
private final TabItem tabItem;
ControlEnableState blockEnableState;
private final Map<String, DBWHandlerConfiguration> loadedConfigs = new HashMap<>();
private HandlerBlock(IObjectPropertyConfigurator<DBWHandlerConfiguration> configurator, Composite blockControl, Button useHandlerCheck, TabItem tabItem)
{
this.configurator = configurator;
this.blockControl = blockControl;
this.useHandlerCheck = useHandlerCheck;
this.tabItem = tabItem;
}
}
private final ConnectionWizard wizard;
private Map<NetworkHandlerDescriptor, HandlerBlock> configurations = new HashMap<>();
ConnectionPageNetwork(ConnectionWizard wizard)
{
super(PAGE_NAME);
this.wizard = wizard;
setTitle(CoreMessages.dialog_connection_network_title);
setDescription(CoreMessages.dialog_tunnel_title);
}
@Override
public void createControl(Composite parent)
{
handlersFolder = new TabFolder(parent, SWT.TOP | SWT.FLAT);
handlersFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
setControl(handlersFolder);
}
private void createHandlerTab(final NetworkHandlerDescriptor descriptor) throws DBException
{
IObjectPropertyConfigurator<DBWHandlerConfiguration> configurator;
try {
String implName = descriptor.getHandlerType().getImplName();
UIPropertyConfiguratorDescriptor configDescriptor = UIPropertyConfiguratorRegistry.getInstance().getDescriptor(implName);
if (configDescriptor == null) {
return;
}
configurator = configDescriptor.createConfigurator();
} catch (DBException e) {
log.error("Can't create network configurator '" + descriptor.getId() + "'", e);
return;
}
TabItem tabItem = new TabItem(handlersFolder, SWT.NONE);
tabItem.setText(descriptor.getLabel());
tabItem.setToolTipText(descriptor.getDescription());
Composite composite = new Composite(handlersFolder, SWT.NONE);
tabItem.setControl(composite);
composite.setLayout(new GridLayout(1, false));
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
final Button useHandlerCheck = UIUtils.createCheckbox(composite, NLS.bind(CoreMessages.dialog_tunnel_checkbox_use_handler, descriptor.getLabel()), false);
useHandlerCheck.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
HandlerBlock handlerBlock = configurations.get(descriptor);
DBWHandlerConfiguration handlerConfiguration = handlerBlock.loadedConfigs.get(wizard.getPageSettings().getActiveDataSource().getId());
handlerConfiguration.setEnabled(useHandlerCheck.getSelection());
enableHandlerContent(descriptor);
}
});
Composite handlerComposite = UIUtils.createPlaceholder(composite, 1);
configurations.put(descriptor, new HandlerBlock(configurator, handlerComposite, useHandlerCheck, tabItem));
handlerComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
configurator.createControl(handlerComposite);
}
@Override
public void activatePage() {
DataSourceDescriptor dataSource = wizard.getPageSettings().getActiveDataSource();
DBPDriver driver = wizard.getSelectedDriver();
NetworkHandlerRegistry registry = NetworkHandlerRegistry.getInstance();
if (prevDataSource == null || prevDataSource != dataSource) {
for (TabItem item : handlersFolder.getItems()) {
item.dispose();
}
for (NetworkHandlerDescriptor descriptor : registry.getDescriptors(dataSource)) {
try {
createHandlerTab(descriptor);
} catch (DBException e) {
log.warn(e);
<|fim▁hole|> handlersFolder.layout(true, true);
// for (TabItem item : handlersFolder.getItems()) {
// ((Composite)item.getControl()).layout(false);
// }
}
TabItem selectItem = null;
for (NetworkHandlerDescriptor descriptor : registry.getDescriptors(dataSource)) {
DBWHandlerConfiguration configuration = dataSource.getConnectionConfiguration().getHandler(descriptor.getId());
if (configuration == null) {
configuration = new DBWHandlerConfiguration(descriptor, driver);
}
HandlerBlock handlerBlock = configurations.get(descriptor);
if (handlerBlock == null) {
continue;
}
//handlerBlock.useHandlerCheck.setSelection(configuration.isEnabled());
if (selectItem == null && configuration.isEnabled()) {
selectItem = handlerBlock.tabItem;
}
if (!handlerBlock.loadedConfigs.containsKey(dataSource.getId())) {
handlerBlock.configurator.loadSettings(configuration);
handlerBlock.loadedConfigs.put(dataSource.getId(), configuration);
}
enableHandlerContent(descriptor);
}
if (selectItem != null) {
handlersFolder.setSelection(selectItem);
} else {
handlersFolder.setSelection(0);
}
}
protected void enableHandlerContent(NetworkHandlerDescriptor descriptor)
{
HandlerBlock handlerBlock = configurations.get(descriptor);
DBWHandlerConfiguration handlerConfiguration = handlerBlock.loadedConfigs.get(wizard.getPageSettings().getActiveDataSource().getId());
handlerBlock.useHandlerCheck.setSelection(handlerConfiguration.isEnabled());
if (handlerConfiguration.isEnabled()) {
if (handlerBlock.blockEnableState != null) {
handlerBlock.blockEnableState.restore();
handlerBlock.blockEnableState = null;
}
} else if (handlerBlock.blockEnableState == null) {
handlerBlock.blockEnableState = ControlEnableState.disable(handlerBlock.blockControl);
}
}
@Override
public void saveSettings(DataSourceDescriptor dataSource) {
boolean foundHandlers = false;
java.util.List<DBWHandlerConfiguration> handlers = new ArrayList<>();
for (HandlerBlock handlerBlock : configurations.values()) {
DBWHandlerConfiguration configuration = handlerBlock.loadedConfigs.get(dataSource.getId());
if (configuration != null) {
foundHandlers = true;
handlerBlock.configurator.saveSettings(configuration);
handlers.add(configuration);
}
}
if (foundHandlers) {
dataSource.getConnectionConfiguration().setHandlers(handlers);
}
}
}<|fim▁end|> | }
}
prevDataSource = dataSource;
|
<|file_name|>accounts_options_browsertest.cc<|end_file_name|><|fim▁begin|>// Copyright 2014 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 "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/chromeos/login/login_manager_test.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/ui/user_adding_screen.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/settings/cros_settings_names.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
namespace chromeos {
namespace {
const char* kTestUsers[] = { "[email protected]", "[email protected]" };
} // namespace
class AccountsOptionsTest : public LoginManagerTest {
public:
AccountsOptionsTest()
: LoginManagerTest(false),
device_settings_provider_(NULL) {
stub_settings_provider_.Set(kDeviceOwner, base::StringValue(kTestUsers[0]));
}
virtual ~AccountsOptionsTest() {
}
virtual void SetUpOnMainThread() OVERRIDE {
LoginManagerTest::SetUpOnMainThread();
CrosSettings* settings = CrosSettings::Get();
device_settings_provider_ = settings->GetProvider(kDeviceOwner);
settings->RemoveSettingsProvider(device_settings_provider_);
settings->AddSettingsProvider(&stub_settings_provider_);
}
virtual void TearDownOnMainThread() OVERRIDE {
CrosSettings* settings = CrosSettings::Get();
settings->RemoveSettingsProvider(&stub_settings_provider_);
settings->AddSettingsProvider(device_settings_provider_);
LoginManagerTest::TearDownOnMainThread();
}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
LoginManagerTest::SetUpCommandLine(command_line);
}
protected:
void CheckAccountsUI(const user_manager::User* user, bool is_owner) {
Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user);
profile->GetPrefs()->SetString(prefs::kGoogleServicesUsername,
user->email());
ui_test_utils::BrowserAddedObserver observer;
Browser* browser = CreateBrowser(profile);
observer.WaitForSingleNewBrowser();
ui_test_utils::NavigateToURL(browser,
GURL("chrome://settings-frame/accounts"));
content::WebContents* contents =
browser->tab_strip_model()->GetActiveWebContents();
bool warning_visible;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
contents,
"var e = document.getElementById('ownerOnlyWarning');"
"var visible = e.offsetWidth > 0 && e.offsetHeight > 0;"
"window.domAutomationController.send(visible);",
&warning_visible));
EXPECT_EQ(is_owner, !warning_visible);
bool guest_option_enabled;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
contents,
"var e = document.getElementById('allowBwsiCheck');"
"window.domAutomationController.send(!e.disabled);",
&guest_option_enabled));
EXPECT_EQ(is_owner, guest_option_enabled);
bool supervised_users_enabled;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
contents,
"var e = document.getElementById('allowSupervisedCheck');"
"window.domAutomationController.send(!e.disabled);",
&supervised_users_enabled));
ASSERT_EQ(is_owner, supervised_users_enabled);
bool user_pods_enabled;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
contents,
"var e = document.getElementById('showUserNamesCheck');"
"window.domAutomationController.send(!e.disabled);",
&user_pods_enabled));
EXPECT_EQ(is_owner, user_pods_enabled);
bool whitelist_enabled;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
contents,
"var e = document.getElementById('useWhitelistCheck');"
"window.domAutomationController.send(!e.disabled);",
&whitelist_enabled));
EXPECT_EQ(is_owner, whitelist_enabled);
}
StubCrosSettingsProvider stub_settings_provider_;<|fim▁hole|>};
IN_PROC_BROWSER_TEST_F(AccountsOptionsTest, PRE_MultiProfilesAccountsOptions) {
RegisterUser(kTestUsers[0]);
RegisterUser(kTestUsers[1]);
StartupUtils::MarkOobeCompleted();
}
IN_PROC_BROWSER_TEST_F(AccountsOptionsTest, MultiProfilesAccountsOptions) {
LoginUser(kTestUsers[0]);
UserAddingScreen::Get()->Start();
content::RunAllPendingInMessageLoop();
AddUser(kTestUsers[1]);
user_manager::UserManager* manager = user_manager::UserManager::Get();
ASSERT_EQ(2u, manager->GetLoggedInUsers().size());
CheckAccountsUI(manager->FindUser(kTestUsers[0]), true /* is_owner */);
CheckAccountsUI(manager->FindUser(kTestUsers[1]), false /* is_owner */);
}
} // namespace chromeos<|fim▁end|> | CrosSettingsProvider* device_settings_provider_;
private:
DISALLOW_COPY_AND_ASSIGN(AccountsOptionsTest); |
<|file_name|>axis.py<|end_file_name|><|fim▁begin|># set S-JTSK axes orientation
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
ax=plt.gca()
#ax.set_ylim(ax.get_ylim()[::-1])
# direction of axes
ax.invert_xaxis()
ax.invert_yaxis()
# ticks position
for tick in ax.xaxis.get_major_ticks():
tick.label1On = False
tick.label2On = True
for tick in ax.yaxis.get_major_ticks():
tick.label1On = False
tick.label2On = True
plt.plot([1,2,3,1],[3,1,2,3])
# ticks string formatter
import matplotlib.ticker as ticker
formatter = ticker.FormatStrFormatter('%.2f m')
ax.xaxis.set_major_formatter(formatter)
# ticks func formatter
def format(x, pos):
return "%s - %s" % (x,pos)
formatter = ticker.FuncFormatter(format)
ax.xaxis.set_major_formatter(formatter)<|fim▁hole|>plt.show()<|fim▁end|> | |
<|file_name|>export_test.go<|end_file_name|><|fim▁begin|>// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package block
import (
"github.com/juju/cmd"
"github.com/juju/juju/apiserver/params"<|fim▁hole|>var (
BlockClient = &getBlockClientAPI
UnblockClient = &getUnblockClientAPI
ListClient = &getBlockListAPI
NewDestroyCommand = newDestroyCommand
NewRemoveCommand = newRemoveCommand
NewChangeCommand = newChangeCommand
NewListCommand = newListCommand
)
type MockBlockClient struct {
BlockType string
Msg string
}
func (c *MockBlockClient) Close() error {
return nil
}
func (c *MockBlockClient) SwitchBlockOn(blockType, msg string) error {
c.BlockType = blockType
c.Msg = msg
return nil
}
func (c *MockBlockClient) SwitchBlockOff(blockType string) error {
c.BlockType = blockType
c.Msg = ""
return nil
}
func (c *MockBlockClient) List() ([]params.Block, error) {
if c.BlockType == "" {
return []params.Block{}, nil
}
return []params.Block{
params.Block{
Type: c.BlockType,
Message: c.Msg,
},
}, nil
}
func NewUnblockCommandWithClient(client UnblockClientAPI) cmd.Command {
return envcmd.Wrap(&unblockCommand{client: client})
}<|fim▁end|> | "github.com/juju/juju/cmd/envcmd"
)
|
<|file_name|>ProgramsRouter.ts<|end_file_name|><|fim▁begin|>'use strict';
import ProgramsServerController from '../controllers/ProgramsServerController';
import ProgramsPolicy from '../policies/ProgramsPolicy';
class ProgramsRouter {
public static getInstance() {
return this.instance || (this.instance = new this());
}
private static instance: ProgramsRouter;
private constructor() {
ProgramsPolicy.invokeRolesPolicies();
}
public setupRoutes = app => {
// Programs collection routes
app.route('/api/programs')
.all(ProgramsPolicy.isAllowed)
.get(ProgramsServerController.list)
.post(ProgramsServerController.create);
// Single program routes
app.route('/api/programs/:programId')
.all(ProgramsPolicy.isAllowed)
.get(ProgramsServerController.read)
.put(ProgramsServerController.update)
.delete(ProgramsServerController.delete);
app.route('/api/myadmin/programs')
.all(ProgramsPolicy.isAllowed)
.get(ProgramsServerController.getMyAdminPrograms);
//
// get lists of users
//
app.route('/api/programs/members/:programId').get(ProgramsServerController.listMembers);
app.route('/api/programs/requests/:programId')
.all(ProgramsPolicy.isAllowed)
.get(ProgramsServerController.listRequests);
//
// modify users
//
app.route('/api/programs/requests/confirm/:programId/:userId')
.all(ProgramsPolicy.isAllowed)
.get(ProgramsServerController.confirmMember);
app.route('/api/programs/requests/deny/:programId/:userId')
.all(ProgramsPolicy.isAllowed)
.get(ProgramsServerController.denyMember);
app.route('/api/new/program').get(ProgramsServerController.new);
app.route('/api/request/program/:programId').get(ProgramsServerController.request);
//
// upload logo
//
app.route('/api/upload/logo/program/:programId')<|fim▁hole|> .post(ProgramsServerController.logo);
// Finish by binding the program middleware
app.param('programId', ProgramsServerController.programByID);
};
}
export default ProgramsRouter.getInstance();<|fim▁end|> | .all(ProgramsPolicy.isAllowed) |
<|file_name|>place-picker.js<|end_file_name|><|fim▁begin|>import {inject, customElement, bindable} from 'aurelia-framework';
import mapsapi from 'google-maps-api';
@customElement('place-picker')
// Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key.
@inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places']))
export class PlacePicker {
@bindable location;
constructor(element, mapsApi) {
this.element = element;
this.mapsApi = mapsApi;
}
attached() {
// This loads the Google Maps API asynchronously.
this.mapsApi.then(maps => {
// Now that it's loaded, add a map to our HTML.
var mapContainer = this.element.querySelector('.place-picker-map');
var map = new maps.Map(mapContainer, {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
// Also convert our input field into a place autocomplete field.
var input = this.element.querySelector('input');
var autocomplete = new google.maps.places.Autocomplete(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
autocomplete.bindTo('bounds', map);
// Create a marker that will show where the selected place is.
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
// Create a lambda that moves the marker and the map viewport.
let updateMarker = () => {
var position = new google.maps.LatLng(this.location.lat, this.location.lng);
map.setCenter(position);
marker.setPosition(position);
marker.setVisible(true);
};
// Ensure that the current location is shown properly.
updateMarker();
// Update the location and its marker every time a new place is selected.
autocomplete.addListener('place_changed', () => {
marker.setVisible(false);
var place = autocomplete.getPlace();
if (place.geometry) {
this.location.name = place.name;<|fim▁hole|> });
});
}
}<|fim▁end|> | this.location.lat = place.geometry.location.lat();
this.location.lng = place.geometry.location.lng();
updateMarker();
} |
<|file_name|>material_mutation_resolvers.rs<|end_file_name|><|fim▁begin|>use chrono::prelude::*;
use async_graphql::{
FieldResult,
ID,
Context,
};
use eyre::{
Context as _,
// eyre,
// Result
};
// use printspool_json_store::Record as _;
use printspool_auth::AuthContext;
use printspool_json_store::Record;
use crate::{FdmFilament, MaterialTypeGQL, material::{
Material,
MaterialConfigEnum,
}};
// Input Types
// ---------------------------------------------
#[derive(async_graphql::InputObject, Debug)]
pub struct CreateMaterialInput {
pub material_type: MaterialTypeGQL,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject, Debug)]
pub struct UpdateMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
pub model_version: i32,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject)]
pub struct DeleteMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
}
// Resolvers
// ---------------------------------------------
#[derive(Default)]
pub struct MaterialMutation;
#[async_graphql::Object]
impl MaterialMutation {
async fn create_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: CreateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let config = match input.material_type {
MaterialTypeGQL::FdmFilament => {
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
};
let material = Material {
id: nanoid!(11),
version: 0,
created_at: Utc::now(),
deleted_at: None,
config,
};
material.insert(db).await?;
Ok(material)
}
#[instrument(skip(self, ctx))]
async fn update_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: UpdateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;<|fim▁hole|>
async move {
let mut material = Material::get_with_version(
db,
&input.material_id,
input.model_version,
false,
).await?;
material.config = match material.config {
MaterialConfigEnum::FdmFilament(_) => {
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
};
material.update(db).await?;
for hooks_provider in material_hooks.iter() {
hooks_provider.after_update(
&material.id
).await?;
}
Ok(material)
}
// log the backtrace which is otherwise lost by FieldResult
.await
.map_err(|err: eyre::Error| {
warn!("{:?}", err);
err.into()
})
}
async fn delete_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: DeleteMaterialInput
) -> FieldResult<Option<printspool_common::Void>> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let DeleteMaterialInput { material_id } = input;
Material::get(db, &material_id.0, true)
.await?
.remove(db, false)
.await
.wrap_err_with(|| "Error deleting material")?;
Ok(None)
}
}<|fim▁end|> | let auth: &AuthContext = ctx.data()?;
let material_hooks: &crate::MaterialHooksList = ctx.data()?;
auth.authorize_admins_only()?; |
<|file_name|>_bordercolor.py<|end_file_name|><|fim▁begin|>import _plotly_utils.basevalidators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):<|fim▁hole|> super(BordercolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
)<|fim▁end|> | def __init__(
self, plotly_name="bordercolor", parent_name="sankey.hoverlabel", **kwargs
): |
<|file_name|>SocialNW.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# Author: Rajesh Sinha, Karan Narain
# The base class for Twitter and GPlus Objects
#
import logging
import sys
from bs4 import BeautifulSoup
import urllib2
import re
## Some Important constants
_parser = "lxml" ## remember to pip install lxml or else use another parser
_loggingLevel = logging.DEBUG ## How much trace
class AltmetricBase:
def __init__(self, name, snLink, altmetricId, startPage, endPage):
self.name = name # Name of social network
self.snLink = snLink # The /twitter or /google link
self.amUrl = 'https://www.altmetric.com/details/' + altmetricId + snLink # full link to page1 of social network
self.startPagination = startPage
self.endPagination = endPage
self.baseLink = self.amUrl.replace(self.snLink,'') # The baselink which is shown when a non-existent page is used
self.logger = logging.getLogger(__name__)
logging.basicConfig(level=_loggingLevel)
self.logger.debug('Created Altmetric Object')
def findPosters(self, soup):
raise NotImplementedError("Subclass must implement abstract method")
def getMoreSoup(self):
""" Tries to check all possible links starting from 2 to 1000 and breaks out when
we get a redirect. There is no graceful way i.e. HTTP code on redirect when we
access a nonexistant link. So we check when almetric returns the base URL of the
research arcticle and stop then. This is a generator function and keeps returning
the beautifulsoup of the link
"""
# when the list runs out altmteric returns the base url of the research paper
for a in range(self.startPagination, self.endPagination):
link = self.amUrl + '/page:' + str(a)
self.logger.debug('Trying URL - %s', link)
try:
page = urllib2.urlopen(link)
if self.isRedirect(page):
self.logger.debug('finishing the generator...')
return
else:
self.logger.debug('Yielding Soup')
yield BeautifulSoup(page, _parser)
except urllib2.HTTPError, e:
self.logger.error('Could not open %s because of HTTP error', link)
self.logger.error("%r", e.code)
except urllib2.URLError, e:
self.logger.error('Could not open %s because of URL error', link)
self.logger.error("%r", e.args)
def isRedirect(self, page):
return page.geturl() == self.baseLink
@staticmethod
def isValidURL(url):
testUrl = 'https://www.altmetric.com/details/' + url
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
result = regex.match(testUrl)
return False if result is None else True
def openAndLoadURL(self, fname):
""" Opens the base URL for a network and returns the beautifulSoup through lxml parses """
self.logger.debug('Opening URL ' + fname)
try:
page = urllib2.urlopen(fname)
except urllib2.HTTPError, e:
self.logger.error('Could not open ' + fname+ ': HTTP Error ')
self.logger.error(e.code)
return False, None
except urllib2.URLError, e:
self.logger.error('Could not open ' + fname+ ': URL Error ')
self.logger.error(e.args)
return False, None
soup = BeautifulSoup(page, _parser)
return True, soup
def executeAltmetricAnalysis(self):<|fim▁hole|> if status:
posters = self.findPosters(soup)
self.logger.debug('Found %d posts so far', len(posters))
for soup in self.getMoreSoup():
posters.extend(self.findPosters(soup))
self.logger.debug('Found %d posts so far', len(posters))
self.logger.info('Found %d posts in total for the link', len(posters))
posters = list(set(posters))
self.logger.info('Found %d Unique Posters for the link', len(posters))
for poster in posters:
print (poster).encode('utf-8')
self.logger.info('written all the posters to stdout...')
else:
self.logger.error('found error in URL upfront so bailing out')
sys.stderr.flush()
sys.stdout.flush()
sys.exit(1)<|fim▁end|> | posters = []
status, soup = self.openAndLoadURL(self.amUrl) |
<|file_name|>ServiceFabrikOperation.js<|end_file_name|><|fim▁begin|>'use strict';
const _ = require('lodash');
const config = require('../../../common/config');
const CONST = require('../../../common/constants');
const errors = require('../../../common/errors');
const logger = require('../../../common/logger');
const jwt = require('../jwt');
const utils = require('../../../common/utils');
const cf = require('../../../data-access-layer/cf');
const DirectorManager = require('./DirectorManager');
const cloudController = cf.cloudController;
const Conflict = errors.Conflict;
const DeploymentAlreadyLocked = errors.DeploymentAlreadyLocked;
const DeploymentAttemptRejected = errors.DeploymentAttemptRejected;
function AsyncServiceInstanceOperationInProgress(err) {
const response = _.get(err, 'error', {});
return response.code === 60016 || response.error_code === 'CF-AsyncServiceInstanceOperationInProgress';
}
function DeploymentLocked(err) {
const response = _.get(err, 'error', {});
const description = _.get(response, 'description', '');
return description.indexOf(CONST.OPERATION_TYPE.LOCK) > 0 && response.error_code === 'CF-ServiceBrokerRequestRejected';
}
function DeploymentStaggered(err) {
const response = _.get(err, 'error', {});
const description = _.get(response, 'description', '');
return description.indexOf(CONST.FABRIK_OPERATION_STAGGERED) > 0 && description.indexOf(CONST.FABRIK_OPERATION_COUNT_EXCEEDED) > 0 && response.error_code === 'CF-ServiceBrokerRequestRejected';
}
class ServiceFabrikOperation {
constructor(name, opts) {
this.name = name;
this.guid = undefined;
opts = opts || {};
this.bearer = opts.bearer;
this.username = opts.username;
this.useremail = opts.useremail;
this.arguments = opts.arguments || {};
this.isOperationSync = opts.isOperationSync ? true : false;
this.runImmediately = opts.runImmediately;
if (opts.instance_id) {
this.instanceId = opts.instance_id;
} else if (opts.deployment) {
this.instanceId = _.nth(DirectorManager.parseDeploymentName(opts.deployment), 2);
}
}
toJSON() {
return _.pick(this, 'name', 'guid', 'username', 'useremail', 'arguments');
}
getResult() {
return _.pick(this, 'name', 'guid');
}
getToken() {
return utils
.uuidV4()
.then(guid => _.set(this, 'guid', guid))
.then(() => jwt.sign(this.toJSON(), config.password));
}
updateServiceInstance(token) {
const options = {
parameters: {
'service-fabrik-operation': token
}
};
if (this.runImmediately) {
options.parameters._runImmediately = this.runImmediately;
}
options.isOperationSync = this.isOperationSync;
if (this.bearer) {
options.auth = {
bearer: this.bearer
};
}
return cloudController.updateServiceInstance(this.instanceId, options);
}
invoke() {
return this
.getToken()
.then(token => this.updateServiceInstance(token))
.then(() => this.getResult())
.catch(AsyncServiceInstanceOperationInProgress, err => {
const message = _.get(err.error, 'description', 'Async service instance operation in progress');
throw new Conflict(message);
})
.catch(DeploymentStaggered, err => {
logger.info('Deployment operation not proceeding due to rate limit exceeded', err.message);
throw new DeploymentAttemptRejected(this.deployment || this.instanceId);
})
.catch(DeploymentLocked, err => {
// Sample error description is
// Service broker error: Service Instance abcdefgh-abcd-abcd-abcd-abcdefghijkl __Locked__ at Mon Sep 10 2018 11:17:01 GMT+0000 (UTC) for backup
const description = _.get(err, 'error.description', '');
const lookupString = 'error: ';
const startIdx = description.indexOf(lookupString);
let lockMsg;
if (startIdx !== -1) {
lockMsg = description.substring(startIdx + lookupString.length);
}
logger.info(`Lock message : ${lockMsg}`);
throw new DeploymentAlreadyLocked(this.instanceId, undefined, lockMsg);
});
}
handle(req, res) {
if (_.isObject(req.user)) {
this.username = req.user.name;
this.useremail = req.user.email || '';
}
return this
.invoke()
.then(body => res
.status(202)<|fim▁hole|> .send(body)
);
}
}
module.exports = ServiceFabrikOperation;<|fim▁end|> | |
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>"""
Forms for the project application
"""
# Django
from django import forms
# Third Party
from dal import forward
from dal.autocomplete import TaggitSelect2
from taggit.forms import TagField
# MuckRock
from muckrock.core import autocomplete
from muckrock.project.models import Project
class ProjectCreateForm(forms.ModelForm):
"""Form for the basic fields of a project."""
tags = TagField(
widget=TaggitSelect2(
url="tag-autocomplete",
attrs={"data-placeholder": "Search tags", "data-width": "100%"},
),
help_text="Separate tags with commas.",
required=False,
)
class Meta:
model = Project
fields = ["title", "summary", "image", "tags"]
help_texts = {
"summary": "A short description of the project and its goals.",
"image": "Image should be large and high-resolution.",
}
class ProjectUpdateForm(forms.ModelForm):
"""Form for updating a project instance"""
tags = TagField(
widget=TaggitSelect2(
url="tag-autocomplete",
attrs={"data-placeholder": "Search tags", "data-width": "100%"},
),
help_text="Separate tags with commas.",
required=False,
)
class Meta:
model = Project
fields = [<|fim▁hole|> "description",
"contributors",
"requests",
"articles",
]
widgets = {
"description": forms.Textarea(attrs={"class": "prose-editor"}),
"contributors": autocomplete.ModelSelect2Multiple(
url="user-autocomplete",
attrs={
"data-placeholder": "Search for users",
"data-minimum-input-length": 2,
},
),
"requests": autocomplete.ModelSelect2Multiple(
url="foia-request-autocomplete",
attrs={"data-placeholder": "Search for requests"},
),
"articles": autocomplete.ModelSelect2Multiple(
url="article-autocomplete",
attrs={"data-placeholder": "Search for articles"},
),
}
help_texts = {
"title": "Changing the title will change the URL of your project."
}
class ProjectPublishForm(forms.Form):
"""Form for publishing a project."""
notes = forms.CharField(required=False, widget=forms.Textarea)
class ProjectManagerForm(forms.Form):
"""Form for managing a list of projects"""
projects = forms.ModelMultipleChoiceField(
required=False,
queryset=Project.objects.none(),
widget=autocomplete.ModelSelect2Multiple(
url="project-autocomplete",
attrs={"placeholder": "Search for a project"},
forward=(forward.Const(True, "manager"),),
),
)
def __init__(self, *args, **kwargs):
user = kwargs.pop("user")
super(ProjectManagerForm, self).__init__(*args, **kwargs)
self.fields["projects"].queryset = Project.objects.get_manager(user)<|fim▁end|> | "title",
"summary",
"image",
"tags", |
<|file_name|>generic.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Some code that abstracts away much of the boilerplate of writing
`deriving` instances for traits. Among other things it manages getting
access to the fields of the 4 different sorts of structs and enum
variants, as well as creating the method and impl ast instances.
Supported features (fairly exhaustive):
- Methods taking any number of parameters of any type, and returning
any type, other than vectors, bottom and closures.
- Generating `impl`s for types with type parameters and lifetimes
(e.g. `Option<T>`), the parameters are automatically given the
current trait as a bound. (This includes separate type parameters
and lifetimes for methods.)
- Additional bounds on the type parameters, e.g. the `Ord` instance
requires an explicit `Eq` bound at the
moment. (`TraitDef.additional_bounds`)
Unsupported: FIXME #6257: calling methods on reference fields,
e.g. deriving TotalEq/TotalOrd/Clone don't work on `struct A(&int)`,
because of how the auto-dereferencing happens.
The most important thing for implementers is the `Substructure` and
`SubstructureFields` objects. The latter groups 5 possibilities of the
arguments:
- `Struct`, when `Self` is a struct (including tuple structs, e.g
`struct T(int, char)`).
- `EnumMatching`, when `Self` is an enum and all the arguments are the
same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`)
- `EnumNonMatching` when `Self` is an enum and the arguments are not
the same variant (e.g. `None`, `Some(1)` and `None`). If
`const_nonmatching` is true, this will contain an empty list.
- `StaticEnum` and `StaticStruct` for static methods, where the type
being derived upon is either an enum or struct respectively. (Any
argument with type Self is just grouped among the non-self
arguments.)
In the first two cases, the values from the corresponding fields in
all the arguments are grouped together. In the `EnumNonMatching` case
this isn't possible (different variants have different fields), so the
fields are grouped by which argument they come from. There are no
fields with values in the static cases, so these are treated entirely
differently.
The non-static cases have `Option<ident>` in several places associated
with field `expr`s. This represents the name of the field it is
associated with. It is only not `None` when the associated field has
an identifier in the source code. For example, the `x`s in the
following snippet
```rust
struct A { x : int }
struct B(int);
enum C {
C0(int),
C1 { x: int }
}
```
The `int`s in `B` and `C0` don't have an identifier, so the
`Option<ident>`s would be `None` for them.
In the static cases, the structure is summarised, either into the just
spans of the fields or a list of spans and the field idents (for tuple
structs and record structs, respectively), or a list of these, for
enums (one for each variant). For empty struct and empty enum
variants, it is represented as a count of 0.
# Examples
The following simplified `Eq` is used for in-code examples:
```rust
trait Eq {
fn eq(&self, other: &Self);
}
impl Eq for int {
fn eq(&self, other: &int) -> bool {
*self == *other
}
}
```
Some examples of the values of `SubstructureFields` follow, using the
above `Eq`, `A`, `B` and `C`.
## Structs
When generating the `expr` for the `A` impl, the `SubstructureFields` is
~~~notrust
Struct(~[FieldInfo {
span: <span of x>
name: Some(<ident of x>),
self_: <expr for &self.x>,
other: ~[<expr for &other.x]
}])
~~~
For the `B` impl, called with `B(a)` and `B(b)`,
~~~notrust
Struct(~[FieldInfo {
span: <span of `int`>,
name: None,
<expr for &a>
~[<expr for &b>]
}])
~~~
## Enums
When generating the `expr` for a call with `self == C0(a)` and `other
== C0(b)`, the SubstructureFields is
~~~notrust
EnumMatching(0, <ast::Variant for C0>,
~[FieldInfo {
span: <span of int>
name: None,
self_: <expr for &a>,
other: ~[<expr for &b>]
}])
~~~
For `C1 {x}` and `C1 {x}`,
~~~notrust
EnumMatching(1, <ast::Variant for C1>,
~[FieldInfo {
span: <span of x>
name: Some(<ident of x>),
self_: <expr for &self.x>,<|fim▁hole|>For `C0(a)` and `C1 {x}` ,
~~~notrust
EnumNonMatching(~[(0, <ast::Variant for B0>,
~[(<span of int>, None, <expr for &a>)]),
(1, <ast::Variant for B1>,
~[(<span of x>, Some(<ident of x>),
<expr for &other.x>)])])
~~~
(and vice versa, but with the order of the outermost list flipped.)
## Static
A static method on the above would result in,
~~~~notrust
StaticStruct(<ast::StructDef of A>, Named(~[(<ident of x>, <span of x>)]))
StaticStruct(<ast::StructDef of B>, Unnamed(~[<span of x>]))
StaticEnum(<ast::EnumDef of C>, ~[(<ident of C0>, <span of C0>, Unnamed(~[<span of int>])),
(<ident of C1>, <span of C1>,
Named(~[(<ident of x>, <span of x>)]))])
~~~
*/
use ast;
use ast::{P, EnumDef, Expr, Ident, Generics, StructDef};
use ast_util;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap;
use codemap::Span;
use owned_slice::OwnedSlice;
use parse::token::InternedString;
pub use self::ty::*;
mod ty;
pub struct TraitDef<'a> {
/// The span for the current #[deriving(Foo)] header.
pub span: Span,
pub attributes: Vec<ast::Attribute>,
/// Path of the trait, including any type parameters
pub path: Path<'a>,
/// Additional bounds required of any type parameters of the type,
/// other than the current trait
pub additional_bounds: Vec<Ty<'a>>,
/// Any extra lifetimes and/or bounds, e.g. `D: serialize::Decoder`
pub generics: LifetimeBounds<'a>,
pub methods: Vec<MethodDef<'a>>,
}
pub struct MethodDef<'a> {
/// name of the method
pub name: &'a str,
/// List of generics, e.g. `R: rand::Rng`
pub generics: LifetimeBounds<'a>,
/// Whether there is a self argument (outer Option) i.e. whether
/// this is a static function, and whether it is a pointer (inner
/// Option)
pub explicit_self: Option<Option<PtrTy<'a>>>,
/// Arguments other than the self argument
pub args: Vec<Ty<'a>>,
/// Return type
pub ret_ty: Ty<'a>,
/// Whether to mark this as #[inline]
pub inline: bool,
/// if the value of the nonmatching enums is independent of the
/// actual enum variants, i.e. can use _ => .. match.
pub const_nonmatching: bool,
pub combine_substructure: CombineSubstructureFunc<'a>,
}
/// All the data about the data structure/method being derived upon.
pub struct Substructure<'a> {
/// ident of self
pub type_ident: Ident,
/// ident of the method
pub method_ident: Ident,
/// dereferenced access to any Self or Ptr(Self, _) arguments
pub self_args: &'a [@Expr],
/// verbatim access to any other arguments
pub nonself_args: &'a [@Expr],
pub fields: &'a SubstructureFields<'a>
}
/// Summary of the relevant parts of a struct/enum field.
pub struct FieldInfo {
pub span: Span,
/// None for tuple structs/normal enum variants, Some for normal
/// structs/struct enum variants.
pub name: Option<Ident>,
/// The expression corresponding to this field of `self`
/// (specifically, a reference to it).
pub self_: @Expr,
/// The expressions corresponding to references to this field in
/// the other Self arguments.
pub other: Vec<@Expr>,
}
/// Fields for a static method
pub enum StaticFields {
/// Tuple structs/enum variants like this
Unnamed(Vec<Span> ),
/// Normal structs/struct variants.
Named(Vec<(Ident, Span)> )
}
/// A summary of the possible sets of fields. See above for details
/// and examples
pub enum SubstructureFields<'a> {
Struct(Vec<FieldInfo> ),
/**
Matching variants of the enum: variant index, ast::Variant,
fields: the field name is only non-`None` in the case of a struct
variant.
*/
EnumMatching(uint, &'a ast::Variant, Vec<FieldInfo> ),
/**
non-matching variants of the enum, [(variant index, ast::Variant,
[field span, field ident, fields])] (i.e. all fields for self are in the
first tuple, for other1 are in the second tuple, etc.)
*/
EnumNonMatching(&'a [(uint, P<ast::Variant>, Vec<(Span, Option<Ident>, @Expr)> )]),
/// A static method where Self is a struct.
StaticStruct(&'a ast::StructDef, StaticFields),
/// A static method where Self is an enum.
StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)> )
}
/**
Combine the values of all the fields together. The last argument is
all the fields of all the structures, see above for details.
*/
pub type CombineSubstructureFunc<'a> =
|&mut ExtCtxt, Span, &Substructure|: 'a -> @Expr;
/**
Deal with non-matching enum variants, the arguments are a list
representing each variant: (variant index, ast::Variant instance,
[variant fields]), and a list of the nonself args of the type
*/
pub type EnumNonMatchFunc<'a> =
|&mut ExtCtxt,
Span,
&[(uint, P<ast::Variant>, Vec<(Span, Option<Ident>, @Expr)> )],
&[@Expr]|: 'a
-> @Expr;
impl<'a> TraitDef<'a> {
pub fn expand(&self,
cx: &mut ExtCtxt,
_mitem: @ast::MetaItem,
item: @ast::Item,
push: |@ast::Item|) {
match item.node {
ast::ItemStruct(struct_def, ref generics) => {
push(self.expand_struct_def(cx,
struct_def,
item.ident,
generics));
}
ast::ItemEnum(ref enum_def, ref generics) => {
push(self.expand_enum_def(cx,
enum_def,
item.ident,
generics));
}
_ => ()
}
}
/**
*
* Given that we are deriving a trait `Tr` for a type `T<'a, ...,
* 'z, A, ..., Z>`, creates an impl like:
*
* ```ignore
* impl<'a, ..., 'z, A:Tr B1 B2, ..., Z: Tr B1 B2> Tr for T<A, ..., Z> { ... }
* ```
*
* where B1, B2, ... are the bounds given by `bounds_paths`.'
*
*/
fn create_derived_impl(&self,
cx: &mut ExtCtxt,
type_ident: Ident,
generics: &Generics,
methods: Vec<@ast::Method> ) -> @ast::Item {
let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
let Generics { mut lifetimes, ty_params } =
self.generics.to_generics(cx, self.span, type_ident, generics);
let mut ty_params = ty_params.into_vec();
// Copy the lifetimes
lifetimes.extend(generics.lifetimes.iter().map(|l| *l));
// Create the type parameters.
ty_params.extend(generics.ty_params.iter().map(|ty_param| {
// I don't think this can be moved out of the loop, since
// a TyParamBound requires an ast id
let mut bounds: Vec<_> =
// extra restrictions on the generics parameters to the type being derived upon
self.additional_bounds.iter().map(|p| {
cx.typarambound(p.to_path(cx, self.span,
type_ident, generics))
}).collect();
// require the current trait
bounds.push(cx.typarambound(trait_path.clone()));
cx.typaram(ty_param.ident, OwnedSlice::from_vec(bounds), None)
}));
let trait_generics = Generics {
lifetimes: lifetimes,
ty_params: OwnedSlice::from_vec(ty_params)
};
// Create the reference to the trait.
let trait_ref = cx.trait_ref(trait_path);
// Create the type parameters on the `self` path.
let self_ty_params = generics.ty_params.map(|ty_param| {
cx.ty_ident(self.span, ty_param.ident)
});
let self_lifetimes = generics.lifetimes.clone();
// Create the type of `self`.
let self_type = cx.ty_path(
cx.path_all(self.span, false, vec!( type_ident ), self_lifetimes,
self_ty_params.into_vec()), None);
let attr = cx.attribute(
self.span,
cx.meta_word(self.span,
InternedString::new("automatically_derived")));
let opt_trait_ref = Some(trait_ref);
let ident = ast_util::impl_pretty_name(&opt_trait_ref, self_type);
cx.item(
self.span,
ident,
(vec!(attr)).append(self.attributes.as_slice()),
ast::ItemImpl(trait_generics, opt_trait_ref,
self_type, methods))
}
fn expand_struct_def(&self,
cx: &mut ExtCtxt,
struct_def: &StructDef,
type_ident: Ident,
generics: &Generics) -> @ast::Item {
let methods = self.methods.iter().map(|method_def| {
let (explicit_self, self_args, nonself_args, tys) =
method_def.split_self_nonself_args(
cx, self, type_ident, generics);
let body = if method_def.is_static() {
method_def.expand_static_struct_method_body(
cx,
self,
struct_def,
type_ident,
self_args.as_slice(),
nonself_args.as_slice())
} else {
method_def.expand_struct_method_body(cx,
self,
struct_def,
type_ident,
self_args.as_slice(),
nonself_args.as_slice())
};
method_def.create_method(cx, self,
type_ident, generics,
explicit_self, tys,
body)
}).collect();
self.create_derived_impl(cx, type_ident, generics, methods)
}
fn expand_enum_def(&self,
cx: &mut ExtCtxt,
enum_def: &EnumDef,
type_ident: Ident,
generics: &Generics) -> @ast::Item {
let methods = self.methods.iter().map(|method_def| {
let (explicit_self, self_args, nonself_args, tys) =
method_def.split_self_nonself_args(cx, self,
type_ident, generics);
let body = if method_def.is_static() {
method_def.expand_static_enum_method_body(
cx,
self,
enum_def,
type_ident,
self_args.as_slice(),
nonself_args.as_slice())
} else {
method_def.expand_enum_method_body(cx,
self,
enum_def,
type_ident,
self_args.as_slice(),
nonself_args.as_slice())
};
method_def.create_method(cx, self,
type_ident, generics,
explicit_self, tys,
body)
}).collect();
self.create_derived_impl(cx, type_ident, generics, methods)
}
}
impl<'a> MethodDef<'a> {
fn call_substructure_method(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
type_ident: Ident,
self_args: &[@Expr],
nonself_args: &[@Expr],
fields: &SubstructureFields)
-> @Expr {
let substructure = Substructure {
type_ident: type_ident,
method_ident: cx.ident_of(self.name),
self_args: self_args,
nonself_args: nonself_args,
fields: fields
};
(self.combine_substructure)(cx, trait_.span,
&substructure)
}
fn get_ret_ty(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
generics: &Generics,
type_ident: Ident)
-> P<ast::Ty> {
self.ret_ty.to_ty(cx, trait_.span, type_ident, generics)
}
fn is_static(&self) -> bool {
self.explicit_self.is_none()
}
fn split_self_nonself_args(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
type_ident: Ident,
generics: &Generics)
-> (ast::ExplicitSelf, Vec<@Expr> , Vec<@Expr> , Vec<(Ident, P<ast::Ty>)> ) {
let mut self_args = Vec::new();
let mut nonself_args = Vec::new();
let mut arg_tys = Vec::new();
let mut nonstatic = false;
let ast_explicit_self = match self.explicit_self {
Some(ref self_ptr) => {
let (self_expr, explicit_self) =
ty::get_explicit_self(cx, trait_.span, self_ptr);
self_args.push(self_expr);
nonstatic = true;
explicit_self
}
None => codemap::respan(trait_.span, ast::SelfStatic),
};
for (i, ty) in self.args.iter().enumerate() {
let ast_ty = ty.to_ty(cx, trait_.span, type_ident, generics);
let ident = cx.ident_of(format!("__arg_{}", i));
arg_tys.push((ident, ast_ty));
let arg_expr = cx.expr_ident(trait_.span, ident);
match *ty {
// for static methods, just treat any Self
// arguments as a normal arg
Self if nonstatic => {
self_args.push(arg_expr);
}
Ptr(~Self, _) if nonstatic => {
self_args.push(cx.expr_deref(trait_.span, arg_expr))
}
_ => {
nonself_args.push(arg_expr);
}
}
}
(ast_explicit_self, self_args, nonself_args, arg_tys)
}
fn create_method(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
type_ident: Ident,
generics: &Generics,
explicit_self: ast::ExplicitSelf,
arg_types: Vec<(Ident, P<ast::Ty>)> ,
body: @Expr) -> @ast::Method {
// create the generics that aren't for Self
let fn_generics = self.generics.to_generics(cx, trait_.span, type_ident, generics);
let self_arg = match explicit_self.node {
ast::SelfStatic => None,
_ => Some(ast::Arg::new_self(trait_.span, ast::MutImmutable))
};
let args = {
let args = arg_types.move_iter().map(|(name, ty)| {
cx.arg(trait_.span, name, ty)
});
self_arg.move_iter().chain(args).collect()
};
let ret_type = self.get_ret_ty(cx, trait_, generics, type_ident);
let method_ident = cx.ident_of(self.name);
let fn_decl = cx.fn_decl(args, ret_type);
let body_block = cx.block_expr(body);
let attrs = if self.inline {
vec!(
cx
.attribute(trait_.span,
cx
.meta_word(trait_.span,
InternedString::new(
"inline")))
)
} else {
Vec::new()
};
// Create the method.
@ast::Method {
ident: method_ident,
attrs: attrs,
generics: fn_generics,
explicit_self: explicit_self,
fn_style: ast::NormalFn,
decl: fn_decl,
body: body_block,
id: ast::DUMMY_NODE_ID,
span: trait_.span,
vis: ast::Inherited,
}
}
/**
~~~
#[deriving(Eq)]
struct A { x: int, y: int }
// equivalent to:
impl Eq for A {
fn eq(&self, __arg_1: &A) -> bool {
match *self {
A {x: ref __self_0_0, y: ref __self_0_1} => {
match *__arg_1 {
A {x: ref __self_1_0, y: ref __self_1_1} => {
__self_0_0.eq(__self_1_0) && __self_0_1.eq(__self_1_1)
}
}
}
}
}
}
~~~
*/
fn expand_struct_method_body(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
struct_def: &StructDef,
type_ident: Ident,
self_args: &[@Expr],
nonself_args: &[@Expr])
-> @Expr {
let mut raw_fields = Vec::new(); // ~[[fields of self],
// [fields of next Self arg], [etc]]
let mut patterns = Vec::new();
for i in range(0u, self_args.len()) {
let (pat, ident_expr) = trait_.create_struct_pattern(cx, type_ident, struct_def,
format!("__self_{}", i),
ast::MutImmutable);
patterns.push(pat);
raw_fields.push(ident_expr);
}
// transpose raw_fields
let fields = if raw_fields.len() > 0 {
raw_fields.get(0)
.iter()
.enumerate()
.map(|(i, &(span, opt_id, field))| {
let other_fields = raw_fields.tail().iter().map(|l| {
match l.get(i) {
&(_, _, ex) => ex
}
}).collect();
FieldInfo {
span: span,
name: opt_id,
self_: field,
other: other_fields
}
}).collect()
} else {
cx.span_bug(trait_.span,
"no self arguments to non-static method in generic \
`deriving`")
};
// body of the inner most destructuring match
let mut body = self.call_substructure_method(
cx,
trait_,
type_ident,
self_args,
nonself_args,
&Struct(fields));
// make a series of nested matches, to destructure the
// structs. This is actually right-to-left, but it shoudn't
// matter.
for (&arg_expr, &pat) in self_args.iter().zip(patterns.iter()) {
body = cx.expr_match(trait_.span, arg_expr,
vec!( cx.arm(trait_.span, vec!(pat), body) ))
}
body
}
fn expand_static_struct_method_body(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
struct_def: &StructDef,
type_ident: Ident,
self_args: &[@Expr],
nonself_args: &[@Expr])
-> @Expr {
let summary = trait_.summarise_struct(cx, struct_def);
self.call_substructure_method(cx,
trait_,
type_ident,
self_args, nonself_args,
&StaticStruct(struct_def, summary))
}
/**
~~~
#[deriving(Eq)]
enum A {
A1
A2(int)
}
// is equivalent to (with const_nonmatching == false)
impl Eq for A {
fn eq(&self, __arg_1: &A) {
match *self {
A1 => match *__arg_1 {
A1 => true
A2(ref __arg_1_1) => false
},
A2(self_1) => match *__arg_1 {
A1 => false,
A2(ref __arg_1_1) => self_1.eq(__arg_1_1)
}
}
}
}
~~~
*/
fn expand_enum_method_body(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
enum_def: &EnumDef,
type_ident: Ident,
self_args: &[@Expr],
nonself_args: &[@Expr])
-> @Expr {
let mut matches = Vec::new();
self.build_enum_match(cx, trait_, enum_def, type_ident,
self_args, nonself_args,
None, &mut matches, 0)
}
/**
Creates the nested matches for an enum definition recursively, i.e.
~~~notrust
match self {
Variant1 => match other { Variant1 => matching, Variant2 => nonmatching, ... },
Variant2 => match other { Variant1 => nonmatching, Variant2 => matching, ... },
...
}
~~~
It acts in the most naive way, so every branch (and subbranch,
subsubbranch, etc) exists, not just the ones where all the variants in
the tree are the same. Hopefully the optimisers get rid of any
repetition, otherwise derived methods with many Self arguments will be
exponentially large.
`matching` is Some(n) if all branches in the tree above the
current position are variant `n`, `None` otherwise (including on
the first call).
*/
fn build_enum_match(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
enum_def: &EnumDef,
type_ident: Ident,
self_args: &[@Expr],
nonself_args: &[@Expr],
matching: Option<uint>,
matches_so_far: &mut Vec<(uint, P<ast::Variant>,
Vec<(Span, Option<Ident>, @Expr)> )> ,
match_count: uint) -> @Expr {
if match_count == self_args.len() {
// we've matched against all arguments, so make the final
// expression at the bottom of the match tree
if matches_so_far.len() == 0 {
cx.span_bug(trait_.span,
"no self match on an enum in \
generic `deriving`");
}
// we currently have a vec of vecs, where each
// subvec is the fields of one of the arguments,
// but if the variants all match, we want this as
// vec of tuples, where each tuple represents a
// field.
let substructure;
// most arms don't have matching variants, so do a
// quick check to see if they match (even though
// this means iterating twice) instead of being
// optimistic and doing a pile of allocations etc.
match matching {
Some(variant_index) => {
// `ref` inside let matches is buggy. Causes havoc wih rusc.
// let (variant_index, ref self_vec) = matches_so_far[0];
let (variant, self_vec) = match matches_so_far.get(0) {
&(_, v, ref s) => (v, s)
};
let mut enum_matching_fields = Vec::from_elem(self_vec.len(), Vec::new());
for triple in matches_so_far.tail().iter() {
match triple {
&(_, _, ref other_fields) => {
for (i, &(_, _, e)) in other_fields.iter().enumerate() {
enum_matching_fields.get_mut(i).push(e);
}
}
}
}
let field_tuples =
self_vec.iter()
.zip(enum_matching_fields.iter())
.map(|(&(span, id, self_f), other)| {
FieldInfo {
span: span,
name: id,
self_: self_f,
other: (*other).clone()
}
}).collect();
substructure = EnumMatching(variant_index, variant, field_tuples);
}
None => {
substructure = EnumNonMatching(matches_so_far.as_slice());
}
}
self.call_substructure_method(cx, trait_, type_ident,
self_args, nonself_args,
&substructure)
} else { // there are still matches to create
let current_match_str = if match_count == 0 {
~"__self"
} else {
format!("__arg_{}", match_count)
};
let mut arms = Vec::new();
// the code for nonmatching variants only matters when
// we've seen at least one other variant already
if self.const_nonmatching && match_count > 0 {
// make a matching-variant match, and a _ match.
let index = match matching {
Some(i) => i,
None => cx.span_bug(trait_.span,
"non-matching variants when required to \
be matching in generic `deriving`")
};
// matching-variant match
let variant = *enum_def.variants.get(index);
let (pattern, idents) = trait_.create_enum_variant_pattern(cx,
variant,
current_match_str,
ast::MutImmutable);
matches_so_far.push((index, variant, idents));
let arm_expr = self.build_enum_match(cx,
trait_,
enum_def,
type_ident,
self_args, nonself_args,
matching,
matches_so_far,
match_count + 1);
matches_so_far.pop().unwrap();
arms.push(cx.arm(trait_.span, vec!( pattern ), arm_expr));
if enum_def.variants.len() > 1 {
let e = &EnumNonMatching(&[]);
let wild_expr = self.call_substructure_method(cx, trait_, type_ident,
self_args, nonself_args,
e);
let wild_arm = cx.arm(
trait_.span,
vec!( cx.pat_wild(trait_.span) ),
wild_expr);
arms.push(wild_arm);
}
} else {
// create an arm matching on each variant
for (index, &variant) in enum_def.variants.iter().enumerate() {
let (pattern, idents) = trait_.create_enum_variant_pattern(cx,
variant,
current_match_str,
ast::MutImmutable);
matches_so_far.push((index, variant, idents));
let new_matching =
match matching {
_ if match_count == 0 => Some(index),
Some(i) if index == i => Some(i),
_ => None
};
let arm_expr = self.build_enum_match(cx,
trait_,
enum_def,
type_ident,
self_args, nonself_args,
new_matching,
matches_so_far,
match_count + 1);
matches_so_far.pop().unwrap();
let arm = cx.arm(trait_.span, vec!( pattern ), arm_expr);
arms.push(arm);
}
}
// match foo { arm, arm, arm, ... }
cx.expr_match(trait_.span, self_args[match_count], arms)
}
}
fn expand_static_enum_method_body(&self,
cx: &mut ExtCtxt,
trait_: &TraitDef,
enum_def: &EnumDef,
type_ident: Ident,
self_args: &[@Expr],
nonself_args: &[@Expr])
-> @Expr {
let summary = enum_def.variants.iter().map(|v| {
let ident = v.node.name;
let summary = match v.node.kind {
ast::TupleVariantKind(ref args) => {
Unnamed(args.iter().map(|va| trait_.set_expn_info(cx, va.ty.span)).collect())
}
ast::StructVariantKind(struct_def) => {
trait_.summarise_struct(cx, struct_def)
}
};
(ident, v.span, summary)
}).collect();
self.call_substructure_method(cx, trait_, type_ident,
self_args, nonself_args,
&StaticEnum(enum_def, summary))
}
}
#[deriving(Eq)] // dogfooding!
enum StructType {
Unknown, Record, Tuple
}
// general helper methods.
impl<'a> TraitDef<'a> {
fn set_expn_info(&self,
cx: &mut ExtCtxt,
mut to_set: Span) -> Span {
let trait_name = match self.path.path.last() {
None => cx.span_bug(self.span, "trait with empty path in generic `deriving`"),
Some(name) => *name
};
to_set.expn_info = Some(@codemap::ExpnInfo {
call_site: to_set,
callee: codemap::NameAndSpan {
name: format!("deriving({})", trait_name),
format: codemap::MacroAttribute,
span: Some(self.span)
}
});
to_set
}
fn summarise_struct(&self,
cx: &mut ExtCtxt,
struct_def: &StructDef) -> StaticFields {
let mut named_idents = Vec::new();
let mut just_spans = Vec::new();
for field in struct_def.fields.iter(){
let sp = self.set_expn_info(cx, field.span);
match field.node.kind {
ast::NamedField(ident, _) => named_idents.push((ident, sp)),
ast::UnnamedField(..) => just_spans.push(sp),
}
}
match (just_spans.is_empty(), named_idents.is_empty()) {
(false, false) => cx.span_bug(self.span,
"a struct with named and unnamed \
fields in generic `deriving`"),
// named fields
(_, false) => Named(named_idents),
// tuple structs (includes empty structs)
(_, _) => Unnamed(just_spans)
}
}
fn create_subpatterns(&self,
cx: &mut ExtCtxt,
field_paths: Vec<ast::Path> ,
mutbl: ast::Mutability)
-> Vec<@ast::Pat> {
field_paths.iter().map(|path| {
cx.pat(path.span,
ast::PatIdent(ast::BindByRef(mutbl), (*path).clone(), None))
}).collect()
}
fn create_struct_pattern(&self,
cx: &mut ExtCtxt,
struct_ident: Ident,
struct_def: &StructDef,
prefix: &str,
mutbl: ast::Mutability)
-> (@ast::Pat, Vec<(Span, Option<Ident>, @Expr)> ) {
if struct_def.fields.is_empty() {
return (
cx.pat_ident_binding_mode(
self.span, struct_ident, ast::BindByValue(ast::MutImmutable)),
Vec::new());
}
let matching_path = cx.path(self.span, vec!( struct_ident ));
let mut paths = Vec::new();
let mut ident_expr = Vec::new();
let mut struct_type = Unknown;
for (i, struct_field) in struct_def.fields.iter().enumerate() {
let sp = self.set_expn_info(cx, struct_field.span);
let opt_id = match struct_field.node.kind {
ast::NamedField(ident, _) if (struct_type == Unknown ||
struct_type == Record) => {
struct_type = Record;
Some(ident)
}
ast::UnnamedField(..) if (struct_type == Unknown ||
struct_type == Tuple) => {
struct_type = Tuple;
None
}
_ => {
cx.span_bug(sp, "a struct with named and unnamed fields in `deriving`");
}
};
let path = cx.path_ident(sp, cx.ident_of(format!("{}_{}", prefix, i)));
paths.push(path.clone());
let val = cx.expr(
sp, ast::ExprParen(
cx.expr_deref(sp, cx.expr_path(path))));
ident_expr.push((sp, opt_id, val));
}
let subpats = self.create_subpatterns(cx, paths, mutbl);
// struct_type is definitely not Unknown, since struct_def.fields
// must be nonempty to reach here
let pattern = if struct_type == Record {
let field_pats = subpats.iter().zip(ident_expr.iter()).map(|(&pat, &(_, id, _))| {
// id is guaranteed to be Some
ast::FieldPat { ident: id.unwrap(), pat: pat }
}).collect();
cx.pat_struct(self.span, matching_path, field_pats)
} else {
cx.pat_enum(self.span, matching_path, subpats)
};
(pattern, ident_expr)
}
fn create_enum_variant_pattern(&self,
cx: &mut ExtCtxt,
variant: &ast::Variant,
prefix: &str,
mutbl: ast::Mutability)
-> (@ast::Pat, Vec<(Span, Option<Ident>, @Expr)> ) {
let variant_ident = variant.node.name;
match variant.node.kind {
ast::TupleVariantKind(ref variant_args) => {
if variant_args.is_empty() {
return (cx.pat_ident_binding_mode(variant.span, variant_ident,
ast::BindByValue(ast::MutImmutable)),
Vec::new());
}
let matching_path = cx.path_ident(variant.span, variant_ident);
let mut paths = Vec::new();
let mut ident_expr = Vec::new();
for (i, va) in variant_args.iter().enumerate() {
let sp = self.set_expn_info(cx, va.ty.span);
let path = cx.path_ident(sp, cx.ident_of(format!("{}_{}", prefix, i)));
paths.push(path.clone());
let val = cx.expr(
sp, ast::ExprParen(cx.expr_deref(sp, cx.expr_path(path))));
ident_expr.push((sp, None, val));
}
let subpats = self.create_subpatterns(cx, paths, mutbl);
(cx.pat_enum(variant.span, matching_path, subpats),
ident_expr)
}
ast::StructVariantKind(struct_def) => {
self.create_struct_pattern(cx, variant_ident, struct_def,
prefix, mutbl)
}
}
}
}
/* helpful premade recipes */
/**
Fold the fields. `use_foldl` controls whether this is done
left-to-right (`true`) or right-to-left (`false`).
*/
pub fn cs_fold(use_foldl: bool,
f: |&mut ExtCtxt, Span, @Expr, @Expr, &[@Expr]| -> @Expr,
base: @Expr,
enum_nonmatch_f: EnumNonMatchFunc,
cx: &mut ExtCtxt,
trait_span: Span,
substructure: &Substructure)
-> @Expr {
match *substructure.fields {
EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => {
if use_foldl {
all_fields.iter().fold(base, |old, field| {
f(cx,
field.span,
old,
field.self_,
field.other.as_slice())
})
} else {
all_fields.iter().rev().fold(base, |old, field| {
f(cx,
field.span,
old,
field.self_,
field.other.as_slice())
})
}
},
EnumNonMatching(ref all_enums) => enum_nonmatch_f(cx, trait_span,
*all_enums,
substructure.nonself_args),
StaticEnum(..) | StaticStruct(..) => {
cx.span_bug(trait_span, "static function in `deriving`")
}
}
}
/**
Call the method that is being derived on all the fields, and then
process the collected results. i.e.
~~~
f(cx, span, ~[self_1.method(__arg_1_1, __arg_2_1),
self_2.method(__arg_1_2, __arg_2_2)])
~~~
*/
#[inline]
pub fn cs_same_method(f: |&mut ExtCtxt, Span, Vec<@Expr> | -> @Expr,
enum_nonmatch_f: EnumNonMatchFunc,
cx: &mut ExtCtxt,
trait_span: Span,
substructure: &Substructure)
-> @Expr {
match *substructure.fields {
EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => {
// call self_n.method(other_1_n, other_2_n, ...)
let called = all_fields.iter().map(|field| {
cx.expr_method_call(field.span,
field.self_,
substructure.method_ident,
field.other.iter()
.map(|e| cx.expr_addr_of(field.span, *e))
.collect())
}).collect();
f(cx, trait_span, called)
},
EnumNonMatching(ref all_enums) => enum_nonmatch_f(cx, trait_span,
*all_enums,
substructure.nonself_args),
StaticEnum(..) | StaticStruct(..) => {
cx.span_bug(trait_span, "static function in `deriving`")
}
}
}
/**
Fold together the results of calling the derived method on all the
fields. `use_foldl` controls whether this is done left-to-right
(`true`) or right-to-left (`false`).
*/
#[inline]
pub fn cs_same_method_fold(use_foldl: bool,
f: |&mut ExtCtxt, Span, @Expr, @Expr| -> @Expr,
base: @Expr,
enum_nonmatch_f: EnumNonMatchFunc,
cx: &mut ExtCtxt,
trait_span: Span,
substructure: &Substructure)
-> @Expr {
cs_same_method(
|cx, span, vals| {
if use_foldl {
vals.iter().fold(base, |old, &new| {
f(cx, span, old, new)
})
} else {
vals.iter().rev().fold(base, |old, &new| {
f(cx, span, old, new)
})
}
},
enum_nonmatch_f,
cx, trait_span, substructure)
}
/**
Use a given binop to combine the result of calling the derived method
on all the fields.
*/
#[inline]
pub fn cs_binop(binop: ast::BinOp, base: @Expr,
enum_nonmatch_f: EnumNonMatchFunc,
cx: &mut ExtCtxt, trait_span: Span,
substructure: &Substructure) -> @Expr {
cs_same_method_fold(
true, // foldl is good enough
|cx, span, old, new| {
cx.expr_binary(span,
binop,
old, new)
},
base,
enum_nonmatch_f,
cx, trait_span, substructure)
}
/// cs_binop with binop == or
#[inline]
pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc,
cx: &mut ExtCtxt, span: Span,
substructure: &Substructure) -> @Expr {
cs_binop(ast::BiOr, cx.expr_bool(span, false),
enum_nonmatch_f,
cx, span, substructure)
}
/// cs_binop with binop == and
#[inline]
pub fn cs_and(enum_nonmatch_f: EnumNonMatchFunc,
cx: &mut ExtCtxt, span: Span,
substructure: &Substructure) -> @Expr {
cs_binop(ast::BiAnd, cx.expr_bool(span, true),
enum_nonmatch_f,
cx, span, substructure)
}<|fim▁end|> | other: ~[<expr for &other.x>]
}])
~~~
|
<|file_name|>ScansTest.java<|end_file_name|><|fim▁begin|>package org.nutz.resource;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.Servlet;
import junit.extensions.ActiveTestSuite;
import junit.extensions.RepeatedTest;
import junit.extensions.TestSetup;
import junit.framework.Assert;
import org.junit.Test;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
public class ScansTest {
@Test
public void test_loadResource() throws IOException {
String RNAME = "junit/runner/Version.class";
List<NutResource> nrs = Scans.me().loadResource(".*.class", RNAME);
assertEquals(1, nrs.size());
NutResource nr = nrs.get(0);
assertTrue(nr.getName().indexOf(RNAME) >= 0);
InputStream ins = nr.getInputStream();
int len = 0;
while (-1 != ins.read()) {
len++;
}
ins.close();
assertTrue(len > 600);
}
@Test
public void test_in_normal_file() throws IOException {
String testPath = "~/nutz/unit/rs/test";
File testDir = Files.createDirIfNoExists(testPath);
Files.clearDir(testDir);
List<NutResource> list = Scans.me().scan(testPath, ".*");
assertEquals(0, list.size());
Files.createDirIfNoExists(testPath + "/a/b/c");
list = Scans.me().scan(testPath, ".*");
assertEquals(0, list.size());
Files.createFileIfNoExists(testPath + "/a/b/c/l.txt");
Files.createFileIfNoExists(testPath + "/a/b/c/m.doc");
Files.createFileIfNoExists(testPath + "/a/b/c/n.jpg");
Files.createFileIfNoExists(testPath + "/a/b/c/o.jpg");
list = Scans.me().scan(testPath, ".*");
assertEquals(4, list.size());
list = Scans.me().scan(testPath, null);
assertEquals(4, list.size());
list = Scans.me().scan(testPath, ".+[.]jpg");
assertEquals(2, list.size());
list = Scans.me().scan(testPath, ".*[.]txt");
assertEquals(1, list.size());
Files.deleteDir(testDir);
}
@Test
public void test_in_classpath() {
String testPath = Scans.class.getName().replace('.', '/') + ".class";
String testFilter = "^" + Scans.class.getSimpleName() + ".class$";
List<NutResource> list = Scans.me().scan(testPath, testFilter);
assertEquals(1, list.size());
}
<|fim▁hole|> public void test_in_jar() {
String testPath = Assert.class.getPackage().getName().replace('.', '/');
String testFilter = "^.*(Assert|Test)\\.class$";
List<NutResource> list = Scans.me().scan(testPath, testFilter);
//Collections.sort(list);
assertEquals(2, list.size());
assertTrue(list.get(0).getName().endsWith("Test.class"));
assertTrue(list.get(1).getName().endsWith("Assert.class"));
}
// @Ignore
@Test
public void test_classes_in_jar() {
List<Class<?>> list = Scans.me()
.scanPackage( ActiveTestSuite.class,
".*(ActiveTestSuite|RepeatedTest|TestSetup)\\.class$");
assertEquals(3, list.size());
Collections.sort(list, new Comparator<Class<?>>() {
public int compare(Class<?> o1, Class<?> o2) {
return o1.getSimpleName().compareTo(o2.getSimpleName());
}
});
assertTrue(ActiveTestSuite.class == list.get(0));
assertTrue(RepeatedTest.class == list.get(1));
assertTrue(TestSetup.class == list.get(2));
}
@Test
public void test_classes_in_package_path() {
List<Class<?>> list = Scans.me().scanPackage("org.nutz", "Strings.class");
assertEquals(1, list.size());
assertTrue(Strings.class == list.get(0));
}
@Test
public void test_scan_with_unexists_file() {
List<NutResource> list = Scans.me().scan("org/nutz/lang/notExist.class", null);
assertEquals(0, list.size());
}
@Test
public void test_class_in_jar() {
String testPath = Test.class.getName().replace('.', '/') + ".class";
String testFilter = "^Test.class$";
List<NutResource> list = Scans.me().scan(testPath, testFilter);
assertEquals(1, list.size());
}
@Test
public void test_path_in_jar() {
String testPath = Test.class.getPackage().getName().replace('.', '/');
List<NutResource> list = Scans.me().scan(testPath, null);
assertTrue(list.size() > 10);
}
@Test
public void test_scan_root() {
Scans.me().scan("", ".+\\.xml");
}
@Test
public void test_resource_jar() throws MalformedURLException {
Scans.me().registerLocation(Servlet.class);
Scans.me().registerLocation(getClass().getClassLoader().getResource("javax/servlet/Servlet.class"));
}
}<|fim▁end|> |
// @Ignore
@Test
|
<|file_name|>callExpressionTests.ts<|end_file_name|><|fim▁begin|>import { SyntaxKind } from "@ts-morph/common";
import { expect } from "chai";
import { CallExpression } from "../../../../compiler";
import { getInfoFromText } from "../../testHelpers";<|fim▁hole|> describe(nameof<CallExpression>(e => e.getReturnType), () => {
function doTest(text: string, expectedTypes: string[]) {
const { sourceFile } = getInfoFromText(text);
const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);
expect(callExpressions.map(c => c.getReturnType().getText())).to.deep.equal(expectedTypes);
}
it("should get the call expression's return type", () => {
doTest("const func = () => ''; const myVar = func();", ["string"]);
});
it("should get the call expression's return type when void", () => {
doTest("const func = () => {}; const myVar = func();", ["void"]);
});
it("should get the call expression's return type when chained", () => {
doTest("const func = () => () => 4; const myVar = func()();", ["number", "() => number"]);
});
});
});<|fim▁end|> |
describe(nameof(CallExpression), () => { |
<|file_name|>DefaultGenericCollectionAdaptor.java<|end_file_name|><|fim▁begin|>package net.amygdalum.testrecorder.deserializers.builder;
import static java.util.stream.Collectors.toList;
import static net.amygdalum.testrecorder.deserializers.Templates.assignLocalVariableStatement;
import static net.amygdalum.testrecorder.deserializers.Templates.callMethodStatement;
import static net.amygdalum.testrecorder.deserializers.Templates.newObject;
import static net.amygdalum.testrecorder.types.Computation.variable;
import static net.amygdalum.testrecorder.util.Types.baseType;
import static net.amygdalum.testrecorder.util.Types.equalGenericTypes;
import static net.amygdalum.testrecorder.util.Types.typeArgument;
import static net.amygdalum.testrecorder.util.Types.typeArguments;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import net.amygdalum.testrecorder.deserializers.Deserializer;
import net.amygdalum.testrecorder.types.Computation;
import net.amygdalum.testrecorder.types.DeserializerContext;
import net.amygdalum.testrecorder.types.SerializedReferenceType;
import net.amygdalum.testrecorder.types.SerializedValue;
import net.amygdalum.testrecorder.types.TypeManager;
import net.amygdalum.testrecorder.util.Types;
public abstract class DefaultGenericCollectionAdaptor<T extends SerializedReferenceType> extends DefaultSetupGenerator<T> implements SetupGenerator<T> {
public abstract Class<?>[] matchingTypes();
<|fim▁hole|>
@Override
public boolean matches(Type type) {
return matchType(type).isPresent();
}
public Optional<Class<?>> matchType(Type type) {
return Stream.of(matchingTypes())
.filter(clazz -> clazz.isAssignableFrom(baseType(type)))
.findFirst();
}
@Override
public Computation tryDeserialize(T value, Deserializer generator) {
DeserializerContext context = generator.getContext();
TypeManager types = context.getTypes();
Type type = value.getType();
Type usedType = types.mostSpecialOf(value.getUsedTypes()).orElse(Object.class);
boolean uniqueUsageType = value.getUsedTypes().length == 1 && Collection.class.isAssignableFrom(baseType(usedType));
Type componentType = componentType(value);
Class<?> matchingType = matchType(type).get();
Type effectiveResultType = types.bestType(usedType, matchingType);
Type temporaryType = uniqueUsageType ? effectiveResultType : types.bestType(type, effectiveResultType, matchingType);
Type componentResultType = types.isHidden(componentType) ? typeArgument(temporaryType, 0).orElse(Object.class) : componentType;
types.registerTypes(effectiveResultType, type, componentResultType);
return context.forVariable(value, effectiveResultType, local -> {
List<Computation> elementTemplates = elements(value)
.map(element -> element.accept(generator))
.filter(element -> element != null)
.collect(toList());
List<String> elements = elementTemplates.stream()
.map(template -> context.adapt(template.getValue(), componentResultType, template.getType()))
.collect(toList());
List<String> statements = elementTemplates.stream()
.flatMap(template -> template.getStatements().stream())
.collect(toList());
String tempVar = local.getName();
if (!equalGenericTypes(effectiveResultType, temporaryType)) {
tempVar = context.temporaryLocal();
}
String set = types.isHidden(type)
? context.adapt(types.getWrappedName(type), temporaryType, types.wrapHidden(type))
: newObject(types.getConstructorTypeName(type));
String temporaryTypeName = Optional.of(temporaryType)
.filter(t -> typeArguments(t).count() > 0)
.filter(t -> typeArguments(t).allMatch(Types::isBound))
.map(t -> types.getVariableTypeName(t))
.orElse(types.getRawTypeName(temporaryType));
String setInit = assignLocalVariableStatement(temporaryTypeName, tempVar, set);
statements.add(setInit);
for (String element : elements) {
String addElement = callMethodStatement(tempVar, "add", element);
statements.add(addElement);
}
if (local.isDefined() && !local.isReady()) {
statements.add(callMethodStatement(local.getName(), "addAll", tempVar));
} else if (context.needsAdaptation(effectiveResultType, temporaryType)) {
tempVar = context.adapt(tempVar, effectiveResultType, temporaryType);
statements.add(assignLocalVariableStatement(types.getVariableTypeName(effectiveResultType), local.getName(), tempVar));
} else if (!equalGenericTypes(effectiveResultType, temporaryType)) {
statements.add(assignLocalVariableStatement(types.getVariableTypeName(effectiveResultType), local.getName(), tempVar));
}
return variable(local.getName(), local.getType(), statements);
});
}
}<|fim▁end|> | public abstract Type componentType(T value);
public abstract Stream<SerializedValue> elements(T value); |
<|file_name|>TestSettings.java<|end_file_name|><|fim▁begin|>/*
* JBox2D - A Java Port of Erin Catto's Box2D
*
* JBox2D homepage: http://jbox2d.sourceforge.net/
* Box2D homepage: http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package org.jbox2d.testbed;
public class TestSettings {
public int hz;
public int iterationCount;
public boolean enableWarmStarting;
public boolean enablePositionCorrection;
public boolean enableTOI;
public boolean pause;
public boolean singleStep;
public boolean drawShapes;
public boolean drawJoints;
public boolean drawCoreShapes;
public boolean drawOBBs;
public boolean drawCOMs;
public boolean drawStats;
public boolean drawImpulses;
public boolean drawAABBs;
public boolean drawPairs;
public boolean drawContactPoints;
public boolean drawContactNormals;
public boolean drawContactForces;
public boolean drawFrictionForces;
public TestSettings() {
hz = 60;
iterationCount = 10;
drawStats = true;
drawAABBs = false;
drawPairs = false;
drawShapes = true;
drawJoints = true;
drawCoreShapes = false;
drawContactPoints = false;
drawContactNormals = false;
drawContactForces = false;
drawFrictionForces = false;
drawOBBs = false;
drawCOMs = false;
enableWarmStarting = true;
enablePositionCorrection = true;
enableTOI = true;
pause = false;
singleStep = false;<|fim▁hole|> }
}<|fim▁end|> | |
<|file_name|>tablestatus.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/tablestatus.h"
#include "ofp/writable.h"
using namespace ofp;
bool TableStatus::validateInput(Validation *context) const {
size_t length = context->length();
<|fim▁hole|> return false;
}
size_t remainingLength = length - sizeof(TableStatus);
context->setLengthRemaining(remainingLength);
// FIXME: make sure there is only one table?
return table().validateInput(context);
}
UInt32 TableStatusBuilder::send(Writable *channel) {
UInt8 version = channel->version();
UInt32 xid = channel->nextXid();
UInt16 msgLen = UInt16_narrow_cast(sizeof(msg_) + table_.writeSize(channel));
msg_.header_.setVersion(version);
msg_.header_.setLength(msgLen);
msg_.header_.setXid(xid);
channel->write(&msg_, sizeof(msg_));
table_.write(channel);
channel->flush();
return xid;
}<|fim▁end|> | if (length < sizeof(TableStatus) + sizeof(TableDesc)) {
log_debug("TableStatus too small", length); |
<|file_name|>lazyproxy.py<|end_file_name|><|fim▁begin|>class LazyProxy(object):
def __init__(self, original_module, original_class, init_args):
self._original_module = original_module
self._original_class = original_class
self._original_init_args = init_args
self._instance = None
def __getattr__(self, name):
if self._instance is None:
self.__init_class__()
return getattr(self._instance, name)
def __init_class__(self):
import importlib
module = importlib.import_module(self._original_module)
class_ = getattr(module, self._original_class)
if self._original_init_args is not None:
for index, arg in enumerate(self._original_init_args):
if arg[:1] == '@':
from resources.lib.di.requiredfeature import RequiredFeature
self._original_init_args[index] = RequiredFeature(arg[1:]).request()
import inspect
args = inspect.getargspec(class_.__init__)[0]
if args[0] == 'self':
args.pop(0)
argument_dict = dict(zip(args, self._original_init_args))<|fim▁hole|> self._instance = class_()<|fim▁end|> |
self._instance = class_(**argument_dict)
else: |
<|file_name|>FontOptions.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.colors;
import com.intellij.application.options.EditorFontsConstants;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.FontPreferences;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.*;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.util.EventDispatcher;
import com.intellij.util.ui.JBUI;
import net.miginfocom.swing.MigLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public class FontOptions extends JPanel implements OptionsPanel{
private static final FontInfoRenderer RENDERER = new FontInfoRenderer() {
@Override
protected boolean isEditorFont() {
return true;
}
};
private final EventDispatcher<ColorAndFontSettingsListener> myDispatcher = EventDispatcher.create(ColorAndFontSettingsListener.class);
@NotNull private final ColorAndFontOptions myOptions;
@NotNull private final JTextField myEditorFontSizeField = new JTextField(4);
@NotNull private final JTextField myLineSpacingField = new JTextField(4);
private final FontComboBox myPrimaryCombo = new FontComboBox();
private final JCheckBox myUseSecondaryFontCheckbox = new JCheckBox(ApplicationBundle.message("secondary.font"));
private final JCheckBox myEnableLigaturesCheckbox = new JCheckBox(ApplicationBundle.message("use.ligatures"));
private final FontComboBox mySecondaryCombo = new FontComboBox(false, false);
@NotNull private final JBCheckBox myOnlyMonospacedCheckBox =
new JBCheckBox(ApplicationBundle.message("checkbox.show.only.monospaced.fonts"));
private boolean myIsInSchemeChange;
public FontOptions(@NotNull ColorAndFontOptions options) {
setLayout(new MigLayout("ins 0, gap 5, flowx"));
myOptions = options;
add(myOnlyMonospacedCheckBox, "newline 10, sgx b, sx 2");
add(new JLabel(ApplicationBundle.message("primary.font")), "newline, ax right");
add(myPrimaryCombo, "sgx b");
add(new JLabel(ApplicationBundle.message("editbox.font.size")), "gapleft 20");
add(myEditorFontSizeField);
add(new JLabel(ApplicationBundle.message("editbox.line.spacing")), "gapleft 20");
add(myLineSpacingField);
add(new JLabel(ApplicationBundle.message("label.fallback.fonts.list.description"),
MessageType.INFO.getDefaultIcon(),
SwingConstants.LEFT), "newline, sx 5");
add(myUseSecondaryFontCheckbox, "newline, ax right");
add(mySecondaryCombo, "sgx b");
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
myEnableLigaturesCheckbox.setBorder(null);
panel.add(myEnableLigaturesCheckbox);
JLabel warningIcon = new JLabel(AllIcons.General.BalloonWarning);
IdeTooltipManager.getInstance().setCustomTooltip(
warningIcon,
new TooltipWithClickableLinks.ForBrowser(warningIcon,
ApplicationBundle.message("ligatures.jre.warning",
ApplicationNamesInfo.getInstance().getFullProductName())));
warningIcon.setBorder(JBUI.Borders.emptyLeft(5));
updateWarningIconVisibility(warningIcon);
panel.add(warningIcon);
add(panel, "newline, sx 2");
myOnlyMonospacedCheckBox.setBorder(null);
myUseSecondaryFontCheckbox.setBorder(null);
mySecondaryCombo.setEnabled(false);
myOnlyMonospacedCheckBox.setSelected(EditorColorsManager.getInstance().isUseOnlyMonospacedFonts());
myOnlyMonospacedCheckBox.addActionListener(e -> {
EditorColorsManager.getInstance().setUseOnlyMonospacedFonts(myOnlyMonospacedCheckBox.isSelected());
myPrimaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
mySecondaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
});
myPrimaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
myPrimaryCombo.setRenderer(RENDERER);
mySecondaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
mySecondaryCombo.setRenderer(RENDERER);
myUseSecondaryFontCheckbox.addActionListener(e -> {
mySecondaryCombo.setEnabled(myUseSecondaryFontCheckbox.isSelected());
syncFontFamilies();
});
ItemListener itemListener = this::syncFontFamilies;
myPrimaryCombo.addItemListener(itemListener);
mySecondaryCombo.addItemListener(itemListener);
ActionListener actionListener = this::syncFontFamilies;
myPrimaryCombo.addActionListener(actionListener);
mySecondaryCombo.addActionListener(actionListener);
myEditorFontSizeField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void textChanged(DocumentEvent event) {
if (myIsInSchemeChange || !SwingUtilities.isEventDispatchThread()) return;
String selectedFont = myPrimaryCombo.getFontName();
if (selectedFont != null) {<|fim▁hole|> setFontSize(getFontSizeFromField());
}
updateDescription(true);
}
});
myEditorFontSizeField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) return;
boolean up = e.getKeyCode() == KeyEvent.VK_UP;
try {
int value = Integer.parseInt(myEditorFontSizeField.getText());
value += (up ? 1 : -1);
value = Math.min(EditorFontsConstants.getMaxEditorFontSize(), Math.max(EditorFontsConstants.getMinEditorFontSize(), value));
myEditorFontSizeField.setText(String.valueOf(value));
}
catch (NumberFormatException ignored) {
}
}
});
myLineSpacingField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void textChanged(DocumentEvent event) {
if (myIsInSchemeChange) return;
float lineSpacing = getLineSpacingFromField();
if (getLineSpacing() != lineSpacing) {
setCurrentLineSpacing(lineSpacing);
}
updateDescription(true);
}
});
myLineSpacingField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) return;
boolean up = e.getKeyCode() == KeyEvent.VK_UP;
try {
float value = Float.parseFloat(myLineSpacingField.getText());
value += (up ? 1 : -1) * .1F;
value = Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), value));
myLineSpacingField.setText(String.format(Locale.ENGLISH, "%.1f", value));
}
catch (NumberFormatException ignored) {
}
}
});
myEnableLigaturesCheckbox.addActionListener(e -> {
getFontPreferences().setUseLigatures(myEnableLigaturesCheckbox.isSelected());
updateWarningIconVisibility(warningIcon);
updateDescription(true);
});
}
private void updateWarningIconVisibility(JLabel warningIcon) {
warningIcon.setVisible(!SystemInfo.isJetbrainsJvm && getFontPreferences().useLigatures());
}
private int getFontSizeFromField() {
try {
return Math.min(EditorFontsConstants.getMaxEditorFontSize(),
Math.max(EditorFontsConstants.getMinEditorFontSize(), Integer.parseInt(myEditorFontSizeField.getText())));
}
catch (NumberFormatException e) {
return EditorFontsConstants.getDefaultEditorFontSize();
}
}
private float getLineSpacingFromField() {
try {
return Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), Float.parseFloat(myLineSpacingField.getText())));
} catch (NumberFormatException e){
return EditorFontsConstants.getDefaultEditorLineSpacing();
}
}
/**
* Processes an event from {@code FontComboBox}
* if it is enabled and its item is selected.
*
* @param event the event to process
*/
private void syncFontFamilies(AWTEvent event) {
Object source = event.getSource();
if (source instanceof FontComboBox) {
FontComboBox combo = (FontComboBox)source;
if (combo.isEnabled() && combo.isShowing() && combo.getSelectedItem() != null) {
syncFontFamilies();
}
}
}
private void syncFontFamilies() {
if (myIsInSchemeChange) {
return;
}
FontPreferences fontPreferences = getFontPreferences();
fontPreferences.clearFonts();
String primaryFontFamily = myPrimaryCombo.getFontName();
String secondaryFontFamily = mySecondaryCombo.isEnabled() ? mySecondaryCombo.getFontName() : null;
int fontSize = getFontSizeFromField();
if (primaryFontFamily != null ) {
if (!FontPreferences.DEFAULT_FONT_NAME.equals(primaryFontFamily)) {
fontPreferences.addFontFamily(primaryFontFamily);
}
fontPreferences.register(primaryFontFamily, fontSize);
}
if (secondaryFontFamily != null) {
if (!FontPreferences.DEFAULT_FONT_NAME.equals(secondaryFontFamily)){
fontPreferences.addFontFamily(secondaryFontFamily);
}
fontPreferences.register(secondaryFontFamily, fontSize);
}
updateDescription(true);
}
@Override
public void updateOptionsList() {
myIsInSchemeChange = true;
myLineSpacingField.setText(Float.toString(getLineSpacing()));
FontPreferences fontPreferences = getFontPreferences();
List<String> fontFamilies = fontPreferences.getEffectiveFontFamilies();
myPrimaryCombo.setFontName(fontPreferences.getFontFamily());
boolean isThereSecondaryFont = fontFamilies.size() > 1;
myUseSecondaryFontCheckbox.setSelected(isThereSecondaryFont);
mySecondaryCombo.setFontName(isThereSecondaryFont ? fontFamilies.get(1) : null);
myEditorFontSizeField.setText(String.valueOf(fontPreferences.getSize(fontPreferences.getFontFamily())));
boolean readOnly = ColorAndFontOptions.isReadOnly(myOptions.getSelectedScheme());
myPrimaryCombo.setEnabled(!readOnly);
mySecondaryCombo.setEnabled(isThereSecondaryFont && !readOnly);
myOnlyMonospacedCheckBox.setEnabled(!readOnly);
myLineSpacingField.setEnabled(!readOnly);
myEditorFontSizeField.setEnabled(!readOnly);
myUseSecondaryFontCheckbox.setEnabled(!readOnly);
myEnableLigaturesCheckbox.setEnabled(!readOnly);
myEnableLigaturesCheckbox.setSelected(fontPreferences.useLigatures());
myIsInSchemeChange = false;
}
@NotNull
protected FontPreferences getFontPreferences() {
return getCurrentScheme().getFontPreferences();
}
protected void setFontSize(int fontSize) {
getCurrentScheme().setEditorFontSize(fontSize);
}
protected float getLineSpacing() {
return getCurrentScheme().getLineSpacing();
}
protected void setCurrentLineSpacing(float lineSpacing) {
getCurrentScheme().setLineSpacing(lineSpacing);
}
@Override
@Nullable
public Runnable showOption(final String option) {
return null;
}
@Override
public void applyChangesToScheme() {
}
@Override
public void selectOption(final String typeToSelect) {
}
protected EditorColorsScheme getCurrentScheme() {
return myOptions.getSelectedScheme();
}
public boolean updateDescription(boolean modified) {
EditorColorsScheme scheme = myOptions.getSelectedScheme();
if (modified && ColorAndFontOptions.isReadOnly(scheme)) {
return false;
}
myDispatcher.getMulticaster().fontChanged();
return true;
}
@Override
public void addListener(ColorAndFontSettingsListener listener) {
myDispatcher.addListener(listener);
}
@Override
public JPanel getPanel() {
return this;
}
@Override
public Set<String> processListOptions() {
return new HashSet<>();
}
}<|fim▁end|> | |
<|file_name|>array.rs<|end_file_name|><|fim▁begin|>use juniper::{
graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription,
GraphQLInputObject, RootNode,
};
mod as_output_field {
use super::*;
struct Query;
#[graphql_object]
impl Query {
fn roll() -> [bool; 3] {
[true, false, true]
}
}
#[tokio::test]
async fn works() {
let query = r#"
query Query {
roll
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &())
.await
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(res, graphql_value!({"roll": [true, false, true]}));
}
}
mod as_input_field {
use super::*;
#[derive(GraphQLInputObject)]<|fim▁hole|> two: [bool; 2],
}
#[derive(GraphQLInputObject)]
struct InputSingle {
one: [bool; 1],
}
struct Query;
#[graphql_object]
impl Query {
fn first(input: InputSingle) -> bool {
input.one[0]
}
fn second(input: Input) -> bool {
input.two[1]
}
}
#[tokio::test]
async fn works() {
let query = r#"
query Query {
second(input: { two: [true, false] })
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &())
.await
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(res, graphql_value!({"second": false}));
}
#[tokio::test]
async fn fails_on_incorrect_count() {
let query = r#"
query Query {
second(input: { two: [true, true, false] })
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let res = juniper::execute(query, None, &schema, &graphql_vars! {}, &()).await;
assert!(res.is_err());
assert!(res
.unwrap_err()
.to_string()
.contains(r#"Invalid value for argument "input", expected type "Input!""#));
}
#[tokio::test]
async fn cannot_coerce_from_raw_value_if_multiple() {
let query = r#"
query Query {
second(input: { two: true })
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let res = juniper::execute(query, None, &schema, &graphql_vars! {}, &()).await;
assert!(res.is_err());
assert!(res
.unwrap_err()
.to_string()
.contains(r#"Invalid value for argument "input", expected type "Input!""#));
}
#[tokio::test]
async fn can_coerce_from_raw_value_if_single() {
let query = r#"
query Query {
first(input: { one: true })
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &())
.await
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(res, graphql_value!({"first": true}));
}
}
mod as_input_argument {
use super::*;
struct Query;
#[graphql_object]
impl Query {
fn second(input: [bool; 2]) -> bool {
input[1]
}
fn first(input: [bool; 1]) -> bool {
input[0]
}
fn third(#[graphql(default = [true, false, false])] input: [bool; 3]) -> bool {
input[2]
}
}
#[tokio::test]
async fn works() {
let query = r#"
query Query {
second(input: [false, true])
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &())
.await
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(res, graphql_value!({"second": true}));
}
#[tokio::test]
async fn fails_on_incorrect_count() {
let query = r#"
query Query {
second(input: [true, true, false])
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let res = juniper::execute(query, None, &schema, &graphql_vars! {}, &()).await;
assert!(res.is_err());
assert!(res
.unwrap_err()
.to_string()
.contains(r#"Invalid value for argument "input", expected type "[Boolean!]!""#));
}
#[tokio::test]
async fn cannot_coerce_from_raw_value_if_multiple() {
let query = r#"
query Query {
second(input: true)
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let res = juniper::execute(query, None, &schema, &graphql_vars! {}, &()).await;
assert!(res.is_err());
assert!(res
.unwrap_err()
.to_string()
.contains(r#"Invalid value for argument "input", expected type "[Boolean!]!""#));
}
#[tokio::test]
async fn can_coerce_from_raw_value_if_single() {
let query = r#"
query Query {
first(input: true)
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &())
.await
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(res, graphql_value!({"first": true}));
}
#[tokio::test]
async fn picks_default() {
let query = r#"
query Query {
third
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &())
.await
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(res, graphql_value!({"third": false}));
}
#[tokio::test]
async fn picks_specified_over_default() {
let query = r#"
query Query {
third(input: [false, false, true])
}
"#;
let schema = RootNode::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &())
.await
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(res, graphql_value!({"third": true}));
}
}<|fim▁end|> | struct Input { |
<|file_name|>PEMer_Lite_test.cpp<|end_file_name|><|fim▁begin|>#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include <seqan/sequence.h>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "PEMer_Lite.h"
int median(candidate &input) // erstellt den median muss noch an struct candidate angepasst werden
{
std::nth_element( begin(input.len), begin(input.len) + input.length()/2,end(input.len));
input.e=*(begin(input.len) + input.length()/2 );
return 0;
}
unsigned average(candidate &input) // erzeugt den Durchschnitt und speichert ihm Objekt
{
unsigned tmpi=0;
unsigned n = input.length();
for (unsigned i=0;i<n;i++)
{
tmpi += input.len[i];
}
return tmpi/n;
}
seqan::ArgumentParser::ParseResult commands(modifier &options, int argc, char const ** argv)
{
seqan::ArgumentParser parser("PEMer_Lite");
// Optionen hinzufügen
addOption(parser, seqan::ArgParseOption("i","input-file","Input SAM-file.",seqan::ArgParseArgument::INPUTFILE));
setValidValues(parser, "input-file", "sam");
setRequired(parser, "input-file");
addOption(parser,seqan::ArgParseOption("x","SD-variable", "Variable to use for multiples of standard degression.",seqan::ArgParseArgument::INTEGER, "INT"));
setMinValue(parser, "SD-variable", "1");
setDefaultValue(parser,"SD-variable","1");
addOption(parser,seqan::ArgParseOption("y","Del_SD-variable", "Variable to spezify multiples of standard degression for deletions.",seqan::ArgParseArgument::INTEGER, "INT"));
setMinValue(parser, "Del_SD-variable", "1");
setDefaultValue(parser,"Del_SD-variable","1");
addOption(parser,seqan::ArgParseOption("s","standard_degression", "Variable to use for standard degression for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT"));
setMinValue(parser, "standard_degression", "1");
addOption(parser,seqan::ArgParseOption("e","expected_value", "Variable to use for the expected value for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT"));
setMinValue(parser, "expected_value", "1");
addOption(parser, seqan::ArgParseOption("p","Print", "Select to print temporary solutions."));
// verarbeitet die Kommandozeile
seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv);
// Überprüfung der richtigen Ausführung von commands()
if (res != seqan::ArgumentParser::PARSE_OK)
return res;
// extrahiert Werte aus der parser.
getOptionValue(options.x, parser, "SD-variable");
getOptionValue(options.y, parser, "Del_SD-variable");
getOptionValue(options.e, parser, "expected_value");
getOptionValue(options.sd, parser, "standard_degression");
options.p = isSet(parser, "Print");
getOptionValue(options.inputFile, parser, "input-file");
return seqan::ArgumentParser::PARSE_OK;
}
int analyse(candidate &input) //erzeugt die Standartabweichung
{
median(input);
input.sd=0;
unsigned n = input.length();
for (unsigned i=0;i<n;i++)
{
input.sd += (input.len[i]-input.e)*(input.len[i]-input.e);
}
input.sd /= n;
input.sd = sqrt((double)input.sd);
return 0;
}
int saminput(candidate &save, char *file) // impotiert eine SAM-Datei und speichert sie im Format candidate
{
// BamStream öffnet Eingangsdatenstrom
seqan::BamStream SamInput(file);
if (!isGood(SamInput))
{
std::cerr << "-ERROR- Could not open" << std::endl;
return 1;
}
// record enthält die inhalte aus einer SAM-Datei
seqan::BamAlignmentRecord record;
while (!atEnd(SamInput))
{
readRecord(record, SamInput);
save.len.push_back(length(record.seq));
save.ref.push_back(record.rID);
save.pos.push_back(record.beginPos);
save.type.push_back(candidate::u);
}
return 0;
}
int devide(candidate &input,candidate &result,modifier &options) // sucht nach insertions und deletions
{
result.clear();
if(options.sd==0)
{
analyse(input);
}
else
{
input.e=options.e;
input.sd=options.sd;
}
for (unsigned i=0;i<input.length();i++)
{
if(input.len[i]<input.e-(options.x * input.sd))
{
result.len.push_back(input.len[i]);
result.pos.push_back(input.pos[i]);
result.ref.push_back(input.ref[i]);
result.type.push_back(candidate::d);
}
if(input.len[i]>input.e+(options.y * input.sd))
{
result.len.push_back(input.len[i]);
result.pos.push_back(input.pos[i]);
result.ref.push_back(input.ref[i]);
result.type.push_back(candidate::i);
}
}
return 0;
}
int tsv(std::vector<std::vector<unsigned>> &input,candidate &ref, char *out)
{
std::fstream outFile(out, std::ios::out);
int k=0;
if (!outFile)
{
std::cerr << "-ERROR- Could not open output file" << std::endl;
return 1;
}
else
{
if(!input.empty())
{
for (unsigned i=0;i<input.size();i++)
{
if(!input[i].empty())
{
outFile << "Cluster " << i-k+1 << ":\n";
for(auto j=input[i].begin();j != input[i].end();j++)
{
outFile << " " << ref.ref[*j] << " " << ref.pos[*j] << " " << ref.len[*j] << " " << (candidate::form)ref.type[*j] << std::endl;
}
}
else
{
k++;
}
}
}
}
outFile.close();
return 0;
}
int findCluster(candidate &input, std::vector<std::vector<unsigned> > &dest, candidate::form indel)
{
std::vector<unsigned> currentCluster;
unsigned currentClusterEndPos;
// Iterieren über alle Funde
for(unsigned i = 0; i < input.length(); ++i)
{
// Insertionen bzw. Deletionen herausfiltern
if(input.type[i] == indel)
{
if(currentCluster.empty())
{
// ersten Fund zu bisher leerem ersten Cluster hinzufügen
currentCluster.push_back(i);
currentClusterEndPos = input.pos[i] + input.len[i] - 1;
}
else
{
// Fall 1: Fund liegt innerhalb der Grenzen eines vorherigen Fundes
if(input.pos[i] + input.len[i] - 1 <= currentClusterEndPos){
currentCluster.push_back(i);
}
else
{
unsigned overlapLen = std::max((int)(currentClusterEndPos - input.pos[i] + 1), 0);
// Fall 2: Fund überlappt ausreichend mit dem Cluster
if(overlapLen / std::min(currentClusterEndPos - input.pos[currentCluster.back()] + 1, input.pos[i] + input.len[i] - 1) > 0.5){
currentCluster.push_back(i);
}
// Fall 3: Fund überlappt nicht ausreichend mit dem Cluster
else
{
dest.push_back(currentCluster);
currentCluster.clear();
currentCluster.push_back(i);
}
currentClusterEndPos = input.pos[i] + input.len[i] - 1;
}
}
}
}
dest.push_back(currentCluster);
return 0;
}
SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_input)
{
candidate test;
char *file ="/Informatik/Development/test.sam";
SEQAN_ASSERT(!saminput(test,file));
}
SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_input2)
{
candidate test;
char *file =" ";
SEQAN_ASSERT(saminput(test,file));
}
SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_input3)
{
candidate test;
char *file ="2579816ß15362466183b513ü6ß148z5!§%%!&°%(!%§(%§c465cn4ü457346511425129562e85z148z5!§%%!&°%(!%§(%§&&&&&(";
SEQAN_ASSERT(saminput(test,file));
}
SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_devide)
{
candidate test,result;
modifier opt;
for(unsigned i=1;i<11;i++)
{
test.len.push_back(i);
test.ref.push_back(i);
test.pos.push_back(i);
test.type.push_back(candidate::u);
}
opt.e=5;
opt.sd=2;
<|fim▁hole|> devide(test,result,opt);
SEQAN_ASSERT_EQ(result.type[0],1);
SEQAN_ASSERT_EQ(result.ref[0],1);
SEQAN_ASSERT_EQ(result.type[1],1);
SEQAN_ASSERT_EQ(result.ref[1],2);
SEQAN_ASSERT_EQ(result.type[2],2);
SEQAN_ASSERT_EQ(result.ref[2],8);
SEQAN_ASSERT_EQ(result.type[3],2);
SEQAN_ASSERT_EQ(result.ref[3],9);
SEQAN_ASSERT_EQ(result.type[4],2);
SEQAN_ASSERT_EQ(result.ref[4],10);
}
SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_median)
{
candidate test;
for(unsigned i=1;i<101;i++)
{
test.len.push_back(i);
}
median(test)
SEQAN_ASSERT_EQ(test.e,50);
}
SEQAN_BEGIN_TESTSUITE(test_my_app_funcs)
{
SEQAN_CALL_TEST(test_my_app_PEMer_Lite_median);
SEQAN_CALL_TEST(test_my_app_PEMer_Lite_input);
SEQAN_CALL_TEST(test_my_app_PEMer_Lite_input2);
SEQAN_CALL_TEST(test_my_app_PEMer_Lite_input3);
SEQAN_CALL_TEST(test_my_app_PEMer_Lite_devide);
}
SEQAN_END_TESTSUITE<|fim▁end|> | |
<|file_name|>STATIC_TEMPLATE_MEMBER_INIT.cpp<|end_file_name|><|fim▁begin|>// checking initialization of static template data memebers
template <class T>
struct S
{
static T a;<|fim▁hole|>};
template <class T>
T S<T>::a; // <-- NOT initialized
template <class T>
T S<T>::b = 0; // <-- explicitly initialized
int main ()
{
// g++ on DEC OSF and IBM AIX fails to link
return S<char>::a + S<char>::b;
}<|fim▁end|> | static T b; |
<|file_name|>backdrop.js<|end_file_name|><|fim▁begin|>/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc5-master-76c6299
*/
goog.provide('ng.material.components.backdrop');
goog.require('ng.material.core');
/*
* @ngdoc module
* @name material.components.backdrop
* @description Backdrop
*/
/**
* @ngdoc directive
* @name mdBackdrop
* @module material.components.backdrop
*
* @restrict E
*
* @description
* `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet.<|fim▁hole|>angular
.module('material.components.backdrop', ['material.core'])
.directive('mdBackdrop', ["$mdTheming", "$animate", "$rootElement", "$window", "$log", "$$rAF", "$document", function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) {
var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container.";
return {
restrict: 'E',
link: postLink
};
function postLink(scope, element, attrs) {
// If body scrolling has been disabled using mdUtil.disableBodyScroll(),
// adjust the 'backdrop' height to account for the fixed 'body' top offset
var body = $window.getComputedStyle($document[0].body);
if (body.position == 'fixed') {
var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10));
element.css({
height: hViewport + 'px'
});
}
// backdrop may be outside the $rootElement, tell ngAnimate to animate regardless
if ($animate.pin) $animate.pin(element, $rootElement);
$$rAF(function () {
// Often $animate.enter() is used to append the backDrop element
// so let's wait until $animate is done...
var parent = element.parent()[0];
if (parent) {
if ( parent.nodeName == 'BODY' ) {
element.css({position : 'fixed'});
}
var styles = $window.getComputedStyle(parent);
if (styles.position == 'static') {
// backdrop uses position:absolute and will not work properly with parent position:static (default)
$log.warn(ERROR_CSS_POSITION);
}
}
$mdTheming.inherit(element, element.parent());
});
}
}]);
ng.material.components.backdrop = angular.module("material.components.backdrop");<|fim▁end|> | * Apply class `opaque` to make the backdrop use the theme backdrop color.
*
*/
|
<|file_name|>ebill_payment_contract.py<|end_file_name|><|fim▁begin|># Copyright 2019 Camptocamp SA<|fim▁hole|>from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class EbillPaymentContract(models.Model):
_inherit = "ebill.payment.contract"
paynet_account_number = fields.Char(string="Paynet ID", size=20)
is_paynet_contract = fields.Boolean(
compute="_compute_is_paynet_contract", store=False
)
paynet_service_id = fields.Many2one(
comodel_name="paynet.service", string="Paynet Service", ondelete="restrict"
)
payment_type = fields.Selection(
selection=[("qr", "QR"), ("isr", "ISR")],
string="Payment method",
default="qr",
help="Payment type to use for the invoices sent,"
" PDF will be generated and attached accordingly.",
)
@api.depends("transmit_method_id")
def _compute_is_paynet_contract(self):
transmit_method = self.env.ref("ebill_paynet.paynet_transmit_method")
for record in self:
record.is_paynet_contract = record.transmit_method_id == transmit_method
@api.constrains("transmit_method_id", "paynet_account_number")
def _check_paynet_account_number(self):
for contract in self:
if not contract.is_paynet_contract:
continue
if not contract.paynet_account_number:
raise ValidationError(
_("The Paynet ID is required for a Paynet contract.")
)
@api.constrains("transmit_method_id", "paynet_service_id")
def _check_paynet_service_id(self):
for contract in self:
if contract.is_paynet_contract and not contract.paynet_service_id:
raise ValidationError(
_("A Paynet service is required for a Paynet contract.")
)<|fim▁end|> | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
|
<|file_name|>custom_landing_pages_test.py<|end_file_name|><|fim▁begin|># Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for custom landing pages."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.tests import test_utils
import feconf
class FractionLandingRedirectPageTest(test_utils.GenericTestBase):
"""Test for redirecting landing page for fractions."""
def test_old_fractions_landing_url_without_viewer_type(self):
"""Test to validate the old Fractions landing url without viewerType
redirects to the new Fractions landing url.
"""
response = self.get_html_response(
feconf.FRACTIONS_LANDING_PAGE_URL, expected_status_int=302)
self.assertEqual(
'http://localhost/math/fractions',
response.headers['location'])
def test_old_fraction_landing_url_with_viewer_type(self):
"""Test to validate the old Fractions landing url with viewerType
redirects to the new Fractions landing url.
"""
response = self.get_html_response(
'%s?viewerType=student' % feconf.FRACTIONS_LANDING_PAGE_URL,
expected_status_int=302)
self.assertEqual(
'http://localhost/math/fractions',
response.headers['location'])
class TopicLandingRedirectPageTest(test_utils.GenericTestBase):
"""Test for redirecting the old landing page URL to the new one."""
def test_old_topic_url_redirect(self):
response = self.get_html_response(
'/learn/maths/fractions', expected_status_int=302)
self.assertEqual(
'http://localhost/math/fractions', response.headers['location'])
class TopicLandingPageTest(test_utils.GenericTestBase):
"""Test for showing landing pages."""
def test_valid_subject_and_topic_loads_correctly(self):
response = self.get_html_response('/math/fractions')
response.mustcontain('<topic-landing-page></topic-landing-page>')
class StewardsLandingPageTest(test_utils.GenericTestBase):
"""Test for showing the landing page for stewards (parents, teachers,
volunteers, or NGOs).
"""
def test_nonprofits_landing_page(self):
response = self.get_html_response(
feconf.CUSTOM_NONPROFITS_LANDING_PAGE_URL)
response.mustcontain(
'<stewards-landing-page></stewards-landing-page>')<|fim▁hole|> response.mustcontain(
'<stewards-landing-page></stewards-landing-page>')
def test_teachers_landing_page(self):
response = self.get_html_response(
feconf.CUSTOM_TEACHERS_LANDING_PAGE_URL)
response.mustcontain('<stewards-landing-page></stewards-landing-page>')
def test_volunteers_landing_page(self):
response = self.get_html_response(
feconf.CUSTOM_VOLUNTEERS_LANDING_PAGE_URL)
response.mustcontain('<stewards-landing-page></stewards-landing-page>')<|fim▁end|> |
def test_parents_landing_page(self):
response = self.get_html_response(
feconf.CUSTOM_PARENTS_LANDING_PAGE_URL) |
<|file_name|>bitcoin_lt.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="lt" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About LahCoin</source>
<translation>Apie LahCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>LahCoin</b> version</source>
<translation><b>LahCoin</b> versija</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>Tai eksperimentinė programa.
Platinama pagal MIT/X11 licenciją, kurią rasite faile COPYING arba http://www.opensource.org/licenses/mit-license.php.
Šiame produkte yra OpenSSL projekto kuriamas OpenSSL Toolkit (http://www.openssl.org/), Eric Young parašyta kriptografinė programinė įranga bei Thomas Bernard sukurta UPnP programinė įranga.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The LahCoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresų knygelė</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Spragtelėkite, kad pakeistumėte adresą arba žymę</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Sukurti naują adresą</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopijuoti esamą adresą į mainų atmintį</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Naujas adresas</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your LahCoin 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>Tai yra jūsų LahCoin adresai mokėjimų gavimui. Galite duoti skirtingus adresus atskiriems siuntėjams, kad galėtumėte sekti, kas jums moka.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopijuoti adresą</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Rodyti &QR kodą</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a LahCoin address</source>
<translation>Pasirašykite žinutę, kad įrodytume, jog esate LahCoin adreso savininkas</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Registruoti praneši&mą</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified LahCoin address</source>
<translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas LahCoin adresas</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Tikrinti žinutę</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Trinti</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your LahCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopijuoti ž&ymę</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Keisti</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportuoti adresų knygelės duomenis</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kableliais išskirtas failas (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Eksportavimo klaida</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nepavyko įrašyti į failą %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Žymė</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(nėra žymės)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Slaptafrazės dialogas</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Įvesti slaptafrazę</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nauja slaptafrazė</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Pakartokite naują slaptafrazę</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>Įveskite naują piniginės slaptafrazę.<br/>Prašome naudoti slaptafrazę iš <b> 10 ar daugiau atsitiktinių simbolių</b> arba <b>aštuonių ar daugiau žodžių</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Užšifruoti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai atrakinti.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Atrakinti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai iššifruoti.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Iššifruoti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Pakeisti slaptafrazę</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Įveskite seną ir naują piniginės slaptafrazes.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Patvirtinkite piniginės užšifravimą</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LahCoinS</b>!</source>
<translation>Dėmesio: jei užšifruosite savo piniginę ir pamesite slaptafrazę, jūs<b>PRARASITE VISUS SAVO LahCoinUS</b>! </translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Ar tikrai norite šifruoti savo piniginę?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Įspėjimas: įjungtas Caps Lock klavišas!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Piniginė užšifruota</translation>
</message>
<message>
<location line="-56"/>
<source>LahCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your LahCoins from being stolen by malware infecting your computer.</source>
<translation>LahCoin dabar užsidarys šifravimo proceso pabaigai. Atminkite, kad piniginės šifravimas negali pilnai apsaugoti LahCoinų vagysčių kai tinkle esančios kenkėjiškos programos patenka į jūsų kompiuterį.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Nepavyko užšifruoti piniginę</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dėl vidinės klaidos nepavyko užšifruoti piniginę.Piniginė neužšifruota.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Įvestos slaptafrazės nesutampa.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Nepavyko atrakinti piniginę</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Neteisingai įvestas slaptažodis piniginės iššifravimui.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Nepavyko iššifruoti piniginės</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Piniginės slaptažodis sėkmingai pakeistas.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Pasirašyti ži&nutę...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sinchronizavimas su tinklu ...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Apžvalga</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Rodyti piniginės bendrą apžvalgą</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Sandoriai</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Apžvelgti sandorių istoriją</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels for sending</source>
<translation>Redaguoti išsaugotus adresus bei žymes</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Parodyti adresų sąraša mokėjimams gauti</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Išeiti</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Išjungti programą</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about LahCoin</source>
<translation>Rodyti informaciją apie LahCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Apie &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Rodyti informaciją apie Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Parinktys...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Užšifruoti piniginę...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup piniginę...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Keisti slaptafrazę...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a LahCoin address</source>
<translation>Siųsti monetas LahCoin adresui</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for LahCoin</source>
<translation>Keisti LahCoin konfigūracijos galimybes</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Daryti piniginės atsarginę kopiją</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Pakeisti slaptafrazę naudojamą piniginės užšifravimui</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Derinimo langas</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Atverti derinimo ir diagnostikos konsolę</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Tikrinti žinutę...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>LahCoin</source>
<translation>LahCoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Piniginė</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About LahCoin</source>
<translation>&Apie LahCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Rodyti / Slėpti</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your LahCoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified LahCoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Failas</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Nustatymai</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Pagalba</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Kortelių įrankinė</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testavimotinklas]</translation>
</message>
<message>
<location line="+47"/>
<source>LahCoin client</source>
<translation>LahCoin klientas</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to LahCoin network</source>
<translation><numerusform>%n LahCoin tinklo aktyvus ryšys</numerusform><numerusform>%n LahCoin tinklo aktyvūs ryšiai</numerusform><numerusform>%n LahCoin tinklo aktyvūs ryšiai</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Atnaujinta</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Vejamasi...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Patvirtinti sandorio mokestį</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sandoris nusiųstas</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Ateinantis sandoris</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Suma: %2
Tipas: %3
Adresas: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI apdorojimas</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid LahCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Piniginė <b>užšifruota</b> ir šiuo metu <b>atrakinta</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Piniginė <b>užšifruota</b> ir šiuo metu <b>užrakinta</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. LahCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Tinklo įspėjimas</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Keisti adresą</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>Ž&ymė</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Žymė yra susieta su šios adresų knygelęs turiniu</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresas</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adresas yra susietas su šios adresų knygelęs turiniu. Tai gali būti keičiama tik siuntimo adresams.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Naujas gavimo adresas</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Naujas siuntimo adresas</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Keisti gavimo adresą</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Keisti siuntimo adresą</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Įvestas adresas „%1“ jau yra adresų knygelėje.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid LahCoin address.</source>
<translation>Įvestas adresas „%1“ nėra galiojantis LahCoin adresas.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Nepavyko atrakinti piniginės.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Naujo rakto generavimas nepavyko.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>LahCoin-Qt</source>
<translation>LahCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versija</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Naudojimas:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komandinės eilutės parametrai</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Naudotoji sąsajos parametrai</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Nustatyti kalbą, pavyzdžiui "lt_LT" (numatyta: sistemos kalba)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Paleisti sumažintą</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Parinktys</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Pagrindinės</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>&Mokėti sandorio mokestį</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start LahCoin after logging in to the system.</source>
<translation>Automatiškai paleisti Bitkoin programą įjungus sistemą.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start LahCoin on system login</source>
<translation>&Paleisti LahCoin programą su window sistemos paleidimu</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Tinklas</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the LahCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatiškai atidaryti LahCoin kliento prievadą maršrutizatoriuje. Tai veikia tik tada, kai jūsų maršrutizatorius palaiko UPnP ir ji įjungta.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Persiųsti prievadą naudojant &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the LahCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Jungtis į Bitkoin tinklą per socks proxy (pvz. jungiantis per Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Jungtis per SOCKS tarpinį serverį:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Tarpinio serverio &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Tarpinio serverio IP adresas (pvz. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Prievadas:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Tarpinio serverio preivadas (pvz, 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &versija:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Tarpinio serverio SOCKS versija (pvz., 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Langas</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Po programos lango sumažinimo rodyti tik programos ikoną.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&M sumažinti langą bet ne užduočių juostą</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Uždarant langą neuždaryti programos. Kai ši parinktis įjungta, programa bus uždaryta tik pasirinkus meniu komandą Baigti.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>&Sumažinti uždarant</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Rodymas</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Naudotojo sąsajos &kalba:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting LahCoin.</source>
<translation>Čia gali būti nustatyta naudotojo sąsajos kalba. Šis nustatymas įsigalios iš naujo paleidus LahCoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Vienetai, kuriais rodyti sumas:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Rodomų ir siunčiamų monetų kiekio matavimo vienetai</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show LahCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Rodyti adresus sandorių sąraše</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Gerai</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Atšaukti</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Pritaikyti</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>numatyta</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Įspėjimas</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting LahCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Nurodytas tarpinio serverio adresas negalioja.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the LahCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Balansas:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Nepatvirtinti:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Piniginė</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Nepribrendę:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Naujausi sandoriai</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Jūsų einamasis balansas</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Iš viso sandorių, įskaitant tuos kurie dar turi būti patvirtinti, ir jie dar nėra įskaičiuotii į einamosios sąskaitos balansą</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start LahCoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR kodo dialogas</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Prašau išmokėti</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Suma:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Žymė:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Žinutė:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>Į&rašyti kaip...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Klaida, koduojant URI į QR kodą.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Įvesta suma neteisinga, prašom patikrinti.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Įrašyti QR kodą</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG paveikslėliai (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Kliento pavadinimas</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>nėra</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Kliento versija</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informacija</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Naudojama OpenSSL versija</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Paleidimo laikas</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Tinklas</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Prisijungimų kiekis</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testnete</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokų grandinė</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Dabartinis blokų skaičius</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Paskutinio bloko laikas</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Atverti</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komandinės eilutės parametrai</translation>
</message>
<message>
<location line="+7"/>
<source>Show the LahCoin-Qt help message to get a list with possible LahCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Rodyti</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsolė</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kompiliavimo data</translation>
</message>
<message>
<location line="-104"/>
<source>LahCoin - Debug window</source>
<translation>LahCoin - Derinimo langas</translation>
</message>
<message>
<location line="+25"/>
<source>LahCoin Core</source>
<translation>LahCoin branduolys</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Derinimo žurnalo failas</translation>
</message>
<message>
<location line="+7"/>
<source>Open the LahCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Išvalyti konsolę</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the LahCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Siųsti monetas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Siųsti keliems gavėjams vienu metu</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&A Pridėti gavėją</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Pašalinti visus sandorio laukus</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Išvalyti &viską</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balansas:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Patvirtinti siuntimo veiksmą</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Siųsti</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Patvirtinti monetų siuntimą</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ar tikrai norite siųsti %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> ir </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Negaliojantis gavėjo adresas. Patikrinkite.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Apmokėjimo suma turi būti didesnė nei 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Suma viršija jūsų balansą.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Jei pridedame sandorio mokestį %1 bendra suma viršija jūsų balansą.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Rastas adreso dublikatas.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Klaida: sandoris buvo atmestas.Tai gali įvykti, jei kai kurios monetos iš jūsų piniginėje jau buvo panaudotos, pvz. jei naudojote wallet.dat kopiją ir monetos buvo išleistos kopijoje, bet nepažymėtos kaip skirtos išleisti čia.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message><|fim▁hole|> <message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Su&ma:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Mokėti &gavėjui:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Įveskite žymę šiam adresui kad galėtumėte įtraukti ją į adresų knygelę</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>Ž&ymė:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Pasirinkite adresą iš adresų knygelės</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Įvesti adresą iš mainų atminties</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Pašalinti šį gavėją</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a LahCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Pasirašyti žinutę</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Pasirinkite adresą iš adresų knygelės</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Įvesti adresą iš mainų atminties</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Įveskite pranešimą, kurį norite pasirašyti čia</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this LahCoin address</source>
<translation>Registruotis žinute įrodymuii, kad turite šį adresą</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Išvalyti &viską</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Patikrinti žinutę</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified LahCoin address</source>
<translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas LahCoin adresas</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a LahCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Spragtelėkite "Registruotis žinutę" tam, kad gauti parašą</translation>
</message>
<message>
<location line="+3"/>
<source>Enter LahCoin signature</source>
<translation>Įveskite LahCoin parašą</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Įvestas adresas negalioja.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Prašom patikrinti adresą ir bandyti iš naujo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Piniginės atrakinimas atšauktas.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Žinutės pasirašymas nepavyko.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Žinutė pasirašyta.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Nepavyko iškoduoti parašo.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Prašom patikrinti parašą ir bandyti iš naujo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Parašas neatitinka žinutės.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Žinutės tikrinimas nepavyko.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Žinutė patikrinta.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The LahCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testavimotinklas]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Atidaryta iki %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/neprisijungęs</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nepatvirtintas</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 patvirtinimų</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Būsena</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Šaltinis</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Sugeneruotas</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Nuo</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Kam</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>savo adresas</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>žymė</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kreditas</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>nepriimta</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debitas</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Sandorio mokestis</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Neto suma</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Žinutė</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Komentaras</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Sandorio ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 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, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Išgautos monetos turi sulaukti 120 blokų, kol jos gali būti naudojamos. Kai sukūrėte šį bloką, jis buvo transliuojamas tinkle ir turėjo būti įtrauktas į blokų grandinę. Jei nepavyksta patekti į grandinę, bus pakeista į "nepriėmė", o ne "vartojamas". Tai kartais gali atsitikti, jei kitas mazgas per keletą sekundžių sukuria bloką po jūsų bloko.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Derinimo informacija</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Sandoris</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>tiesa</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>netiesa</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, transliavimas dar nebuvo sėkmingas</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nežinomas</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Sandorio detelės</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Šis langas sandorio detalų aprašymą</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipas</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Atidaryta iki %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Atjungta (%1 patvirtinimai)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Nepatvirtintos (%1 iš %2 patvirtinimų)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Patvirtinta (%1 patvirtinimai)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Šis blokas negautas nė vienu iš mazgų ir matomai nepriimtas</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Išgauta bet nepriimta</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Gauta su</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Gauta iš</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Siųsta </translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Mokėjimas sau</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Išgauta</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>nepasiekiama</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Sandorio būklė. Užvedus pelės žymeklį ant šios srities matysite patvirtinimų skaičių.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Sandorio gavimo data ir laikas</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Sandorio tipas.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Sandorio paskirties adresas</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Suma pridėta ar išskaičiuota iš balanso</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Visi</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Šiandien</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Šią savaitę</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Šį mėnesį</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Paskutinį mėnesį</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Šiais metais</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervalas...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Gauta su</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Išsiųsta</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Skirta sau</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Išgauta</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Kita</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Įveskite adresą ar žymę į paiešką</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimali suma</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopijuoti adresą</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopijuoti žymę</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopijuoti sumą</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Taisyti žymę</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Rodyti sandėrio detales</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Sandorio duomenų eksportavimas</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kableliais atskirtų duomenų failas (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Patvirtintas</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipas</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Žymė</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eksportavimo klaida</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Neįmanoma įrašyti į failą %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Grupė:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>skirta</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Siųsti monetas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>LahCoin version</source>
<translation>LahCoin versija</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Naudojimas:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or LahCoind</source>
<translation>Siųsti komandą serveriui arba LahCoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Komandų sąrašas</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Suteikti pagalba komandai</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Parinktys:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: LahCoin.conf)</source>
<translation>Nurodyti konfigūracijos failą (pagal nutylėjimąt: LahCoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: LahCoind.pid)</source>
<translation>Nurodyti pid failą (pagal nutylėjimą: LahCoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Nustatyti duomenų aplanką</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 22556 or testnet: 44556)</source>
<translation>Sujungimo klausymas prijungčiai <port> (pagal nutylėjimą: 22556 arba testnet: 44556)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Palaikyti ne daugiau <n> jungčių kolegoms (pagal nutylėjimą: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Atjungimo dėl netinkamo kolegų elgesio riba (pagal nutylėjimą: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Sekundžių kiekis eikiamas palaikyti ryšį dėl lygiarangių nestabilumo (pagal nutylėjimą: 86.400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 22555 or testnet: 44555)</source>
<translation>Klausymas JSON-RPC sujungimui prijungčiai <port> (pagal nutylėjimą: 22555 or testnet: 44555)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Priimti komandinę eilutę ir JSON-RPC komandas</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Dirbti fone kaip šešėlyje ir priimti komandas</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Naudoti testavimo tinklą</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=LahCoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "LahCoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. LahCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Įspėjimas: -paytxfee yra nustatytas per didelis. Tai sandorio mokestis, kurį turėsite mokėti, jei siųsite sandorį.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong LahCoin will not work properly.</source>
<translation>Įspėjimas: Patikrinkite, kad kompiuterio data ir laikas yra teisingi.Jei Jūsų laikrodis neteisingai nustatytas LahCoin, veiks netinkamai.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Prisijungti tik prie nurodyto mazgo</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Neteisingas tor adresas: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maksimalus buferis priėmimo sujungimui <n>*1000 bitų (pagal nutylėjimą: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maksimalus buferis siuntimo sujungimui <n>*1000 bitų (pagal nutylėjimą: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Išvesti papildomą derinimo informaciją. Numanomi visi kiti -debug* parametrai</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Išvesti papildomą tinklo derinimo informaciją</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation>Prideėti laiko žymę derinimo rezultatams</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the LahCoin Wiki for SSL setup instructions)</source>
<translation>SSL opcijos (žr.e LahCoin Wiki for SSL setup instructions)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Siųsti atsekimo/derinimo info į konsolę vietoj debug.log failo</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Siųsti sekimo/derinimo info derintojui</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Nustatyti sujungimo trukmę milisekundėmis (pagal nutylėjimą: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Vartotojo vardas JSON-RPC jungimuisi</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Slaptažodis JSON-RPC sujungimams</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Leisti JSON-RPC tik iš nurodytų IP adresų</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Siųsti komandą mazgui dirbančiam <ip> (pagal nutylėjimą: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Atnaujinti piniginę į naujausią formatą</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Nustatyti rakto apimties dydį <n> (pagal nutylėjimą: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Ieškoti prarastų piniginės sandorių blokų grandinėje</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Naudoti OpenSSL (https) jungimuisi JSON-RPC </translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Serverio sertifikato failas (pagal nutylėjimą: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Serverio privatus raktas (pagal nutylėjimą: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Priimtini šifrai (pagal nutylėjimą: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Pagelbos žinutė</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Nepavyko susieti šiame kompiuteryje prievado %s (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Jungtis per socks tarpinį serverį</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Leisti DNS paiešką sujungimui ir mazgo pridėjimui</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Užkraunami adresai...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation> wallet.dat pakrovimo klaida, wallet.dat sugadintas</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of LahCoin</source>
<translation> wallet.dat pakrovimo klaida, wallet.dat reikalauja naujasnės LahCoin versijos</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart LahCoin to complete</source>
<translation>Piniginė turi būti prrašyta: įvykdymui perkraukite LahCoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation> wallet.dat pakrovimo klaida</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Neteisingas proxy adresas: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Neteisinga suma -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Neteisinga suma</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Nepakanka lėšų</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Įkeliamas blokų indeksas...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Pridėti mazgą prie sujungti su and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. LahCoin is probably already running.</source>
<translation>Nepavyko susieti šiame kompiuteryje prievado %s. LahCoin tikriausiai jau veikia.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Įtraukti mokestį už kB siunčiamiems sandoriams</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Užkraunama piniginė...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Peržiūra</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Įkėlimas baigtas</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Klaida</translation>
</message>
<message>
<location line="-31"/>
<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 type="unfinished"/>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>build.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::process::Command;
use std::env;
fn main() {
assert!(Command::new("make")
.args(&["-f", "makefile.cargo"])
.status()
.unwrap()
.success());
println!("cargo:rustc-flags=-L native={}", env::var("OUT_DIR").unwrap());
}<|fim▁end|> | /* 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_name|>PracticeQuestions.py<|end_file_name|><|fim▁begin|>"""Chapter 22 Practice Questions
Answers Chapter 22 Practice Questions via Python code.<|fim▁hole|>
from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage
def main():
# 1. How many prime numbers are there?
# Hint: Check page 322
message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 2. What are integers that are not prime called?
# Hint: Check page 323
message = "Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd." # Encrypted with key "NOTCALLEDEVENS"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 3. What are two algorithms for finding prime numbers?
# Hint: Check page 323
# Encrypted with key "ALGORITHMS"
message = "Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mkhfgsenseml, hzv Rlhwe-Ubsxwr."
#print(decryptMessage(blank, blank)) # Fill in the blanks
# If PracticeQuestions.py is run (instead of imported as a module), call
# the main() function:
if __name__ == '__main__':
main()<|fim▁end|> | """ |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// SPDX-License-Identifier: Unlicense
mod device;
mod handler;
mod pager;
const UPPER_VA_BITS: usize = 39; // 512 GB, avoids 1 level
const LOWER_VA_BITS: usize = 48; // 256 TB
/// Live hardware abstraction layer for integration tests and releases.
#[cfg(not(test))]
mod hal;
/// Mock hardware abstraction layer for unit tests.
#[cfg(test)]
mod hal_test;
/// Publish hardware abstraction layer for unit tests.
#[cfg(test)]
use hal_test as hal;
/// Materialise empty struct implementing Arch trait.
pub struct Arch {}
#[cfg(not(test))]
pub use hal::reset;
/// Construct an empty page directory.
pub fn new_page_directory() -> impl super::PageDirectory {
pager::new_page_directory()
}
#[cfg(not(test))]
pub use hal::core_id;
#[cfg(test)]<|fim▁hole|>
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_use() {
assert_eq!(LOWER_VA_BITS, 48)
}
}<|fim▁end|> | pub use hal_test::core_id;
pub use pager::PageBlockDescriptor;
pub use pager::PageDirectory; |
<|file_name|>metrics.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::cell::RefCell;
use std::mem;
use crate::storage::{kv::PerfStatisticsDelta, FlowStatsReporter, Statistics};
use collections::HashMap;
use kvproto::metapb;
use raftstore::store::util::build_key_range;
use raftstore::store::ReadStats;
use crate::server::metrics::{GcKeysCF, GcKeysDetail};
use prometheus::*;
use prometheus_static_metric::*;
make_auto_flush_static_metric! {
pub label_enum ReqTag {
select,
index,
analyze_table,
analyze_index,
checksum_table,
checksum_index,
test,
}
pub label_enum CF {
default,
lock,
write,
}
pub label_enum ScanKeysKind {
processed_keys,
total,
}
pub label_enum ScanKind {
processed_keys,
get,
next,
prev,
seek,
seek_for_prev,
over_seek_bound,
next_tombstone,
prev_tombstone,
seek_tombstone,
seek_for_prev_tombstone,
ttl_tombstone,
}
pub label_enum WaitType {
all,
schedule,
snapshot,
}
pub label_enum PerfMetric {
user_key_comparison_count,
block_cache_hit_count,
block_read_count,
block_read_byte,
block_read_time,
block_cache_index_hit_count,
index_block_read_count,
block_cache_filter_hit_count,
filter_block_read_count,
block_checksum_time,
block_decompress_time,
get_read_bytes,
iter_read_bytes,
internal_key_skipped_count,
internal_delete_skipped_count,
internal_recent_skipped_count,
get_snapshot_time,
get_from_memtable_time,
get_from_memtable_count,
get_post_process_time,
get_from_output_files_time,
seek_on_memtable_time,
seek_on_memtable_count,
next_on_memtable_count,
prev_on_memtable_count,
seek_child_seek_time,
seek_child_seek_count,
seek_min_heap_time,
seek_max_heap_time,
seek_internal_seek_time,
db_mutex_lock_nanos,
db_condition_wait_nanos,
read_index_block_nanos,
read_filter_block_nanos,
new_table_block_iter_nanos,
new_table_iterator_nanos,
block_seek_nanos,
find_table_nanos,
bloom_memtable_hit_count,
bloom_memtable_miss_count,
bloom_sst_hit_count,
bloom_sst_miss_count,
get_cpu_nanos,
iter_next_cpu_nanos,
iter_prev_cpu_nanos,
iter_seek_cpu_nanos,
encrypt_data_nanos,
decrypt_data_nanos,
}
pub label_enum MemLockCheckResult {
unlocked,
locked,
}
pub struct CoprReqHistogram: LocalHistogram {
"req" => ReqTag,
}
pub struct ReqWaitHistogram: LocalHistogram {
"req" => ReqTag,
"type" => WaitType,
}
pub struct PerfCounter: LocalIntCounter {
"req" => ReqTag,
"metric" => PerfMetric,
}
pub struct CoprScanKeysHistogram: LocalHistogram {
"req" => ReqTag,
"kind" => ScanKeysKind,
}
pub struct CoprScanDetails : LocalIntCounter {
"req" => ReqTag,
"cf" => CF,
"tag" => ScanKind,
}
pub struct MemLockCheckHistogramVec: LocalHistogram {
"result" => MemLockCheckResult,
}
}
lazy_static! {
pub static ref COPR_REQ_HISTOGRAM_VEC: HistogramVec = register_histogram_vec!(
"tikv_coprocessor_request_duration_seconds",
"Bucketed histogram of coprocessor request duration",
&["req"],
exponential_buckets(0.0005, 2.0, 20).unwrap()
)
.unwrap();
pub static ref COPR_REQ_HISTOGRAM_STATIC: CoprReqHistogram =
auto_flush_from!(COPR_REQ_HISTOGRAM_VEC, CoprReqHistogram);
pub static ref COPR_REQ_HANDLE_TIME: HistogramVec = register_histogram_vec!(
"tikv_coprocessor_request_handle_seconds",
"Bucketed histogram of coprocessor handle request duration",
&["req"],
exponential_buckets(0.0005, 2.0, 20).unwrap()
)
.unwrap();
pub static ref COPR_REQ_HANDLE_TIME_STATIC: CoprReqHistogram =
auto_flush_from!(COPR_REQ_HANDLE_TIME, CoprReqHistogram);
pub static ref COPR_REQ_WAIT_TIME: HistogramVec = register_histogram_vec!(
"tikv_coprocessor_request_wait_seconds",
"Bucketed histogram of coprocessor request wait duration",
&["req", "type"],
exponential_buckets(0.0005, 2.0, 20).unwrap()
)
.unwrap();
pub static ref COPR_REQ_WAIT_TIME_STATIC: ReqWaitHistogram =
auto_flush_from!(COPR_REQ_WAIT_TIME, ReqWaitHistogram);
pub static ref COPR_REQ_HANDLER_BUILD_TIME: HistogramVec = register_histogram_vec!(
"tikv_coprocessor_request_handler_build_seconds",
"Bucketed histogram of coprocessor request handler build duration",
&["req"],
exponential_buckets(0.0005, 2.0, 20).unwrap()
)
.unwrap();
pub static ref COPR_REQ_HANDLER_BUILD_TIME_STATIC: CoprReqHistogram =
auto_flush_from!(COPR_REQ_HANDLER_BUILD_TIME, CoprReqHistogram);
pub static ref COPR_REQ_ERROR: IntCounterVec = register_int_counter_vec!(
"tikv_coprocessor_request_error",
"Total number of push down request error.",
&["reason"]
)
.unwrap();
pub static ref COPR_SCAN_KEYS: HistogramVec = register_histogram_vec!(
"tikv_coprocessor_scan_keys",
"Bucketed histogram of coprocessor per request scan keys",
&["req", "kind"],
exponential_buckets(1.0, 2.0, 20).unwrap()
)
.unwrap();
pub static ref COPR_SCAN_KEYS_STATIC: CoprScanKeysHistogram =
auto_flush_from!(COPR_SCAN_KEYS, CoprScanKeysHistogram);
pub static ref COPR_SCAN_DETAILS: IntCounterVec = register_int_counter_vec!(
"tikv_coprocessor_scan_details",
"Bucketed counter of coprocessor scan details for each CF",
&["req", "cf", "tag"]
)
.unwrap();
pub static ref COPR_SCAN_DETAILS_STATIC: CoprScanDetails =
auto_flush_from!(COPR_SCAN_DETAILS, CoprScanDetails);
pub static ref COPR_ROCKSDB_PERF_COUNTER: IntCounterVec = register_int_counter_vec!(
"tikv_coprocessor_rocksdb_perf",
"Total number of RocksDB internal operations from PerfContext",
&["req", "metric"]
)
.unwrap();
pub static ref COPR_ROCKSDB_PERF_COUNTER_STATIC: PerfCounter =
auto_flush_from!(COPR_ROCKSDB_PERF_COUNTER, PerfCounter);
pub static ref COPR_DAG_REQ_COUNT: IntCounterVec = register_int_counter_vec!(
"tikv_coprocessor_dag_request_count",
"Total number of DAG requests",
&["vec_type"]
)
.unwrap();
pub static ref COPR_RESP_SIZE: IntCounter = register_int_counter!(
"tikv_coprocessor_response_bytes",
"Total bytes of response body"
)
.unwrap();
pub static ref COPR_ACQUIRE_SEMAPHORE_TYPE: CoprAcquireSemaphoreTypeCounterVec =
register_static_int_counter_vec!(
CoprAcquireSemaphoreTypeCounterVec,
"tikv_coprocessor_acquire_semaphore_type",
"The acquire type of the coprocessor semaphore",
&["type"],
)
.unwrap();
pub static ref COPR_WAITING_FOR_SEMAPHORE: IntGauge = register_int_gauge!(
"tikv_coprocessor_waiting_for_semaphore",
"The number of tasks waiting for the semaphore"
)
.unwrap();
pub static ref MEM_LOCK_CHECK_HISTOGRAM_VEC: HistogramVec =
register_histogram_vec!(
"tikv_coprocessor_mem_lock_check_duration_seconds",
"Duration of memory lock checking for coprocessor",
&["result"],
exponential_buckets(1e-6f64, 4f64, 10).unwrap() // 1us ~ 262ms
)
.unwrap();
pub static ref MEM_LOCK_CHECK_HISTOGRAM_VEC_STATIC: MemLockCheckHistogramVec =
auto_flush_from!(MEM_LOCK_CHECK_HISTOGRAM_VEC, MemLockCheckHistogramVec);
}
make_static_metric! {
pub label_enum AcquireSemaphoreType {
unacquired,
acquired,
}
pub struct CoprAcquireSemaphoreTypeCounterVec: IntCounter {
"type" => AcquireSemaphoreType,
}
}
pub struct CopLocalMetrics {
local_scan_details: HashMap<ReqTag, Statistics>,
local_read_stats: ReadStats,
local_perf_stats: HashMap<ReqTag, PerfStatisticsDelta>,
}
thread_local! {
pub static TLS_COP_METRICS: RefCell<CopLocalMetrics> = RefCell::new(
CopLocalMetrics {
local_scan_details: HashMap::default(),
local_read_stats: ReadStats::default(),
local_perf_stats: HashMap::default(),
}
);
}
macro_rules! tls_flush_perf_stats {
($tag:ident, $local_stats:ident, $stat:ident) => {
COPR_ROCKSDB_PERF_COUNTER_STATIC
.get($tag)
.$stat
.inc_by($local_stats.0.$stat as i64);
};
}
impl From<GcKeysCF> for CF {
fn from(cf: GcKeysCF) -> CF {
match cf {
GcKeysCF::default => CF::default,
GcKeysCF::lock => CF::lock,
GcKeysCF::write => CF::write,
}
}
}
impl From<GcKeysDetail> for ScanKind {
fn from(detail: GcKeysDetail) -> ScanKind {
match detail {
GcKeysDetail::processed_keys => ScanKind::processed_keys,
GcKeysDetail::get => ScanKind::get,
GcKeysDetail::next => ScanKind::next,
GcKeysDetail::prev => ScanKind::prev,
GcKeysDetail::seek => ScanKind::seek,
GcKeysDetail::seek_for_prev => ScanKind::seek_for_prev,
GcKeysDetail::over_seek_bound => ScanKind::over_seek_bound,
GcKeysDetail::next_tombstone => ScanKind::next_tombstone,
GcKeysDetail::prev_tombstone => ScanKind::prev_tombstone,
GcKeysDetail::seek_tombstone => ScanKind::seek_tombstone,
GcKeysDetail::seek_for_prev_tombstone => ScanKind::seek_for_prev_tombstone,
GcKeysDetail::ttl_tombstone => ScanKind::ttl_tombstone,
}
}
}
pub fn tls_flush<R: FlowStatsReporter>(reporter: &R) {
TLS_COP_METRICS.with(|m| {
// Flush Prometheus metrics
let mut m = m.borrow_mut();
for (req_tag, stat) in m.local_scan_details.drain() {
for (cf, cf_details) in stat.details_enum().iter() {
for (tag, count) in cf_details.iter() {
COPR_SCAN_DETAILS_STATIC
.get(req_tag)
.get((*cf).into())
.get((*tag).into())
.inc_by(*count as i64);
}
}
}
// Report PD metrics
if !m.local_read_stats.is_empty() {
let mut read_stats = ReadStats::default();
mem::swap(&mut read_stats, &mut m.local_read_stats);
reporter.report_read_stats(read_stats);
}
for (req_tag, perf_stats) in m.local_perf_stats.drain() {
tls_flush_perf_stats!(req_tag, perf_stats, user_key_comparison_count);
tls_flush_perf_stats!(req_tag, perf_stats, block_cache_hit_count);
tls_flush_perf_stats!(req_tag, perf_stats, block_read_count);
tls_flush_perf_stats!(req_tag, perf_stats, block_read_byte);
tls_flush_perf_stats!(req_tag, perf_stats, block_read_time);
tls_flush_perf_stats!(req_tag, perf_stats, block_cache_index_hit_count);
tls_flush_perf_stats!(req_tag, perf_stats, index_block_read_count);
tls_flush_perf_stats!(req_tag, perf_stats, block_cache_filter_hit_count);
tls_flush_perf_stats!(req_tag, perf_stats, filter_block_read_count);
tls_flush_perf_stats!(req_tag, perf_stats, block_checksum_time);
tls_flush_perf_stats!(req_tag, perf_stats, block_decompress_time);
tls_flush_perf_stats!(req_tag, perf_stats, get_read_bytes);
tls_flush_perf_stats!(req_tag, perf_stats, iter_read_bytes);
tls_flush_perf_stats!(req_tag, perf_stats, internal_key_skipped_count);
tls_flush_perf_stats!(req_tag, perf_stats, internal_delete_skipped_count);
tls_flush_perf_stats!(req_tag, perf_stats, internal_recent_skipped_count);
tls_flush_perf_stats!(req_tag, perf_stats, get_snapshot_time);<|fim▁hole|> tls_flush_perf_stats!(req_tag, perf_stats, get_from_memtable_time);
tls_flush_perf_stats!(req_tag, perf_stats, get_from_memtable_count);
tls_flush_perf_stats!(req_tag, perf_stats, get_post_process_time);
tls_flush_perf_stats!(req_tag, perf_stats, get_from_output_files_time);
tls_flush_perf_stats!(req_tag, perf_stats, seek_on_memtable_time);
tls_flush_perf_stats!(req_tag, perf_stats, seek_on_memtable_count);
tls_flush_perf_stats!(req_tag, perf_stats, next_on_memtable_count);
tls_flush_perf_stats!(req_tag, perf_stats, prev_on_memtable_count);
tls_flush_perf_stats!(req_tag, perf_stats, seek_child_seek_time);
tls_flush_perf_stats!(req_tag, perf_stats, seek_child_seek_count);
tls_flush_perf_stats!(req_tag, perf_stats, seek_min_heap_time);
tls_flush_perf_stats!(req_tag, perf_stats, seek_max_heap_time);
tls_flush_perf_stats!(req_tag, perf_stats, seek_internal_seek_time);
tls_flush_perf_stats!(req_tag, perf_stats, db_mutex_lock_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, db_condition_wait_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, read_index_block_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, read_filter_block_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, new_table_block_iter_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, new_table_iterator_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, block_seek_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, find_table_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, bloom_memtable_hit_count);
tls_flush_perf_stats!(req_tag, perf_stats, bloom_memtable_miss_count);
tls_flush_perf_stats!(req_tag, perf_stats, bloom_sst_hit_count);
tls_flush_perf_stats!(req_tag, perf_stats, bloom_sst_miss_count);
tls_flush_perf_stats!(req_tag, perf_stats, get_cpu_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, iter_next_cpu_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, iter_prev_cpu_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, iter_seek_cpu_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, encrypt_data_nanos);
tls_flush_perf_stats!(req_tag, perf_stats, decrypt_data_nanos);
}
});
}
pub fn tls_collect_scan_details(cmd: ReqTag, stats: &Statistics) {
TLS_COP_METRICS.with(|m| {
m.borrow_mut()
.local_scan_details
.entry(cmd)
.or_insert_with(Default::default)
.add(stats);
});
}
pub fn tls_collect_read_flow(region_id: u64, statistics: &Statistics) {
TLS_COP_METRICS.with(|m| {
let mut m = m.borrow_mut();
m.local_read_stats.add_flow(
region_id,
&statistics.write.flow_stats,
&statistics.data.flow_stats,
);
});
}
pub fn tls_collect_qps(
region_id: u64,
peer: &metapb::Peer,
start_key: &[u8],
end_key: &[u8],
reverse_scan: bool,
) {
TLS_COP_METRICS.with(|m| {
let mut m = m.borrow_mut();
let key_range = build_key_range(start_key, end_key, reverse_scan);
m.local_read_stats.add_qps(region_id, peer, key_range);
});
}
pub fn tls_collect_perf_stats(cmd: ReqTag, perf_stats: &PerfStatisticsDelta) {
TLS_COP_METRICS.with(|m| {
*(m.borrow_mut()
.local_perf_stats
.entry(cmd)
.or_insert_with(Default::default)) += *perf_stats;
});
}<|fim▁end|> | |
<|file_name|>CXXII.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#----------------------------------------------------------------------------
#
# Copyright (C) 2015 José Flávio de Souza Dias Júnior
#
# This file is part of CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CXXII 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 CXXII. If not, see http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
#
# Direitos Autorais Reservados (C) 2015 José Flávio de Souza Dias Júnior
#
# Este arquivo é parte de CXXII - http://www.joseflavio.com/cxxii/
#
# CXXII é software livre: você pode redistribuí-lo e/ou modificá-lo
# sob os termos da Licença Pública Menos Geral GNU conforme publicada pela
# Free Software Foundation, tanto a versão 3 da Licença, como
# (a seu critério) qualquer versão posterior.
#
# CXXII é distribuído na expectativa de que seja útil,
# porém, SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
# COMERCIABILIDADE ou ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a
# Licença Pública Menos Geral do GNU para mais detalhes.
#
# Você deve ter recebido uma cópia da Licença Pública Menos Geral do GNU
# junto com CXXII. Se não, veja http://www.gnu.org/licenses/.
#
#----------------------------------------------------------------------------
# "Não vos conformeis com este mundo,
# mas transformai-vos pela renovação do vosso espírito,
# para que possais discernir qual é a vontade de Deus,
# o que é bom, o que lhe agrada e o que é perfeito."
# (Bíblia Sagrada, Romanos 12:2)
# "Do not conform yourselves to this age
# but be transformed by the renewal of your mind,
# that you may discern what is the will of God,
# what is good and pleasing and perfect."
# (Holy Bible, Romans 12:2)
import sys
if sys.version_info[0] < 3:
print('CXXII exige Python 3 ou mais recente.')
sys.exit(1)
import os
import time
import datetime
import unicodedata
import urllib.request
import tempfile
import zipfile
import re
from xml.etree.ElementTree import ElementTree as CXXII_XML_Arvore
#----------------------------------------------------------------------------
class CXXII_XML_Arquivo:
"""Classe que representa um arquivo XML."""
def __init__(self, endereco):
self.endereco = endereco
self.nome = NomeDoArquivo(endereco)
self.arvore = CXXII_XML_Arvore()
self.arvore.parse(endereco)
def raiz(self):
return self.arvore.getroot()
def CXXII_Baixar( url, destino=None, nome=None, forcar=False ):
"""Download de arquivo."""
if url[-1] == '/' : url = url[0:-1]
if destino is None :
global CXXII_Diretorio
destino = CXXII_Diretorio
if destino[-1] == os.sep : destino = destino[0:-1]
if nome is None : nome = url.replace('/', '_').replace(':', '_')
endereco = destino + os.sep + nome
existe = os.path.exists(endereco)
baixar = forcar or not existe
if not baixar:
global CXXII_Gerador_TempoMaximo
baixar = ( time.time() - os.path.getmtime(endereco) ) > CXXII_Gerador_TempoMaximo
if baixar:
try:
urllib.request.urlretrieve(url, endereco)
except:
raise Exception('Não foi possível baixar o gerador.')
return endereco
def CXXII_XML_Adicionar( endereco ):
global CXXII_XML_Arquivos
CXXII_XML_Arquivos.append( CXXII_XML_Arquivo(endereco) )
def CXXII_Separadores( endereco ):
"""Substitui os separadores "/" pelo separador real do sistema operacional."""
return endereco.replace('/', os.sep)
def CXXII_Python_Formato( arquivo ):
"""Retorna o valor de "# coding=".
arquivo -- Arquivo ou endereço de arquivo. Pode-se utilizar "/" como separador.
"""
if type(arquivo) is str: arquivo = open( CXXII_Separadores(arquivo), 'r', encoding='iso-8859-1' )
formato = 'utf-8'
arquivo.seek(0)
for i in range(2):
linha = arquivo.readline()
if linha.startswith('# coding='):
formato = linha[9:-1]
break
arquivo.close()
return formato
def CXXII_Abrir_Python( endereco ):
"""Abre um arquivo ".py" respeitando a codificação especificada no cabeçalho "# coding=".
endereco -- Endereço do arquivo. Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
return open( endereco, 'r', encoding=CXXII_Python_Formato(endereco) )
def CXXII_Atual( endereco, modo='w', formato='utf-8' ):
"""Determina o arquivo em geração atual.
endereco -- Endereço do arquivo desejado, relativo ao CXXII_Destino. Pode-se utilizar "/" como separador.
"""
global CXXII_Saida
global CXXII_Destino
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep: endereco = os.sep + endereco
if CXXII_Saida != None and CXXII_Saida != sys.stdout: CXXII_Saida.close()
arquivo = CXXII_Texto(CXXII_Destino + endereco)
diretorio = CXXII_Texto(os.path.dirname(arquivo))
if not os.path.exists(diretorio): os.makedirs(diretorio)
CXXII_Saida = open( arquivo, modo, encoding=formato )
def CXXII_Escrever( texto ):
"""Escreve no arquivo em geração atual. Ver CXXII_Atual()."""
global CXXII_Saida
if not CXXII_Saida is None:
CXXII_Saida.write(texto)
def CXXII_ContarIdentacao( linha ):
comprimento = len(linha)
if comprimento == 0: return 0
tamanho = comprimento - len(linha.lstrip())
if linha[0] == ' ': tamanho /= 4
return tamanho
def CXXII_Identar( linha, total=1 ):
espaco = '\t' if len(linha) > 0 and linha[0] == '\t' else ' '
while total > 0:
linha = espaco + linha
total -= 1
return linha
def CXXII_EscreverArquivo( endereco, inicio=1, fim=None, quebraFinal=True, formato='utf-8', dicGlobal=None, dicLocal=None ):
"""Escreve no arquivo em geração atual (CXXII_Atual()) o conteúdo de um arquivo-modelo.
Arquivo-modelo é qualquer conteúdo que contenha instruções CXXII embutidas.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo-modelo. Pode-se utilizar "/" como separador.
inicio -- Número inicial do intervalo de linhas desejado. Padrão: 1
fim -- Número final do intervalo de linhas desejado. Padrão: None (última linha)
quebraFinal -- Quebra de linha na última linha?
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
global CXXII_Saida
if CXXII_Saida is None: return
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
codigo = []
modelo = open( endereco, 'r', encoding=formato )
linhas = list(modelo)
modelo.close()
total = len(linhas)
if inicio != 1 or fim != None:
inicio = inicio - 1 if inicio != None else 0
fim = fim if fim != None else total
linhas = linhas[inicio:fim]
if not quebraFinal and linhas[-1][-1] == '\n': linhas[-1] = linhas[-1][0:-1]
total = len(linhas)
identacao = 0
i = 0
while i < total:
linha = linhas[i]
if linha == '@@@\n':
i += 1
if i < total and identacao > 0 and linhas[i] == '@@@\n':
identacao -= 1
else:
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
identacao = CXXII_ContarIdentacao(linha)
codigo.append(linha)
linha = linha.strip()
if len(linha) > 0 and linha[-1] == ':':
if linha.startswith('for ') or linha.startswith('while '):
identacao += 1
i += 1
else:
codigo.append(CXXII_Identar('"""~\n', identacao))
finalComQuebra = False
while i < total and linhas[i] != '@@@\n':
linha = linhas[i]
finalComQuebra = linha.endswith('\n')
if not finalComQuebra: linha += '\n'
codigo.append(linha)
i += 1
if finalComQuebra: codigo.append('\n')
codigo.append(CXXII_Identar('"""\n', identacao))
i -= 1
i += 1
CXXII_Executar( CXXII_CompilarPython(codigo), dicGlobal, dicLocal )
def CXXII_Texto( texto, decodificar=False ):
if decodificar and type(texto) is bytes: texto = texto.decode(sys.getfilesystemencoding())
return unicodedata.normalize('NFC', texto)
def CXXII_EscapeParaTexto( texto ):
return texto.replace('\n','\\n').replace('\r','\\r').replace('\t','\\t').replace('\'','\\\'')
def CXXII_TextoParaEscape( texto ):
return texto.replace('\\n','\n').replace('\\r','\r').replace('\\t','\t').replace('\\\'','\'')
def NomeDoArquivo( endereco, extensao=True ):
if endereco[-1] == os.sep: endereco = endereco[0:-1]
nome = endereco[endereco.rfind(os.sep)+1:]
if not extensao:
nome = nome[0:len(nome)-nome.rfind('.')]
return nome
def CXXII_Compilar( endereco ):
"""Compila um arquivo codificado com a linguagem Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
endereco -- Endereço do arquivo ".py". Pode-se utilizar "/" como separador.
"""
endereco = CXXII_Separadores(endereco)
if endereco[0] != os.sep and os.path.exists(CXXII_Gerador_Diretorio + os.sep + endereco):
endereco = CXXII_Gerador_Diretorio + os.sep + endereco
py_arquivo = CXXII_Abrir_Python(endereco)
py = list(py_arquivo)
py_arquivo.close()
return CXXII_CompilarPython(py)
def CXXII_CompilarPython( codigoFonte ):
"""Compila um código fonte codificado com a linguagem Python."""
py = list(codigoFonte) if type(codigoFonte) != list else codigoFonte
if py[0].startswith('# coding='):
py = py[1:]
elif py[1].startswith('# coding='):
py = py[2:]
py[-1] += '\n'
i = 0
total = len(py)
embutido = re.compile('({{{[^{}]*}}})')
while i < total:
linha = py[i]
passo = 1
if linha.endswith('"""~\n'):
desconsiderar = False
tokenstr = None
cpre = None
for c in linha:
if tokenstr != None:
if c == tokenstr and cpre != '\\': tokenstr = None
elif c == '#':
desconsiderar = True
break
elif c == '\'' or c == '\"':
tokenstr = c
cpre = c
if desconsiderar:
i += passo
continue
linha = linha[:-5] + 'CXXII_Escrever(\''
a = i
b = a + 1
while b < total and not py[b].lstrip().startswith('"""'): b += 1
if b >= total: raise Exception('Bloco de escrita não finalizado: linha ' + str(i))
py[b] = py[b][py[b].index('"""')+3:]
passo = b - a
if (b-a) > 1:
primeiro = True
a += 1
while a < b:
linha += ( '\\n' if not primeiro else '' ) + CXXII_EscapeParaTexto( py[a][:-1] )
py[a] = ''
primeiro = False
a += 1
linhapos = 0
while True:
codigo = embutido.search(linha, linhapos)
if not codigo is None:
parte1 = \
linha[0:codigo.start(0)] +\
'\'+' +\
CXXII_TextoParaEscape(codigo.group(0)[3:-3]) +\
'+\''
parte2 = linha[codigo.end(0):]
linha = parte1 + parte2
linhapos = len(parte1)
else:
break
linha += '\');'
py[i] = linha
i += passo
return compile( ''.join(py), 'CXXII_Python', 'exec' )
def CXXII_Executar( python, dicGlobal=None, dicLocal=None ):
"""Executa um código Python pré-compilado com CXXII_Compilar() ou um arquivo Python.
Se o endereço do arquivo for relativo, ele primeiro será buscado em CXXII_Gerador_Diretorio.
python -- Código pré-compilado ou endereço do arquivo. Pode-se utilizar "/" como separador.
dicGlobal -- Ver globals()
dicLocal -- Ver locals()
"""
if dicGlobal is None: dicGlobal = globals()
if dicLocal is None: dicLocal = locals()
exec( CXXII_Compilar(python) if type(python) is str else python, dicGlobal, dicLocal )
#----------------------------------------------------------------------------
CXXII_Repositorio = 'http://www.joseflavio.com/cxxii/'
CXXII_Inicio = datetime.datetime.today()
CXXII_Gerador_Endereco = None
CXXII_Gerador_Diretorio = None
CXXII_Gerador_TempoMaximo = 6*60*60 #6h
CXXII_Gerador_Baixar = False
CXXII_Destino = None
CXXII_XML_Arquivos = []
CXXII_Extensao = 'xml'
CXXII_Saida = sys.stdout
CXXII_Diretorio = CXXII_Texto(os.path.expanduser('~')) + os.sep + 'CXXII'<|fim▁hole|>#----------------------------------------------------------------------------
try:
#----------------------------------------------------------------------------
argumentos = CXXII_Texto(' '.join(sys.argv), True)
argumentos = argumentos.replace(' -g', '###g')
argumentos = argumentos.replace(' -f', '###fSIM')
argumentos = argumentos.replace(' -t', '###tSIM')
argumentos = argumentos.replace(' -d', '###d')
argumentos = argumentos.replace(' -e', '###e')
argumentos = argumentos.replace(' -a', '###a')
argumentos = argumentos.split('###')
argumento_g = None
argumento_f = None
argumento_t = None
argumento_d = None
argumento_e = None
argumento_a = None
for argumento in argumentos[1:]:
valor = argumento[1:].strip()
if len(valor) == 0: continue
exec( 'argumento_' + argumento[0] + '=\'' + valor + '\'' )
if argumento_g is None or argumento_a is None:
print('\nCXXII 1.0-A1 : Gerador de arquivos a partir de XML\n')
print('cxxii -g GERADOR [-f] [-t] [-d DESTINO] [-e EXTENSAO] -a ARQUIVOS\n')
print('Argumentos:')
print(' -g URL ou endereço local do gerador a utilizar: .py ou .zip')
print(' Nome sem extensão = ' + CXXII_Repositorio + 'Nome.zip')
print(' -f Forçar download do gerador')
print(' -t Imprimir detalhes do erro que possa ocorrer')
print(' -d Destino dos arquivos gerados')
print(' -e Extensão padrão dos arquivos de entrada: xml')
print(' -a Arquivos XML de entrada ou diretórios que os contenham\n')
sys.exit(1)
#----------------------------------------------------------------------------
if argumento_e != None: CXXII_Extensao = argumento_e.lower()
argumento_a = argumento_a.replace('.' + CXXII_Extensao, '.' + CXXII_Extensao + '###')
argumento_a = argumento_a.split('###')
for xml in argumento_a:
xml = xml.strip()
if len(xml) == 0: continue
xml = CXXII_Texto(os.path.abspath(xml))
if os.path.isdir(xml):
for arquivo in os.listdir(xml):
arquivo = CXXII_Texto(arquivo)
if arquivo.lower().endswith('.' + CXXII_Extensao):
CXXII_XML_Adicionar(xml + os.sep + arquivo)
else:
CXXII_XML_Adicionar(xml)
if len(CXXII_XML_Arquivos) == 0:
sys.exit(0)
#----------------------------------------------------------------------------
try:
CXXII_Gerador_Baixar = not argumento_f is None
gerurl = argumento_g.startswith('http://')
if( gerurl and argumento_g[-1] == '/' ): argumento_g = argumento_g[0:-1]
gernome = argumento_g[argumento_g.rfind('/' if gerurl else os.sep)+1:]
gerpy = gernome.endswith('.py')
gerzip = gernome.endswith('.zip')
if gerurl:
argumento_g = CXXII_Baixar(url=argumento_g, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
elif gerpy or gerzip:
argumento_g = CXXII_Texto(os.path.abspath(argumento_g))
else:
gerurl = True
gernome += '.zip'
gerzip = True
argumento_g = CXXII_Baixar(url=CXXII_Repositorio + gernome, destino=CXXII_Geradores, forcar=CXXII_Gerador_Baixar)
if gerzip:
destino = argumento_g[0:-4]
if not os.path.exists(destino): os.makedirs(destino)
CXXII_Gerador_Endereco = destino + os.sep + gernome[0:-4] + '.py'
descompactar = not os.path.exists(CXXII_Gerador_Endereco)
if not descompactar:
descompactar = os.path.getmtime(argumento_g) > os.path.getmtime(CXXII_Gerador_Endereco)
if descompactar:
zip = zipfile.ZipFile(argumento_g, 'r')
zip.extractall(destino)
del zip
else:
CXXII_Gerador_Endereco = argumento_g
CXXII_Gerador_Diretorio = CXXII_Texto(os.path.dirname(CXXII_Gerador_Endereco))
except:
raise Exception('Gerador inválido.')
#----------------------------------------------------------------------------
CXXII_Destino = argumento_d if not argumento_d is None else 'CXXII_' + CXXII_Inicio.strftime('%Y%m%d%H%M%S')
CXXII_Destino = CXXII_Texto(os.path.abspath(CXXII_Destino))
if not os.path.exists(CXXII_Destino): os.makedirs(CXXII_Destino)
#----------------------------------------------------------------------------
gerador_nome = ''
gerador_versao = ''
gerador_multiplo = True
cxxii_con = CXXII_Abrir_Python(CXXII_Gerador_Endereco)
cxxii_lin = list(cxxii_con)
cxxii_ini = 0
cxxii_tot = len(cxxii_lin)
while cxxii_ini < cxxii_tot and cxxii_lin[cxxii_ini] != '### CXXII\n': cxxii_ini += 1
if cxxii_ini < cxxii_tot:
fim = cxxii_ini + 1
while fim < cxxii_tot and cxxii_lin[fim] != '###\n': fim += 1
if fim < cxxii_tot: exec(''.join(cxxii_lin[(cxxii_ini+1):fim]))
cxxii_con.close()
del cxxii_con
del cxxii_lin
del cxxii_ini
del cxxii_tot
gerador_nome = gerador_nome if gerador_nome != None and len(gerador_nome) > 0 else NomeDoArquivo(argumento_g)
if gerador_versao == None: gerador_versao = 'Desconhecida'
if not type(gerador_versao) is str: gerador_versao = str(gerador_versao)
print( 'Gerador: ' + gerador_nome )
print( 'Versão: ' + gerador_versao )
#----------------------------------------------------------------------------
CXXII_Gerador_Compilado = CXXII_Compilar( CXXII_Gerador_Endereco )
CXXII_XML = CXXII_XML_Arquivos[0]
if gerador_multiplo:
for xml in CXXII_XML_Arquivos:
print(xml.endereco)
CXXII_XML = xml
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
else:
CXXII_Executar( CXXII_Gerador_Compilado, globals(), locals() )
#----------------------------------------------------------------------------
except Exception as e:
if not argumento_t is None:
import traceback
traceback.print_exc()
print('Erro: ' + str(e))
#----------------------------------------------------------------------------<|fim▁end|> | CXXII_Geradores = CXXII_Diretorio + os.sep + 'Geradores'
if not os.path.exists(CXXII_Geradores): os.makedirs(CXXII_Geradores)
|
<|file_name|>openclose.cpp<|end_file_name|><|fim▁begin|>#include "hooks/hooks.H"
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include "libdft_api.h"
#include "tagmap.h"
#include "pin.H"
#include "provlog.H"<|fim▁hole|>/* tracks whether path existed before the execution of syscall */
static struct {
std::string pathname;
int existed_before_syscall;
} exist_status;
/*
* open(2)/creat(2) handlers
*
* Signatures:
* int open(const char *pathname, int flags);
* int open(const char *pathname, int flags, mode_t mode);
* int creat(const char *pathname, mode_t mode);
*/
#define DEF_SYSCALL_OPEN
#include "hooks/syscall_args.h"
template<>
void pre_open_hook<libdft_tag_bitset>(syscall_ctx_t *ctx) {
/* Check the status of the pathname we are about to open/create. */
exist_status.pathname = std::string(_PATHNAME);
exist_status.existed_before_syscall = path_exists(exist_status.pathname);
//std::cerr << exist_status.pathname << std::endl;
//std::cerr << exist_status.existed_before_syscall << std::endl;
}
template<>
void post_open_hook<libdft_tag_bitset>(syscall_ctx_t *ctx) {
/* not successful; optimized branch */
if (unlikely(_FD < 0)) {
LOG("ERROR " _CALL_LOG_STR + " (" + strerror(errno) + ")\n");
return;
}
/* Resolve fd to full pathname. Use this instead of syscall argument. */
const std::string fdn = fdname(_FD);
if ( !in_dtracker_whitelist(fdn) && !path_isdir(fdn) ) {
const PROVLOG::ufd_t ufd = PROVLOG::ufdmap[_FD];
fdset.insert(_FD);
int created = (
exist_status.existed_before_syscall != 1 &&
(_FLAGS & O_CREAT) &&
exist_status.pathname == std::string(_PATHNAME)
);
LOG("OK " _CALL_LOG_STR + "\n");
LOG("INFO mapped fd" + decstr(_FD) + ":ufd" + decstr(ufd) + "\n");
PROVLOG::open(ufd, fdn, _FLAGS, created);
}
else {
LOG("INFO ignoring fd" + decstr(_FD) + " (" + fdn + ")\n");
}
/* reset the exist_status */
exist_status.existed_before_syscall = 0;
}
#define UNDEF_SYSCALL_OPEN
#include "hooks/syscall_args.h"
/*
* close(2) handler - updates watched fds
*
* Signature: int close(int fd);
*/
#define DEF_SYSCALL_CLOSE
#include "hooks/syscall_args.h"
template<>
void post_close_hook<libdft_tag_bitset>(syscall_ctx_t *ctx) {
/* not successful; optimized branch */
if (unlikely(_RET_STATUS < 0)) {
LOG("ERROR " _CALL_LOG_STR + " (" + strerror(errno) + ")\n");
return;
}
LOG("OK " _CALL_LOG_STR + "\n");
std::set<int>::iterator it = fdset.find(_FD);
if (it == fdset.end()) return;
const PROVLOG::ufd_t ufd = PROVLOG::ufdmap[_FD];
fdset.erase(it);
PROVLOG::ufdmap.del(_FD);
if (IS_STDFD(_FD)) stdcount[_FD] = 0;
LOG("INFO removed mapping fd" + decstr(_FD) + ":ufd" + decstr(ufd) + "\n");
PROVLOG::close(ufd);
}
#define UNDEF_SYSCALL_CLOSE
#include "hooks/syscall_args.h"
/* vim: set noet ts=4 sts=4 sw=4 ai : */<|fim▁end|> | #include "dtracker.H"
#include "osutils.H"
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import os<|fim▁hole|>import threading
from flask import Flask
app = Flask(__name__)
app.config.from_envvar("PEGASUS_METRICS_CONFIG")
# This is required for sessions and message flashing
app.secret_key = os.urandom(24)
import pegasus.metrics.views
import pegasus.metrics.filters<|fim▁end|> | import sys
import logging |
<|file_name|>IssueEvent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <[email protected]> #
# Copyright 2012 Zearin <[email protected]> #<|fim▁hole|># This file is part of PyGithub. #
# http://pygithub.github.io/PyGithub/v1/index.html #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub 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 PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
import Framework
import datetime
class IssueEvent(Framework.TestCase):
def setUp(self):
Framework.TestCase.setUp(self)
self.event = self.g.get_user().get_repo("PyGithub").get_issues_event(16348656)
def testAttributes(self):
self.assertEqual(self.event.actor.login, "jacquev6")
self.assertEqual(self.event.commit_id, "ed866fc43833802ab553e5ff8581c81bb00dd433")
self.assertEqual(self.event.created_at, datetime.datetime(2012, 5, 27, 7, 29, 25))
self.assertEqual(self.event.event, "referenced")
self.assertEqual(self.event.id, 16348656)
self.assertEqual(self.event.issue.number, 30)
self.assertEqual(self.event.url, "https://api.github.com/repos/jacquev6/PyGithub/issues/events/16348656")
# test __repr__() based on this attributes
self.assertEqual(self.event.__repr__(), 'IssueEvent(id=16348656)')<|fim▁end|> | # Copyright 2013 Vincent Jacques <[email protected]> #
# # |
<|file_name|>user-edit.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core';
import { GLOBAL } from '../services/global';
import { UserService } from '../services/user.service';
import { User } from '../models/user';
@Component({
selector: 'user-edit',
templateUrl: '../views/user-edit.html',
providers: [UserService]
})
export class UserEditComponent implements OnInit {
public titulo: string;
public user: User;
public identity;
public token;
public alertMessage;
public filesToUpload: Array<File>;
public url: string;
constructor(private _userService: UserService) { }
ngOnInit() {
this.titulo = 'Update my profile';
// localStorage
this.identity = this._userService.getIdentity();
this.token = this._userService.getToken();
this.user = this.identity;
this.url = GLOBAL.url;
}
onSubmit() {
this._userService.updateUser(this.user).subscribe(
response => {
if (!response.user) {
this.alertMessage = 'The user could not be updated';
} else {
localStorage.setItem('identity', JSON.stringify(this.user));
document.getElementById('identity_name').innerHTML = this.user.name;
if (!this.filesToUpload) {
// Redirect
} else {
this.makeFileRequest(this.url + 'upload-image-user/'
+ this.user._id, [], this.filesToUpload).then(
(result: any) => {
this.user.image = result.image;
localStorage.setItem('identity', JSON.stringify(this.user));
const image_path = this.url + 'get-image-user/' + this.user.image;
document.getElementById('image-logged').setAttribute('src', image_path);
});
}
}
this.alertMessage = 'User updated';
},
error => {
const errorMessage = <any>error;
if (errorMessage != null) {
const body = JSON.parse(error._body);
this.alertMessage = body.message;
console.log(error);
}
}
);
}
fileChangeEvent(fileInput: any) {
this.filesToUpload = <Array<File>>fileInput.target.files;
}
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {<|fim▁hole|> return new Promise(function(resolve, reject) {
let formData: any = new FormData();
let xhr = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append('image', files[i], files[i].name);
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open('POST', url, true);
xhr.setRequestHeader('Authorization', token);
xhr.send(formData);
});
}
}<|fim▁end|> | let token = this.token;
|
<|file_name|>transform_feedback.py<|end_file_name|><|fim▁begin|>'''OpenGL extension NV.transform_feedback
This module customises the behaviour of the
OpenGL.raw.GL.NV.transform_feedback to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a new mode to the GL, called transform feedback,
which records vertex attributes of the primitives processed by the GL.
The selected attributes are written into buffer objects, and can be
written with each attribute in a separate buffer object or with all
attributes interleaved into a single buffer object. If a geometry program
or shader is active, the primitives recorded are those emitted by the
geometry program. Otherwise, transform feedback captures primitives whose
vertex are transformed by a vertex program or shader, or by fixed-function
vertex processing. In either case, the primitives captured are those
generated prior to clipping. Transform feedback mode is capable of
capturing transformed vertex data generated by fixed-function vertex
processing, outputs from assembly vertex or geometry programs, or varying
variables emitted from GLSL vertex or geometry shaders.
The vertex data recorded in transform feedback mode is stored into buffer
objects as an array of vertex attributes. The regular representation and
the use of buffer objects allows the recorded data to be processed
directly by the GL without requiring CPU intervention to copy data. In
particular, transform feedback data can be used for vertex arrays (via
vertex buffer objects), as the source for pixel data (via pixel buffer
objects), as program constant data (via the NV_parameter_buffer_object or
EXT_bindable_uniform extension), or via any other extension that makes use
of buffer objects.<|fim▁hole|> This extension introduces new query object support to allow transform
feedback mode to operate asynchronously. Query objects allow applications
to determine when transform feedback results are complete, as well as the
number of primitives processed and written back to buffer objects while in
transform feedback mode. This extension also provides a new rasterizer
discard enable, which allows applications to use transform feedback to
capture vertex attributes without rendering anything.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/NV/transform_feedback.txt
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.NV.transform_feedback import *
### END AUTOGENERATED SECTION<|fim▁end|> | |
<|file_name|>PyStdlibCanonicalPathProvider.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");<|fim▁hole|> *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.stdlib;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.psi.resolve.PyCanonicalPathProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class PyStdlibCanonicalPathProvider implements PyCanonicalPathProvider {
@Nullable
@Override
public QualifiedName getCanonicalPath(@NotNull QualifiedName qName, PsiElement foothold) {
return restoreStdlibCanonicalPath(qName);
}
public static QualifiedName restoreStdlibCanonicalPath(QualifiedName qName) {
if (qName.getComponentCount() > 0) {
final List<String> components = qName.getComponents();
final String head = components.get(0);
if (head.equals("_abcoll") || head.equals("_collections")) {
components.set(0, "collections");
return QualifiedName.fromComponents(components);
}
else if (head.equals("posix") || head.equals("nt")) {
components.set(0, "os");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_functools")) {
components.set(0, "functools");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_struct")) {
components.set(0, "struct");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_io") || head.equals("_pyio") || head.equals("_fileio")) {
components.set(0, "io");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_datetime")) {
components.set(0, "datetime");
return QualifiedName.fromComponents(components);
}
else if (head.equals("ntpath") || head.equals("posixpath") || head.equals("path")) {
final List<String> result = new ArrayList<String>();
result.add("os");
components.set(0, "path");
result.addAll(components);
return QualifiedName.fromComponents(result);
}
else if (head.equals("_sqlite3")) {
components.set(0, "sqlite3");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_pickle")) {
components.set(0, "pickle");
return QualifiedName.fromComponents(components);
}
}
return null;
}
}<|fim▁end|> | * 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 |
<|file_name|>g_items.cpp<|end_file_name|><|fim▁begin|>/*
This file is part of Jedi Knight 2.
Jedi Knight 2 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
Jedi Knight 2 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 Jedi Knight 2. If not, see <http://www.gnu.org/licenses/>.
*/
// Copyright 2001-2013 Raven Software
// leave this line at the top for all g_xxxx.cpp files...
#include "g_headers.h"
#include "g_local.h"
#include "g_functions.h"
#include "g_items.h"
#include "wp_saber.h"
extern qboolean missionInfo_Updated;
extern void CrystalAmmoSettings(gentity_t *ent);
extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel );
extern void ChangeWeapon( gentity_t *ent, int newWeapon );
extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath );
extern qboolean PM_InKnockDown( playerState_t *ps );
extern qboolean PM_InGetUp( playerState_t *ps );
extern cvar_t *g_spskill;
#define MAX_BACTA_HEAL_AMOUNT 25
/*
Items are any object that a player can touch to gain some effect.
Pickup will return the number of seconds until they should respawn.
all items should pop when dropped in lava or slime
Respawnable items don't actually go away when picked up, they are
just made invisible and untouchable. This allows them to ride
movers and respawn apropriately.
*/
// Item Spawn flags
#define ITMSF_SUSPEND 1
#define ITMSF_TEAM 2
#define ITMSF_MONSTER 4
#define ITMSF_NOTSOLID 8
#define ITMSF_VERTICAL 16
#define ITMSF_INVISIBLE 32
//======================================================================
/*
===============
G_InventorySelectable
===============
*/
qboolean G_InventorySelectable( int index,gentity_t *other)
{
if (other->client->ps.inventory[index])
{
return qtrue;
}
return qfalse;
}
extern qboolean INV_GoodieKeyGive( gentity_t *target );
extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname );
int Pickup_Holdable( gentity_t *ent, gentity_t *other )
{
int i,original;
other->client->ps.stats[STAT_ITEMS] |= (1<<ent->item->giTag);
if ( ent->item->giTag == INV_SECURITY_KEY )
{//give the key
//FIXME: temp message
gi.SendServerCommand( 0, "cp @INGAME_YOU_TOOK_SECURITY_KEY" );
INV_SecurityKeyGive( other, ent->message );
}
else if ( ent->item->giTag == INV_GOODIE_KEY )
{//give the key
//FIXME: temp message
gi.SendServerCommand( 0, "cp @INGAME_YOU_TOOK_SUPPLY_KEY" );
INV_GoodieKeyGive( other );
}
else
{// Picking up a normal item?
other->client->ps.inventory[ent->item->giTag]++;
}
// Got a security key
// Set the inventory select, just in case it hasn't
original = cg.inventorySelect;
for ( i = 0 ; i < INV_MAX ; i++ )
{
if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX))
{
cg.inventorySelect = (INV_MAX - 1);
}
if ( G_InventorySelectable( cg.inventorySelect,other ) )
{
return 60;
}
cg.inventorySelect++;
}
cg.inventorySelect = original;
return 60;
}
//======================================================================
int Add_Ammo2 (gentity_t *ent, int ammoType, int count)
{
if (ammoType != AMMO_FORCE)
{
ent->client->ps.ammo[ammoType] += count;
// since the ammo is the weapon in this case, picking up ammo should actually give you the weapon
switch( ammoType )
{
case AMMO_THERMAL:
ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_THERMAL );
break;
case AMMO_DETPACK:
ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_DET_PACK );
break;
case AMMO_TRIPMINE:
ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_TRIP_MINE );
break;
}
if ( ent->client->ps.ammo[ammoType] > ammoData[ammoType].max )
{
ent->client->ps.ammo[ammoType] = ammoData[ammoType].max;
return qfalse;
}
}
else
{
if ( ent->client->ps.forcePower >= ammoData[ammoType].max )
{//if have full force, just get 25 extra per crystal
ent->client->ps.forcePower += 25;
}
else
{//else if don't have full charge, give full amount, up to max + 25
ent->client->ps.forcePower += count;
if ( ent->client->ps.forcePower >= ammoData[ammoType].max + 25 )
{//cap at max + 25
ent->client->ps.forcePower = ammoData[ammoType].max + 25;
}
}
if ( ent->client->ps.forcePower >= ammoData[ammoType].max*2 )
{//always cap at twice a full charge
ent->client->ps.forcePower = ammoData[ammoType].max*2;
return qfalse; // can't hold any more
}
}
return qtrue;
}
//-------------------------------------------------------
void Add_Ammo (gentity_t *ent, int weapon, int count)
{
Add_Ammo2(ent,weaponData[weapon].ammoIndex,count);
}
//-------------------------------------------------------
int Pickup_Ammo (gentity_t *ent, gentity_t *other)
{
int quantity;
if ( ent->count ) {
quantity = ent->count;
} else {
quantity = ent->item->quantity;
}
Add_Ammo2 (other, ent->item->giTag, quantity);
return 30;
}
//======================================================================
void Add_Batteries( gentity_t *ent, int *count )
{
if ( ent->client && ent->client->ps.batteryCharge < MAX_BATTERIES && *count )
{
if ( *count + ent->client->ps.batteryCharge > MAX_BATTERIES )
{
// steal what we need, then leave the rest for later
*count -= ( MAX_BATTERIES - ent->client->ps.batteryCharge );
ent->client->ps.batteryCharge = MAX_BATTERIES;
}
else
{
// just drain all of the batteries
ent->client->ps.batteryCharge += *count;
*count = 0;
}
G_AddEvent( ent, EV_BATTERIES_CHARGED, 0 );
}
}
//-------------------------------------------------------
int Pickup_Battery( gentity_t *ent, gentity_t *other )
{
int quantity;
if ( ent->count )
{
quantity = ent->count;
}
else
{
quantity = ent->item->quantity;
}
// There may be some left over in quantity if the player is close to full, but with pickup items, this amount will just be lost
Add_Batteries( other, &quantity );
return 30;
}
//======================================================================
extern void WP_SaberInitBladeData( gentity_t *ent );
extern void CG_ChangeWeapon( int num );
int Pickup_Weapon (gentity_t *ent, gentity_t *other)
{
int quantity;
qboolean hadWeapon = qfalse;
/*
if ( ent->count || (ent->activator && !ent->activator->s.number) )
{
quantity = ent->count;
}
else
{
quantity = ent->item->quantity;
}
*/
// dropped items are always picked up
if ( ent->flags & FL_DROPPED_ITEM )
{
quantity = ent->count;
}
else
{//wasn't dropped
quantity = ent->item->quantity?ent->item->quantity:50;
}
// add the weapon
if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) )
{
hadWeapon = qtrue;
}
other->client->ps.stats[STAT_WEAPONS] |= ( 1 << ent->item->giTag );
if ( ent->item->giTag == WP_SABER && !hadWeapon )
{
WP_SaberInitBladeData( other );
}
if ( other->s.number )
{//NPC
if ( other->s.weapon == WP_NONE )
{//NPC with no weapon picked up a weapon, change to this weapon
//FIXME: clear/set the alt-fire flag based on the picked up weapon and my class?
other->client->ps.weapon = ent->item->giTag;
other->client->ps.weaponstate = WEAPON_RAISING;
ChangeWeapon( other, ent->item->giTag );
if ( ent->item->giTag == WP_SABER )
{
other->client->ps.saberActive = qtrue;
G_CreateG2AttachedWeaponModel( other, other->client->ps.saberModel );
}
else
{
G_CreateG2AttachedWeaponModel( other, weaponData[ent->item->giTag].weaponMdl );
}
}
}
if ( quantity )
{
// Give ammo
Add_Ammo( other, ent->item->giTag, quantity );
}
return 5;
}
//======================================================================
int ITM_AddHealth (gentity_t *ent, int count)
{
ent->health += count;
if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) // Past max health
{
ent->health = ent->client->ps.stats[STAT_MAX_HEALTH];
return qfalse;
}
return qtrue;
}
int Pickup_Health (gentity_t *ent, gentity_t *other) {
int max;
int quantity;
max = other->client->ps.stats[STAT_MAX_HEALTH];
if ( ent->count ) {
quantity = ent->count;
} else {
quantity = ent->item->quantity;
}
other->health += quantity;
if (other->health > max ) {
other->health = max;
}
if ( ent->item->giTag == 100 ) { // mega health respawns slow
return 120;
}
return 30;
}
//======================================================================
int ITM_AddArmor (gentity_t *ent, int count)
{
ent->client->ps.stats[STAT_ARMOR] += count;
if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH])
{
ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH];
return qfalse;
}
return qtrue;
}
int Pickup_Armor( gentity_t *ent, gentity_t *other ) {
// make sure that the shield effect is on
other->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE;
other->client->ps.stats[STAT_ARMOR] += ent->item->quantity;
if ( other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH] ) {
other->client->ps.stats[STAT_ARMOR] = other->client->ps.stats[STAT_MAX_HEALTH];
}
return 30;
}
//======================================================================
int Pickup_Holocron( gentity_t *ent, gentity_t *other )
{
int forcePower = ent->item->giTag;
int forceLevel = ent->count;
// check if out of range
if( forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS )
{
gi.Printf(" Pickup_Holocron : count %d not in valid range\n", forceLevel );
return 1;
}
// don't pick up if already known AND your level is higher than pickup level
if ( ( other->client->ps.forcePowersKnown & ( 1 << forcePower )) )
{
//don't pickup if item is lower than current level
if( other->client->ps.forcePowerLevel[forcePower] >= forceLevel )
{
return 1;
}
}
other->client->ps.forcePowerLevel[forcePower] = forceLevel;
other->client->ps.forcePowersKnown |= ( 1 << forcePower );
missionInfo_Updated = qtrue; // Activate flashing text
gi.cvar_set("cg_updatedDataPadForcePower1", va("%d",forcePower+1)); // The +1 is offset in the print routine.
cg_updatedDataPadForcePower1.integer = forcePower+1;
gi.cvar_set("cg_updatedDataPadForcePower2", "0"); // The +1 is offset in the print routine.
cg_updatedDataPadForcePower2.integer = 0;
gi.cvar_set("cg_updatedDataPadForcePower3", "0"); // The +1 is offset in the print routine.
cg_updatedDataPadForcePower3.integer = 0;
return 1;
}
//======================================================================
/*
===============
RespawnItem
===============
*/
void RespawnItem( gentity_t *ent ) {
}
qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper )
{
if ( !item->item ) {
return qfalse;
}
if ( item->item->giType == IT_HOLDABLE &&
item->item->giTag == INV_SECURITY_KEY ) {
return qfalse;
}
if ( (item->flags&FL_DROPPED_ITEM)
&& item->activator != &g_entities[0]
&& pickerupper->s.number
&& pickerupper->s.weapon == WP_NONE
&& pickerupper->enemy
&& pickerupper->painDebounceTime < level.time
&& pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time //not surrendering
&& !(pickerupper->NPC->scriptFlags&SCF_FORCED_MARCH) ) // not being forced to march
{//non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a security key
if ( level.time - item->s.time < 3000 )//was 5000
{
return qfalse;
}
return qtrue;
}
return qfalse;
}
/*
===============
Touch_Item
===============
*/
extern cvar_t *g_timescale;
void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) {
int respawn = 0;
if (!other->client)
return;
if (other->health < 1)
return; // dead people can't pickup
if ( other->client->ps.pm_time > 0 )
{//cant pick up when out of control
return;
}
// Only monsters can pick it up
if ((ent->spawnflags & ITMSF_MONSTER) && (other->client->playerTeam == TEAM_PLAYER))
{
return;
}
// Only starfleet can pick it up
if ((ent->spawnflags & ITMSF_TEAM) && (other->client->playerTeam != TEAM_PLAYER))
{
return;
}
if ( other->client->NPC_class == CLASS_ATST ||
other->client->NPC_class == CLASS_GONK ||
other->client->NPC_class == CLASS_MARK1 ||
other->client->NPC_class == CLASS_MARK2 ||
other->client->NPC_class == CLASS_MOUSE ||
other->client->NPC_class == CLASS_PROBE ||
other->client->NPC_class == CLASS_PROTOCOL ||
other->client->NPC_class == CLASS_R2D2 ||
other->client->NPC_class == CLASS_R5D2 ||
other->client->NPC_class == CLASS_SEEKER ||
other->client->NPC_class == CLASS_REMOTE ||
other->client->NPC_class == CLASS_SENTRY )
{//FIXME: some flag would be better
//droids can't pick up items/weapons!
return;
}
//FIXME: need to make them run toward a dropped weapon when fleeing without one?
//FIXME: need to make them come out of flee mode when pick up their old weapon?
if ( CheckItemCanBePickedUpByNPC( ent, other ) )
{
if ( other->NPC && other->NPC->goalEntity && other->NPC->goalEntity->enemy == ent )
{//they were running to pick me up, they did, so clear goal
other->NPC->goalEntity = NULL;
other->NPC->squadState = SQUAD_STAND_AND_SHOOT;
}
}
else if (!(ent->spawnflags & ITMSF_TEAM) && !(ent->spawnflags & ITMSF_MONSTER))
{// Only player can pick it up
if ( other->s.number != 0 ) // Not the player?
{
return;
}
}
// the same pickup rules are used for client side and server side
if ( !BG_CanItemBeGrabbed( &ent->s, &other->client->ps ) ) {
return;
}
if ( other->client )
{
if ( other->client->ps.eFlags&EF_FORCE_GRIPPED )
{//can't pick up anything while being gripped
return;
}
if ( PM_InKnockDown( &other->client->ps ) && !PM_InGetUp( &other->client->ps ) )
{//can't pick up while in a knockdown
return;
}
}
if (!ent->item) { //not an item!
gi.Printf( "Touch_Item: %s is not an item!\n", ent->classname);
return;
}
qboolean bHadWeapon = qfalse;
// call the item-specific pickup function
switch( ent->item->giType )
{
case IT_WEAPON:
if ( other->NPC && other->s.weapon == WP_NONE )
{//Make them duck and sit here for a few seconds
int pickUpTime = Q_irand( 1000, 3000 );
TIMER_Set( other, "duck", pickUpTime );
TIMER_Set( other, "roamTime", pickUpTime );
TIMER_Set( other, "stick", pickUpTime );
TIMER_Set( other, "verifyCP", pickUpTime );
TIMER_Set( other, "attackDelay", 600 );
respawn = 0;
}
if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) )
{
bHadWeapon = qtrue;
}
respawn = Pickup_Weapon(ent, other);
break;
case IT_AMMO:
respawn = Pickup_Ammo(ent, other);
break;
case IT_ARMOR:
respawn = Pickup_Armor(ent, other);
break;
case IT_HEALTH:
respawn = Pickup_Health(ent, other);
break;
case IT_HOLDABLE:
respawn = Pickup_Holdable(ent, other);
break;
case IT_BATTERY:
respawn = Pickup_Battery( ent, other );
break;
case IT_HOLOCRON:
respawn = Pickup_Holocron( ent, other );
break;
default:
return;
}
if ( !respawn )
{
return;
}
// play the normal pickup sound
if ( !other->s.number && g_timescale->value < 1.0f )
{//SIGH... with timescale on, you lose events left and right
extern void CG_ItemPickup( int itemNum, qboolean bHadItem );
// but we're SP so we'll cheat
cgi_S_StartSound( NULL, other->s.number, CHAN_AUTO, cgi_S_RegisterSound( ent->item->pickup_sound ) );
// show icon and name on status bar
CG_ItemPickup( ent->s.modelindex, bHadWeapon );
}
else
{
if ( bHadWeapon )
{
G_AddEvent( other, EV_ITEM_PICKUP, -ent->s.modelindex );
}
else
{
G_AddEvent( other, EV_ITEM_PICKUP, ent->s.modelindex );
}
}
// fire item targets
G_UseTargets (ent, other);
// wait of -1 will not respawn
// if ( ent->wait == -1 )
{
//why not just remove me?
G_FreeEntity( ent );
/*
//NOTE: used to do this: (for respawning?)
ent->svFlags |= SVF_NOCLIENT;
ent->s.eFlags |= EF_NODRAW;
ent->contents = 0;
ent->unlinkAfterEvent = qtrue;
*/
return;
}
}
//======================================================================
/*
================
LaunchItem
Spawns an item and tosses it forward
================
*/
gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity, char *target ) {
gentity_t *dropped;
dropped = G_Spawn();
dropped->s.eType = ET_ITEM;
dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex
dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item
dropped->classname = item->classname;
dropped->item = item;
// try using the "correct" mins/maxs first
VectorSet( dropped->mins, item->mins[0], item->mins[1], item->mins[2] );
VectorSet( dropped->maxs, item->maxs[0], item->maxs[1], item->maxs[2] );
if ((!dropped->mins[0] && !dropped->mins[1] && !dropped->mins[2]) &&
(!dropped->maxs[0] && !dropped->maxs[1] && !dropped->maxs[2]))
{
VectorSet( dropped->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS );
VectorScale( dropped->maxs, -1, dropped->mins );
}
dropped->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_TRIGGER;//not CONTENTS_BODY for dropped items, don't need to ID them
if ( target && target[0] )
{
dropped->target = G_NewString( target );
}
else
{
// if not targeting something, auto-remove after 30 seconds
// only if it's NOT a security or goodie key
if (dropped->item->giTag != INV_SECURITY_KEY )
{
dropped->e_ThinkFunc = thinkF_G_FreeEntity;
dropped->nextthink = level.time + 30000;
}
if ( dropped->item->giType == IT_AMMO && dropped->item->giTag == AMMO_FORCE )
{
dropped->nextthink = -1;
dropped->e_ThinkFunc = thinkF_NULL;
}
}
dropped->e_TouchFunc = touchF_Touch_Item;
if ( item->giType == IT_WEAPON )
{
// give weapon items zero pitch, a random yaw, and rolled onto their sides...but would be bad to do this for a bowcaster
if ( item->giTag != WP_BOWCASTER
&& item->giTag != WP_THERMAL
&& item->giTag != WP_TRIP_MINE
&& item->giTag != WP_DET_PACK )
{
VectorSet( dropped->s.angles, 0, crandom() * 180, 90.0f );
G_SetAngles( dropped, dropped->s.angles );
}
}
G_SetOrigin( dropped, origin );
dropped->s.pos.trType = TR_GRAVITY;
dropped->s.pos.trTime = level.time;
VectorCopy( velocity, dropped->s.pos.trDelta );
dropped->s.eFlags |= EF_BOUNCE_HALF;
dropped->flags = FL_DROPPED_ITEM;
gi.linkentity (dropped);
return dropped;
}
/*
================
Drop_Item
Spawns an item and tosses it forward
================
*/
gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle, qboolean copytarget ) {
gentity_t *dropped = NULL;
vec3_t velocity;
vec3_t angles;
VectorCopy( ent->s.apos.trBase, angles );
angles[YAW] += angle;
angles[PITCH] = 0; // always forward
AngleVectors( angles, velocity, NULL, NULL );
VectorScale( velocity, 150, velocity );
velocity[2] += 200 + crandom() * 50;
if ( copytarget )
{
dropped = LaunchItem( item, ent->s.pos.trBase, velocity, ent->opentarget );
}
else
{
dropped = LaunchItem( item, ent->s.pos.trBase, velocity, NULL );
}
dropped->activator = ent;//so we know who we belonged to so they can pick it back up later
dropped->s.time = level.time;//mark this time so we aren't picked up instantly by the guy who dropped us
return dropped;
}
/*
================
Use_Item
Respawn the item
================
*/
void Use_Item( gentity_t *ent, gentity_t *other, gentity_t *activator )
{
if ( (ent->svFlags&SVF_PLAYER_USABLE) && other && !other->s.number )
{//used directly by the player, pick me up
GEntity_TouchFunc( ent, other, NULL );
}
else
{//use me
if ( ent->spawnflags & 32 ) // invisible
{
// If it was invisible, first use makes it visible....
ent->s.eFlags &= ~EF_NODRAW;
ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;
ent->spawnflags &= ~32;
return;
}
G_ActivateBehavior( ent, BSET_USE );
RespawnItem( ent );
}
}
//======================================================================
/*
================
FinishSpawningItem
Traces down to find where an item should rest, instead of letting them
free fall from their spawn points
================
*/
#ifndef FINAL_BUILD
extern int delayedShutDown;
#endif
void FinishSpawningItem( gentity_t *ent ) {
trace_t tr;
vec3_t dest;
gitem_t *item;
int itemNum;
itemNum=1;
for ( item = bg_itemlist + 1 ; item->classname ; item++,itemNum++)
{
if (!strcmp(item->classname,ent->classname))
{
break;
}
}
// Set bounding box for item
VectorSet( ent->mins, item->mins[0],item->mins[1] ,item->mins[2]);
VectorSet( ent->maxs, item->maxs[0],item->maxs[1] ,item->maxs[2]);
if ((!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) &&
(!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2]))
{
VectorSet (ent->mins, -ITEM_RADIUS, -ITEM_RADIUS, -2);//to match the comments in the items.dat file!
VectorSet (ent->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS);
}
if ((item->quantity) && (item->giType == IT_AMMO))
{
ent->count = item->quantity;
}
if ((item->quantity) && (item->giType == IT_BATTERY))
{
ent->count = item->quantity;
}
// if ( item->giType == IT_WEAPON ) // NOTE: james thought it was ok to just always do this?
{
ent->s.radius = 20;
VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f );
gi.G2API_InitGhoul2Model( ent->ghoul2, ent->item->world_model, G_ModelIndex( ent->item->world_model ), NULL_HANDLE, NULL_HANDLE, 0, 0);
}
// Set crystal ammo amount based on skill level
/* if ((itemNum == ITM_AMMO_CRYSTAL_BORG) ||
(itemNum == ITM_AMMO_CRYSTAL_DN) ||
(itemNum == ITM_AMMO_CRYSTAL_FORGE) ||
(itemNum == ITM_AMMO_CRYSTAL_SCAVENGER) ||
(itemNum == ITM_AMMO_CRYSTAL_STASIS))
{
CrystalAmmoSettings(ent);
}
*/
ent->s.eType = ET_ITEM;
ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex
ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item
ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_BODY;//CONTENTS_TRIGGER|
ent->e_TouchFunc = touchF_Touch_Item;
// useing an item causes it to respawn
ent->e_UseFunc = useF_Use_Item;
ent->svFlags |= SVF_PLAYER_USABLE;//so player can pick it up
// Hang in air?
ent->s.origin[2] += 1;//just to get it off the damn ground because coplanar = insolid
if ( ent->spawnflags & ITMSF_SUSPEND)
{
// suspended
G_SetOrigin( ent, ent->s.origin );
}
else
{
// drop to floor
VectorSet( dest, ent->s.origin[0], ent->s.origin[1], MIN_WORLD_COORD );
gi.trace( &tr, ent->s.origin, ent->mins, ent->maxs, dest, ent->s.number, MASK_SOLID|CONTENTS_PLAYERCLIP, G2_NOCOLLIDE, 0 );
if ( tr.startsolid )
{
if ( &g_entities[tr.entityNum] != NULL )
{
gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin), g_entities[tr.entityNum].classname );
}
else
{
gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin) );
}
assert( 0 && "item starting in solid");
#ifndef FINAL_BUILD
if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region
delayedShutDown = level.time + 100;
}
#endif
G_FreeEntity( ent );
return;
}
// allow to ride movers
ent->s.groundEntityNum = tr.entityNum;
G_SetOrigin( ent, tr.endpos );
}
/* ? don't need this
// team slaves and targeted items aren't present at start
if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) {
ent->s.eFlags |= EF_NODRAW;
ent->contents = 0;
return;
}
*/
if ( ent->spawnflags & ITMSF_INVISIBLE ) // invisible
{
ent->s.eFlags |= EF_NODRAW;
ent->contents = 0;
}
if ( ent->spawnflags & ITMSF_NOTSOLID ) // not solid
{
ent->contents = 0;
}
gi.linkentity (ent);
}
char itemRegistered[MAX_ITEMS+1];
/*
==============
ClearRegisteredItems
==============
*/
void ClearRegisteredItems( void ) {
for ( int i = 0; i < bg_numItems; i++ )
{
itemRegistered[i] = '0';
}<|fim▁hole|> itemRegistered[ bg_numItems ] = 0;
RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL ) ); //these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts.
RegisterItem( FindItemForWeapon( WP_STUN_BATON ) ); //these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts.
RegisterItem( FindItemForInventory( INV_ELECTROBINOCULARS ));
// saber or baton is cached in SP_info_player_deathmatch now.
extern void Player_CacheFromPrevLevel(void);//g_client.cpp
Player_CacheFromPrevLevel(); //reads from transition carry-over;
}
/*
===============
RegisterItem
The item will be added to the precache list
===============
*/
void RegisterItem( gitem_t *item ) {
if ( !item ) {
G_Error( "RegisterItem: NULL" );
}
itemRegistered[ item - bg_itemlist ] = '1';
gi.SetConfigstring(CS_ITEMS, itemRegistered); //Write the needed items to a config string
}
/*
===============
SaveRegisteredItems
Write the needed items to a config string
so the client will know which ones to precache
===============
*/
void SaveRegisteredItems( void ) {
/* char string[MAX_ITEMS+1];
int i;
int count;
count = 0;
for ( i = 0 ; i < bg_numItems ; i++ ) {
if ( itemRegistered[i] ) {
count++;
string[i] = '1';
} else {
string[i] = '0';
}
}
string[ bg_numItems ] = 0;
gi.Printf( "%i items registered\n", count );
gi.SetConfigstring(CS_ITEMS, string);
*/
gi.SetConfigstring(CS_ITEMS, itemRegistered);
}
/*
============
item_spawn_use
if an item is given a targetname, it will be spawned in when used
============
*/
void item_spawn_use( gentity_t *self, gentity_t *other, gentity_t *activator )
//-----------------------------------------------------------------------------
{
self->nextthink = level.time + 50;
self->e_ThinkFunc = thinkF_FinishSpawningItem;
// I could be fancy and add a count or something like that to be able to spawn the item numerous times...
self->e_UseFunc = useF_NULL;
}
/*
============
G_SpawnItem
Sets the clipping size and plants the object on the floor.
Items can't be immediately dropped to floor, because they might
be on an entity that hasn't spawned yet.
============
*/
void G_SpawnItem (gentity_t *ent, gitem_t *item) {
G_SpawnFloat( "random", "0", &ent->random );
G_SpawnFloat( "wait", "0", &ent->wait );
RegisterItem( item );
ent->item = item;
// targetname indicates they want to spawn it later
if( ent->targetname )
{
ent->e_UseFunc = useF_item_spawn_use;
}
else
{ // some movers spawn on the second frame, so delay item
// spawns until the third frame so they can ride trains
ent->nextthink = level.time + START_TIME_MOVERS_SPAWNED + 50;
ent->e_ThinkFunc = thinkF_FinishSpawningItem;
}
ent->physicsBounce = 0.50; // items are bouncy
// Set a default infoString text color
// NOTE: if we want to do cool cross-hair colors for items, we can just modify this, but for now, don't do it
VectorSet( ent->startRGBA, 1.0f, 1.0f, 1.0f );
}
/*
================
G_BounceItem
================
*/
void G_BounceItem( gentity_t *ent, trace_t *trace ) {
vec3_t velocity;
float dot;
int hitTime;
// reflect the velocity on the trace plane
hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction;
EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity );
dot = DotProduct( velocity, trace->plane.normal );
VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta );
// cut the velocity to keep from bouncing forever
VectorScale( ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta );
// check for stop
if ( trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40 ) {
G_SetOrigin( ent, trace->endpos );
ent->s.groundEntityNum = trace->entityNum;
return;
}
VectorAdd( ent->currentOrigin, trace->plane.normal, ent->currentOrigin);
VectorCopy( ent->currentOrigin, ent->s.pos.trBase );
ent->s.pos.trTime = level.time;
}
/*
================
G_RunItem
================
*/
void G_RunItem( gentity_t *ent ) {
vec3_t origin;
trace_t tr;
int contents;
int mask;
// if groundentity has been set to -1, it may have been pushed off an edge
if ( ent->s.groundEntityNum == ENTITYNUM_NONE )
{
if ( ent->s.pos.trType != TR_GRAVITY )
{
ent->s.pos.trType = TR_GRAVITY;
ent->s.pos.trTime = level.time;
}
}
if ( ent->s.pos.trType == TR_STATIONARY )
{
// check think function
G_RunThink( ent );
if ( !g_gravity->value )
{
ent->s.pos.trType = TR_GRAVITY;
ent->s.pos.trTime = level.time;
ent->s.pos.trDelta[0] += crandom() * 40.0f; // I dunno, just do this??
ent->s.pos.trDelta[1] += crandom() * 40.0f;
ent->s.pos.trDelta[2] += random() * 20.0f;
}
return;
}
// get current position
EvaluateTrajectory( &ent->s.pos, level.time, origin );
// trace a line from the previous position to the current position
if ( ent->clipmask )
{
mask = ent->clipmask;
}
else
{
mask = MASK_SOLID|CONTENTS_PLAYERCLIP;//shouldn't be able to get anywhere player can't
}
int ignore = ENTITYNUM_NONE;
if ( ent->owner )
{
ignore = ent->owner->s.number;
}
else if ( ent->activator )
{
ignore = ent->activator->s.number;
}
gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, G2_NOCOLLIDE, 0 );
VectorCopy( tr.endpos, ent->currentOrigin );
if ( tr.startsolid )
{
tr.fraction = 0;
}
gi.linkentity( ent ); // FIXME: avoid this for stationary?
// check think function
G_RunThink( ent );
if ( tr.fraction == 1 )
{
if ( g_gravity->value <= 0 )
{
if ( ent->s.apos.trType != TR_LINEAR )
{
VectorCopy( ent->currentAngles, ent->s.apos.trBase );
ent->s.apos.trType = TR_LINEAR;
ent->s.apos.trDelta[1] = Q_flrand( -300, 300 );
ent->s.apos.trDelta[0] = Q_flrand( -10, 10 );
ent->s.apos.trDelta[2] = Q_flrand( -10, 10 );
ent->s.apos.trTime = level.time;
}
}
//friction in zero-G
if ( !g_gravity->value )
{
float friction = 0.975f;
/*friction -= ent->mass/1000.0f;
if ( friction < 0.1 )
{
friction = 0.1f;
}
*/
VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta );
VectorCopy( ent->currentOrigin, ent->s.pos.trBase );
ent->s.pos.trTime = level.time;
}
return;
}
// if it is in a nodrop volume, remove it
contents = gi.pointcontents( ent->currentOrigin, -1 );
if ( contents & CONTENTS_NODROP )
{
G_FreeEntity( ent );
return;
}
if ( !tr.startsolid )
{
G_BounceItem( ent, &tr );
}
}
/*
================
ItemUse_Bacta
================
*/
void ItemUse_Bacta(gentity_t *ent)
{
if (!ent || !ent->client)
{
return;
}
if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH] || !ent->client->ps.inventory[INV_BACTA_CANISTER] )
{
return;
}
ent->health += MAX_BACTA_HEAL_AMOUNT;
if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH])
{
ent->health = ent->client->ps.stats[STAT_MAX_HEALTH];
}
ent->client->ps.inventory[INV_BACTA_CANISTER]--;
G_SoundOnEnt( ent, CHAN_VOICE, va( "sound/weapons/force/heal%d.mp3", Q_irand( 1, 4 ) ) );
}<|fim▁end|> | |
<|file_name|>delete_specialist_pool_sample.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def make_name(name: str) -> str:
# Sample function parameter name in delete_specialist_pool_sample<|fim▁hole|> return name<|fim▁end|> | name = name
|
<|file_name|>ores.py<|end_file_name|><|fim▁begin|>from core.rule_core import *
from core import yapi
from core.config_loader import cur_conf
class YunoModule:
name = "ores"
cfg_ver = None
ores_api = yapi.ORES
config = [
{
"models": {
"damaging": {"max_false": 0.15, "min_true": 0.8},
"goodfaith": {"min_false": 0.8, "max_true": 0.15}
},
"score": 1,
"expiry": 24
}
]
def load_config(self):
if core.config.config_mode == "online":
pass
def getScores(self, rev):
tries = 2
revid_data = 1
# Check result and check for errors
# If error faced then try again once
for i in reversed(range(tries)):
scores = self.ores_api.getScore([rev["revision"]["new"]])[cur_conf["core"]["lang"]+"wiki"]["scores"]
revid_data = scores[str(rev["revision"]["new"])]
<|fim▁hole|> logger.error("failed to fetch ores revision data: %s" % str(revid_data))
return False
else:
break
return revid_data
def run(self, rev):
score = 0
expiry = None
revid_data = self.getScores(rev)
if not revid_data:
return score, expiry
for rule in self.config:
failed = False
for item in rule["models"]:
if failed:
break
for value in rule["models"][item]:
if value == "max_false" and rule["models"][item][value] < revid_data[item]["score"]["probability"]["false"]:
failed = True
break
elif value == "min_false" and rule["models"][item][value] > revid_data[item]["score"]["probability"]["false"]:
failed = True
break
elif value == "max_true" and rule["models"][item][value] < revid_data[item]["score"]["probability"]["true"]:
failed = True
break
elif value == "min_true" and rule["models"][item][value] > revid_data[item]["score"]["probability"]["true"]:
failed = True
break
if not failed and rule["score"] > score:
score = rule["score"]
expiry = rule["expiry"]
return score, expiry<|fim▁end|> | for item in revid_data:
if "error" in revid_data[item] and "scores" not in revid_data[item]:
if i <= 0: |
<|file_name|>init.go<|end_file_name|><|fim▁begin|>package models
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"github.com/astaxie/beego"
"github.com/yaozijian/MiningOpt/distribution"
"github.com/yaozijian/relayr"
log "github.com/cihub/seelog"
)
func Init(webcfg *WebConfig) error {
switch webcfg.StartType {
case WebType_Manager:
return runTaskManager(webcfg)
case WebType_Worker:
return runTaskWorker(webcfg)
default:
return fmt.Errorf("Wrong StartType")
}
}
func runTaskManager(webcfg *WebConfig) error {
task_manager = &manager{}
task_manager.readin_task_list()
sort.SliceStable(task_manager.task_list, func(x, y int) bool {
a := task_manager.task_list[x]
b := task_manager.task_list[y]
return a.create.Unix() < b.create.Unix()
})
//-----
rpcxcfg := distribution.RpcxServerConfig{
ServiceAddr: fmt.Sprintf("%v:%v", webcfg.MyIpAddr, webcfg.RpcxPort),
EtcdServers: webcfg.EtcdServers,
URLPrefix: fmt.Sprintf("http://%v:%v", webcfg.MyIpAddr, webcfg.HttpPort),
Async: true,
}
task_manager.urlprefix = rpcxcfg.URLPrefix
task_manager.task_center = distribution.StartManager(rpcxcfg)
if task_manager.task_center == nil {
return fmt.Errorf("Error to start manager")
}
//-----
go task_manager.waitNotify()
task_manager.client_notify = relayr.NewExchange()
task_manager.client_notify.RegisterRelay(TaskStatusNotify{})
beego.Handler("/relayr/", task_manager.client_notify, true)
return nil
}
func GetTaskManager() TaskManager {
return task_manager
}<|fim▁hole|> filepath.Walk(Task_data_dir, func(p string, info os.FileInfo, e error) error {
if e != nil {
return e
}
if info.IsDir() && p != Task_data_dir {
m.readin_task(p)
}
return nil
})
}
func (m *manager) readin_task(dir string) error {
idx := strings.LastIndex(dir, string(os.PathSeparator))
id := dir[idx+1:]
f := dir + "/" + Task_status_file
cont, e := ioutil.ReadFile(f)
if e != nil {
log.Errorf("failed to read task status file %v: %v", f, e)
return e
}
var status task_status
if e = json.Unmarshal(cont, &status); e != nil {
log.Errorf("failed to parse task's status file %v: %v", f, e)
return e
}
item := &task_item{
id: id,
create: status.Create,
status: status.Status,
}
m.task_list = append(m.task_list, item)
return nil
}<|fim▁end|> |
func (m *manager) readin_task_list() {
|
<|file_name|>resource_loader.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/loader/resource_loader.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/loader/doomed_resource_handler.h"
#include "content/browser/loader/resource_loader_delegate.h"
#include "content/browser/loader/resource_request_info_impl.h"
#include "content/browser/ssl/ssl_client_auth_handler.h"
#include "content/browser/ssl/ssl_manager.h"
#include "content/common/ssl_status_serialization.h"
#include "content/public/browser/cert_store.h"
#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
#include "content/public/browser/site_instance.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/process_type.h"
#include "content/public/common/resource_response.h"
#include "content/public/common/url_constants.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/ssl/client_cert_store.h"
#include "net/ssl/client_cert_store_impl.h"
#include "webkit/appcache/appcache_interceptor.h"
using base::TimeDelta;
using base::TimeTicks;
namespace content {
namespace {
void PopulateResourceResponse(net::URLRequest* request,
ResourceResponse* response) {
response->head.error_code = request->status().error();
response->head.request_time = request->request_time();
response->head.response_time = request->response_time();
response->head.headers = request->response_headers();
request->GetCharset(&response->head.charset);
response->head.content_length = request->GetExpectedContentSize();
request->GetMimeType(&response->head.mime_type);
net::HttpResponseInfo response_info = request->response_info();
response->head.was_fetched_via_spdy = response_info.was_fetched_via_spdy;
response->head.was_npn_negotiated = response_info.was_npn_negotiated;
response->head.npn_negotiated_protocol =
response_info.npn_negotiated_protocol;
response->head.was_fetched_via_proxy = request->was_fetched_via_proxy();
response->head.socket_address = request->GetSocketAddress();
appcache::AppCacheInterceptor::GetExtraResponseInfo(
request,
&response->head.appcache_id,
&response->head.appcache_manifest_url);
}
} // namespace
ResourceLoader::ResourceLoader(scoped_ptr<net::URLRequest> request,
scoped_ptr<ResourceHandler> handler,
ResourceLoaderDelegate* delegate)
: weak_ptr_factory_(this) {
scoped_ptr<net::ClientCertStore> client_cert_store;
#if !defined(USE_OPENSSL)
client_cert_store.reset(new net::ClientCertStoreImpl());
#endif
Init(request.Pass(), handler.Pass(), delegate, client_cert_store.Pass());
}
ResourceLoader::~ResourceLoader() {
if (login_delegate_)
login_delegate_->OnRequestCancelled();
if (ssl_client_auth_handler_)
ssl_client_auth_handler_->OnRequestCancelled();
// Run ResourceHandler destructor before we tear-down the rest of our state
// as the ResourceHandler may want to inspect the URLRequest and other state.
handler_.reset();
}
void ResourceLoader::StartRequest() {
if (delegate_->HandleExternalProtocol(this, request_->url())) {
CancelAndIgnore();
return;
}
// Give the handler a chance to delay the URLRequest from being started.
bool defer_start = false;<|fim▁hole|> if (!handler_->OnWillStart(GetRequestInfo()->GetRequestID(), request_->url(),
&defer_start)) {
Cancel();
return;
}
if (defer_start) {
deferred_stage_ = DEFERRED_START;
} else {
StartRequestInternal();
}
}
void ResourceLoader::CancelRequest(bool from_renderer) {
CancelRequestInternal(net::ERR_ABORTED, from_renderer);
}
void ResourceLoader::CancelAndIgnore() {
ResourceRequestInfoImpl* info = GetRequestInfo();
info->set_was_ignored_by_handler(true);
CancelRequest(false);
}
void ResourceLoader::CancelWithError(int error_code) {
CancelRequestInternal(error_code, false);
}
void ResourceLoader::ReportUploadProgress() {
ResourceRequestInfoImpl* info = GetRequestInfo();
if (waiting_for_upload_progress_ack_)
return; // Send one progress event at a time.
net::UploadProgress progress = request_->GetUploadProgress();
if (!progress.size())
return; // Nothing to upload.
if (progress.position() == last_upload_position_)
return; // No progress made since last time.
const uint64 kHalfPercentIncrements = 200;
const TimeDelta kOneSecond = TimeDelta::FromMilliseconds(1000);
uint64 amt_since_last = progress.position() - last_upload_position_;
TimeDelta time_since_last = TimeTicks::Now() - last_upload_ticks_;
bool is_finished = (progress.size() == progress.position());
bool enough_new_progress =
(amt_since_last > (progress.size() / kHalfPercentIncrements));
bool too_much_time_passed = time_since_last > kOneSecond;
if (is_finished || enough_new_progress || too_much_time_passed) {
if (request_->load_flags() & net::LOAD_ENABLE_UPLOAD_PROGRESS) {
handler_->OnUploadProgress(
info->GetRequestID(), progress.position(), progress.size());
waiting_for_upload_progress_ack_ = true;
}
last_upload_ticks_ = TimeTicks::Now();
last_upload_position_ = progress.position();
}
}
void ResourceLoader::MarkAsTransferring() {
is_transferring_ = true;
// When an URLRequest is transferred to a new RenderViewHost, its
// ResourceHandler should not receive any notifications because it may depend
// on the state of the old RVH. We set a ResourceHandler that only allows
// canceling requests, because on shutdown of the RDH all pending requests
// are canceled. The RVH of requests that are being transferred may be gone
// by that time. In CompleteTransfer, the ResoureHandlers are substituted
// again.
handler_.reset(new DoomedResourceHandler(handler_.Pass()));
}
void ResourceLoader::WillCompleteTransfer() {
handler_.reset();
}
void ResourceLoader::CompleteTransfer(scoped_ptr<ResourceHandler> new_handler) {
DCHECK_EQ(DEFERRED_REDIRECT, deferred_stage_);
DCHECK(!handler_.get());
handler_ = new_handler.Pass();
handler_->SetController(this);
is_transferring_ = false;
Resume();
}
ResourceRequestInfoImpl* ResourceLoader::GetRequestInfo() {
return ResourceRequestInfoImpl::ForRequest(request_.get());
}
void ResourceLoader::ClearLoginDelegate() {
login_delegate_ = NULL;
}
void ResourceLoader::ClearSSLClientAuthHandler() {
ssl_client_auth_handler_ = NULL;
}
void ResourceLoader::OnUploadProgressACK() {
waiting_for_upload_progress_ack_ = false;
}
ResourceLoader::ResourceLoader(
scoped_ptr<net::URLRequest> request,
scoped_ptr<ResourceHandler> handler,
ResourceLoaderDelegate* delegate,
scoped_ptr<net::ClientCertStore> client_cert_store)
: weak_ptr_factory_(this) {
Init(request.Pass(), handler.Pass(), delegate, client_cert_store.Pass());
}
void ResourceLoader::Init(scoped_ptr<net::URLRequest> request,
scoped_ptr<ResourceHandler> handler,
ResourceLoaderDelegate* delegate,
scoped_ptr<net::ClientCertStore> client_cert_store) {
deferred_stage_ = DEFERRED_NONE;
request_ = request.Pass();
handler_ = handler.Pass();
delegate_ = delegate;
last_upload_position_ = 0;
waiting_for_upload_progress_ack_ = false;
is_transferring_ = false;
client_cert_store_ = client_cert_store.Pass();
request_->set_delegate(this);
handler_->SetController(this);
}
void ResourceLoader::OnReceivedRedirect(net::URLRequest* unused,
const GURL& new_url,
bool* defer) {
DCHECK_EQ(request_.get(), unused);
VLOG(1) << "OnReceivedRedirect: " << request_->url().spec();
DCHECK(request_->status().is_success());
ResourceRequestInfoImpl* info = GetRequestInfo();
if (info->process_type() != PROCESS_TYPE_PLUGIN &&
!ChildProcessSecurityPolicyImpl::GetInstance()->
CanRequestURL(info->GetChildID(), new_url)) {
VLOG(1) << "Denied unauthorized request for "
<< new_url.possibly_invalid_spec();
// Tell the renderer that this request was disallowed.
Cancel();
return;
}
delegate_->DidReceiveRedirect(this, new_url);
if (delegate_->HandleExternalProtocol(this, new_url)) {
// The request is complete so we can remove it.
CancelAndIgnore();
return;
}
scoped_refptr<ResourceResponse> response(new ResourceResponse());
PopulateResourceResponse(request_.get(), response);
if (!handler_->OnRequestRedirected(info->GetRequestID(), new_url, response,
defer)) {
Cancel();
} else if (*defer) {
deferred_stage_ = DEFERRED_REDIRECT; // Follow redirect when resumed.
}
}
void ResourceLoader::OnAuthRequired(net::URLRequest* unused,
net::AuthChallengeInfo* auth_info) {
DCHECK_EQ(request_.get(), unused);
if (request_->load_flags() & net::LOAD_DO_NOT_PROMPT_FOR_LOGIN) {
request_->CancelAuth();
return;
}
if (!delegate_->AcceptAuthRequest(this, auth_info)) {
request_->CancelAuth();
return;
}
// Create a login dialog on the UI thread to get authentication data, or pull
// from cache and continue on the IO thread.
DCHECK(!login_delegate_) <<
"OnAuthRequired called with login_delegate pending";
login_delegate_ = delegate_->CreateLoginDelegate(this, auth_info);
if (!login_delegate_)
request_->CancelAuth();
}
void ResourceLoader::OnCertificateRequested(
net::URLRequest* unused,
net::SSLCertRequestInfo* cert_info) {
DCHECK_EQ(request_.get(), unused);
if (!delegate_->AcceptSSLClientCertificateRequest(this, cert_info)) {
request_->Cancel();
return;
}
#if !defined(USE_OPENSSL)
client_cert_store_->GetClientCerts(*cert_info, &cert_info->client_certs);
if (cert_info->client_certs.empty()) {
// No need to query the user if there are no certs to choose from.
request_->ContinueWithCertificate(NULL);
return;
}
#endif
DCHECK(!ssl_client_auth_handler_) <<
"OnCertificateRequested called with ssl_client_auth_handler pending";
ssl_client_auth_handler_ = new SSLClientAuthHandler(request_.get(),
cert_info);
ssl_client_auth_handler_->SelectCertificate();
}
void ResourceLoader::OnSSLCertificateError(net::URLRequest* request,
const net::SSLInfo& ssl_info,
bool fatal) {
ResourceRequestInfoImpl* info = GetRequestInfo();
int render_process_id;
int render_view_id;
if (!info->GetAssociatedRenderView(&render_process_id, &render_view_id))
NOTREACHED();
SSLManager::OnSSLCertificateError(
weak_ptr_factory_.GetWeakPtr(),
info->GetGlobalRequestID(),
info->GetResourceType(),
request_->url(),
render_process_id,
render_view_id,
ssl_info,
fatal);
}
void ResourceLoader::OnResponseStarted(net::URLRequest* unused) {
DCHECK_EQ(request_.get(), unused);
VLOG(1) << "OnResponseStarted: " << request_->url().spec();
// The CanLoadPage check should take place after any server redirects have
// finished, at the point in time that we know a page will commit in the
// renderer process.
ResourceRequestInfoImpl* info = GetRequestInfo();
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->CanLoadPage(info->GetChildID(),
request_->url(),
info->GetResourceType())) {
Cancel();
return;
}
if (!request_->status().is_success()) {
ResponseCompleted();
return;
}
// We want to send a final upload progress message prior to sending the
// response complete message even if we're waiting for an ack to to a
// previous upload progress message.
waiting_for_upload_progress_ack_ = false;
ReportUploadProgress();
CompleteResponseStarted();
if (is_deferred())
return;
if (request_->status().is_success()) {
StartReading(false); // Read the first chunk.
} else {
ResponseCompleted();
}
}
void ResourceLoader::OnReadCompleted(net::URLRequest* unused, int bytes_read) {
DCHECK_EQ(request_.get(), unused);
VLOG(1) << "OnReadCompleted: \"" << request_->url().spec() << "\""
<< " bytes_read = " << bytes_read;
// bytes_read == -1 always implies an error.
if (bytes_read == -1 || !request_->status().is_success()) {
ResponseCompleted();
return;
}
CompleteRead(bytes_read);
if (is_deferred())
return;
if (request_->status().is_success() && bytes_read > 0) {
StartReading(true); // Read the next chunk.
} else {
ResponseCompleted();
}
}
void ResourceLoader::CancelSSLRequest(const GlobalRequestID& id,
int error,
const net::SSLInfo* ssl_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// The request can be NULL if it was cancelled by the renderer (as the
// request of the user navigating to a new page from the location bar).
if (!request_->is_pending())
return;
DVLOG(1) << "CancelSSLRequest() url: " << request_->url().spec();
if (ssl_info) {
request_->CancelWithSSLError(error, *ssl_info);
} else {
request_->CancelWithError(error);
}
}
void ResourceLoader::ContinueSSLRequest(const GlobalRequestID& id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DVLOG(1) << "ContinueSSLRequest() url: " << request_->url().spec();
request_->ContinueDespiteLastError();
}
void ResourceLoader::Resume() {
DCHECK(!is_transferring_);
DeferredStage stage = deferred_stage_;
deferred_stage_ = DEFERRED_NONE;
switch (stage) {
case DEFERRED_NONE:
NOTREACHED();
break;
case DEFERRED_START:
StartRequestInternal();
break;
case DEFERRED_REDIRECT:
request_->FollowDeferredRedirect();
break;
case DEFERRED_READ:
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&ResourceLoader::ResumeReading,
weak_ptr_factory_.GetWeakPtr()));
break;
case DEFERRED_FINISH:
// Delay self-destruction since we don't know how we were reached.
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&ResourceLoader::CallDidFinishLoading,
weak_ptr_factory_.GetWeakPtr()));
break;
}
}
void ResourceLoader::Cancel() {
CancelRequest(false);
}
void ResourceLoader::StartRequestInternal() {
DCHECK(!request_->is_pending());
request_->Start();
delegate_->DidStartRequest(this);
}
void ResourceLoader::CancelRequestInternal(int error, bool from_renderer) {
VLOG(1) << "CancelRequestInternal: " << request_->url().spec();
ResourceRequestInfoImpl* info = GetRequestInfo();
// WebKit will send us a cancel for downloads since it no longer handles
// them. In this case, ignore the cancel since we handle downloads in the
// browser.
if (from_renderer && (info->is_download() || info->is_stream()))
return;
// TODO(darin): Perhaps we should really be looking to see if the status is
// IO_PENDING?
bool was_pending = request_->is_pending();
if (login_delegate_) {
login_delegate_->OnRequestCancelled();
login_delegate_ = NULL;
}
if (ssl_client_auth_handler_) {
ssl_client_auth_handler_->OnRequestCancelled();
ssl_client_auth_handler_ = NULL;
}
request_->CancelWithError(error);
if (!was_pending) {
// If the request isn't in flight, then we won't get an asynchronous
// notification from the request, so we have to signal ourselves to finish
// this request.
MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&ResourceLoader::ResponseCompleted,
weak_ptr_factory_.GetWeakPtr()));
}
}
void ResourceLoader::CompleteResponseStarted() {
ResourceRequestInfoImpl* info = GetRequestInfo();
scoped_refptr<ResourceResponse> response(new ResourceResponse());
PopulateResourceResponse(request_.get(), response);
// The --site-per-process flag enables an out-of-process iframes
// prototype. It works by changing the MIME type of cross-site subframe
// responses to a Chrome specific one. This new type causes the subframe
// to be replaced by a <webview> tag with the same URL, which results in
// using a renderer in a different process.
//
// For prototyping purposes, we will use a small hack to ensure same site
// iframes are not changed. We can compare the URL for the subframe
// request with the referrer. If the two don't match, then it should be a
// cross-site iframe.
// Also, we don't do the MIME type change for chrome:// URLs, as those
// require different privileges and are not allowed in regular renderers.
//
// The usage of SiteInstance::IsSameWebSite is safe on the IO thread,
// if the browser_context parameter is NULL. This does not work for hosted
// apps, but should be fine for prototyping.
// TODO(nasko): Once the SiteInstance check is fixed, ensure we do the
// right thing here. http://crbug.com/160576
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kSitePerProcess) &&
GetRequestInfo()->GetResourceType() == ResourceType::SUB_FRAME &&
response->head.mime_type == "text/html" &&
!request_->url().SchemeIs(chrome::kChromeUIScheme) &&
!SiteInstance::IsSameWebSite(NULL, request_->url(),
request_->GetSanitizedReferrer())) {
response->head.mime_type = "application/browser-plugin";
}
if (request_->ssl_info().cert) {
int cert_id =
CertStore::GetInstance()->StoreCert(request_->ssl_info().cert,
info->GetChildID());
response->head.security_info = SerializeSecurityInfo(
cert_id,
request_->ssl_info().cert_status,
request_->ssl_info().security_bits,
request_->ssl_info().connection_status);
} else {
// We should not have any SSL state.
DCHECK(!request_->ssl_info().cert_status &&
request_->ssl_info().security_bits == -1 &&
!request_->ssl_info().connection_status);
}
delegate_->DidReceiveResponse(this);
bool defer = false;
if (!handler_->OnResponseStarted(info->GetRequestID(), response, &defer)) {
Cancel();
} else if (defer) {
deferred_stage_ = DEFERRED_READ; // Read first chunk when resumed.
}
}
void ResourceLoader::StartReading(bool is_continuation) {
int bytes_read = 0;
ReadMore(&bytes_read);
// If IO is pending, wait for the URLRequest to call OnReadCompleted.
if (request_->status().is_io_pending())
return;
if (!is_continuation || bytes_read <= 0) {
OnReadCompleted(request_.get(), bytes_read);
} else {
// Else, trigger OnReadCompleted asynchronously to avoid starving the IO
// thread in case the URLRequest can provide data synchronously.
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&ResourceLoader::OnReadCompleted,
weak_ptr_factory_.GetWeakPtr(),
request_.get(), bytes_read));
}
}
void ResourceLoader::ResumeReading() {
DCHECK(!is_deferred());
if (request_->status().is_success()) {
StartReading(false); // Read the next chunk (OK to complete synchronously).
} else {
ResponseCompleted();
}
}
void ResourceLoader::ReadMore(int* bytes_read) {
ResourceRequestInfoImpl* info = GetRequestInfo();
DCHECK(!is_deferred());
net::IOBuffer* buf;
int buf_size;
if (!handler_->OnWillRead(info->GetRequestID(), &buf, &buf_size, -1)) {
Cancel();
return;
}
DCHECK(buf);
DCHECK(buf_size > 0);
request_->Read(buf, buf_size, bytes_read);
// No need to check the return value here as we'll detect errors by
// inspecting the URLRequest's status.
}
void ResourceLoader::CompleteRead(int bytes_read) {
DCHECK(bytes_read >= 0);
DCHECK(request_->status().is_success());
ResourceRequestInfoImpl* info = GetRequestInfo();
bool defer = false;
if (!handler_->OnReadCompleted(info->GetRequestID(), bytes_read, &defer)) {
Cancel();
} else if (defer) {
deferred_stage_ = DEFERRED_READ; // Read next chunk when resumed.
}
}
void ResourceLoader::ResponseCompleted() {
VLOG(1) << "ResponseCompleted: " << request_->url().spec();
ResourceRequestInfoImpl* info = GetRequestInfo();
std::string security_info;
const net::SSLInfo& ssl_info = request_->ssl_info();
if (ssl_info.cert != NULL) {
int cert_id = CertStore::GetInstance()->StoreCert(ssl_info.cert,
info->GetChildID());
security_info = SerializeSecurityInfo(
cert_id, ssl_info.cert_status, ssl_info.security_bits,
ssl_info.connection_status);
}
if (handler_->OnResponseCompleted(info->GetRequestID(), request_->status(),
security_info)) {
// This will result in our destruction.
CallDidFinishLoading();
} else {
// The handler is not ready to die yet. We will call DidFinishLoading when
// we resume.
deferred_stage_ = DEFERRED_FINISH;
}
}
void ResourceLoader::CallDidFinishLoading() {
delegate_->DidFinishLoading(this);
}
} // namespace content<|fim▁end|> | |
<|file_name|>cover.js<|end_file_name|><|fim▁begin|>// @flow
var React = require('react')
var {assign} = require('lodash')
import {Source, emptySource} from './model/source'
import {displayIf, Colors} from './style'
// but get the images at 2x resolution so they can be retina yo
// or just get the photos at that ratio
// 200x320 x2
// 150x240
// 100x160
// Blank Image - http://i.imgur.com/bMwt85W.jpg
type Size = {
Width: number;
Height: number;
}
export var CoverSize = {
Width: 150,
Height: 240,
Ratio: 1.6
}
export var CoverThumb = {
Width: 50,
Height: 80,
}
export function coverStyle(url:string, size:Size = CoverSize):Object {
// otherwise it forgets about the cover. Wait until the image is ready
if (!url) {
return {}
}
return {
background: 'url('+url+') no-repeat center center',
backgroundSize: 'cover',
width: size.Width,
height: size.Height
}
}
export class CoverOverlay extends React.Component {
render():React.Element {
var style = assign(
displayIf(this.props.show !== false),
OverlayStyle,
CoverTextStyle,
this.props.style
)
return <div style={style}>
{this.props.children}
</div>
}
}
export class Cover extends React.Component {
props: {
src: string;
size?: Size;
children: Array<React.Element>;
};
render():React.Element {
var size = this.props.size || CoverSize
return <div style={assign(coverStyle(this.props.src, size), {position: 'relative'})}>
{this.props.children}
</div>
}
}
export class SourceCover extends React.Component {
render():React.Element {
var source:Source = this.props.source || emptySource()
var showTitle:bool = source.imageMissingTitle
return <Cover src={source.imageUrl}>
<CoverOverlay show={showTitle}>{source.name}</CoverOverlay>
</Cover>
}
}
// I could specify it in terms of percentages instead?
// that's a good idea.
// so do I want 2 or 3 across?
// definitely 3 :)
export var OverlayStyle = {
padding: 10,
color: Colors.light,
textAlign: 'center',
position: 'absolute',
bottom: 0,
fontSize: 18,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
width: CoverSize.Width
}<|fim▁hole|><|fim▁end|> |
export var CoverTextStyle = {
fontSize: 18,
} |
<|file_name|>value.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 Grove Enterprises LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//use std::fmt;
//use std::ops::Add;
//use std::rc::Rc;
//
//use arrow::array::{Int32Array, Int64Array};
//use arrow::datatypes::DataType;
//
//use super::error::{ExecutionError, Result};
//impl ScalarValue {
// pub fn get_datatype(&self) -> DataType {
// match *self {
// ScalarValue::Boolean(_) => DataType::Boolean,
// ScalarValue::UInt8(_) => DataType::UInt8,
// ScalarValue::UInt16(_) => DataType::UInt16,
// ScalarValue::UInt32(_) => DataType::UInt32,
// ScalarValue::UInt64(_) => DataType::UInt64,
// ScalarValue::Int8(_) => DataType::Int8,
// ScalarValue::Int16(_) => DataType::Int16,
// ScalarValue::Int32(_) => DataType::Int32,
// ScalarValue::Int64(_) => DataType::Int64,
// ScalarValue::Float32(_) => DataType::Float32,
// ScalarValue::Float64(_) => DataType::Float64,
// ScalarValue::Utf8(_) => DataType::Utf8,
// ScalarValue::Struct(_) => unimplemented!(),
// ScalarValue::Null => unimplemented!(),
// }
// }
//}
//
//pub fn can_coerce_from(left: &DataType, other: &DataType) -> bool {
// use self::DataType::*;
// match left {
// Int8 => match other {
// Int8 => true,
// _ => false,
// },
// Int16 => match other {
// Int8 | Int16 => true,
// _ => false,
// },
// Int32 => match other {
// Int8 | Int16 | Int32 => true,
// _ => false,
// },
// Int64 => match other {
// Int8 | Int16 | Int32 | Int64 => true,
// _ => false,
// },
// UInt8 => match other {
// UInt8 => true,
// _ => false,
// },
// UInt16 => match other {
// UInt8 | UInt16 => true,
// _ => false,
// },
// UInt32 => match other {
// UInt8 | UInt16 | UInt32 => true,
// _ => false,
// },
// UInt64 => match other {
// UInt8 | UInt16 | UInt32 | UInt64 => true,
// _ => false,
// },
// Float32 => match other {
// Int8 | Int16 | Int32 | Int64 => true,
// UInt8 | UInt16 | UInt32 | UInt64 => true,
// Float32 => true,
// _ => false,
// },
// Float64 => match other {
// Int8 | Int16 | Int32 | Int64 => true,
// UInt8 | UInt16 | UInt32 | UInt64 => true,
// Float32 | Float64 => true,
// _ => false,
// },
// _ => false,
// }
//}
//
//macro_rules! primitive_accessor {
// ($NAME:ident, $VARIANT:ident, $TY:ty) => {
// pub fn $NAME(&self) -> Result<$TY> {
// match self {
// ScalarValue::$VARIANT(v) => Ok(*v),
// other => Err(ExecutionError::General(format!("Cannot access scalar value {:?} as {}", other, stringify!($VARIANT))))
// }
// }
// }
//}
//
//impl ScalarValue {
// primitive_accessor!(get_bool, Boolean, bool);
// primitive_accessor!(get_i8, Int8, i8);
// primitive_accessor!(get_i16, Int16, i16);
// primitive_accessor!(get_i32, Int32, i32);
// primitive_accessor!(get_i64, Int64, i64);
// primitive_accessor!(get_u8, UInt8, u8);
// primitive_accessor!(get_u16, UInt16, u16);
// primitive_accessor!(get_u32, UInt32, u32);
// primitive_accessor!(get_u64, UInt64, u64);
// primitive_accessor!(get_f32, Float32, f32);
// primitive_accessor!(get_f64, Float64, f64);
//
// pub fn get_string(&self) -> Result<&String> {
// match *self {
// ScalarValue::Utf8(ref v) => Ok(v),
// _ => Err(ExecutionError::from("TBD")),
// }
// }
//<|fim▁hole|>// }
// }
//}
//
//impl Add for ScalarValue {
// type Output = ScalarValue;
//
// fn add(self, rhs: ScalarValue) -> ScalarValue {
// assert_eq!(self.get_datatype(), rhs.get_datatype());
// match self {
// ScalarValue::UInt8(x) => ScalarValue::UInt8(x + rhs.get_u8().unwrap()),
// ScalarValue::UInt16(x) => ScalarValue::UInt16(x + rhs.get_u16().unwrap()),
// ScalarValue::UInt32(x) => ScalarValue::UInt32(x + rhs.get_u32().unwrap()),
// ScalarValue::UInt64(x) => ScalarValue::UInt64(x + rhs.get_u64().unwrap()),
// ScalarValue::Float32(x) => ScalarValue::Float32(x + rhs.get_f32().unwrap()),
// ScalarValue::Float64(x) => ScalarValue::Float64(x + rhs.get_f64().unwrap()),
// ScalarValue::Int8(x) => ScalarValue::Int8(x.saturating_add(rhs.get_i8().unwrap())),
// ScalarValue::Int16(x) => ScalarValue::Int16(x.saturating_add(rhs.get_i16().unwrap())),
// ScalarValue::Int32(x) => ScalarValue::Int32(x.saturating_add(rhs.get_i32().unwrap())),
// ScalarValue::Int64(x) => ScalarValue::Int64(x.saturating_add(rhs.get_i64().unwrap())),
// _ => panic!("Unsupported type for addition"),
// }
// }
//}
//
//impl fmt::Display for ScalarValue {
// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// match self {
// ScalarValue::Null => write!(f, "NULL"),
// ScalarValue::Boolean(v) => write!(f, "{}", v),
// ScalarValue::Int8(v) => write!(f, "{}", v),
// ScalarValue::Int16(v) => write!(f, "{}", v),
// ScalarValue::Int32(v) => write!(f, "{}", v),
// ScalarValue::Int64(v) => write!(f, "{}", v),
// ScalarValue::UInt8(v) => write!(f, "{}", v),
// ScalarValue::UInt16(v) => write!(f, "{}", v),
// ScalarValue::UInt32(v) => write!(f, "{}", v),
// ScalarValue::UInt64(v) => write!(f, "{}", v),
// ScalarValue::Float32(v) => write!(f, "{}", v),
// ScalarValue::Float64(v) => write!(f, "{}", v),
// ScalarValue::Utf8(ref v) => write!(f, "{}", v),
// ScalarValue::Struct(ref v) => {
// for i in 0..v.len() {
// if i > 0 {
// write!(f, ", ")?;
// }
// write!(f, "{}", v[i])?;
// }
// Ok(())
// }
// }
// }
//}<|fim▁end|> | // pub fn get_struct(&self) -> Result<&Vec<ScalarValue>> {
// match *self {
// ScalarValue::Struct(ref v) => Ok(v),
// _ => Err(ExecutionError::from("TBD")), |
<|file_name|>gulpfile-advanced.js<|end_file_name|><|fim▁begin|>var basePaths = {
src: 'public/',
dest: 'public.dist/',
bower: 'bower_components/'
};
var paths = {
images: {
src: basePaths.src + 'images/',
dest: basePaths.dest + 'images/min/'
},
scripts: {
src: basePaths.src + 'scripts/',
dest: basePaths.dest + 'scripts/min/'
},
styles: {
src: basePaths.src + 'styles/',
dest: basePaths.dest + 'styles/min/'
},
sprite: {
src: basePaths.src + 'sprite/*'
}
};
var appFiles = {
styles: paths.styles.src + '**/*.scss',
scripts: [paths.scripts.src + 'scripts.js']
};
var vendorFiles = {
styles: '',
scripts: ''
};
var spriteConfig = {
imgName: 'sprite.png',
cssName: '_sprite.scss',
imgPath: paths.images.dest.replace('public', '') + 'sprite.png'
};
// let the magic begin
var gulp = require('gulp');
var es = require('event-stream');
var gutil = require('gulp-util');
var autoprefixer = require('gulp-autoprefixer');
var plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/
});
// allows gulp --dev to be run for a more verbose output
var isProduction = true;
var sassStyle = 'compressed';
var sourceMap = false;
if (gutil.env.dev === true) {
sassStyle = 'expanded';
sourceMap = true;<|fim▁hole|> isProduction = false;
}
var changeEvent = function(evt) {
gutil.log('File', gutil.colors.cyan(evt.path.replace(new RegExp('/.*(?=/' + basePaths.src + ')/'), '')), 'was', gutil.colors.magenta(evt.type));
};
gulp.task('css', function() {
var sassFiles = gulp.src(appFiles.styles)
/*
.pipe(plugins.rubySass({
style: sassStyle, sourcemap: sourceMap, precision: 2
}))
*/
.pipe(plugins.sass())
.on('error', function(err) {
new gutil.PluginError('CSS', err, {showStack: true});
});
return es.concat(gulp.src(vendorFiles.styles), sassFiles)
.pipe(plugins.concat('style.min.css'))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4', 'Firefox >= 4'))
/*
.pipe(isProduction ? plugins.combineMediaQueries({
log: true
}) : gutil.noop())
*/
.pipe(isProduction ? plugins.cssmin() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.styles.dest))
;
});
gulp.task('scripts', function() {
gulp.src(vendorFiles.scripts.concat(appFiles.scripts))
.pipe(plugins.concat('app.js'))
.pipe(isProduction ? plugins.uglify() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.scripts.dest))
;
});
// sprite generator
gulp.task('sprite', function() {
var spriteData = gulp.src(paths.sprite.src).pipe(plugins.spritesmith({
imgName: spriteConfig.imgName,
cssName: spriteConfig.cssName,
imgPath: spriteConfig.imgPath,
cssOpts: {
functions: false
},
cssVarMap: function (sprite) {
sprite.name = 'sprite-' + sprite.name;
}
}));
spriteData.img.pipe(gulp.dest(paths.images.dest));
spriteData.css.pipe(gulp.dest(paths.styles.src));
});
gulp.task('watch', ['sprite', 'css', 'scripts'], function() {
gulp.watch(appFiles.styles, ['css']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.scripts.src + '*.js', ['scripts']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.sprite.src, ['sprite']).on('change', function(evt) {
changeEvent(evt);
});
});
gulp.task('default', ['css', 'scripts']);<|fim▁end|> | |
<|file_name|>add_file.py<|end_file_name|><|fim▁begin|>import re
from __future__ import print_function
HEADER_TEMPLATE=r"""/*
Copyright 2016, Austen Satterlee
This file is part of VOSIMProject.
VOSIMProject 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.
VOSIMProject 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 VOSIMProject. If not, see <http://www.gnu.org/licenses/>.
*/
{guard}
"""
IFNDEF_TEMPLATE = r"""
#ifndef __{guardname}__
#define __{guardname}__
#endif
"""
PRAGMA_ONCE_TEMPLATE = r"""
#pragma once
"""
SOURCE_TEMPLATE="#include \"{filename:}.h\""
def find_valid_directories(source_dir, include_dir):
sofar = []
def _walker(ret_list, dirname, fnames):
if (source_dir in fnames) and (include_dir in fnames):
ret_list.append(dirname)
# m_dirname = re.sub(r'\binclude\b|\bsrc\b', '', dirname)
# if m_dirname in sofar:
# ret_list.append(dirname)
# else:
# sofar.append(m_dirname)
valid_directories = []
os.path.walk(".", _walker, valid_directories)<|fim▁hole|>
if __name__=="__main__":
import argparse as ap
import os,sys,datetime
parser = ap.ArgumentParser(formatter_class=ap.ArgumentDefaultsHelpFormatter)
parser.add_argument("-n", "--dry-run", action="store_true",
help="Don't perform any actions, just print would be done")
parser.add_argument("-f", "--force", action="store_true",
help="Overwrite existing files")
parser.add_argument("--guard",choices=["pragma","ifndef"], default="pragma",
help="Choose the type of header guard to use")
subparsers = parser.add_subparsers(title="commands")
parser_auto_add = subparsers.add_parser("auto-add",
help="Add source and include files to their respective directories. Automatically detect source and\
include directories given a base directory")
parser_auto_add.add_argument("directory", nargs='?', type=str, help="Directory that contains 'src' and 'include' dirs")
parser_auto_add.add_argument("filenames", nargs='*', type=str, help="Name of the new files to add (without extension)")
parser_auto_add.add_argument("--list", "-l", action="store_true", help="List valid directories and exit")
parser_auto_add.set_defaults(command="auto-add")
parser_add = subparsers.add_parser("add", help="Add source and include files to the specified directories")
parser_add.add_argument("source_dir", type=str)
parser_add.add_argument("include_dir", type=str)
parser_add.add_argument("filenames", nargs='+', type=str)
parser_add.set_defaults(command="add")
parsed = parser.parse_args()
if parsed.command=="auto-add":
if parsed.list:
print('\n'.join(find_valid_directories('src', 'include')))
sys.exit(1)
if not parsed.directory:
sys.stderr.write("ERROR: Please provide a directory\n")
sys.exit(1)
if not parsed.filenames:
sys.stderr.write("ERROR: Please provide at least one filename\n")
sys.exit(1)
directory = os.path.normpath(parsed.directory)
dir_contents = os.listdir(directory)
if ('src' not in dir_contents) or ('include' not in dir_contents):
raise RuntimeError("'%s' and '%s' directories not found" % (parsed.source_dir,parsed.include_dir))
include_dir = os.path.join(directory,"include")
src_dir = os.path.join(directory,"src")
if parsed.command=="add":
include_dir = os.path.normpath(parsed.include_dir)
src_dir = os.path.normpath(parsed.source_dir)
# Check that directories exist
if not os.path.exists(src_dir):
sys.stderr.write("ERROR: Source directory '%s' does not exist\n" % source_dir)
sys.exit(1)
if not os.path.exists(include_dir):
sys.stderr.write("ERROR: Include directory '%s' does not exist\n" % include_dir)
sys.exit(1)
for filename in parsed.filenames:
include_fname = os.path.join(include_dir, filename+".h")
src_fname = os.path.join(src_dir, filename+".cpp")
if not parsed.force and (os.path.exists(include_fname) or os.path.exists(src_fname)):
sys.stderr.write("ERROR: '%s' or '%s' already exists!\n" % (include_fname,src_fname))
sys.exit(1)
guard_str = PRAGMA_ONCE_TEMPLATE if parsed.guard=="pragma" else IFNDEF_TEMPLATE.format(guardname=filename.toupper())
include_contents = HEADER_TEMPLATE.format(
filename=filename,
guard=guard_str,
date=datetime.date.today().strftime("%m/%Y")
)
src_contents = SOURCE_TEMPLATE.format(filename=filename)
if not parsed.dry_run:
with open(include_fname,"w") as fp:
fp.write(include_contents)
sys.stdout.write("Added header file to {}\n".format(include_fname))
if not parsed.dry_run:
with open(src_fname,"w") as fp:
fp.write(src_contents)
sys.stdout.write("Added source file to {}\n".format(src_fname))
sys.exit()<|fim▁end|> | return valid_directories |
<|file_name|>tata.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: Mr.Blamo
import base64
import json
import re
import urllib
import urlparse
from openscrapers.modules import cleantitle
from openscrapers.modules import client
from openscrapers.modules import directstream
from openscrapers.modules import dom_parser
from openscrapers.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['tata.to']
self.base_link = 'http://tata.to'
self.search_link = '/filme?suche=%s&type=alle'
self.ajax_link = '/ajax/stream/%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search_movie(imdb, year)
return url if url else None
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'localtvshowtitle': localtvshowtitle,
'aliases': aliases, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if not url:
return
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
tvshowtitle = data['tvshowtitle']
localtvshowtitle = data['localtvshowtitle']
aliases = source_utils.aliases_to_array(eval(data['aliases']))
year = re.findall('(\d{4})', premiered)
year = year[0] if year else data['year']
url = self.__search([localtvshowtitle] + aliases, year, season, episode)
if not url and tvshowtitle != localtvshowtitle:
url = self.__search([tvshowtitle] + aliases, year, season, episode)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
ref = urlparse.urljoin(self.base_link, url)
url = urlparse.urljoin(self.base_link, self.ajax_link % re.findall('-(\w+)$', ref)[0])
headers = {'Referer': ref, 'User-Agent': client.randomagent()}
result = client.request(url, headers=headers, post='')
result = base64.decodestring(result)
result = json.loads(result).get('playinfo', [])
if isinstance(result, basestring):
result = result.replace('embed.html', 'index.m3u8')
base_url = re.sub('index\.m3u8\?token=[\w\-]+[^/$]*', '', result)
r = client.request(result, headers=headers)
r = [(i[0], i[1]) for i in
re.findall('#EXT-X-STREAM-INF:.*?RESOLUTION=\d+x(\d+)[^\n]+\n([^\n]+)', r, re.DOTALL) if i]
r = [(source_utils.label_to_quality(i[0]), i[1] + source_utils.append_headers(headers)) for i in r]
r = [{'quality': i[0], 'url': base_url + i[1]} for i in r]
for i in r: sources.append(
{'source': 'CDN', 'quality': i['quality'], 'language': 'de', 'url': i['url'], 'direct': True,
'debridonly': False})
elif result:
result = [i.get('link_mp4') for i in result]
result = [i for i in result if i]
for i in result:
try:
sources.append(
{'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'de',
'url': i, 'direct': True, 'debridonly': False})
except:<|fim▁hole|> return sources
except:
return
def resolve(self, url):
return url
def __search_movie(self, imdb, year):
try:
query = urlparse.urljoin(self.base_link, self.search_link % imdb)
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
r = [(dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href'),
dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})) for i in r]
r = [(i[0][0].attrs['href'], re.findall('calendar.+?>.+?(\d{4})', ''.join([x.content for x in i[1]]))) for i
in r if i[0] and i[1]]
r = [(i[0], i[1][0] if len(i[1]) > 0 else '0') for i in r]
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if i[1] in y][0]
return source_utils.strip_domain(r)
except:
return
def __search(self, titles, year, season=0, episode=False):
try:
query = self.search_link % (urllib.quote_plus(cleantitle.query(titles[0])))
query = urlparse.urljoin(self.base_link, query)
t = [cleantitle.get(i) for i in set(titles) if i]
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
f = []
for i in r:
_url = dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href')[0].attrs['href']
_title = re.sub('<.+?>|</.+?>', '', dom_parser.parse_dom(i, 'h6')[0].content).strip()
try:
_title = re.search('(.*?)\s(?:staf+el|s)\s*(\d+)', _title, re.I).group(1)
except:
pass
_season = '0'
_year = re.findall('calendar.+?>.+?(\d{4})', ''.join(
[x.content for x in dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})]))
_year = _year[0] if len(_year) > 0 else '0'
if season > 0:
s = dom_parser.parse_dom(i, 'span', attrs={'class': 'season-label'})
s = dom_parser.parse_dom(s, 'span', attrs={'class': 'el-num'})
if s: _season = s[0].content.strip()
if cleantitle.get(_title) in t and _year in y and int(_season) == int(season):
f.append((_url, _year))
r = f
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if r[0]][0]
url = source_utils.strip_domain(r)
if episode:
r = client.request(urlparse.urljoin(self.base_link, url))
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'season-list'})
r = dom_parser.parse_dom(r, 'li')
r = dom_parser.parse_dom(r, 'a', req='href')
r = [(i.attrs['href'], i.content) for i in r]
r = [i[0] for i in r if i[1] and int(i[1]) == int(episode)][0]
url = source_utils.strip_domain(r)
return url
except:
return<|fim▁end|> | pass
|
<|file_name|>pgitemdata.py<|end_file_name|><|fim▁begin|>#-------------------------------------------------------------------------------
#
# This file is part of pygimplib.
#
# Copyright (C) 2014, 2015 khalim19 <[email protected]>
#
# pygimplib 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.
#
# pygimplib 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 pygimplib. If not, see <http://www.gnu.org/licenses/>.
#
#-------------------------------------------------------------------------------
"""
This module defines the following classes:
* `ItemData` - an associative container that stores all GIMP items and item
groups of a certain type
* subclasses of `ItemData`:
* `LayerData` for layers
* `ChannelData` for channels
* `PathData` for paths
* `_ItemDataElement` - wrapper for `gimp.Item` objects containing custom
attributes derived from the original `gimp.Item` attributes
"""
#===============================================================================
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
str = unicode
#===============================================================================
import os
import abc
from collections import OrderedDict
from collections import namedtuple
import gimp
from . import pgpath
from . import objectfilter
#===============================================================================
pdb = gimp.pdb
#===============================================================================
class ItemData(object):
"""
This class is an interface to store all items (and item groups) of a certain
type (e.g. layers, channels or paths) of a GIMP image in an ordered
dictionary, allowing to access the items via their names and get various
custom attributes derived from the existing item attributes.
Use one of the subclasses for items of a certain type:
* `LayerData` for layers,
* `ChannelData` for channels,
* `PathData` for paths (vectors).
For custom item attributes, see the documentation for the `_ItemDataElement`
class. `_ItemDataElement` is common for all `ItemData` subclasses.
Attributes:
* `image` - GIMP image to get item data from.
* `is_filtered` - If True, ignore items that do not match the filter
(`ObjectFilter`) in this object when iterating.
* `filter` (read-only) - `ObjectFilter` instance where you can add or remove
filter rules or subfilters to filter items.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, image, is_filtered=False, filter_match_type=objectfilter.ObjectFilter.MATCH_ALL):
self.image = image
self.is_filtered = is_filtered
# Filters applied to all items in self._itemdata
self._filter = objectfilter.ObjectFilter(filter_match_type)
# Contains all items (including item groups) in the item tree.
# key: `_ItemDataElement.orig_name` (derived from `gimp.Item.name`, which is unique)
# value: `_ItemDataElement` object
self._itemdata = OrderedDict()
# key `_ItemDataElement` object (parent) or None (root of the item tree)
# value: set of `_ItemDataElement` objects
self._uniquified_itemdata = {}
self._fill_item_data()
@property
def filter(self):
return self._filter
def __getitem__(self, name):
"""
Access an `_ItemDataElement` object by its `orig_name` attribute.
"""
return self._itemdata[name]
def __contains__(self, name):
"""
Return True if an `_ItemDataElement` object, specified by its `orig_name`
attribute, is in the item data. Otherwise return False.
"""
return name in self._itemdata
def __len__(self):
"""
Return the number of all item data elements - that is, all immediate
children of the image and all nested children.
"""
return len([item_elem for item_elem in self])
def __iter__(self):
"""
If `is_filtered` is False, iterate over all items. If `is_filtered` is True,
iterate only over items that match the filter in this object.
Yields:
* `item_elem` - The current `_ItemDataElement` object.
"""
if not self.is_filtered:
for item_elem in self._itemdata.values():
yield item_elem
else:
for item_elem in self._itemdata.values():
if self._filter.is_match(item_elem):
yield item_elem
def _items(self):
"""
Yield current (`gimp.Item.name`, `_ItemDataElement` object) tuple.
"""
if not self.is_filtered:
for name, item_elem in self._itemdata.items():
yield name, item_elem
else:
for name, item_elem in self._itemdata.items():
if self._filter.is_match(item_elem):
yield name, item_elem
def uniquify_name(self, item_elem, include_item_path=True,
uniquifier_position=None, uniquifier_position_parents=None):
"""
Make the `name` attribute in the specified `_ItemDataElement` object
unique among all other, already uniquified `_ItemDataElement` objects.
To achieve uniquification, a string ("uniquifier") in the form of
" (<number>)" is inserted at the end of the item names.
Parameters:
* `item_elem` - `_ItemDataElement` object whose `name` attribute
will be uniquified.
* `include_item_path` - If True, take the item path into account when
uniquifying.
* `uniquifier_position` - Position (index) where the uniquifier is inserted
into the current item. If the position is None, insert the uniquifier at
the end of the item name (i.e. append it).
* `uniquifier_position_parents` - Position (index) where the uniquifier is
inserted into the parents of the current item. If the position is None,
insert the uniquifier at the end of the name of each parent. This
parameter has no effect if `include_item_path` is False.
"""
if include_item_path:
for elem in item_elem.parents + [item_elem]:
parent = elem.parent
if parent not in self._uniquified_itemdata:
self._uniquified_itemdata[parent] = set()
if elem not in self._uniquified_itemdata[parent]:
item_names = set([elem_.name for elem_ in self._uniquified_itemdata[parent]])
if elem.name not in item_names:
self._uniquified_itemdata[parent].add(elem)
else:
if elem == item_elem:
position = uniquifier_position
else:
position = uniquifier_position_parents
elem.name = pgpath.uniquify_string(elem.name, item_names, position)
self._uniquified_itemdata[parent].add(elem)
else:
# Use None as the root of the item tree.
parent = None
if parent not in self._uniquified_itemdata:
self._uniquified_itemdata[parent] = set()
item_elem.name = pgpath.uniquify_string(
item_elem.name, self._uniquified_itemdata[parent], uniquifier_position)
self._uniquified_itemdata[parent].add(item_elem.name)
def _fill_item_data(self):
"""
Fill the _itemdata dictionary, containing
<gimp.Item.name, _ItemDataElement> pairs.
"""
_ItemTreeNode = namedtuple('_ItemTreeNode', ['children', 'parents'])
item_tree = [_ItemTreeNode(self._get_children_from_image(self.image), [])]
while item_tree:
node = item_tree.pop(0)
index = 0
for item in node.children:
parents = list(node.parents)
item_elem = _ItemDataElement(item, parents)
if pdb.gimp_item_is_group(item):
item_tree.insert(index, _ItemTreeNode(self._get_children_from_item(item), parents + [item_elem]))
index += 1
self._itemdata[item_elem.orig_name] = item_elem
@abc.abstractmethod
def _get_children_from_image(self, image):
"""
Return a list of immediate child items from the specified image.
If no child items exist, return an empty list.
"""
pass
@abc.abstractmethod
def _get_children_from_item(self, item):
"""
Return a list of immediate child items from the specified item.
If no child items exist, return an empty list.
"""
pass
class LayerData(ItemData):
def _get_children_from_image(self, image):
return image.layers
def _get_children_from_item(self, item):
return item.layers
class ChannelData(ItemData):
def _get_children_from_image(self, image):
return image.channels
def _get_children_from_item(self, item):
return item.children
class PathData(ItemData):
def _get_children_from_image(self, image):
return image.vectors
def _get_children_from_item(self, item):
return item.children
#===============================================================================
class _ItemDataElement(object):
"""
This class wraps a `gimp.Item` object and defines custom item attributes.
Note that the attributes will not be up to date if changes were made to the
original `gimp.Item` object.
Attributes:
* `item` (read-only) - `gimp.Item` object.
* `parents` (read-only) - List of `_ItemDataElement` parents for this item,
sorted from the topmost parent to the bottommost (immediate) parent.
* `level` (read-only) - Integer indicating which level in the item tree is
the item positioned at. 0 means the item is at the top level. The higher
the level, the deeper the item is in the item tree.
* `parent` (read-only) - Immediate `_ItemDataElement` parent of this object.
If this object has no parent, return None.
* `item_type` (read-only) - Item type - one of the following:
* `ITEM` - normal item,
* `NONEMPTY_GROUP` - non-empty item group (contains children),
* `EMPTY_GROUP` - empty item group (contains no children).
* `name` - Item name as a `unicode` string, initially equal to the `orig_name`
attribute. Modify this attribute instead of `gimp.Item.name` to avoid
modifying the original item.
* `orig_name` (read-only) - original `gimp.Item.name` as a `unicode` string.
* `path_visible` (read-only) - Visibility of all item's parents and this
item. If all items are visible, `path_visible` is True. If at least one
of these items is invisible, `path_visible` is False.
"""
__ITEM_TYPES = ITEM, NONEMPTY_GROUP, EMPTY_GROUP = (0, 1, 2)
def __init__(self, item, parents=None):
if item is None:
raise TypeError("item cannot be None")
self.name = item.name.decode()
self.tags = set()
self._orig_name = self.name
self._item = item
self._parents = parents if parents is not None else []
self._level = len(self._parents)
if self._parents:
self._parent = self._parents[-1]
else:
self._parent = None
if pdb.gimp_item_is_group(self._item):
if self._item.children:
self._item_type = self.NONEMPTY_GROUP
else:
self._item_type = self.EMPTY_GROUP
else:
self._item_type = self.ITEM
self._path_visible = self._get_path_visibility()
@property
def item(self):
return self._item
@property
def parents(self):
return self._parents
@property
def level(self):
return self._level
@property
def parent(self):
return self._parent
@property
def item_type(self):
return self._item_type
@property
def orig_name(self):
return self._orig_name
@property
def path_visible(self):
return self._path_visible
def get_file_extension(self):
"""
Get file extension from the `name` attribute.
If `name` has no file extension, return an empty string.
"""
return pgpath.get_file_extension(self.name)
def set_file_extension(self, file_extension):
"""
Set file extension in the `name` attribute.
To remove the file extension from `name`, pass an empty string or None.
"""
root = os.path.splitext(self.name)[0]
if file_extension:
self.name = '.'.join((root, file_extension))
else:
self.name = root
def get_filepath(self, directory, include_item_path=True):
"""
Return file path given the specified directory, item name and names of its
parents.
If `include_item_path` is True, create file path in the following format:
<directory>/<item path components>/<item name>
If `include_item_path` is False, create file path in the following format:
<directory>/<item name>
If directory is not an absolute path or is None, prepend the current working
directory.
Item path components consist of parents' item names, starting with the
topmost parent.
"""
if directory is None:
directory = ""
path = os.path.abspath(directory)
if include_item_path:
path_components = self.get_path_components()<|fim▁hole|> path = os.path.join(path, self.name)
return path
def get_path_components(self):
"""
Return a list of names of all parents of this item as path components.
"""
return [parent.name for parent in self.parents]
def validate_name(self):
"""
Validate the `name` attribute of this item and all of its parents.
"""
self.name = pgpath.FilenameValidator.validate(self.name)
for parent in self._parents:
parent.name = pgpath.FilenameValidator.validate(parent.name)
def _get_path_visibility(self):
"""
If this item and all of its parents are visible, return True, otherwise
return False.
"""
path_visible = True
if not self._item.visible:
path_visible = False
else:
for parent in self._parents:
if not parent.item.visible:
path_visible = False
break
return path_visible<|fim▁end|> | if path_components:
path = os.path.join(path, os.path.join(*path_components))
|
<|file_name|>iter-sum-overflow-overflow-checks.rs<|end_file_name|><|fim▁begin|>// run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// compile-flags: -C overflow-checks
use std::panic;
fn main() {
let r = panic::catch_unwind(|| {<|fim▁hole|> [1, i32::MAX].iter().sum::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[2, i32::MAX].iter().product::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[1, i32::MAX].iter().cloned().sum::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[2, i32::MAX].iter().cloned().product::<i32>();
});
assert!(r.is_err());
}<|fim▁end|> | |
<|file_name|>u-shapelets_clustering.py<|end_file_name|><|fim▁begin|>'''
Created on 15 Aug 2016
<|fim▁hole|>from os import listdir
import numpy
import json
import operator
from operator import itemgetter
from itertools import islice
import math
import dis
from itertools import islice
# TODO: try Livenstein distance,
base_dir = os.path.dirname(os.path.dirname(__file__))
data_dir = os.path.join(base_dir, 'data')
seed_dir = os.path.join(data_dir, 'seed')
baseline_dir = os.path.join(data_dir, 'baseline')
general_dir = os.path.join(data_dir, 'general')
# u-shapelets folders
clustering_dir =os.path.join(data_dir, 'clustering')
u_shapelets_dir = os.path.join(clustering_dir, 'u-shapelets_candidates')
u_shapelets_seed = os.path.join(u_shapelets_dir, 'seed')
u_shapelets_baseline = os.path.join(u_shapelets_dir, 'baseline')
u_shapelets_test = os.path.join(u_shapelets_dir, 'test')
# SAX folders
sax_dir = os.path.join(data_dir, 'sax_representation')
views_sax = os.path.join(sax_dir, 'views')
edits_sax = os.path.join(sax_dir, 'edits')
google_trends_sax = os.path.join(sax_dir, 'google_trends')
# scientists or topics
views_sax_sci = os.path.join(views_sax, 'scientists')
edits_sax_sci = os.path.join(edits_sax, 'scientists')
gooogle_trends_sax_sci = os.path.join(google_trends_sax, 'scientists')
test_sax = os.path.join(sax_dir, 'test')
views_sax_topic = os.path.join(views_sax, 'topics')
edits_sax_topic = os.path.join(edits_sax, 'topics')
gooogle_trends_sax_topic = os.path.join(google_trends_sax, 'topics')
# lists of topics and scientists change seed/baseline
scientists_file = os.path.join(general_dir, 'seed_scientists_list.txt')
topic_file = os.path.join(general_dir, 'seed_topics_list.txt')
test_file = os.path.join(general_dir, 'test.txt')
def load_simple_json(filename):
print filename
with open(filename, 'r') as f:
return json.load(f)
# returns list of list, where each raw is a time-series of scientist (topic) and each column is a sax - word
def read_sax (dir):
ts_dict = {}
files_list = listdir(dir)
with open(scientists_file) as f:
name_list = f.read().splitlines()
# read only SAX representation of seed or baseline data
for filename in name_list:
name = filename
filename = filename + '.txt'
if filename in files_list:
ts_list = []
temp_list = []
try:
with open(dir+'\\'+filename) as f:
temp_list = f.read().splitlines()
temp_list = list(set(temp_list))
for word in temp_list:
word = list(word.replace(',',''))
word = map(int,word)
ts_list.append(word)
except IOError:
print filename
continue
if ts_list!=[]:
ts_dict.update({name:ts_list})
else:
print filename
return ts_dict
# Bounds change back!!
lower_bound_seed_sci = 262*0.05
upper_bound_seed_sci = 262*0.6
lower_bound_baseline_sci = 276*0.1
upper_bound_baseline_sci = 276*0.9
lower_bound_seed_topic = 1912*0.1
upper_bound_seed_topic = 1912*0.9
lower_bound_baseline_topic = 1071*0.1
upper_bound_basleine_topic = 1071*0.9
# sorts shapelet candidates based on its random masking variance, exclude outliers
def sort_shapelets(filename, upper_bound, lower_bound):
u_shapelets_file = os.path.join(u_shapelets_seed, filename)
u_shapelets_dict = load_simple_json(u_shapelets_file)
shapelet_dict = {}
for shapelet, masks in u_shapelets_dict.iteritems():
shapelet_mean = numpy.mean(numpy.array(masks))
if shapelet_mean<upper_bound and shapelet_mean>lower_bound:
#print shapelet, masks, numpy.var(numpy.array(masks))
shapelet_dict.update({shapelet:numpy.var(numpy.array(masks))})
sorted_shapelets = sorted(shapelet_dict.items(), key=operator.itemgetter(1)) # sort by values
return sorted_shapelets
# compute the vector of distances between u-shapelet and each time series
# Works correct
def compute_distance(sax_dict, shapelet):
dis = [float("inf")]*len(sax_dict)
dis_dict = {}
i=-1
for name in sax_dict:
i+=1
ts = sax_dict[name]
# for j in range(0, len(ts)-len(shapelet)+1): # every start position of ts
for j in range(0, len(ts)):
# chack dist
# print 'ts= ', ts[j]
# print 'shapelet', shapelet
d = numpy.linalg.norm(numpy.array(ts[j])-numpy.array(shapelet)) # calculate euclidian distance between u-shapelet and each SAX word of the time series
dis[i] = min(dis[i], d) # we take min dist as a dist between u-shapelet and SAX word
dis_dict.update({name:dis[i]/ math.sqrt(len(shapelet))})
#norm_dis = [x / math.sqrt(len(shapelet)) for x in dis] # length normalized Euclidian distance (normalized by square root of shapelet length, optional)
return dis_dict
# works correct
def compute_gap(sax_dict, shapelet, lb, ub):
ts_dict = {}
names = []
dis = []
dis_dict = compute_distance(sax_dict, shapelet)
dis_list = sorted(dis_dict.items(), key=operator.itemgetter(1))
for item in dis_list:
names.append(item[0])
dis.append(item[1])
gap = 0
curr_gap = 0
cluster = []
# print dis
if len(dis)<ub:
ub = len(dis)
for j in range(lb, ub): #for each location of separation point
d_a = [x for x in dis if x <= dis[j]] # points to the left
a_ind = [ind for ind,v in enumerate(dis) if v <= dis[j]]
if a_ind!=[]:
cluster_a = itemgetter(*a_ind)(names)
else:
cluster_a = []
d_b = [x for x in dis if x > dis[j]] # points to the right
# print 'd_a', d_a
# print 'd_b', d_b
# print lb, len(d_a), ub
if lb<=len(d_a)<=ub:
mean_a = numpy.mean(numpy.array(d_a))
mean_b = numpy.mean(numpy.array(d_b))
std_a = numpy.std(numpy.array(d_a))
std_b = numpy.std(numpy.array(d_b))
# print 'j= ', j
# print ' d_a = ', d_a
# print ' mean_a = ', mean_a
# print ' std_a = ', std_a
#
# print ' d_b = ', d_b
# print ' mean_b = ', mean_b
# print ' std_b = ', std_b
# TODO: test abs gap values !!!!!
curr_gap = mean_b-std_b-(mean_a+std_a)
# print ' curr_gap = ', curr_gap, cluster_a
if curr_gap>gap:
gap=curr_gap
cluster = cluster_a
# print cluster
# print 'returned values ', shapelet, gap, cluster
return gap, cluster, shapelet
def clustering(sax_dict, shapelets, gap_dict, iter, clustering_result):
print 'in the clustering function'
# bounds for scientists
cluster_list = []
gap_list = []
shap_list = []
lb = int(262*0.05)
ub = int(262*0.6)
# lb = 4
# ub = 6
candidate_dict = {}
sorted_candidate_dict = {}
gap_shap_dict = {}
for i in range(0,len(shapelets)):
curr_gap = 0
# if iter == 0:
# shapelets[i] = str(shapelets[i].replace('\'',''))
# shapelets[i] = shapelets[i].strip('[]').split(',')
# shapelets[i] = map(int,shapelets[i])
gap, cluster, shap = compute_gap(sax_dict, shapelets[i], lb, ub)
# FIND A PROBLEM
# if cluster==[]:
# iter+=1
# shapelets.remove(shapelets[i])
# return clustering(sax_dict, shapelets, gap_dict, iter, clustering_result)
gap_list.append(gap)
cluster_list.append(cluster)
shap_list.append(shap)
index, max_gap = max(enumerate(gap_list), key=operator.itemgetter(1)) # find max gap and its index
for l in range (0, len(gap_list)):
gap_shap_dict.update({str(shap_list[l]):gap_list[l]})
sorted_gap = sorted(gap_shap_dict.items(), key=operator.itemgetter(1)) # sort by values
# print 'current gap', max_gap
# print 'shapelet', shap_list[index]
print 'sorted ', sorted_gap
if gap_dict!={}:
print 'first gap', gap_dict.get(0)
#if max_gap < gap_dict.get(0)/3:
# return clustering_result
#else:
d_a = list(cluster_list[index])
#print 'd_a, cluster that has to be removed', d_a
candidate = shapelets[index]
# remove cluster from the rest of the data
for ts in d_a:
sax_dict.pop(ts, None)
# remove shapelets candidate from the list of shapelets
shapelets.remove(candidate)
clustering_result.update({iter:d_a})
gap_dict.update({iter:max_gap})
iter+=1
if len(sax_dict)>=lb:
print clustering_result
return clustering(sax_dict, shapelets, gap_dict, iter, clustering_result)
else:
return clustering_result
else:
d_a = list(cluster_list[index])
candidate = shapelets[index]
# remove cluster from the rest of the data
#print 'd_a, cluster that has to be removed', d_a
for ts in d_a:
sax_dict.pop(ts, None)
# remove shapelets candidate from the list of shapelets
shapelets.remove(candidate)
clustering_result.update({iter:d_a})
gap_dict.update({iter:max_gap})
iter+=1
if len(sax_dict)>=lb:
print clustering_result
return clustering(sax_dict, shapelets, gap_dict, iter, clustering_result)
else:
return clustering_result
sax_dict = read_sax(views_sax_sci)
# to eliminate filtering
# shapelets = []
# for name, ts in sax_dict.iteritems():
# for word in ts:
# if word not in shapelets:
# shapelets.append(word)
# filtered shapelets
shapelets = []
shapelets_pairs = sort_shapelets('views_scientists_candidates.json', upper_bound_seed_sci, lower_bound_seed_sci)
for i in range(0,int(len(shapelets_pairs)*0.01)):
shapelet = str(shapelets_pairs[i][0].replace('\'',''))
shapelet = shapelet.strip('[]').split(',')
shapelet = map(int,shapelet)
shapelets.append(shapelet)
cluster_list = clustering(sax_dict, shapelets, {}, 0, {})
print cluster_list
# for name in name_list:
# filename = os.path.join(views_sax_sci + '\\' + topic + '.txt')
#get_candidate(scientists_file, shapelets)<|fim▁end|> |
@author: sennikta
'''
import os
|
<|file_name|>bitcoin_ru.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About VPSCoin</source>
<translation>О VPSCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>VPSCoin</b> version</source>
<translation><b>VPSCoin</b> версия</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The VPSCoin developers</source>
<translation>Все права защищены © 2009-2014 Разработчики Bitcoin
Все права защищены © 2012-2014 Разработчики NovaCoin
Все права защищены © 2014 Разработчики VPSCoin</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Это экспериментальная программа.
Распространяется на правах лицензии MIT/X11, см. файл license.txt или http://www.opensource.org/licenses/mit-license.php.
Этот продукт включает ПО, разработанное OpenSSL Project для использования в OpenSSL Toolkit (http://www.openssl.org/) и криптографическое ПО, написанное Eric Young ([email protected]) и ПО для работы с UPnP, написанное Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Адресная книга</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Для того, чтобы изменить адрес или метку давжды кликните по изменяемому объекту</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Создать новый адрес</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копировать текущий выделенный адрес в буфер обмена</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Новый адрес</translation>
</message>
<message>
<location line="-46"/>
<source>These are your VPSCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Это Ваши адреса для получения платежей. Вы можете дать разные адреса отправителям, чтобы отслеживать, кто именно вам платит.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Копировать адрес</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Показать &QR код</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a VPSCoin address</source>
<translation>Подписать сообщение, чтобы доказать владение адресом VPSCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Удалить выбранный адрес из списка</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified VPSCoin address</source>
<translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом VPSCoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Проверить сообщение</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Удалить</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Копировать &метку</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Правка</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Экспортировать адресную книгу</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Текст, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>[нет метки]</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Диалог ввода пароля</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Введите пароль</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Новый пароль</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Повторите новый пароль</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Служит для предотвращения тривиальной отправки монет, если ваша система скомпрометирована. Не предоставляет реальной безопасности.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Только для участия в доле</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<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>Введите новый пароль для бумажника. <br/> Пожалуйста, используйте фразы из <b>10 или более случайных символов,</b> или <b>восьми и более слов.</b></translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Зашифровать бумажник</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Разблокировать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Расшифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Сменить пароль</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Введите старый и новый пароль для бумажника.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Подтвердите шифрование бумажника</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Внимание: если вы зашифруете бумажник и потеряете пароль, вы <b>ПОТЕРЯЕТЕ ВСЕ ВАШИ МОНЕТЫ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Вы уверены, что хотите зашифровать ваш бумажник?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ВАЖНО: все предыдущие резервные копии вашего кошелька должны быть заменены новым зашифрованным файлом. В целях безопасности предыдущие резервные копии нешифрованного кошелька станут бесполезны, как только вы начнёте использовать новый шифрованный кошелёк.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Внимание: Caps Lock включен!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Бумажник зашифрован</translation>
</message>
<message>
<location line="-58"/>
<source>VPSCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>Сейчас программа закроется для завершения процесса шифрования. Помните, что шифрование вашего бумажника не может полностью защитить ваши монеты от кражи с помощью инфицирования вашего компьютера вредоносным ПО.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Не удалось зашифровать бумажник</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Шифрование бумажника не удалось из-за внутренней ошибки. Ваш бумажник не был зашифрован.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Введённые пароли не совпадают.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Разблокировка бумажника не удалась</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Указанный пароль не подходит.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Расшифрование бумажника не удалось</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Пароль бумажника успешно изменён.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Синхронизация с сетью...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>О&бзор</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Показать общий обзор действий с бумажником</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Транзакции</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Показать историю транзакций</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Адресная книга</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Изменить список сохранённых адресов и меток к ним</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&Получение монет</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Показать список адресов для получения платежей</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>Отп&равка монет</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>В&ыход</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Закрыть приложение</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about VPSCoin</source>
<translation>Показать информацию о VPSCoin'е</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>О &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Показать информацию о Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>Оп&ции...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Зашифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Сделать резервную копию бумажника</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Изменить пароль</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>остался ~%n блок</numerusform><numerusform>осталось ~%n блоков</numerusform><numerusform>осталось ~%n блоков</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Загружено %1 из %2 блоков истории операций (%3% завершено).</translation>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation>&Экспорт...</translation>
</message>
<message>
<location line="-64"/>
<source>Send coins to a VPSCoin address</source>
<translation>Отправить монеты на указанный адрес VPSCoin</translation>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for VPSCoin</source>
<translation>Изменить параметры конфигурации VPSCoin</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>Экспортировать данные из вкладки в файл</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>Зашифровать или расшифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Сделать резервную копию бумажника в другом месте</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Изменить пароль шифрования бумажника</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Окно отладки</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Открыть консоль отладки и диагностики</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Проверить сообщение...</translation>
</message>
<message>
<location line="-202"/>
<source>VPSCoin</source>
<translation>VPSCoin</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Бумажник</translation>
</message>
<message>
<location line="+180"/>
<source>&About VPSCoin</source>
<translation>&О VPSCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Показать / Скрыть</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>Разблокировать бумажник</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Заблокировать бумажник</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Заблокировать бумажник</translation>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Настройки</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Помощь</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Панель вкладок</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>Панель действий</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[тестовая сеть]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>VPSCoin client</source>
<translation>VPSCoin клиент</translation>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to VPSCoin network</source>
<translation><numerusform>%n активное соединение с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Загружено %1 блоков истории транзакций.</translation>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Участвуем в доле.<br>Ваш вес %1<br>Вес сети %2<br>Ожидаемое время получения награды %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Не участвуем в доле, так как кошелёк заблокирован</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Не участвуем в доле, так как кошелёк оффлайн</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Не участвуем в доле, так как кошелёк синхронизируется</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Не участвуем в доле, так как нет зрелых монет</translation>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n секунду назад</numerusform><numerusform>%n секунды назад</numerusform><numerusform>%n секунд назад</numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About VPSCoin card</source>
<translation>О карте VPSCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about VPSCoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation>&Разблокировать бумажник</translation>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n минуту назад</numerusform><numerusform>%n минуты назад</numerusform><numerusform>%n минут назад</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n час назад</numerusform><numerusform>%n часа назад</numerusform><numerusform>%n часов назад</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n день назад</numerusform><numerusform>%n дня назад</numerusform><numerusform>%n дней назад</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Синхронизировано</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Синхронизируется...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation>Последний полученный блок был сгенерирован %1.</translation>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Данная транзакция превышает предельно допустимый размер. Но Вы можете всё равно совершить её, добавив комиссию в %1, которая отправится тем узлам, которые обработают Вашу транзакцию, и поможет поддержать сеть. Вы хотите добавить комиссию?</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>Подтвердите комиссию</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Исходящая транзакция</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Входящая транзакция</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1<|fim▁hole|> <translation>Дата: %1
Количество: %2
Тип: %3
Адрес: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>Обработка URI</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid VPSCoin address or malformed URI parameters.</source>
<translation>Не удалось обработать URI! Это может быть связано с неверным адресом VPSCoin или неправильными параметрами URI.</translation>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>разблокирован</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>заблокирован</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>Сделать резервную копию бумажника</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Данные бумажника (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Резервное копирование не удалось</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>При попытке сохранения данных бумажника в новое место произошла ошибка.</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation><numerusform>%n секунда</numerusform><numerusform>%n секунды</numerusform><numerusform>%n секунд</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n минута</numerusform><numerusform>%n минуты</numerusform><numerusform>%n минут</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n час</numerusform><numerusform>%n часа</numerusform><numerusform>%n часов</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n день</numerusform><numerusform>%n дня</numerusform><numerusform>%n дней</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation>Не участвуем в доле</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. VPSCoin can no longer continue safely and will quit.</source>
<translation>Произошла неисправимая ошибка. VPSCoin не может безопасно продолжать работу и будет закрыт.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Сетевая Тревога</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Выбор входов</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Количество:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Размер:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Сумма:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Приоритет:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Комиссия:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Мелкие входы:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>нет</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>С комиссией:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Сдача:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>Выбрать все</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Дерево</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Список</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Сумма</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Подтверждения</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Подтверждено</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Приоритет</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Копировать адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Копировать метку</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Копировать сумму</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Скопировать ID транзакции</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Копировать количество</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Копировать комиссию</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Копировать с комиссией</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Копировать объем</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Копировать приоритет</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Копировать сдачу</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>наивысший</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>высокий</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>выше среднего</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>средний</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>ниже среднего</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>низкий</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>наименьший</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>да</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(нет метки)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(сдача)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Изменить адрес</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Метка</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Метка, связанная с данной записью</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Адрес</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Адрес, связанный с данной записью.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Новый адрес для получения</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Новый адрес для отправки</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Изменение адреса для получения</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Изменение адреса для отправки</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Введённый адрес «%1» уже находится в адресной книге.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid VPSCoin address.</source>
<translation>Введённый адрес "%1" не является правильным VPSCoin-адресом.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Не удается разблокировать бумажник.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Генерация нового ключа не удалась.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>VPSCoin-Qt</source>
<translation>VPSCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>версия</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Использование:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>параметры командной строки</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Опции интерфейса</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Выберите язык, например "de_DE" (по умолчанию: как в системе)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Запускать свёрнутым</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Показывать сплэш при запуске (по умолчанию: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Опции</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Главная</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Опциональная комиссия за каждый КБ транзакции, которая позволяет быть уверенным, что Ваша транзакция будет обработана быстро. Большинство транзакций занимают 1КБ. Рекомендуется комиссия 0.01.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Заплатить ко&миссию</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Зарезервированная сумма не участвует в доле, и поэтому может быть потрачена в любое время.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Зарезервировать</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start VPSCoin after logging in to the system.</source>
<translation>Автоматически запускать VPSCoin после входа в систему</translation>
</message>
<message>
<location line="+3"/>
<source>&Start VPSCoin on system login</source>
<translation>&Запускать VPSCoin при входе в систему</translation>
</message>
<message>
<location line="+7"/>
<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>Отключить базы данных блоков и адресов при выходе. Это означает, что их можно будет переместить в другой каталог данных, но завершение работы будет медленнее. Бумажник всегда отключается.</translation>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation>&Отключать базы данных при выходе</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Сеть</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the VPSCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Автоматически открыть порт для VPSCoin-клиента на роутере. Работает только если Ваш роутер поддерживает UPnP, и данная функция включена.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Пробросить порт через &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the VPSCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Подключаться к сети VPSCoin через прокси SOCKS (например, при подключении через Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Подключаться через SOCKS прокси:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP Прокси: </translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-адрес прокси (например 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>По&рт: </translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Порт прокси-сервера (например, 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Версия SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Версия SOCKS-прокси (например, 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Окно</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Показывать только иконку в системном лотке после сворачивания окна.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Cворачивать в системный лоток вместо панели задач</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Сворачивать вместо закрытия. Если данная опция будет выбрана — приложение закроется только после выбора соответствующего пункта в меню.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>С&ворачивать при закрытии</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>О&тображение</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Язык интерфейса:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting VPSCoin.</source>
<translation>Здесь можно выбрать язык интерфейса. Настройки вступят в силу после перезапуска VPSCoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Отображать суммы в единицах: </translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Выберите единицу измерения монет при отображении и отправке.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show VPSCoin addresses in the transaction list or not.</source>
<translation>Показывать ли адреса VPSCoin в списке транзакций.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Показывать адреса в списке транзакций</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Выключает и включает отображение панели выбора входов.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Управление &входами (только для продвинутых пользователей!)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>О&К</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Отмена</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Применить</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>по умолчанию</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation>Внимание</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting VPSCoin.</source>
<translation>Эта настройка вступит в силу после перезапуска VPSCoin</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Адрес прокси неверен.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the VPSCoin network after a connection is established, but this process has not completed yet.</source>
<translation>Отображаемая информация может быть устаревшей. Ваш бумажник автоматически синхронизируется с сетью VPSCoin после подключения, но этот процесс пока не завершён.</translation>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation>Доля:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Не подтверждено:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Бумажник</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Доступно:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Баланс, доступный в настоящее время</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Незрелые:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Баланс добытых монет, который ещё не созрел</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Итого:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Ваш суммарный баланс</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Последние транзакции</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Общая сумма всех транзакций, которые до сих пор не подтверждены, и до сих пор не учитываются в текущем балансе</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Общая сумма всех монет, используемых для Proof-of-Stake, и не учитывающихся на балансе</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>не синхронизировано</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Диалог QR-кода</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Запросить платёж</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Количество:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Метка:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Сообщение:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Сохранить как...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Ошибка кодирования URI в QR-код</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Введено неверное количество, проверьте ещё раз.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Получившийся URI слишком длинный, попробуйте сократить текст метки / сообщения.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Сохранить QR-код</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Изображения (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Имя клиента</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>Н/Д</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Версия клиента</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Информация</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Используется версия OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Время запуска</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Сеть</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Число подключений</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>В тестовой сети</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Цепь блоков</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Текущее число блоков</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Расчётное число блоков</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Время последнего блока</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Открыть</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Параметры командной строки</translation>
</message>
<message>
<location line="+7"/>
<source>Show the VPSCoin-Qt help message to get a list with possible VPSCoin command-line options.</source>
<translation>Показать помощь по VPSCoin-Qt, чтобы получить список доступных параметров командной строки.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Показать</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>Консоль</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Дата сборки</translation>
</message>
<message>
<location line="-104"/>
<source>VPSCoin - Debug window</source>
<translation>VPSCoin - Окно отладки</translation>
</message>
<message>
<location line="+25"/>
<source>VPSCoin Core</source>
<translation>Ядро VPSCoin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Отладочный лог-файл</translation>
</message>
<message>
<location line="+7"/>
<source>Open the VPSCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Открыть отладочный лог-файл VPSCoin из текущего каталога данных. Это может занять несколько секунд для больших лог-файлов.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Очистить консоль</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the VPSCoin RPC console.</source>
<translation>Добро пожаловать в RPC-консоль VPSCoin.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Используйте стрелки вверх и вниз для просмотра истории и <b>Ctrl-L</b> для очистки экрана.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Напишите <b>help</b> для просмотра доступных команд.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Отправка</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Выбор входов</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Входы...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>автоматический выбор</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Недостаточно средств!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 VPS</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Приоритет:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>средний</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>нет</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>адрес для сдачи</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Отправить нескольким получателям одновременно</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Добавить получателя</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Удалить все поля транзакции</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Очистить &всё</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 VPS</source>
<translation>123.456 VPS</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Подтвердить отправку</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Отправить</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation>Введите VPSCoin-адрес (например Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Копировать комиссию</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Копировать сдачу</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> адресату %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Подтвердите отправку монет</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Вы уверены, что хотите отправить %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> и </translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Адрес получателя неверный, пожалуйста, перепроверьте.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Количество монет для отправки должно быть больше 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Количество отправляемых монет превышает Ваш баланс</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Сумма превысит Ваш баланс, если комиссия в размере %1 будет добавлена к транзакции</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Обнаружен дублирующийся адрес. Отправка на один и тот же адрес возможна только один раз за одну операцию отправки</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation>Ошибка: не удалось создать транзакцию.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Ошибка: В транзакции отказано. Такое может произойти, если некоторые монеты уже были потрачены, например, если Вы используете одну копию файла wallet.dat, а монеты были потрачены из другой копии, но не были отмечены как потраченные в этой.</translation>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid VPSCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(нет метки)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>ПРЕДУПРЕЖДЕНИЕ: неизвестный адрес для сдачи</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Ко&личество:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Полу&чатель:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Введите метку для данного адреса (для добавления в адресную книгу)</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Метка:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation>Адрес получателя платежа (например Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>Выберите адрес из адресной книги</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Вставить адрес из буфера обмена</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Удалить этого получателя</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation>Введите VPSCoin-адрес (например Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Подписи - подписать/проверить сообщение</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Вы можете подписывать сообщения своими адресами, чтобы доказать владение ими. Будьте осторожны, не подписывайте что-то неопределённое, так как фишинговые атаки могут обманным путём заставить вас подписать нежелательные сообщения. Подписывайте только те сообщения, с которыми вы согласны вплоть до мелочей.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation>Адрес, которым вы хотите подписать сообщение (напр. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Выберите адрес из адресной книги</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Вставить адрес из буфера обмена</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Введите сообщение для подписи</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Скопировать текущую подпись в системный буфер обмена</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this VPSCoin address</source>
<translation>Подписать сообщение, чтобы доказать владение адресом VPSCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Сбросить значения всех полей подписывания сообщений</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Очистить &всё</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Проверить сообщение</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Введите ниже адрес для подписи, сообщение (убедитесь, что переводы строк, пробелы, табы и т.п. в точности скопированы) и подпись, чтобы проверить сообщение. Убедитесь, что не скопировали лишнего в подпись, по сравнению с самим подписываемым сообщением, чтобы не стать жертвой атаки "man-in-the-middle".</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation>Адрес, которым было подписано сообщение (напр. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified VPSCoin address</source>
<translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом VPSCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Сбросить все поля проверки сообщения</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation>Введите адрес VPSCoin (напр. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Нажмите "Подписать сообщение" для создания подписи</translation>
</message>
<message>
<location line="+3"/>
<source>Enter VPSCoin signature</source>
<translation>Введите подпись VPSCoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Введённый адрес неверен</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Пожалуйста, проверьте адрес и попробуйте ещё раз.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Введённый адрес не связан с ключом</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Разблокировка бумажника была отменена.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Для введённого адреса недоступен закрытый ключ</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Не удалось подписать сообщение</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Сообщение подписано</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Подпись не может быть раскодирована.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Пожалуйста, проверьте подпись и попробуйте ещё раз.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Подпись не соответствует отпечатку сообщения.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Проверка сообщения не удалась.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Сообщение проверено.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Открыто для %n блока</numerusform><numerusform>Открыто для %n блоков</numerusform><numerusform>Открыто для %n блоков</numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation>конфликт</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/оффлайн</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/не подтверждено</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 подтверждений</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Статус</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, разослано через %n узел</numerusform><numerusform>, разослано через %n узла</numerusform><numerusform>, разослано через %n узлов</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Источник</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Сгенерировано</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>От</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Для</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>свой адрес</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>метка</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Кредит</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>будет доступно через %n блок</numerusform><numerusform>будет доступно через %n блока</numerusform><numerusform>будет доступно через %n блоков</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>не принято</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Дебет</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Комиссия</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Чистая сумма</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Сообщение</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Комментарий</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID транзакции</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Сгенерированные монеты должны подождать 510 блоков, прежде чем они могут быть потрачены. Когда Вы сгенерировали этот блок, он был отправлен в сеть для добавления в цепочку блоков. Если данная процедура не удастся, статус изменится на «не подтверждено», и монеты будут недействительны. Это иногда происходит в случае, если другой узел сгенерирует блок на несколько секунд раньше вас.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Отладочная информация</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Транзакция</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Входы</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>истина</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>ложь</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ещё не было успешно разослано</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>неизвестно</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Детали транзакции</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Данный диалог показывает детализированную статистику по выбранной транзакции</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Подтверждено (%1 подтверждений)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Открыто для ещё %n блока</numerusform><numerusform>Открыто для ещё %n блоков</numerusform><numerusform>Открыто для ещё %n блоков</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Оффлайн</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Не подтверждено</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Подтверждается (%1 из %2 рекомендованных подтверждений)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Конфликт</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Незрелые (%1 подтверждений, будут доступны после %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Этот блок не был получен другими узлами и, возможно, не будет принят!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Сгенерировано, но не принято</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Получено</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Получено от</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Отправлено</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Отправлено себе</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Добыто</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>[не доступно]</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Статус транзакции. Подведите курсор к нужному полю для того, чтобы увидеть количество подтверждений.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Дата и время, когда транзакция была получена.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Тип транзакции.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Адрес назначения транзакции.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Сумма, добавленная, или снятая с баланса.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Все</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Сегодня</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>На этой неделе</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>В этом месяце</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>За последний месяц</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>В этом году</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Промежуток...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Получено на</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Отправлено на</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Отправленные себе</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Добытые</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Другое</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Введите адрес или метку для поиска</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Мин. сумма</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Копировать адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Копировать метку</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Скопировать сумму</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Скопировать ID транзакции</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Изменить метку</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Показать подробности транзакции</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>Экспортировать данные транзакций</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Текст, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Подтверждено</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Промежуток от:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>до</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>Отправка....</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>VPSCoin version</source>
<translation>Версия</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Использование:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or VPSCoind</source>
<translation>Отправить команду на -server или VPSCoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Список команд
</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Получить помощь по команде</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Опции:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: VPSCoin.conf)</source>
<translation>Указать конфигурационный файл (по умолчанию: VPSCoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: VPSCoind.pid)</source>
<translation>Указать pid-файл (по умолчанию: VPSCoind.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Указать файл кошелька (в пределах DATA директории)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Укажите каталог данных</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Установить размер кэша базы данных в мегабайтах (по умолчанию: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Установить размер лога базы данных в мегабайтах (по умолчанию: 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>Принимать входящие подключения на <port> (по умолчанию: 15714 или 25714 в тестовой сети)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Поддерживать не более <n> подключений к узлам (по умолчанию: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Подключиться к узлу, чтобы получить список адресов других участников и отключиться</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Укажите ваш собственный публичный адрес</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Привязаться (bind) к указанному адресу. Используйте запись вида [хост]:порт для IPv6</translation>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Порог для отключения неправильно ведущих себя узлов (по умолчанию: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Число секунд блокирования неправильно ведущих себя узлов (по умолчанию: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Произошла ошибка при открытии RPC-порта %u для прослушивания на IPv4: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Отключить базы данных блоков и адресов. Увеличивает время завершения работы (по умолчанию: 0)</translation>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Ошибка: В транзакции отказано. Такое может произойти, если некоторые монеты уже были потрачены, например, если Вы используете одну копию файла wallet.dat, а монеты были потрачены из другой копии, но не были отмечены как потраченные в этой.</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Ошибка: эта транзакция требует комиссию в размере как минимум %s из-за её объёма, сложности или использования недавно полученных средств </translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation>Прослушивать подключения JSON-RPC на <порту> (по умолчанию: 15715 или для testnet: 25715)</translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Принимать командную строку и команды JSON-RPC</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>Ошибка: Создание транзакции не удалось </translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Ошибка: бумажник заблокирован, невозможно создать транзакцию </translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>Импортируется файл цепи блоков.</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>Импортируется bootstrap-файл цепи блоков.</translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Запускаться в фоне как демон и принимать команды</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Использовать тестовую сеть</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Принимать подключения извне (по умолчанию: 1, если не используется -proxy или -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Произошла ошибка при открытии на прослушивание IPv6 RCP-порта %u, возвращаемся к IPv4: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>Ошибка инициализации окружения БД %s! Для восстановления СДЕЛАЙТЕ РЕЗЕРВНУЮ КОПИЮ этой директории, затем удалите из нее все, кроме wallet.dat.</translation>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Максимальный размер высокоприоритетных/низкокомиссионных транзакций в байтах (по умолчанию: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Внимание: установлено очень большое значение -paytxfee. Это комиссия, которую вы заплатите при проведении транзакции.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong VPSCoin will not work properly.</source>
<translation>Внимание: убедитесь, что дата и время на Вашем компьютере выставлены верно. Если Ваши часы идут неправильно, VPSCoin будет работать некорректно.</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Внимание: ошибка чтения wallet.dat! Все ключи восстановлены, но записи в адресной книге и истории транзакций могут быть некорректными.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Внимание: wallet.dat был поврежден, данные восстановлены! Оригинальный wallet.dat сохранен как wallet.{timestamp}.bak в %s;, если ваши транзакции или баланс отображаются неправильно, следует восстановить его из данной копии.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Попытка восстановления ключей из поврежденного wallet.dat</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Параметры создания блоков:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Подключаться только к указанному узлу(ам)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Определить свой IP (по умолчанию: 1 при прослушивании и если не используется -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Не удалось начать прослушивание на порту. Используйте -listen=0 если вас это устраивает.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Искать узлы с помощью DNS (по умолчанию: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Политика синхронизированных меток (по умолчанию: strict)</translation>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation>Неверный адрес -tor: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Максимальный размер буфера приёма на соединение, <n>*1000 байт (по умолчанию: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Максимальный размер буфера отправки на соединение, <n>*1000 байт (по умолчанию: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Подключаться только к узлам из сети <net> (IPv4, IPv6 или Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Выводить больше отладочной информации. Включает все остальные опции -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Выводить дополнительную сетевую отладочную информацию</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>Дописывать отметки времени к отладочному выводу</translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>
Параметры SSL: (см. Bitcoin Wiki для инструкций по настройке SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Выберите версию SOCKS-прокси (4-5, по умолчанию: 5)</translation>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Выводить информацию трассировки/отладки на консоль вместо файла debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Отправлять информацию трассировки/отладки в отладчик</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Максимальный размер блока в байтах (по умолчанию: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Минимальный размер блока в байтах (по умолчанию: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Сжимать файл debug.log при запуске клиента (по умолчанию: 1, если нет -debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Таймаут соединения в миллисекундах (по умолчанию: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Использовать UPnP для проброса порта (по умолчанию: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Использовать UPnP для проброса порта (по умолчанию: 1, если используется прослушивание)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Использовать прокси для скрытых сервисов (по умолчанию: тот же, что и в -proxy)</translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Имя для подключений JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>Проверка целостности базы данных...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Внимание: мало места на диске!</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Внимание: эта версия устарела, требуется обновление!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat поврежден, восстановление не удалось</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Пароль для подключений JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=VPSCoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "VPSCoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Разрешить подключения JSON-RPC с указанного IP</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Посылать команды узлу, запущенному на <ip> (по умолчанию: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Выполнить команду, когда появляется новый блок (%s в команде заменяется на хэш блока)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Выполнить команду, когда получена новая транзакция (%s в команде заменяется на ID транзакции)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Требовать подтверждения для сдачи (по умолчанию: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Обновить бумажник до последнего формата</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Установить размер запаса ключей в <n> (по умолчанию: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Перепроверить цепь блоков на предмет отсутствующих в бумажнике транзакций</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Сколько блоков проверять при запуске (по умолчанию: 2500, 0 = все)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Насколько тщательно проверять блоки (0-6, по умолчанию: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Импортировать блоки из внешнего файла blk000?.dat</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Использовать OpenSSL (https) для подключений JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Файл серверного сертификата (по умолчанию: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Приватный ключ сервера (по умолчанию: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Разрешённые алгоритмы (по умолчанию: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Эта справка</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Кошелек %s находится вне рабочей директории %s.</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. VPSCoin is probably already running.</source>
<translation>Невозможно установить блокировку на рабочую директорию %s. Возможно, бумажник уже запущен.</translation>
</message>
<message>
<location line="-98"/>
<source>VPSCoin</source>
<translation>VPSCoin</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Невозможно привязаться к %s на этом компьютере (bind вернул ошибку %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>Подключаться через socks прокси</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Разрешить поиск в DNS для -addnode, -seednode и -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Загрузка адресов...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>Ошибка чтения blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Ошибка загрузки wallet.dat: Бумажник поврежден</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of VPSCoin</source>
<translation>Ошибка загрузки wallet.dat: бумажник требует более новую версию VPSCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart VPSCoin to complete</source>
<translation>Необходимо перезаписать бумажник, перезапустите VPSCoin для завершения операции</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Ошибка при загрузке wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Неверный адрес -proxy: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>В параметре -onlynet указана неизвестная сеть: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>В параметре -socks запрошена неизвестная версия: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Не удаётся разрешить адрес в параметре -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Не удаётся разрешить адрес в параметре -externalip: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Неверное количество в параметре -paytxfee=<кол-во>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Ошибка: не удалось запустить узел</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Отправка...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Неверное количество</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Недостаточно монет</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Загрузка индекса блоков...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Добавить узел для подключения и пытаться поддерживать соединение открытым</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. VPSCoin is probably already running.</source>
<translation>Невозможно привязаться к %s на этом компьютере. Возможно, VPSCoin уже работает.</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Комиссия на килобайт, добавляемая к вашим транзакциям</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Загрузка бумажника...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Не удаётся понизить версию бумажника</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Не удаётся инициализировать массив ключей</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Не удаётся записать адрес по умолчанию</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Сканирование...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Загрузка завершена</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Чтобы использовать опцию %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Ошибка</translation>
</message>
<message>
<location line="+6"/>
<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=<password> в конфигурационном файле:
%s
Если файл не существует, создайте его и установите права доступа только для владельца.</translation>
</message>
</context>
</TS><|fim▁end|> | Amount: %2
Type: %3
Address: %4
</source> |
<|file_name|>static-mut-foreign.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Constants (static variables) can be used to match in patterns, but mutable
// statics cannot. This ensures that there's some form of error if this is
// attempted.
// pretty-expanded FIXME #23616
#![feature(libc)]
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
static mut rust_dbg_static_mut: libc::c_int;
pub fn rust_dbg_static_mut_check_four();
}
unsafe fn static_bound(_: &'static libc::c_int) {}
fn static_bound_set(a: &'static mut libc::c_int) {
*a = 3;
}
unsafe fn run() {
assert!(rust_dbg_static_mut == 3);
rust_dbg_static_mut = 4;
assert!(rust_dbg_static_mut == 4);
rust_dbg_static_mut_check_four();
rust_dbg_static_mut += 1;
assert!(rust_dbg_static_mut == 5);
rust_dbg_static_mut *= 3;
assert!(rust_dbg_static_mut == 15);
rust_dbg_static_mut = -3;<|fim▁hole|> assert!(rust_dbg_static_mut == -3);
static_bound(&rust_dbg_static_mut);
static_bound_set(&mut rust_dbg_static_mut);
}
pub fn main() {
unsafe { run() }
}<|fim▁end|> | |
<|file_name|>userlist_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins, secs) = time_string.strip().split(splitter)
return(mins + '.' + secs)
def get_coach_data(filename):
try:<|fim▁hole|> except IOError as ioerr:
print('File Error:' + str(ioerr))
return(None)
sarah = get_coach_data('sarah2.txt')
(sarah_name, sarach_dob) = sarah.pop(0), sarah.pop(0)
print(sarah_name + "'s fastest time are:"+
str(sorted(set([sanitize(t) for t in sarah]))[0:3]))<|fim▁end|> | with open(filename) as fn:
data = fn.readline()
return(data.strip().split(',')) |
<|file_name|>Sequences.cpp<|end_file_name|><|fim▁begin|>#include <seqan/sequence.h>
#include <seqan/basic.h>
#include <seqan/find_motif.h>
#include <seqan/file.h>
#include <iostream>
using namespace seqan;
template<typename TString>//String<char>
void countOneMers(TString const& str){
Iterator<TString>::Type StringIterator = begin(str);
Iterator<TString>::Type EndIterator = end(str);
String<unsigned int> counter;<|fim▁hole|> unsigned int a=0;
while(StringIterator != EndIterator){
a= ordValue(*StringIterator);
std::cout<<a-normalize<<std::endl;
++value(counter,(a-normalize));
++StringIterator;
}
StringIterator = begin(str);
//Iterator<String<unsigned int> >::Type countIterator = begin(counter);
int i=0;
while(i<26){
if(counter[i]>0)
std::cout<<char(i+'a')<<" "<<counter[i]<<std::endl;
++i;
}
}
void replaceAs(String<char>& str){
str="hi";
}
int main(){
String<char> str = "helloworld";
//countOneMers(str);
replaceAs(str);
std::cout<<str;
return 0;
}<|fim▁end|> | resize(counter, 26,0);//26 = AlphSize
unsigned int normalize =ordValue('a'); |
<|file_name|>0007_add_descriptions_to_project_and_tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10b1 on 2016-09-17 02:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timeblob', '0006_auto_20160820_1908'),
]
operations = [
migrations.AddField(
model_name='project',
name='description',
field=models.TextField(default=''),
preserve_default=False,
),<|fim▁hole|> field=models.TextField(default=''),
preserve_default=False,
),
]<|fim▁end|> | migrations.AddField(
model_name='task',
name='description', |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>"""
TutorialWorld - basic objects - Griatch 2011
This module holds all "dead" object definitions for
the tutorial world. Object-commands and -cmdsets
are also defined here, together with the object.
Objects:
TutorialObject
Readable
Climbable
Obelisk
LightSource
CrumblingWall
Weapon
WeaponRack
"""
from future.utils import listvalues
import random
from evennia import DefaultObject, DefaultExit, Command, CmdSet
from evennia import utils
from evennia.utils import search
from evennia.utils.spawner import spawn
#------------------------------------------------------------
#
# TutorialObject
#
# The TutorialObject is the base class for all items
# in the tutorial. They have an attribute "tutorial_info"
# on them that the global tutorial command can use to extract
# interesting behind-the scenes information about the object.
#
# TutorialObjects may also be "reset". What the reset means
# is up to the object. It can be the resetting of the world
# itself, or the removal of an inventory item from a
# character's inventory when leaving the tutorial, for example.
#
#------------------------------------------------------------
class TutorialObject(DefaultObject):
"""
This is the baseclass for all objects in the tutorial.
"""
def at_object_creation(self):
"Called when the object is first created."
super(TutorialObject, self).at_object_creation()
self.db.tutorial_info = "No tutorial info is available for this object."
def reset(self):
"Resets the object, whatever that may mean."
self.location = self.home
#------------------------------------------------------------
#
# Readable - an object that can be "read"
#
#------------------------------------------------------------
#
# Read command
#
class CmdRead(Command):
"""
Usage:
read [obj]
Read some text of a readable object.
"""
key = "read"
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
Implements the read command. This simply looks for an
Attribute "readable_text" on the object and displays that.
"""
if self.args:
obj = self.caller.search(self.args.strip())
else:
obj = self.obj
if not obj:
return
# we want an attribute read_text to be defined.
readtext = obj.db.readable_text
if readtext:
string = "You read {C%s{n:\n %s" % (obj.key, readtext)
else:
string = "There is nothing to read on %s." % obj.key
self.caller.msg(string)
class CmdSetReadable(CmdSet):
"""
A CmdSet for readables.
"""
def at_cmdset_creation(self):
"""
Called when the cmdset is created.
"""
self.add(CmdRead())
class Readable(TutorialObject):
"""
This simple object defines some attributes and
"""
def at_object_creation(self):
"""
Called when object is created. We make sure to set the needed
Attribute and add the readable cmdset.
"""
super(Readable, self).at_object_creation()
self.db.tutorial_info = "This is an object with a 'read' command defined in a command set on itself."
self.db.readable_text = "There is no text written on %s." % self.key
# define a command on the object.
self.cmdset.add_default(CmdSetReadable, permanent=True)
#------------------------------------------------------------
#
# Climbable object
#
# The climbable object works so that once climbed, it sets
# a flag on the climber to show that it was climbed. A simple
# command 'climb' handles the actual climbing. The memory
# of what was last climbed is used in a simple puzzle in the
# tutorial.
#
#------------------------------------------------------------
class CmdClimb(Command):
"""
Climb an object
Usage:
climb <object>
This allows you to climb.
"""
key = "climb"
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"Implements function"
if not self.args:
self.caller.msg("What do you want to climb?")
return
obj = self.caller.search(self.args.strip())
if not obj:
return
if obj != self.obj:
self.caller.msg("Try as you might, you cannot climb that.")
return
ostring = self.obj.db.climb_text
if not ostring:
ostring = "You climb %s. Having looked around, you climb down again." % self.obj.name
self.caller.msg(ostring)
# set a tag on the caller to remember that we climbed.
self.caller.tags.add("tutorial_climbed_tree", category="tutorial_world")
class CmdSetClimbable(CmdSet):
"Climbing cmdset"
def at_cmdset_creation(self):
"populate set"
self.add(CmdClimb())
class Climbable(TutorialObject):
"""
A climbable object. All that is special about it is that it has
the "climb" command available on it.
"""
def at_object_creation(self):
"Called at initial creation only"
self.cmdset.add_default(CmdSetClimbable, permanent=True)
#------------------------------------------------------------
#
# Obelisk - a unique item
#
# The Obelisk is an object with a modified return_appearance method
# that causes it to look slightly different every time one looks at it.
# Since what you actually see is a part of a game puzzle, the act of
# looking also stores a key attribute on the looking object (different
# depending on which text you saw) for later reference.
#
#------------------------------------------------------------
class Obelisk(TutorialObject):
"""
This object changes its description randomly, and which is shown
determines which order "clue id" is stored on the Character for
future puzzles.
Important Attribute:
puzzle_descs (list): list of descriptions. One of these is
picked randomly when this object is looked at and its index
in the list is used as a key for to solve the puzzle.
"""
def at_object_creation(self):
"Called when object is created."
super(Obelisk, self).at_object_creation()
self.db.tutorial_info = "This object changes its desc randomly, and makes sure to remember which one you saw."
self.db.puzzle_descs = ["You see a normal stone slab"]
# make sure this can never be picked up
self.locks.add("get:false()")
def return_appearance(self, caller):
"""
This hook is called by the look command to get the description
of the object. We overload it with our own version.
"""
# randomly get the index for one of the descriptions
descs = self.db.puzzle_descs
clueindex = random.randint(0, len(descs) - 1)
# set this description, with the random extra
string = "The surface of the obelisk seem to waver, shift and writhe under your gaze, with " \
"different scenes and structures appearing whenever you look at it. "
self.db.desc = string + descs[clueindex]
# remember that this was the clue we got. The Puzzle room will
# look for this later to determine if you should be teleported
# or not.
caller.db.puzzle_clue = clueindex
# call the parent function as normal (this will use
# the new desc Attribute we just set)
return super(Obelisk, self).return_appearance(caller)
#------------------------------------------------------------
#
# LightSource
#
# This object emits light. Once it has been turned on it
# cannot be turned off. When it burns out it will delete
# itself.
#
# This could be implemented using a single-repeat Script or by
# registering with the TickerHandler. We do it simpler by
# using the delay() utility function. This is very simple
# to use but does not survive a server @reload. Because of
# where the light matters (in the Dark Room where you can
# find new light sources easily), this is okay here.
#
#------------------------------------------------------------
class CmdLight(Command):
"""
Creates light where there was none. Something to burn.
"""
key = "on"
aliases = ["light", "burn"]
# only allow this command if command.obj is carried by caller.
locks = "cmd:holds()"
help_category = "TutorialWorld"
def func(self):
"""
Implements the light command. Since this command is designed
to sit on a "lightable" object, we operate only on self.obj.
"""
if self.obj.light():
self.caller.msg("You light %s." % self.obj.key)
self.caller.location.msg_contents("%s lights %s!" % (self.caller, self.obj.key), exclude=[self.caller])
else:
self.caller.msg("%s is already burning." % self.obj.key)
class CmdSetLight(CmdSet):
"CmdSet for the lightsource commands"
key = "lightsource_cmdset"
# this is higher than the dark cmdset - important!
priority = 3
def at_cmdset_creation(self):
"called at cmdset creation"
self.add(CmdLight())
class LightSource(TutorialObject):
"""
This implements a light source object.
When burned out, the object will be deleted.
"""
def at_init(self):
"""
If this is called with the Attribute is_giving_light already
set, we know that the timer got killed by a server
reload/reboot before it had time to finish. So we kill it here
instead. This is the price we pay for the simplicity of the
non-persistent delay() method.
"""
if self.db.is_giving_light:
self.delete()
def at_object_creation(self):
"Called when object is first created."
super(LightSource, self).at_object_creation()
self.db.tutorial_info = "This object can be lit to create light. It has a timeout for how long it burns."
self.db.is_giving_light = False
self.db.burntime = 60 * 3 # 3 minutes
# this is the default desc, it can of course be customized
# when created.
self.db.desc = "A splinter of wood with remnants of resin on it, enough for burning."
# add the Light command
self.cmdset.add_default(CmdSetLight, permanent=True)
def _burnout(self):
"""
This is called when this light source burns out. We make no
use of the return value.
"""
# delete ourselves from the database
self.db.is_giving_light = False
try:
self.location.location.msg_contents("%s's %s flickers and dies." %
(self.location, self.key), exclude=self.location)
self.location.msg("Your %s flickers and dies." % self.key)
self.location.location.check_light_state()
except AttributeError:
try:
self.location.msg_contents("A %s on the floor flickers and dies." % self.key)
self.location.location.check_light_state()
except AttributeError:
pass
self.delete()
def light(self):
"""
Light this object - this is called by Light command.
"""
if self.db.is_giving_light:
return False
# burn for 3 minutes before calling _burnout
self.db.is_giving_light = True
# if we are in a dark room, trigger its light check
try:
self.location.location.check_light_state()
except AttributeError:
try:
# maybe we are directly in the room
self.location.check_light_state()
except AttributeError:
pass
finally:
# start the burn timer. When it runs out, self._burnout
# will be called.
utils.delay(60 * 3, self._burnout)
return True
#------------------------------------------------------------
#
# Crumbling wall - unique exit
#
# This implements a simple puzzle exit that needs to be
# accessed with commands before one can get to traverse it.
#
# The puzzle-part is simply to move roots (that have
# presumably covered the wall) aside until a button for a
# secret door is revealed. The original position of the
# roots blocks the button, so they have to be moved to a certain
# position - when they have, the "press button" command
# is made available and the Exit is made traversable.
#
#------------------------------------------------------------
# There are four roots - two horizontal and two vertically
# running roots. Each can have three positions: top/middle/bottom
# and left/middle/right respectively. There can be any number of
# roots hanging through the middle position, but only one each
# along the sides. The goal is to make the center position clear.
# (yes, it's really as simple as it sounds, just move the roots
# to each side to "win". This is just a tutorial, remember?)
#
# The ShiftRoot command depends on the root object having an
# Attribute root_pos (a dictionary) to describe the current
# position of the roots.
class CmdShiftRoot(Command):
"""
Shifts roots around.
Usage:
shift blue root left/right
shift red root left/right
shift yellow root up/down
shift green root up/down
"""
key = "shift"
aliases = ["shiftroot", "push", "pull", "move"]
# we only allow to use this command while the
# room is properly lit, so we lock it to the
# setting of Attribute "is_lit" on our location.
locks = "cmd:locattr(is_lit)"
help_category = "TutorialWorld"
def parse(self):
"""
Custom parser; split input by spaces for simplicity.
"""
self.arglist = self.args.strip().split()
def func(self):
"""
Implement the command.
blue/red - vertical roots
yellow/green - horizontal roots
"""
if not self.arglist:
self.caller.msg("What do you want to move, and in what direction?")
return
if "root" in self.arglist:
# we clean out the use of the word "root"
self.arglist.remove("root")
# we accept arguments on the form <color> <direction>
if not len(self.arglist) > 1:
self.caller.msg("You must define which colour of root you want to move, and in which direction.")
return
color = self.arglist[0].lower()
direction = self.arglist[1].lower()
# get current root positions dict
root_pos = self.obj.db.root_pos
if not color in root_pos:
self.caller.msg("No such root to move.")
return
# first, vertical roots (red/blue) - can be moved left/right
if color == "red":
if direction == "left":
root_pos[color] = max(-1, root_pos[color] - 1)
self.caller.msg("You shift the reddish root to the left.")
if root_pos[color] != 0 and root_pos[color] == root_pos["blue"]:
root_pos["blue"] += 1
self.caller.msg("The root with blue flowers gets in the way and is pushed to the right.")
elif direction == "right":
root_pos[color] = min(1, root_pos[color] + 1)
self.caller.msg("You shove the reddish root to the right.")
if root_pos[color] != 0 and root_pos[color] == root_pos["blue"]:
root_pos["blue"] -= 1
self.caller.msg("The root with blue flowers gets in the way and is pushed to the left.")
else:
self.caller.msg("You cannot move the root in that direction.")
elif color == "blue":
if direction == "left":
root_pos[color] = max(-1, root_pos[color] - 1)
self.caller.msg("You shift the root with small blue flowers to the left.")
if root_pos[color] != 0 and root_pos[color] == root_pos["red"]:
root_pos["red"] += 1
self.caller.msg("The reddish root is to big to fit as well, so that one falls away to the left.")
elif direction == "right":
root_pos[color] = min(1, root_pos[color] + 1)
self.caller.msg("You shove the root adorned with small blue flowers to the right.")
if root_pos[color] != 0 and root_pos[color] == root_pos["red"]:
root_pos["red"] -= 1
self.caller.msg("The thick reddish root gets in the way and is pushed back to the left.")
else:
self.caller.msg("You cannot move the root in that direction.")
# now the horizontal roots (yellow/green). They can be moved up/down
elif color == "yellow":
if direction == "up":
root_pos[color] = max(-1, root_pos[color] - 1)
self.caller.msg("You shift the root with small yellow flowers upwards.")
if root_pos[color] != 0 and root_pos[color] == root_pos["green"]:
root_pos["green"] += 1
self.caller.msg("The green weedy root falls down.")
elif direction == "down":
root_pos[color] = min(1, root_pos[color] + 1)
self.caller.msg("You shove the root adorned with small yellow flowers downwards.")
if root_pos[color] != 0 and root_pos[color] == root_pos["green"]:
root_pos["green"] -= 1
self.caller.msg("The weedy green root is shifted upwards to make room.")
else:
self.caller.msg("You cannot move the root in that direction.")
elif color == "green":
if direction == "up":
root_pos[color] = max(-1, root_pos[color] - 1)
self.caller.msg("You shift the weedy green root upwards.")
if root_pos[color] != 0 and root_pos[color] == root_pos["yellow"]:
root_pos["yellow"] += 1
self.caller.msg("The root with yellow flowers falls down.")
elif direction == "down":
root_pos[color] = min(1, root_pos[color] + 1)
self.caller.msg("You shove the weedy green root downwards.")
if root_pos[color] != 0 and root_pos[color] == root_pos["yellow"]:
root_pos["yellow"] -= 1
self.caller.msg("The root with yellow flowers gets in the way and is pushed upwards.")
else:
self.caller.msg("You cannot move the root in that direction.")
# we have moved the root. Store new position
self.obj.db.root_pos = root_pos
# Check victory condition
if listvalues(root_pos).count(0) == 0: # no roots in middle position
# This will affect the cmd: lock of CmdPressButton
self.obj.db.button_exposed = True
self.caller.msg("Holding aside the root you think you notice something behind it ...")
class CmdPressButton(Command):
"""
Presses a button.
"""
key = "press"
aliases = ["press button", "button", "push button"]
# only accessible if the button was found and there is light. This checks
# the Attribute button_exposed on the Wall object so that
# you can only push the button when the puzzle is solved. It also
# checks the is_lit Attribute on the location.
locks = "cmd:objattr(button_exposed) and objlocattr(is_lit)"
help_category = "TutorialWorld"
def func(self):
"Implements the command"
if self.caller.db.crumbling_wall_found_exit:
# we already pushed the button
self.caller.msg("The button folded away when the secret passage opened. You cannot push it again.")
return
# pushing the button
string = "You move your fingers over the suspicious depression, then gives it a " \
"decisive push. First nothing happens, then there is a rumble and a hidden " \
"{wpassage{n opens, dust and pebbles rumbling as part of the wall moves aside."
self.caller.msg(string)
string = "%s moves their fingers over the suspicious depression, then gives it a " \
"decisive push. First nothing happens, then there is a rumble and a hidden " \
"{wpassage{n opens, dust and pebbles rumbling as part of the wall moves aside."
self.caller.location.msg_contents(string % self.caller.key, exclude=self.caller)
self.obj.open_wall()
class CmdSetCrumblingWall(CmdSet):
"Group the commands for crumblingWall"
key = "crumblingwall_cmdset"
priority = 2
def at_cmdset_creation(self):
"called when object is first created."
self.add(CmdShiftRoot())
self.add(CmdPressButton())
class CrumblingWall(TutorialObject, DefaultExit):
"""
This is a custom Exit.
The CrumblingWall can be examined in various ways, but only if a
lit light source is in the room. The traversal itself is blocked
by a traverse: lock on the exit that only allows passage if a
certain attribute is set on the trying player.
Important attribute
destination - this property must be set to make this a valid exit
whenever the button is pushed (this hides it as an exit
until it actually is)
"""
def at_init(self):
"""
Called when object is recalled from cache.
"""
self.reset()
def at_object_creation(self):
"called when the object is first created."
super(CrumblingWall, self).at_object_creation()
self.aliases.add(["secret passage", "passage",
"crack", "opening", "secret door"])
# starting root positions. H1/H2 are the horizontally hanging roots,
# V1/V2 the vertically hanging ones. Each can have three positions:
# (-1, 0, 1) where 0 means the middle position. yellow/green are
# horizontal roots and red/blue vertical, all may have value 0, but n
# ever any other identical value.
self.db.root_pos = {"yellow": 0, "green": 0, "red": 0, "blue": 0}
# flags controlling the puzzle victory conditions
self.db.button_exposed = False
self.db.exit_open = False
# this is not even an Exit until it has a proper destination, and we won't assign
# that until it is actually open. Until then we store the destination here. This
# should be given a reasonable value at creation!
self.db.destination = 2
# we lock this Exit so that one can only execute commands on it
# if its location is lit and only traverse it once the Attribute
# exit_open is set to True.
self.locks.add("cmd:locattr(is_lit);traverse:objattr(exit_open)")
# set cmdset
self.cmdset.add(CmdSetCrumblingWall, permanent=True)
def open_wall(self):
"""
This method is called by the push button command once the puzzle
is solved. It opens the wall and sets a timer for it to reset
itself.
"""
# this will make it into a proper exit (this returns a list)
eloc = search.search_object(self.db.destination)
if not eloc:
self.caller.msg("The exit leads nowhere, there's just more stone behind it ...")
else:
self.destination = eloc[0]
self.exit_open = True
# start a 45 second timer before closing again
utils.delay(45, self.reset)
def _translate_position(self, root, ipos):
"Translates the position into words"
rootnames = {"red": "The {rreddish{n vertical-hanging root ",
"blue": "The thick vertical root with {bblue{n flowers ",
"yellow": "The thin horizontal-hanging root with {yyellow{n flowers ",
"green": "The weedy {ggreen{n horizontal root "}
vpos = {-1: "hangs far to the {wleft{n on the wall.",
0: "hangs straight down the {wmiddle{n of the wall.",
1: "hangs far to the {wright{n of the wall."}
hpos = {-1: "covers the {wupper{n part of the wall.",
0: "passes right over the {wmiddle{n of the wall.",
1: "nearly touches the floor, near the {wbottom{n of the wall."}
if root in ("yellow", "green"):
string = rootnames[root] + hpos[ipos]
else:
string = rootnames[root] + vpos[ipos]
return string
def return_appearance(self, caller):
"""
This is called when someone looks at the wall. We need to echo the<|fim▁hole|> string = "Having moved all the roots aside, you find that the center of the wall, " \
"previously hidden by the vegetation, hid a curious square depression. It was maybe once " \
"concealed and made to look a part of the wall, but with the crumbling of stone around it," \
"it's now easily identifiable as some sort of button."
elif self.db.exit_open:
# we pressed the button; the exit is open
string = "With the button pressed, a crack has opened in the root-covered wall, just wide enough " \
"to squeeze through. A cold draft is coming from the hole and you get the feeling the " \
"opening may close again soon."
else:
# puzzle not solved yet.
string = "The wall is old and covered with roots that here and there have permeated the stone. " \
"The roots (or whatever they are - some of them are covered in small non-descript flowers) " \
"crisscross the wall, making it hard to clearly see its stony surface. Maybe you could " \
"try to {wshift{n or {wmove{n them.\n"
# display the root positions to help with the puzzle
for key, pos in self.db.root_pos.items():
string += "\n" + self._translate_position(key, pos)
self.db.desc = string
# call the parent to continue execution (will use the desc we just set)
return super(CrumblingWall, self).return_appearance(caller)
def at_after_traverse(self, traverser, source_location):
"""
This is called after we traversed this exit. Cleans up and resets
the puzzle.
"""
del traverser.db.crumbling_wall_found_buttothe
del traverser.db.crumbling_wall_found_exit
self.reset()
def at_failed_traverse(self, traverser):
"This is called if the player fails to pass the Exit."
traverser.msg("No matter how you try, you cannot force yourself through %s." % self.key)
def reset(self):
"""
Called by tutorial world runner, or whenever someone successfully
traversed the Exit.
"""
self.location.msg_contents("The secret door closes abruptly, roots falling back into place.")
# reset the flags and remove the exit destination
self.db.button_exposed = False
self.db.exit_open = False
self.destination = None
# Reset the roots with some random starting positions for the roots:
start_pos = [{"yellow":1, "green":0, "red":0, "blue":0},
{"yellow":0, "green":0, "red":0, "blue":0},
{"yellow":0, "green":1, "red":-1, "blue":0},
{"yellow":1, "green":0, "red":0, "blue":0},
{"yellow":0, "green":0, "red":0, "blue":1}]
self.db.root_pos = random.choice(start_pos)
#------------------------------------------------------------
#
# Weapon - object type
#
# A weapon is necessary in order to fight in the tutorial
# world. A weapon (which here is assumed to be a bladed
# melee weapon for close combat) has three commands,
# stab, slash and defend. Weapons also have a property "magic"
# to determine if they are usable against certain enemies.
#
# Since Characters don't have special skills in the tutorial,
# we let the weapon itself determine how easy/hard it is
# to hit with it, and how much damage it can do.
#
#------------------------------------------------------------
class CmdAttack(Command):
"""
Attack the enemy. Commands:
stab <enemy>
slash <enemy>
parry
stab - (thrust) makes a lot of damage but is harder to hit with.
slash - is easier to land, but does not make as much damage.
parry - forgoes your attack but will make you harder to hit on next
enemy attack.
"""
# this is an example of implementing many commands as a single
# command class, using the given command alias to separate between them.
key = "attack"
aliases = ["hit","kill", "fight", "thrust", "pierce", "stab",
"slash", "chop", "parry", "defend"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"Implements the stab"
cmdstring = self.cmdstring
if cmdstring in ("attack", "fight"):
string = "How do you want to fight? Choose one of 'stab', 'slash' or 'defend'."
self.caller.msg(string)
return
# parry mode
if cmdstring in ("parry", "defend"):
string = "You raise your weapon in a defensive pose, ready to block the next enemy attack."
self.caller.msg(string)
self.caller.db.combat_parry_mode = True
self.caller.location.msg_contents("%s takes a defensive stance" % self.caller, exclude=[self.caller])
return
if not self.args:
self.caller.msg("Who do you attack?")
return
target = self.caller.search(self.args.strip())
if not target:
return
string = ""
tstring = ""
ostring = ""
if cmdstring in ("thrust", "pierce", "stab"):
hit = float(self.obj.db.hit) * 0.7 # modified due to stab
damage = self.obj.db.damage * 2 # modified due to stab
string = "You stab with %s. " % self.obj.key
tstring = "%s stabs at you with %s. " % (self.caller.key, self.obj.key)
ostring = "%s stabs at %s with %s. " % (self.caller.key, target.key, self.obj.key)
self.caller.db.combat_parry_mode = False
elif cmdstring in ("slash", "chop"):
hit = float(self.obj.db.hit) # un modified due to slash
damage = self.obj.db.damage # un modified due to slash
string = "You slash with %s. " % self.obj.key
tstring = "%s slash at you with %s. " % (self.caller.key, self.obj.key)
ostring = "%s slash at %s with %s. " % (self.caller.key, target.key, self.obj.key)
self.caller.db.combat_parry_mode = False
else:
self.caller.msg("You fumble with your weapon, unsure of whether to stab, slash or parry ...")
self.caller.location.msg_contents("%s fumbles with their weapon." % self.caller, exclude=self.caller)
self.caller.db.combat_parry_mode = False
return
if target.db.combat_parry_mode:
# target is defensive; even harder to hit!
target.msg("{GYou defend, trying to avoid the attack.{n")
hit *= 0.5
if random.random() <= hit:
self.caller.msg(string + "{gIt's a hit!{n")
target.msg(tstring + "{rIt's a hit!{n")
self.caller.location.msg_contents(ostring + "It's a hit!", exclude=[target,self.caller])
# call enemy hook
if hasattr(target, "at_hit"):
# should return True if target is defeated, False otherwise.
return target.at_hit(self.obj, self.caller, damage)
elif target.db.health:
target.db.health -= damage
else:
# sorry, impossible to fight this enemy ...
self.caller.msg("The enemy seems unaffacted.")
return False
else:
self.caller.msg(string + "{rYou miss.{n")
target.msg(tstring + "{gThey miss you.{n")
self.caller.location.msg_contents(ostring + "They miss.", exclude=[target, self.caller])
class CmdSetWeapon(CmdSet):
"Holds the attack command."
def at_cmdset_creation(self):
"called at first object creation."
self.add(CmdAttack())
class Weapon(TutorialObject):
"""
This defines a bladed weapon.
Important attributes (set at creation):
hit - chance to hit (0-1)
parry - chance to parry (0-1)
damage - base damage given (modified by hit success and
type of attack) (0-10)
"""
def at_object_creation(self):
"Called at first creation of the object"
super(Weapon, self).at_object_creation()
self.db.hit = 0.4 # hit chance
self.db.parry = 0.8 # parry chance
self.db.damage = 1.0
self.db.magic = False
self.cmdset.add_default(CmdSetWeapon, permanent=True)
def reset(self):
"""
When reset, the weapon is simply deleted, unless it has a place
to return to.
"""
if self.location.has_player and self.home == self.location:
self.location.msg_contents("%s suddenly and magically fades into nothingness, as if it was never there ..." % self.key)
self.delete()
else:
self.location = self.home
#------------------------------------------------------------
#
# Weapon rack - spawns weapons
#
# This is a spawner mechanism that creates custom weapons from a
# spawner prototype dictionary. Note that we only create a single typeclass
# (Weapon) yet customize all these different weapons using the spawner.
# The spawner dictionaries could easily sit in separate modules and be
# used to create unique and interesting variations of typeclassed
# objects.
#
#------------------------------------------------------------
WEAPON_PROTOTYPES = {
"weapon": {
"typeclass": "evennia.contrib.tutorial_world.objects.Weapon",
"key": "Weapon",
"hit": 0.2,
"parry": 0.2,
"damage": 1.0,
"magic": False,
"desc": "A generic blade."},
"knife": {
"prototype": "weapon",
"aliases": "sword",
"key": "Kitchen knife",
"desc":"A rusty kitchen knife. Better than nothing.",
"damage": 3},
"dagger": {
"prototype": "knife",
"key": "Rusty dagger",
"aliases": ["knife", "dagger"],
"desc": "A double-edged dagger with a nicked edge and a wooden handle.",
"hit": 0.25},
"sword": {
"prototype": "weapon",
"key": "Rusty sword",
"aliases": ["sword"],
"desc": "A rusty shortsword. It has a leather-wrapped handle covered i food grease.",
"hit": 0.3,
"damage": 5,
"parry": 0.5},
"club": {
"prototype": "weapon",
"key":"Club",
"desc": "A heavy wooden club, little more than a heavy branch.",
"hit": 0.4,
"damage": 6,
"parry": 0.2},
"axe": {
"prototype": "weapon",
"key":"Axe",
"desc": "A woodcutter's axe with a keen edge.",
"hit": 0.4,
"damage": 6,
"parry": 0.2},
"ornate longsword": {
"prototype":"sword",
"key": "Ornate longsword",
"desc": "A fine longsword with some swirling patterns on the handle.",
"hit": 0.5,
"magic": True,
"damage": 5},
"warhammer": {
"prototype": "club",
"key": "Silver Warhammer",
"aliases": ["hammer", "warhammer", "war"],
"desc": "A heavy war hammer with silver ornaments. This huge weapon causes massive damage - if you can hit.",
"hit": 0.4,
"magic": True,
"damage": 8},
"rune axe": {
"prototype": "axe",
"key": "Runeaxe",
"aliases": ["axe"],
"hit": 0.4,
"magic": True,
"damage": 6},
"thruning": {
"prototype": "ornate longsword",
"key": "Broadsword named Thruning",
"desc": "This heavy bladed weapon is marked with the name 'Thruning'. It is very powerful in skilled hands.",
"hit": 0.6,
"parry": 0.6,
"damage": 7},
"slayer waraxe": {
"prototype": "rune axe",
"key": "Slayer waraxe",
"aliases": ["waraxe", "war", "slayer"],
"desc": "A huge double-bladed axe marked with the runes for 'Slayer'. It has more runic inscriptions on its head, which you cannot decipher.",
"hit": 0.7,
"damage": 8},
"ghostblade": {
"prototype": "ornate longsword",
"key": "The Ghostblade",
"aliases": ["blade", "ghost"],
"desc": "This massive sword is large as you are tall, yet seems to weigh almost nothing. It's almost like it's not really there.",
"hit": 0.9,
"parry": 0.8,
"damage": 10},
"hawkblade": {
"prototype": "ghostblade",
"key": "The Hawblade",
"aliases": ["hawk", "blade"],
"desc": "The weapon of a long-dead heroine and a more civilized age, the hawk-shaped hilt of this blade almost has a life of its own.",
"hit": 0.85,
"parry": 0.7,
"damage": 11}
}
class CmdGetWeapon(Command):
"""
Usage:
get weapon
This will try to obtain a weapon from the container.
"""
key = "get weapon"
aliases = "get weapon"
locks = "cmd:all()"
help_cateogory = "TutorialWorld"
def func(self):
"""
Get a weapon from the container. It will
itself handle all messages.
"""
self.obj.produce_weapon(self.caller)
class CmdSetWeaponRack(CmdSet):
"""
The cmdset for the rack.
"""
key = "weaponrack_cmdset"
def at_cmdset_creation(self):
"Called at first creation of cmdset"
self.add(CmdGetWeapon())
class WeaponRack(TutorialObject):
"""
This object represents a weapon store. When people use the
"get weapon" command on this rack, it will produce one
random weapon from among those registered to exist
on it. This will also set a property on the character
to make sure they can't get more than one at a time.
Attributes to set on this object:
available_weapons: list of prototype-keys from
WEAPON_PROTOTYPES, the weapons available in this rack.
no_more_weapons_msg - error message to return to players
who already got one weapon from the rack and tries to
grab another one.
"""
def at_object_creation(self):
"""
called at creation
"""
self.cmdset.add_default(CmdSetWeaponRack, permanent=True)
self.db.rack_id = "weaponrack_1"
# these are prototype names from the prototype
# dictionary above.
self.db.get_weapon_msg = "You find {c%s{n."
self.db.no_more_weapons_msg = "you find nothing else of use."
self.db.available_weapons = ["knife", "dagger",
"sword", "club"]
def produce_weapon(self, caller):
"""
This will produce a new weapon from the rack,
assuming the caller hasn't already gotten one. When
doing so, the caller will get Tagged with the id
of this rack, to make sure they cannot keep
pulling weapons from it indefinitely.
"""
rack_id = self.db.rack_id
if caller.tags.get(rack_id, category="tutorial_world"):
caller.msg(self.db.no_more_weapons_msg)
else:
prototype = random.choice(self.db.available_weapons)
# use the spawner to create a new Weapon from the
# spawner dictionary, tag the caller
wpn = spawn(WEAPON_PROTOTYPES[prototype], prototype_parents=WEAPON_PROTOTYPES)[0]
caller.tags.add(rack_id, category="tutorial_world")
wpn.location = caller
caller.msg(self.db.get_weapon_msg % wpn.key)<|fim▁end|> | current root positions.
"""
if self.db.button_exposed:
# we found the button by moving the roots |
<|file_name|>main.go<|end_file_name|><|fim▁begin|><|fim▁hole|>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by cloud.google.com/go/internal/gapicgen/gensnippets. DO NOT EDIT.
// [START compute_v1_generated_NetworkEndpointGroups_DetachNetworkEndpoints_sync]
package main
import (
"context"
compute "cloud.google.com/go/compute/apiv1"
computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)
func main() {
ctx := context.Background()
c, err := compute.NewNetworkEndpointGroupsRESTClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &computepb.DetachNetworkEndpointsNetworkEndpointGroupRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/compute/v1#DetachNetworkEndpointsNetworkEndpointGroupRequest.
}
op, err := c.DetachNetworkEndpoints(ctx, req)
if err != nil {
// TODO: Handle error.
}
err = op.Wait(ctx)
if err != nil {
// TODO: Handle error.
}
}
// [END compute_v1_generated_NetworkEndpointGroups_DetachNetworkEndpoints_sync]<|fim▁end|> | |
<|file_name|>solutions.py<|end_file_name|><|fim▁begin|>__problem_title__ = "Number Rotations"
__problem_url___ = "https://projecteuler.net/problem=168"
__problem_description__ = "Consider the number 142857. We can right-rotate this number by moving " \
"the last digit (7) to the front of it, giving us 714285. It can be " \
"verified that 714285=5×142857. This demonstrates an unusual property " \
"of 142857: it is a divisor of its right-rotation. Find the last 5 " \
"digits of the sum of all integers , 10 < < 10 , that have this " \
"property."
import timeit
class Solution():
@staticmethod
def solution1():
pass
@staticmethod
def time_solutions():
setup = 'from __main__ import Solution'
print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1))
if __name__ == '__main__':<|fim▁hole|> s = Solution()
print(s.solution1())
s.time_solutions()<|fim▁end|> | |
<|file_name|>autoxml.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2005, TUBITAK/UEKAE
#
# 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.
#
# Please read the COPYING file.
#
#
# Authors: Eray Ozkural <[email protected]>
# Gurer Ozen <[email protected]>
# Bahadir Kandemir <[email protected]>
# Baris Metin <[email protected]>
"""
autoxml is a metaclass for automatic XML translation, using
a miniature type system. (w00t!) This is based on an excellent
high-level XML processing prototype that Gurer prepared.
Method names are mixedCase for compatibility with minidom,
an old library.
"""
# System
import locale
import codecs
import types
import formatter
import sys
from StringIO import StringIO
import gettext
__trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext
# PiSi
import pisi
from pisi.exml.xmlext import *
from pisi.exml.xmlfile import XmlFile
import pisi.context as ctx
import pisi.util as util
import pisi.oo as oo
class Error(pisi.Error):
pass
# requirement specs
mandatory, optional = range(2) # poor man's enum
# basic types
String = types.StringType
Text = types.UnicodeType
Integer = types.IntType
Long = types.LongType
Float = types.FloatType
#class datatype(type):
# def __init__(cls, name, bases, dict):
# """entry point for metaclass code"""
# # standard initialization
# super(autoxml, cls).__init__(name, bases, dict)
class LocalText(dict):
"""Handles XML tags with localized text"""
def __init__(self, tag = "", req = optional):
self.tag = tag
self.req = req
dict.__init__(self)
def decode(self, node, errs, where = ""):
# flags, tag name, instance attribute
assert self.tag != ''
nodes = getAllNodes(node, self.tag)
if not nodes:
if self.req == mandatory:
errs.append(where + ': ' + _("At least one '%s' tag should have local text") %
self.tag )
else:
for node in nodes:
lang = getNodeAttribute(node, 'xml:lang')
c = getNodeText(node)
if not c:
errs.append(where + ': ' + _("'%s' language of tag '%s' is empty") %
(lang, self.tag))
# FIXME: check for dups and 'en'
if not lang:
lang = 'en'
self[lang] = c
def encode(self, node, errs):
assert self.tag != ''
for key in self.iterkeys():
newnode = addNode(node, self.tag)
setNodeAttribute(newnode, 'xml:lang', key)
addText(newnode, '', self[key].encode('utf8'))
#FIXME: maybe more appropriate for pisi.util
@staticmethod
def get_lang():
try:
(lang, encoding) = locale.getlocale()
if not lang:
(lang, encoding) = locale.getdefaultlocale()
if lang==None: # stupid python means it is C locale
return 'en'
else:
return lang[0:2]
except:
raise Error(_('LocalText: unable to get either current or default locale'))
def errors(self, where = unicode()):
errs = []
langs = [ LocalText.get_lang(), 'en', 'tr', ]
if not util.any(lambda x : self.has_key(x), langs):
errs.append( where + ': ' + _("Tag should have at least the current locale, or failing that an English or Turkish version"))
#FIXME: check if all entries are unicode
return errs
def format(self, f, errs):
L = LocalText.get_lang()
if self.has_key(L):
f.add_flowing_data(self[L])
elif self.has_key('en'):
# fallback to English, blah
f.add_flowing_data(self['en'])
elif self.has_key('tr'):
# fallback to Turkish
f.add_flowing_data(self['tr'])
else:
errs.append(_("Tag should have at least the current locale, or failing that an English or Turkish version"))
#FIXME: factor out these common routines
def print_text(self, file = sys.stdout):
w = Writer(file) # plain text
f = formatter.AbstractFormatter(w)
errs = []
self.format(f, errs)
if errs:
for x in errs:
ctx.ui.warning(x)
def __str__(self):
L = LocalText.get_lang()
if self.has_key(L):
return self[L]
elif self.has_key('en'):
# fallback to English, blah
return self['en']
elif self.has_key('tr'):
# fallback to Turkish
return self['tr']
else:
return ""
class Writer(formatter.DumbWriter):
"""adds unicode support"""
def __init__(self, file=None, maxcol=78):
formatter.DumbWriter.__init__(self, file, maxcol)
def send_literal_data(self, data):
self.file.write(data.encode("utf-8"))
i = data.rfind('\n')
if i >= 0:
self.col = 0
data = data[i+1:]
data = data.expandtabs()
self.col = self.col + len(data)
self.atbreak = 0
class autoxml(oo.autosuper, oo.autoprop):
"""High-level automatic XML transformation interface for xmlfile.
The idea is to declare a class for each XML tag. Inside the
class the tags and attributes nested in the tag are further
elaborated. A simple example follows:
class Employee:
__metaclass__ = autoxml
t_Name = [xmlfile.Text, xmlfile.mandatory]
a_Type = [xmlfile.Integer, xmlfile.optional]
This class defines a tag and an attribute nested in Employee
class. Name is a string and type is an integer, called basic
types.
While the tag is mandatory, the attribute may be left out.
Other basic types supported are: xmlfile.Float, xmlfile.Double
and (not implemented yet): xmlfile.Binary
By default, the class name is taken as the corresponding tag,
which may be overridden by defining a tag attribute. Thus,
the same tag may also be written as:
class EmployeeXML:
...
tag = 'Employee'
...
In addition to basic types, we allow for two kinds of complex
types: class types and list types.
A declared class can be nested in another class as follows
class Position:
__metaclass__ = autoxml
t_Name = [xmlfile.Text, xmlfile.mandatory]
t_Description = [xmlfile.Text, xmlfile.optional]
which we can add to our Employee class.
class Employee:
__metaclass__ = autoxml
t_Name = [xmlfile.Text, xmlfile.mandatory]
a_Type = [xmlfile.Integer, xmlfile.optional]
t_Position = [Position, xmlfile.mandatory]
Note some unfortunate redundancy here with Position; this is
justified by the implementation (kidding). Still, you might
want to assign a different name than the class name that
goes in there, which may be fully qualified.
There is more! Suppose we want to define a company, with
of course many employees.
class Company:
__metaclass__ = autoxml
t_Employees = [ [Employee], xmlfile.mandatory, 'Employees/Employee']
Logically, inside the Company/Employees tag, we will have several
Employee tags, which are inserted to the Employees instance variable of
Company in order of appearance. We can define lists of any other valid
type. Here we used a list of an autoxml class defined above.
The mandatory flag here asserts that at least one such record
is to be found.
You see, it works like magic, when it works of course. All of it
done without a single brain exploding.
"""
def __init__(cls, name, bases, dict):
"""entry point for metaclass code"""
#print 'generating class', name
# standard initialization
super(autoxml, cls).__init__(name, bases, dict)
xmlfile_support = XmlFile in bases
cls.autoxml_bases = filter(lambda base: isinstance(base, autoxml), bases)
#TODO: initialize class attribute __xml_tags
#setattr(cls, 'xml_variables', [])
# default class tag is class name
if not dict.has_key('tag'):
cls.tag = name
# generate helper routines, for each XML component
names = []
inits = []
decoders = []
encoders = []
errorss = []
formatters = []
# read declaration order from source
# code contributed by bahadir kandemir
from inspect import getsourcelines
from itertools import ifilter
import re
fn = re.compile('\s*([tas]_[a-zA-Z]+).*').findall
lines = filter(fn, getsourcelines(cls)[0])
decl_order = map(lambda x:x.split()[0], lines)
# there should be at most one str member, and it should be
# the first to process
order = filter(lambda x: not x.startswith('s_'), decl_order)
# find string member
str_members = filter(lambda x:x.startswith('s_'), decl_order)
if len(str_members)>1:
raise Error('Only one str member can be defined')
elif len(str_members)==1:
order.insert(0, str_members[0])
for var in order:
if var.startswith('t_') or var.startswith('a_') or var.startswith('s_'):
name = var[2:]
if var.startswith('a_'):
x = autoxml.gen_attr_member(cls, name)
elif var.startswith('t_'):
x = autoxml.gen_tag_member(cls, name)
elif var.startswith('s_'):
x = autoxml.gen_str_member(cls, name)
(name, init, decoder, encoder, errors, format_x) = x
names.append(name)
inits.append(init)
decoders.append(decoder)
encoders.append(encoder)
errorss.append(errors)
formatters.append(format_x)
# generate top-level helper functions
cls.initializers = inits
def initialize(self, uri = None, keepDoc = False, tmpDir = '/tmp',
**args):
if xmlfile_support:
if args.has_key('tag'):
XmlFile.__init__(self, tag = args['tag'])
else:
XmlFile.__init__(self, tag = cls.tag)
for base in cls.autoxml_bases:
base.__init__(self)
#super(cls, self).__init__(tag = tag) cooperative shit disabled for now
for init in inits:#self.__class__.initializers:
init(self)
for x in args.iterkeys():
setattr(self, x, args[x])
# init hook
if hasattr(self, 'init'):
self.init(tag)
if xmlfile_support and uri:
self.read(uri, keepDoc, tmpDir)
cls.__init__ = initialize
cls.decoders = decoders
def decode(self, node, errs, where = unicode(cls.tag)):
for base in cls.autoxml_bases:
base.decode(self, node, errs, where)
for decode_member in decoders:#self.__class__.decoders:
decode_member(self, node, errs, where)
if hasattr(self, 'decode_hook'):
self.decode_hook(node, errs, where)
cls.decode = decode
cls.encoders = encoders
def encode(self, node, errs):
for base in cls.autoxml_bases:
base.encode(self, node, errs)
for encode_member in encoders:#self.__class__.encoders:
encode_member(self, node, errs)
if hasattr(self, 'encode_hook'):
self.encode_hook(node, errs)
cls.encode = encode
cls.errorss = errorss
def errors(self, where = unicode(name)):
errs = []
for base in cls.autoxml_bases:
errs.extend(base.errors(self, where))
for errors in errorss:#self.__class__.errorss:
errs.extend(errors(self, where))
if hasattr(self, 'errors_hook'):
errs.extend(self.errors_hook(where))
return errs
cls.errors = errors
def check(self):
errs = self.errors()
if errs:
errs.append(_("autoxml.check: '%s' errors") % len(errs))
raise Error(*errs)
cls.check = check
cls.formatters = formatters
def format(self, f, errs):
for base in cls.autoxml_bases:
base.format(self, f, errs)
for formatter in formatters:#self.__class__.formatters:
formatter(self, f, errs)
cls.format = format
def print_text(self, file = sys.stdout):
w = Writer(file) # plain text
f = formatter.AbstractFormatter(w)
errs = []
self.format(f, errs)
if errs:
for x in errs:
ctx.ui.warning(x)
cls.print_text = print_text
if not dict.has_key('__str__'):
def str(self):
strfile = StringIO(u'')
self.print_text(strfile)
print 'strfile=',unicode(strfile)
s = strfile.getvalue()
strfile.close()
print 's=',s,type(s)
return s
cls.__str__ = str
if not dict.has_key('__eq__'):
def equal(self, other):
# handle None
if other ==None:
return False # well, must be False at this point :)
for name in names:
try:
if getattr(self, name) != getattr(other, name):
return False
except:
return False
return True
def notequal(self, other):
return not self.__eq__(other)
cls.__eq__ = equal
cls.__ne__ = notequal
if xmlfile_support:
def read(self, uri, keepDoc = False, tmpDir = '/tmp',
sha1sum = False, compress = None, sign = None, copylocal = False):
"read XML file and decode it into a python object"
self.readxml(uri, tmpDir, sha1sum=sha1sum,
compress=compress, sign=sign, copylocal=copylocal)
errs = []
self.decode(self.rootNode(), errs)
if errs:
errs.append(_("autoxml.read: File '%s' has errors") % uri)
raise Error(*errs)
if hasattr(self, 'read_hook'):
self.read_hook(errs)
if not keepDoc:
self.unlink() # get rid of the tree
errs = self.errors()
if errs:<|fim▁hole|> sha1sum = False, compress = None, sign = None):
"encode the contents of the python object into an XML file"
errs = self.errors()
if errs:
errs.append(_("autoxml.write: object validation has failed"))
raise Error(*errs)
errs = []
self.newDocument()
self.encode(self.rootNode(), errs)
if hasattr(self, 'write_hook'):
self.write_hook(errs)
if errs:
errs.append(_("autoxml.write: File encoding '%s' has errors") % uri)
raise Error(*errs)
self.writexml(uri, tmpDir, sha1sum=sha1sum, compress=compress, sign=sign)
if not keepDoc:
self.unlink() # get rid of the tree
cls.read = read
cls.write = write
def gen_attr_member(cls, attr):
"""generate readers and writers for an attribute member"""
#print 'attr:', attr
spec = getattr(cls, 'a_' + attr)
tag_type = spec[0]
assert type(tag_type) == type(type)
def readtext(node, attr):
return getNodeAttribute(node, attr)
def writetext(node, attr, text):
#print 'write attr', attr, text
setNodeAttribute(node, attr, text)
anonfuns = cls.gen_anon_basic(attr, spec, readtext, writetext)
return cls.gen_named_comp(attr, spec, anonfuns)
def gen_tag_member(cls, tag):
"""generate helper funs for tag member of class"""
#print 'tag:', tag
spec = getattr(cls, 't_' + tag)
anonfuns = cls.gen_tag(tag, spec)
return cls.gen_named_comp(tag, spec, anonfuns)
def gen_tag(cls, tag, spec):
"""generate readers and writers for the tag"""
tag_type = spec[0]
if type(tag_type) is types.TypeType and \
autoxml.basic_cons_map.has_key(tag_type):
def readtext(node, tagpath):
#print 'read tag', node, tagpath
return getNodeText(node, tagpath)
def writetext(node, tagpath, text):
#print 'write tag', node, tagpath, text
addText(node, tagpath, text.encode('utf8'))
return cls.gen_anon_basic(tag, spec, readtext, writetext)
elif type(tag_type) is types.ListType:
return cls.gen_list_tag(tag, spec)
elif tag_type is LocalText:
return cls.gen_insetclass_tag(tag, spec)
elif type(tag_type) is autoxml or type(tag_type) is types.TypeType:
return cls.gen_class_tag(tag, spec)
else:
raise Error(_('gen_tag: unrecognized tag type %s in spec') %
str(tag_type))
def gen_str_member(cls, token):
"""generate readers and writers for a string member"""
spec = getattr(cls, 's_' + token)
tag_type = spec[0]
assert type(tag_type) == type(type)
def readtext(node, blah):
#node.normalize() # piksemel doesn't have this
return getNodeText(node)
def writetext(node, blah, text):
#print 'writing', text, type(text)
addText(node, "", text.encode('utf-8'))
anonfuns = cls.gen_anon_basic(token, spec, readtext, writetext)
return cls.gen_named_comp(token, spec, anonfuns)
def gen_named_comp(cls, token, spec, anonfuns):
"""generate a named component tag/attr. a decoration of
anonymous functions that do not bind to variable names"""
name = cls.mixed_case(token)
token_type = spec[0]
req = spec[1]
(init_a, decode_a, encode_a, errors_a, format_a) = anonfuns
def init(self):
"""initialize component"""
setattr(self, name, init_a())
def decode(self, node, errs, where):
"""decode component from DOM node"""
#print '*', name
setattr(self, name, decode_a(node, errs, where + '.' + unicode(name)))
def encode(self, node, errs):
"""encode self inside, possibly new, DOM node using xml"""
if hasattr(self, name):
value = getattr(self, name)
else:
value = None
encode_a(node, value, errs)
def errors(self, where):
"""return errors in the object"""
errs = []
if hasattr(self, name) and getattr(self, name) != None:
value = getattr(self,name)
errs.extend(errors_a(value, where + '.' + name))
else:
if req == mandatory:
errs.append(where + ': ' + _('Mandatory variable %s not available') % name)
return errs
def format(self, f, errs):
if hasattr(self, name):
value = getattr(self,name)
f.add_literal_data(token + ': ')
format_a(value, f, errs)
f.add_line_break()
else:
if req == mandatory:
errs.append(_('Mandatory variable %s not available') % name)
return (name, init, decode, encode, errors, format)
def mixed_case(cls, identifier):
"""helper function to turn token name into mixed case"""
if identifier is "":
return ""
else:
if identifier[0]=='I':
lowly = 'i' # because of pythonic idiots we can't choose locale in lower
else:
lowly = identifier[0].lower()
return lowly + identifier[1:]
def tagpath_head_last(cls, tagpath):
"returns split of the tag path into last tag and the rest"
try:
lastsep = tagpath.rindex('/')
except ValueError, e:
return ('', tagpath)
return (tagpath[:lastsep], tagpath[lastsep+1:])
def parse_spec(cls, token, spec):
"""decompose member specification"""
name = cls.mixed_case(token)
token_type = spec[0]
req = spec[1]
if len(spec)>=3:
path = spec[2] # an alternative path specified
elif type(token_type) is type([]):
if type(token_type[0]) is autoxml:
# if list of class, by default nested like in most PSPEC
path = token + '/' + token_type[0].tag
else:
# if list of ordinary type, just take the name for
path = token
elif type(token_type) is autoxml:
# if a class, by default its tag
path = token_type.tag
else:
path = token # otherwise it's the same name as
# the token
return name, token_type, req, path
def gen_anon_basic(cls, token, spec, readtext, writetext):
"""Generate a tag or attribute with one of the basic
types like integer. This has got to be pretty generic
so that we can invoke it from the complex types such as Class
and List. The readtext and writetext arguments achieve
the DOM text access for this datatype."""
name, token_type, req, tagpath = cls.parse_spec(token, spec)
def initialize():
"""default value for all basic types is None"""
return None
def decode(node, errs, where):
"""decode from DOM node, the value, watching the spec"""
#text = unicode(readtext(node, token), 'utf8') # CRUFT FIXME
text = readtext(node, token)
#print 'decoding', token_type, text, type(text), '.'
if text:
try:
#print token_type, autoxml.basic_cons_map[token_type]
value = autoxml.basic_cons_map[token_type](text)
except Exception, e:
print 'exception', e
value = None
errs.append(where + ': ' + _('Type mismatch: read text cannot be decoded'))
return value
else:
if req == mandatory:
errs.append(where + ': ' + _('Mandatory token %s not available') % token)
return None
def encode(node, value, errs):
"""encode given value inside DOM node"""
if value:
writetext(node, token, unicode(value))
else:
if req == mandatory:
errs.append(_('Mandatory token %s not available') % token)
def errors(value, where):
errs = []
if value and not isinstance(value, token_type):
errs.append(where + ': ' + _('Type mismatch. Expected %s, got %s') %
(token_type, type(value)) )
return errs
def format(value, f, errs):
"""format value for pretty printing"""
f.add_literal_data(unicode(value))
return initialize, decode, encode, errors, format
def gen_class_tag(cls, tag, spec):
"""generate a class datatype"""
name, tag_type, req, path = cls.parse_spec(tag, spec)
def make_object():
obj = tag_type.__new__(tag_type)
obj.__init__(tag=tag, req=req)
return obj
def init():
return make_object()
def decode(node, errs, where):
node = getNode(node, tag)
if node:
try:
obj = make_object()
obj.decode(node, errs, where)
return obj
except Error:
errs.append(where + ': '+ _('Type mismatch: DOM cannot be decoded'))
else:
if req == mandatory:
errs.append(where + ': ' + _('Mandatory argument not available'))
return None
def encode(node, obj, errs):
if node and obj:
try:
#FIXME: this doesn't look pretty
classnode = newNode(node, tag)
obj.encode(classnode, errs)
addNode(node, '', classnode)
except Error:
if req == mandatory:
# note: we can receive an error if obj has no content
errs.append(_('Object cannot be encoded'))
else:
if req == mandatory:
errs.append(_('Mandatory argument not available'))
def errors(obj, where):
return obj.errors(where)
def format(obj, f, errs):
try:
obj.format(f, errs)
except Error:
if req == mandatory:
errs.append(_('Mandatory argument not available'))
return (init, decode, encode, errors, format)
def gen_list_tag(cls, tag, spec):
"""generate a list datatype. stores comps in tag/comp_tag"""
name, tag_type, req, path = cls.parse_spec(tag, spec)
pathcomps = path.split('/')
comp_tag = pathcomps.pop()
list_tagpath = util.makepath(pathcomps, sep='/', relative=True)
if len(tag_type) != 1:
raise Error(_('List type must contain only one element'))
x = cls.gen_tag(comp_tag, [tag_type[0], mandatory])
(init_item, decode_item, encode_item, errors_item, format_item) = x
def init():
return []
def decode(node, errs, where):
l = []
nodes = getAllNodes(node, path)
#print node, tag + '/' + comp_tag, nodes
if len(nodes)==0 and req==mandatory:
errs.append(where + ': ' + _('Mandatory list empty'))
ix = 1
for node in nodes:
dummy = newNode(node, "Dummy")
addNode(dummy, '', node)
l.append(decode_item(dummy, errs, where + unicode("[%s]" % ix, 'utf8')))
#l.append(decode_item(node, errs, where + unicode("[%s]" % ix)))
ix += 1
return l
def encode(node, l, errs):
if l and len(l) > 0:
for item in l:
if list_tagpath:
listnode = addNode(node, list_tagpath, branch = False)
else:
listnode = node
encode_item(listnode, item, errs)
#encode_item(node, item, errs)
else:
if req is mandatory:
errs.append(_('Mandatory list empty'))
def errors(l, where):
errs = []
ix = 1
for node in l:
errs.extend(errors_item(node, where + '[%s]' % ix))
ix += 1
return errs
def format(l, f, errs):
# TODO: indent here
ix = 1
length = len(l)
for node in l:
f.add_flowing_data(str(ix) + ': ')
format_item(node, f, errs)
if ix != length:
f.add_flowing_data(', ')
ix += 1
return (init, decode, encode, errors, format)
def gen_insetclass_tag(cls, tag, spec):
"""generate a class datatype that is highly integrated
don't worry if that means nothing to you. this is a silly
hack to implement local text quickly. it's not the most
elegant thing in the world. it's basically a copy of
class tag"""
name, tag_type, req, path = cls.parse_spec(tag, spec)
def make_object():
obj = tag_type.__new__(tag_type)
obj.__init__(tag=tag, req=req)
return obj
def init():
return make_object()
def decode(node, errs, where):
if node:
try:
obj = make_object()
obj.decode(node, errs, where)
return obj
except Error:
errs.append(where + ': ' + _('Type mismatch: DOM cannot be decoded'))
else:
if req == mandatory:
errs.append(where + ': ' + _('Mandatory argument not available'))
return None
def encode(node, obj, errs):
if node and obj:
try:
#FIXME: this doesn't look pretty
obj.encode(node, errs)
except Error:
if req == mandatory:
# note: we can receive an error if obj has no content
errs.append(_('Object cannot be encoded'))
else:
if req == mandatory:
errs.append(_('Mandatory argument not available'))
def errors(obj, where):
return obj.errors(where)
def format(obj, f, errs):
try:
obj.format(f, errs)
except Error:
if req == mandatory:
errs.append(_('Mandatory argument not available'))
return (init, decode, encode, errors, format)
basic_cons_map = {
types.StringType : str,
#TODO: python 3.x: same behavior?
#python 2.x: basic_cons_map[unicode](a) where a is unicode str yields
#TypeError: decoding Unicode is not supported
#types.UnicodeType : lambda x: unicode(x,'utf8'), lambda x:x?
types.UnicodeType : lambda x:x, #: unicode
types.IntType : int,
types.FloatType : float,
types.LongType : long
}<|fim▁end|> | errs.append(_("autoxml.read: File '%s' has errors") % uri)
raise Error(*errs)
def write(self, uri, keepDoc = False, tmpDir = '/tmp', |
<|file_name|>classDeclarationBlockScoping1.js<|end_file_name|><|fim▁begin|>//// [classDeclarationBlockScoping1.ts]
class C {
}
{
class C {
}
}
//// [classDeclarationBlockScoping1.js]
var C = (function () {
<|fim▁hole|>}());
{
var C_1 = (function () {
function C_1() {
}
return C_1;
}());
}<|fim▁end|> | function C() {
}
return C;
|
<|file_name|>pairwise.rs<|end_file_name|><|fim▁begin|>#[macro_use]
mod utils;
inject_indy_dependencies!();
extern crate indyrs as indy;
extern crate indyrs as api;
use crate::utils::{did, pairwise};
use crate::utils::constants::*;
use crate::utils::Setup;
use self::indy::ErrorCode;
mod high_cases {
use super::*;
mod create_pairwise {
use super::*;
#[test]
fn indy_create_pairwise_works() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, Some(METADATA)).unwrap();
}
#[test]
fn indy_create_pairwise_works_for_not_found_my_did() {
let setup = Setup::wallet();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
let res = pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, DID, None);
assert_code!(ErrorCode::WalletItemNotFound,res);
}
#[test]
fn indy_create_pairwise_works_for_not_found_their_did() {
let setup = Setup::did();
let res = pairwise::create_pairwise(setup.wallet_handle, DID, &setup.did, None);
assert_code!(ErrorCode::WalletItemNotFound, res);
}
#[test]
fn indy_create_pairwise_works_for_fully_qualified() {
let setup = Setup::did_fully_qualified();
did::store_their_did_from_parts(setup.wallet_handle, DID_MY1_V1, VERKEY_MY1).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_MY1_V1, &setup.did, Some(METADATA)).unwrap();
did::store_their_did_from_parts(setup.wallet_handle, DID, VERKEY).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID, &setup.did, Some(METADATA)).unwrap();
}
}
mod list_pairwise {
use super::*;
#[test]
fn indy_list_pairwise_works() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, None).unwrap();
let list_pairwise_json = pairwise::list_pairwise(setup.wallet_handle).unwrap();
let list_pairwise: Vec<String> = serde_json::from_str(&list_pairwise_json).unwrap();
assert_eq!(list_pairwise.len(), 1);
assert!(list_pairwise.contains(&format!(r#"{{"my_did":"{}","their_did":"{}"}}"#, setup.did, DID_TRUSTEE)));
}
#[test]
fn indy_list_pairwise_works_for_empty_result() {
let setup = Setup::wallet();
let list_pairwise_json = pairwise::list_pairwise(setup.wallet_handle).unwrap();
let list_pairwise: Vec<String> = serde_json::from_str(&list_pairwise_json).unwrap();
assert_eq!(list_pairwise.len(), 0);
}
}
mod pairwise_exists {
use super::*;
#[test]
fn indy_is_pairwise_exists_works() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, None).unwrap();
assert!(pairwise::pairwise_exists(setup.wallet_handle, DID_TRUSTEE).unwrap());
}
#[test]
fn indy_is_pairwise_exists_works_for_not_created() {
let setup = Setup::wallet();
assert!(!pairwise::pairwise_exists(setup.wallet_handle, DID_TRUSTEE).unwrap());
}
}
mod get_pairwise {
use super::*;
#[test]
fn indy_get_pairwise_works() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, Some(METADATA)).unwrap();
let pairwise_info_json = pairwise::get_pairwise(setup.wallet_handle, DID_TRUSTEE).unwrap();
assert_eq!(format!(r#"{{"my_did":"{}","metadata":"{}"}}"#, setup.did, METADATA), pairwise_info_json);
}
#[test]
fn indy_get_pairwise_works_for_not_created_pairwise() {
let setup = Setup::wallet();
let res = pairwise::get_pairwise(setup.wallet_handle, DID_TRUSTEE);
assert_code!(ErrorCode::WalletItemNotFound, res);
}
}
mod set_pairwise_metadata {
use super::*;
#[test]
fn indy_set_pairwise_metadata_works() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, None).unwrap();
let pairwise_info_without_metadata = pairwise::get_pairwise(setup.wallet_handle, DID_TRUSTEE).unwrap();
assert_eq!(format!(r#"{{"my_did":"{}"}}"#, setup.did), pairwise_info_without_metadata);
pairwise::set_pairwise_metadata(setup.wallet_handle, DID_TRUSTEE, Some(METADATA)).unwrap();
let pairwise_info_with_metadata = pairwise::get_pairwise(setup.wallet_handle, DID_TRUSTEE).unwrap();
assert_ne!(pairwise_info_without_metadata, pairwise_info_with_metadata);
assert_eq!(format!(r#"{{"my_did":"{}","metadata":"{}"}}"#, setup.did, METADATA), pairwise_info_with_metadata);
}
#[test]
fn indy_set_pairwise_metadata_works_for_not_created_pairwise() {
let setup = Setup::wallet();
let res = pairwise::set_pairwise_metadata(setup.wallet_handle, DID_TRUSTEE, Some(METADATA));
assert_code!(ErrorCode::WalletItemNotFound, res);
}
}
}
#[cfg(not(feature = "only_high_cases"))]
mod medium_cases {
use super::*;
use crate::api::INVALID_WALLET_HANDLE;
mod create_pairwise {
use super::*;
#[test]
fn indy_create_pairwise_works_for_empty_metadata() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, None).unwrap();
}
#[test]
fn indy_create_pairwise_works_for_invalid_wallet_handle() {
Setup::empty();
let res = pairwise::create_pairwise(INVALID_WALLET_HANDLE, DID_TRUSTEE, DID, None);
assert_code!(ErrorCode::WalletInvalidHandle, res);
}
#[test]
fn indy_create_pairwise_works_for_twice() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, Some(METADATA)).unwrap();
let res = pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, None);
assert_code!(ErrorCode::WalletItemAlreadyExists, res);
}
}
mod list_pairwise {
use super::*;
#[test]
fn indy_list_pairwise_works_for_invalid_handle() {
Setup::empty();
let res = pairwise::list_pairwise(INVALID_WALLET_HANDLE);
assert_code!(ErrorCode::WalletInvalidHandle, res);
}
}
mod pairwise_exists {
use super::*;
#[test]
fn indy_is_pairwise_exists_works_for_invalid_handle() {
Setup::empty();
let res = pairwise::pairwise_exists(INVALID_WALLET_HANDLE, DID_TRUSTEE);
assert_code!(ErrorCode::WalletInvalidHandle, res);
}
}
mod get_pairwise {
use super::*;
#[test]
fn indy_get_pairwise_works_for_invalid_handle() {
Setup::empty();
let res = pairwise::get_pairwise(INVALID_WALLET_HANDLE, DID_TRUSTEE);
assert_code!(ErrorCode::WalletInvalidHandle, res);
}
}
mod set_pairwise_metadata {
use super::*;
#[test]
fn indy_set_pairwise_metadata_works_for_reset() {
let setup = Setup::did();
did::store_their_did_from_parts(setup.wallet_handle, DID_TRUSTEE, VERKEY_TRUSTEE).unwrap();
pairwise::create_pairwise(setup.wallet_handle, DID_TRUSTEE, &setup.did, Some(METADATA)).unwrap();
let pairwise_info_with_metadata = pairwise::get_pairwise(setup.wallet_handle, DID_TRUSTEE).unwrap();
assert_eq!(format!(r#"{{"my_did":"{}","metadata":"{}"}}"#, setup.did, METADATA), pairwise_info_with_metadata);
pairwise::set_pairwise_metadata(setup.wallet_handle, DID_TRUSTEE, None).unwrap();
let pairwise_info_without_metadata = pairwise::get_pairwise(setup.wallet_handle, DID_TRUSTEE).unwrap();
assert_ne!(pairwise_info_with_metadata, pairwise_info_without_metadata);
assert_eq!(format!(r#"{{"my_did":"{}"}}"#, setup.did), pairwise_info_without_metadata);
}<|fim▁hole|>
let res = pairwise::set_pairwise_metadata(INVALID_WALLET_HANDLE, DID_TRUSTEE, Some(METADATA));
assert_code!(ErrorCode::WalletInvalidHandle, res);
}
}
}<|fim▁end|> |
#[test]
fn indy_set_pairwise_metadata_works_for_invalid_wallet_handle() {
Setup::empty(); |
<|file_name|>S15.1.2.1_A1.2_T1.js<|end_file_name|><|fim▁begin|>// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
If the eval function is called with some argument, then use a first
argument
es5id: 15.1.2.1_A1.2_T1
description: eval("x = 1", "x = 2"), x equal 1, not 2<|fim▁hole|>//CHECK#1
var x;
eval("x = 1", "x = 2");
if (x !== 1) {
$ERROR('#1: eval("x = 1", "x = 2"); x === 1. Actual: ' + (x));
}<|fim▁end|> | ---*/
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2015 Alex Maslakov, <http://www.gildedhonour.com>, <http://www.alexmaslakov.com>
*
* 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.
*
* For questions and comments about this product, please see the project page at:
*
* https://github.com/GildedHonour/frank_jwt
*
*/
extern crate rustc_serialize;
extern crate time;
extern crate crypto;
use time::Duration;
use rustc_serialize::base64;
use rustc_serialize::base64::{ToBase64, FromBase64};
use rustc_serialize::json;
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
use crypto::sha2::{Sha256, Sha384, Sha512};
use crypto::hmac::Hmac;
use crypto::digest::Digest;
use crypto::mac::Mac;
use std::str;
use std::fmt;
use std::fmt::Formatter;
use std::fmt::Debug;
pub type Payload = BTreeMap<String, String>; //todo replace with &str
pub struct Header {
algorithm: Algorithm,
ttype: String
}
impl Header {
pub fn new(alg: Algorithm) -> Header {
Header { algorithm: alg, ttype: Header::std_type() }
}
pub fn std_type() -> String {
"JWT".to_string()
}
}
#[derive(Clone, Copy)]
pub enum Algorithm {
HS256,
HS384,
HS512,
RS256
}
impl ToString for Algorithm {
fn to_string(&self) -> String {
match *self {
Algorithm::HS256 => "HS256".to_string(),
Algorithm::HS384 => "HS384".to_string(),
Algorithm::HS512 => "HS512".to_string(),
Algorithm::RS256 => "RS256".to_string()
}
}
}
pub enum Error {
SignatureExpired,
SignatureInvalid,
JWTInvalid,
IssuerInvalid,
ExpirationInvalid,
AudienceInvalid
}
impl ToJson for Header {
fn to_json(&self) -> json::Json {
let mut map = BTreeMap::new();
map.insert("typ".to_string(), self.ttype.to_json());
map.insert("alg".to_string(), self.algorithm.to_string().to_json());
Json::Object(map)
}
}
pub fn encode(header: Header, secret: String, payload: Payload) -> String {
let signing_input = get_signing_input(payload, &header.algorithm);
let signature = sign_hmac(&signing_input, secret, header.algorithm);
format!("{}.{}", signing_input, signature)
}
pub fn decode(encoded_token: String, secret: String, algorithm: Algorithm) -> Result<(Header, Payload), Error> {
match decode_segments(encoded_token) {
Some((header, payload, signature, signing_input)) => {
if !verify_signature(algorithm, signing_input, &signature, secret.to_string()) {
return Err(Error::SignatureInvalid)
}
//todo
// verify_issuer(payload_json);
// verify_expiration(payload_json);
// verify_audience();
// verify_subject();
// verify_notbefore();
// verify_issuedat();
// verify_jwtid();
//todo
Ok((header, payload))
},
None => Err(Error::JWTInvalid)
}
}
fn segments_count() -> usize {<|fim▁hole|>
fn get_signing_input(payload: Payload, algorithm: &Algorithm) -> String {
let header = Header::new(*algorithm);
let header_json_str = header.to_json();
let encoded_header = base64_url_encode(header_json_str.to_string().as_bytes()).to_string();
let p = payload.into_iter().map(|(k, v)| (k, v.to_json())).collect();
let payload_json = Json::Object(p);
let encoded_payload = base64_url_encode(payload_json.to_string().as_bytes()).to_string();
format!("{}.{}", encoded_header, encoded_payload)
}
fn sign_hmac(signing_input: &str, secret: String, algorithm: Algorithm) -> String {
let mut hmac = match algorithm {
Algorithm::HS256 => create_hmac(Sha256::new(), secret),
Algorithm::HS384 => create_hmac(Sha384::new(), secret),
Algorithm::HS512 => create_hmac(Sha512::new(), secret),
Algorithm::RS256 => unimplemented!()
};
hmac.input(signing_input.as_bytes());
base64_url_encode(hmac.result().code())
}
fn base64_url_encode(bytes: &[u8]) -> String {
bytes.to_base64(base64::URL_SAFE)
}
fn json_to_tree(input: Json) -> BTreeMap<String, String> {
match input {
Json::Object(json_tree) => json_tree.into_iter().map(|(k, v)| (k, match v {
Json::String(s) => s,
_ => unreachable!()
})).collect(),
_ => unreachable!()
}
}
fn decode_segments(encoded_token: String) -> Option<(Header, Payload, Vec<u8>, String)> {
let raw_segments: Vec<&str> = encoded_token.split(".").collect();
if raw_segments.len() != segments_count() {
return None
}
let header_segment = raw_segments[0];
let payload_segment = raw_segments[1];
let crypto_segment = raw_segments[2];
let (header, payload) = decode_header_and_payload(header_segment, payload_segment);
let signature = &crypto_segment.as_bytes().from_base64().unwrap();
let signing_input = format!("{}.{}", header_segment, payload_segment);
Some((header, payload, signature.clone(), signing_input))
}
fn decode_header_and_payload<'a>(header_segment: &str, payload_segment: &str) -> (Header, Payload) {
fn base64_to_json(input: &str) -> Json {
let bytes = input.as_bytes().from_base64().unwrap();
let s = str::from_utf8(&bytes).unwrap();
Json::from_str(s).unwrap()
};
let header_json = base64_to_json(header_segment);
let header_tree = json_to_tree(header_json);
let alg = header_tree.get("alg").unwrap();
let header = Header::new(parse_algorithm(alg));
let payload_json = base64_to_json(payload_segment);
let payload = json_to_tree(payload_json);
(header, payload)
}
fn parse_algorithm(alg: &str) -> Algorithm {
match alg {
"HS256" => Algorithm::HS256,
"HS384" => Algorithm::HS384,
"HS512" => Algorithm::HS512,
"RS256" => Algorithm::HS512,
_ => panic!("Unknown algorithm")
}
}
fn verify_signature(algorithm: Algorithm, signing_input: String, signature: &[u8], secret: String) -> bool {
let mut hmac = match algorithm {
Algorithm::HS256 => create_hmac(Sha256::new(), secret),
Algorithm::HS384 => create_hmac(Sha384::new(), secret),
Algorithm::HS512 => create_hmac(Sha512::new(), secret),
Algorithm::RS256 => unimplemented!()
};
hmac.input(signing_input.to_string().as_bytes());
secure_compare(signature, hmac.result().code())
}
fn secure_compare(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false
}
let mut res = 0_u8;
for (&x, &y) in a.iter().zip(b.iter()) {
res |= x ^ y;
}
res == 0
}
fn create_hmac<'a, D: Digest + 'a>(digest: D, some_str: String) -> Box<Mac + 'a> {
Box::new(Hmac::new(digest, some_str.as_bytes()))
}
#[cfg(test)]
mod tests {
extern crate time;
use time::Duration;
use super::Header;
use super::Payload;
use super::encode;
use super::decode;
use super::Algorithm;
use super::secure_compare;
#[test]
fn test_encode_and_decode_jwt_hs256() {
let mut p1 = Payload::new();
p1.insert("key1".to_string(), "val1".to_string());
p1.insert("key2".to_string(), "val2".to_string());
p1.insert("key3".to_string(), "val3".to_string());
let secret = "secret123";
let header = Header::new(Algorithm::HS256);
let jwt1 = encode(header, secret.to_string(), p1.clone());
let maybe_res = decode(jwt1, secret.to_string(), Algorithm::HS256);
assert!(maybe_res.is_ok());
}
#[test]
fn test_decode_valid_jwt_hs256() {
let mut p1 = Payload::new();
p1.insert("key11".to_string(), "val1".to_string());
p1.insert("key22".to_string(), "val2".to_string());
let secret = "secret123";
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkxMSI6InZhbDEiLCJrZXkyMiI6InZhbDIifQ.jrcoVcRsmQqDEzSW9qOhG1HIrzV_n3nMhykNPnGvp9c";
let maybe_res = decode(jwt.to_string(), secret.to_string(), Algorithm::HS256);
assert!(maybe_res.is_ok());
}
#[test]
fn test_secure_compare_same_strings() {
let str1 = "same same".as_bytes();
let str2 = "same same".as_bytes();
let res = secure_compare(str1, str2);
assert!(res);
}
#[test]
fn test_fails_when_secure_compare_different_strings() {
let str1 = "same same".as_bytes();
let str2 = "same same but different".as_bytes();
let res = secure_compare(str1, str2);
assert!(!res);
}
#[test]
fn test_encode_and_decode_jwt_hs384() {
let mut p1 = Payload::new();
p1.insert("key1".to_string(), "val1".to_string());
p1.insert("key2".to_string(), "val2".to_string());
p1.insert("key3".to_string(), "val3".to_string());
let secret = "secret123";
let header = Header::new(Algorithm::HS384);
let jwt1 = encode(header, secret.to_string(), p1.clone());
let maybe_res = decode(jwt1, secret.to_string(), Algorithm::HS384);
assert!(maybe_res.is_ok());
}
#[test]
fn test_encode_and_decode_jwt_hs512() {
let mut p1 = Payload::new();
p1.insert("key12".to_string(), "val1".to_string());
p1.insert("key22".to_string(), "val2".to_string());
p1.insert("key33".to_string(), "val3".to_string());
let secret = "secret123456";
let header = Header::new(Algorithm::HS512);
let jwt1 = encode(header, secret.to_string(), p1.clone());
let maybe_res = decode(jwt1, secret.to_string(), Algorithm::HS512);
assert!(maybe_res.is_ok());
}
// #[test]
// fn test_fails_when_expired() {
// let now = time::get_time();
// let past = now + Duration::minutes(-5);
// let mut p1 = BTreeMap::new();
// p1.insert("exp".to_string(), past.sec.to_string());
// p1.insert("key1".to_string(), "val1".to_string());
// let secret = "secret123";
// let jwt = sign(secret, Some(p1.clone()), None);
// let res = verify(jwt.as_slice(), secret, None);
// assert!(res.is_ok());
// }
// #[test]
// fn test_ok_when_expired_not_verified() {
// let now = time::get_time();
// let past = now + Duration::minutes(-5);
// let mut p1 = BTreeMap::new();
// p1.insert("exp".to_string(), past.sec.to_string());
// p1.insert("key1".to_string(), "val1".to_string());
// let secret = "secret123";
// let jwt = sign(secret, Some(p1.clone()), None);
// let res = verify(jwt.as_slice(), secret, None);
// assert!(res.is_ok());
// }
}<|fim▁end|> | 3
} |
<|file_name|>Calculator.py<|end_file_name|><|fim▁begin|># Numbers 数字
print(2 + 2) # 4
print(50 - 5*6) # 20
print((50 - 5*6) / 4) # 5.0
print(8/5) # 1.6
print(17 / 3) # 5.666666666666667 float
print(17 // 3) # 5 取整
print(17 % 3) # 2 取模
print(5*3+2) # 17 先乘除,后加减
print(2+5*3) # 17 先乘除,后加减
print(5**2) # 5的平方 25
print(5**3) # 5的立方 125
print(2**7) # 2的7次方128
print("--华丽的分割线--")
# 给变量赋值,使用“ = ”号,不需要定义变量的类型
width=50
height=10*10
print(width*height) # 5000
# n # n 没有定义 NameError: name 'n' is not defined
print(4 * 3.75 - 1)
tax = 12.5 / 100
price = 100.50
print(price * tax)
# print(price+_); #在控制台可行,但是在本文件中不行,提示ameError: name '_' is not defined
# round(_, 2) #在控制台可行,但是在本文件中不行,提示ameError: name '_' is not defined
print("--华丽的分割线--")
# Strings 字符串
print('spam eggs')
print( 'doesn\'t') # \' 会进行转义
print("doesn't") # 也可使用双引号来输出,此时‘ 就不需要转义
print('"Yes," he said.') # 被单引号包含的双引号会被当成字符处理
print("\"Yes,\" he said.") # 被双引号包含中的双银行需要转义
print('"Isn\'t," she said.') #被单引号包含的单引号需要进行转义,不是用print函数打印时'"Isn\'t," she said.'
s = 'First line.\nSecond line.'
print(s) # 使用print打印\n会被转义换行 ,使用命令行是\n不会被转义 First line.\nSecond line.
print("----")
print('C:\some\name') # 这里 \n 会被转义
print(r'C:\some\name' ) # 声明 r' 后面的字符串不会被转义
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
# """...""" or '''...''' 相当于html中p标签的作用,允许多行,排列格式
# 不加\ : 空一行
print(3 * 'un' + 'ium') # 字符串可以跟数字进行相乘
print('Py' 'thon') # Python ,在同一个print方法中,用多个空格隔开,最终会拼接成一个
prefix = 'Py'
#prefix 'thon' #不能连接变量和字符串文字
#print(('un' * 3)* 'ium')
print(prefix + 'thon') # 字符串用+ 进行拼接
text = ('Put several strings within parentheses to have them joined together.')
print(text)
word = 'Python'
print(word[0]) # 字符串也可以当成数组来取值
print(word[5])
print(word[-1]) # 截取最后一个字符
print(word[-2]) # 截取最后第二个字符
print(word[-6]) # 截取最后第六个字符
print(word[0:2]) # 从第一个字符所在索引截取2个字符
print(word[2:5]) # 从第三个字符所在索引截取5个字符
<|fim▁hole|>print(word[:2] + word[2:]) # s[:i] + s[i:] = s ,不管i为某个整数
print(word[:4] + word[4:])
print(word[:70] + word[70:])
print(word[:2]) # 从第一个字符开始取2个 字符
print(word[4:]) # 从第四个字符取到最后的 字符
print(word[-2:]) # 从最后第二个字符取到最后的 字符
print("---------");
# +---+---+---+---+---+---+
# | P | y | t | h | o | n |
# +---+---+---+---+---+---+
# 0 1 2 3 4 5 6
# -6 -5 -4 -3 -2 -1
print( word[4:42]) #从第四个字符取到最后的 字符
print(word[42:]) #从第42个字符取到最后的字符 空
# word[0] = 'J'
# word[2:] = 'py' 不允许修改字符串
print('J' + word[1:]) #可以重新拼接新字符串
print(word[:2] + 'py')
s = 'supercalifragilisticexpialidocious'
print(len(s)) # 获取字符串的长度<|fim▁end|> | |
<|file_name|>SimulatorStore.js<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import Reflux from 'reflux';
import URLUtils from 'util/URLUtils';
import ApiRoutes from 'routing/ApiRoutes';
import fetch from 'logic/rest/FetchProvider';
import MessageFormatter from 'logic/message/MessageFormatter';
import ObjectUtils from 'util/ObjectUtils';
import CombinedProvider from 'injection/CombinedProvider';
const { SimulatorActions } = CombinedProvider.get('Simulator');
const SimulatorStore = Reflux.createStore({
listenables: [SimulatorActions],
simulate(stream, messageFields, inputId) {
const url = URLUtils.qualifyUrl(ApiRoutes.SimulatorController.simulate().url);
const simulation = {
stream_id: stream.id,
message: messageFields,
input_id: inputId,
};
let promise = fetch('POST', url, simulation);
promise = promise.then((response) => {
const formattedResponse = ObjectUtils.clone(response);
formattedResponse.messages = response.messages.map((msg) => MessageFormatter.formatMessageSummary(msg));
return formattedResponse;
});
<|fim▁hole|>
export default SimulatorStore;<|fim▁end|> | SimulatorActions.simulate.promise(promise);
},
}); |
<|file_name|>CommandBuilder.py<|end_file_name|><|fim▁begin|>import Utils
from Utils import printe
<|fim▁hole|>
def __init__(self, *command_args):
self.command_args = list(command_args)
def append(self, *args):
for arg in args:
if isinstance(arg, str):
self.command_args += [arg]
elif isinstance(arg, list) or isinstance(arg, tuple):
for sub_arg in arg:
self.append(sub_arg)
else:
printe('Error appending argument of unknown type: {}'.format(
str(type(arg))), terminate=True)
return self
def debug(self):
return Utils.debug(*self.command_args)
def run(self, replaceForeground=False):
return Utils.run(*self.command_args,
replaceForeground=replaceForeground)<|fim▁end|> | class CommandBuilder(object): |
<|file_name|>uint.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::cmp;
use std::str::FromStr;
use rustc_serialize::hex::ToHex;
use serde;
use util::{U256 as EthU256, Uint};
macro_rules! impl_uint {
($name: ident, $other: ident, $size: expr) => {
/// Uint serialization.
#[derive(Debug, Default, Clone, Copy, PartialEq, Hash)]
pub struct $name($other);
impl Eq for $name { }
impl<T> From<T> for $name where $other: From<T> {
fn from(o: T) -> Self {
$name($other::from(o))
}
}
impl FromStr for $name {
type Err = <$other as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
$other::from_str(s).map($name)
}
}
impl Into<$other> for $name {
fn into(self) -> $other {
self.0
}
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
let mut hex = "0x".to_owned();
let mut bytes = [0u8; 8 * $size];
self.0.to_big_endian(&mut bytes);
let len = cmp::max((self.0.bits() + 7) / 8, 1);
let bytes_hex = bytes[bytes.len() - len..].to_hex();
if bytes_hex.starts_with('0') {<|fim▁hole|> }
serializer.serialize_str(&hex)
}
}
impl serde::Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<$name, D::Error>
where D: serde::Deserializer {
struct UintVisitor;
impl serde::de::Visitor for UintVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: serde::Error {
// 0x + len
if value.len() > 2 + $size * 16 || value.len() < 2 {
return Err(serde::Error::custom("Invalid length."));
}
if &value[0..2] != "0x" {
return Err(serde::Error::custom("Use hex encoded numbers with 0x prefix."))
}
$other::from_str(&value[2..]).map($name).map_err(|_| serde::Error::custom("Invalid hex value."))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: serde::Error {
self.visit_str(&value)
}
}
deserializer.deserialize(UintVisitor)
}
}
}
}
impl_uint!(U256, EthU256, 4);
#[cfg(test)]
mod tests {
use super::U256;
use serde_json;
type Res = Result<U256, serde_json::Error>;
#[test]
fn should_serialize_u256() {
let serialized1 = serde_json::to_string(&U256(0.into())).unwrap();
let serialized2 = serde_json::to_string(&U256(1.into())).unwrap();
let serialized3 = serde_json::to_string(&U256(16.into())).unwrap();
let serialized4 = serde_json::to_string(&U256(256.into())).unwrap();
assert_eq!(serialized1, r#""0x0""#);
assert_eq!(serialized2, r#""0x1""#);
assert_eq!(serialized3, r#""0x10""#);
assert_eq!(serialized4, r#""0x100""#);
}
#[test]
fn should_fail_to_deserialize_decimals() {
let deserialized1: Res = serde_json::from_str(r#""""#);
let deserialized2: Res = serde_json::from_str(r#""0""#);
let deserialized3: Res = serde_json::from_str(r#""10""#);
let deserialized4: Res = serde_json::from_str(r#""1000000""#);
let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""#);
assert!(deserialized1.is_err());
assert!(deserialized2.is_err());
assert!(deserialized3.is_err());
assert!(deserialized4.is_err());
assert!(deserialized5.is_err());
}
#[test]
fn should_deserialize_u256() {
let deserialized1: U256 = serde_json::from_str(r#""0x""#).unwrap();
let deserialized2: U256 = serde_json::from_str(r#""0x0""#).unwrap();
let deserialized3: U256 = serde_json::from_str(r#""0x1""#).unwrap();
let deserialized4: U256 = serde_json::from_str(r#""0x01""#).unwrap();
let deserialized5: U256 = serde_json::from_str(r#""0x100""#).unwrap();
assert_eq!(deserialized1, U256(0.into()));
assert_eq!(deserialized2, U256(0.into()));
assert_eq!(deserialized3, U256(1.into()));
assert_eq!(deserialized4, U256(1.into()));
assert_eq!(deserialized5, U256(256.into()));
}
}<|fim▁end|> | hex.push_str(&bytes_hex[1..]);
} else {
hex.push_str(&bytes_hex); |
<|file_name|>image.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the specified value of
//! [`image`][image]s
//!
//! [image]: https://drafts.csswg.org/css-images/#image-values
use Atom;
use cssparser::{Parser, Token, BasicParseError};
use custom_properties::SpecifiedValue;
use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseError;
#[cfg(feature = "servo")]
use servo_url::ServoUrl;
use std::cmp::Ordering;
use std::f32::consts::PI;
use std::fmt;
use style_traits::{ToCss, ParseError, StyleParseError};
use values::{Either, None_};
#[cfg(feature = "gecko")]
use values::computed::{Context, Position as ComputedPosition, ToComputedValue};
use values::generics::image::{Circle, CompatMode, Ellipse, ColorStop as GenericColorStop};
use values::generics::image::{EndingShape as GenericEndingShape, Gradient as GenericGradient};
use values::generics::image::{GradientItem as GenericGradientItem, GradientKind as GenericGradientKind};
use values::generics::image::{Image as GenericImage, LineDirection as GenericsLineDirection};
use values::generics::image::{MozImageRect as GenericMozImageRect, ShapeExtent};
use values::generics::image::PaintWorklet;
use values::generics::position::Position as GenericPosition;
use values::specified::{Angle, Color, Length, LengthOrPercentage};
use values::specified::{Number, NumberOrPercentage, Percentage, RGBAColor};
use values::specified::position::{LegacyPosition, Position, PositionComponent, Side, X, Y};
use values::specified::url::SpecifiedUrl;
/// A specified image layer.
pub type ImageLayer = Either<None_, Image>;
/// Specified values for an image according to CSS-IMAGES.
/// https://drafts.csswg.org/css-images/#image-values
pub type Image = GenericImage<Gradient, MozImageRect, SpecifiedUrl>;
/// Specified values for a CSS gradient.
/// https://drafts.csswg.org/css-images/#gradients
#[cfg(not(feature = "gecko"))]
pub type Gradient = GenericGradient<
LineDirection,
Length,
LengthOrPercentage,
Position,
RGBAColor,
Angle,
>;
/// Specified values for a CSS gradient.
/// https://drafts.csswg.org/css-images/#gradients
#[cfg(feature = "gecko")]
pub type Gradient = GenericGradient<
LineDirection,
Length,
LengthOrPercentage,
GradientPosition,
RGBAColor,
Angle,
>;
/// A specified gradient kind.
#[cfg(not(feature = "gecko"))]
pub type GradientKind = GenericGradientKind<
LineDirection,
Length,
LengthOrPercentage,
Position,
Angle,
>;
/// A specified gradient kind.
#[cfg(feature = "gecko")]
pub type GradientKind = GenericGradientKind<
LineDirection,
Length,
LengthOrPercentage,
GradientPosition,
Angle,
>;
/// A specified gradient line direction.
#[derive(Clone, Debug, HasViewportPercentage, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum LineDirection {
/// An angular direction.
Angle(Angle),
/// A horizontal direction.
Horizontal(X),
/// A vertical direction.
Vertical(Y),
/// A direction towards a corner of a box.
Corner(X, Y),
/// A Position and an Angle for legacy `-moz-` prefixed gradient.
/// `-moz-` prefixed linear gradient can contain both a position and an angle but it
/// uses legacy syntax for position. That means we can't specify both keyword and
/// length for each horizontal/vertical components.
#[cfg(feature = "gecko")]
MozPosition(Option<LegacyPosition>, Option<Angle>),
}
/// A binary enum to hold either Position or LegacyPosition.
#[derive(Clone, Debug, HasViewportPercentage, PartialEq, ToCss)]
#[cfg(feature = "gecko")]
pub enum GradientPosition {
/// 1, 2, 3, 4-valued <position>.
Modern(Position),
/// 1, 2-valued <position>.
Legacy(LegacyPosition),
}
/// A specified ending shape.
pub type EndingShape = GenericEndingShape<Length, LengthOrPercentage>;
/// A specified gradient item.
pub type GradientItem = GenericGradientItem<RGBAColor, LengthOrPercentage>;
/// A computed color stop.
pub type ColorStop = GenericColorStop<RGBAColor, LengthOrPercentage>;
/// Specified values for `moz-image-rect`
/// -moz-image-rect(<uri>, top, right, bottom, left);
pub type MozImageRect = GenericMozImageRect<NumberOrPercentage, SpecifiedUrl>;
impl Parse for Image {
#[cfg_attr(not(feature = "gecko"), allow(unused_mut))]
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Image, ParseError<'i>> {
if let Ok(mut url) = input.try(|input| SpecifiedUrl::parse(context, input)) {
#[cfg(feature = "gecko")]
{
url.build_image_value();
}
return Ok(GenericImage::Url(url));
}
if let Ok(gradient) = input.try(|i| Gradient::parse(context, i)) {
return Ok(GenericImage::Gradient(gradient));
}
#[cfg(feature = "servo")]
{
if let Ok(paint_worklet) = input.try(|i| PaintWorklet::parse(context, i)) {
return Ok(GenericImage::PaintWorklet(paint_worklet));
}
}
if let Ok(mut image_rect) = input.try(|input| MozImageRect::parse(context, input)) {
#[cfg(feature = "gecko")]
{
image_rect.url.build_image_value();
}
return Ok(GenericImage::Rect(image_rect));
}
Ok(GenericImage::Element(Image::parse_element(input)?))
}
}
impl Image {
/// Creates an already specified image value from an already resolved URL
/// for insertion in the cascade.
#[cfg(feature = "servo")]
pub fn for_cascade(url: ServoUrl) -> Self {
GenericImage::Url(SpecifiedUrl::for_cascade(url))
}
/// Parses a `-moz-element(# <element-id>)`.
fn parse_element<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Atom, ParseError<'i>> {
input.try(|i| i.expect_function_matching("-moz-element"))?;
input.parse_nested_block(|i| {
match *i.next()? {
Token::IDHash(ref id) => Ok(Atom::from(id.as_ref())),
ref t => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
}
})
}
}
impl Parse for Gradient {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
enum Shape {
Linear,
Radial,
}
// FIXME: remove clone() when lifetimes are non-lexical
let func = input.expect_function()?.clone();
let result = match_ignore_ascii_case! { &func,
"linear-gradient" => {
Some((Shape::Linear, false, CompatMode::Modern))
},
"-webkit-linear-gradient" => {
Some((Shape::Linear, false, CompatMode::WebKit))
},
#[cfg(feature = "gecko")]
"-moz-linear-gradient" => {
Some((Shape::Linear, false, CompatMode::Moz))
},
"repeating-linear-gradient" => {
Some((Shape::Linear, true, CompatMode::Modern))
},
"-webkit-repeating-linear-gradient" => {
Some((Shape::Linear, true, CompatMode::WebKit))
},
#[cfg(feature = "gecko")]
"-moz-repeating-linear-gradient" => {
Some((Shape::Linear, true, CompatMode::Moz))
},
"radial-gradient" => {
Some((Shape::Radial, false, CompatMode::Modern))
},
"-webkit-radial-gradient" => {
Some((Shape::Radial, false, CompatMode::WebKit))
}
#[cfg(feature = "gecko")]
"-moz-radial-gradient" => {
Some((Shape::Radial, false, CompatMode::Moz))
},
"repeating-radial-gradient" => {
Some((Shape::Radial, true, CompatMode::Modern))
},
"-webkit-repeating-radial-gradient" => {
Some((Shape::Radial, true, CompatMode::WebKit))
},
#[cfg(feature = "gecko")]
"-moz-repeating-radial-gradient" => {
Some((Shape::Radial, true, CompatMode::Moz))
},
"-webkit-gradient" => {
return input.parse_nested_block(|i| Self::parse_webkit_gradient_argument(context, i));
},
_ => None,
};
let (shape, repeating, mut compat_mode) = match result {
Some(result) => result,
None => return Err(StyleParseError::UnexpectedFunction(func.clone()).into()),
};
let (kind, items) = input.parse_nested_block(|i| {
let shape = match shape {
Shape::Linear => GradientKind::parse_linear(context, i, &mut compat_mode)?,
Shape::Radial => GradientKind::parse_radial(context, i, &mut compat_mode)?,
};
let items = GradientItem::parse_comma_separated(context, i)?;
Ok((shape, items))
})?;
if items.len() < 2 {
return Err(StyleParseError::UnspecifiedError.into());
}
Ok(Gradient {
items: items,
repeating: repeating,
kind: kind,
compat_mode: compat_mode,
})
}
}
impl Gradient {
fn parse_webkit_gradient_argument<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
type Point = GenericPosition<Component<X>, Component<Y>>;
#[derive(Clone, Copy)]
enum Component<S> {
Center,
Number(NumberOrPercentage),
Side(S),
}
impl LineDirection {
fn from_points(first: Point, second: Point) -> Self {
let h_ord = first.horizontal.partial_cmp(&second.horizontal);
let v_ord = first.vertical.partial_cmp(&second.vertical);
let (h, v) = match (h_ord, v_ord) {
(Some(h), Some(v)) => (h, v),
_ => return LineDirection::Vertical(Y::Bottom),
};
match (h, v) {
(Ordering::Less, Ordering::Less) => {
LineDirection::Corner(X::Right, Y::Bottom)
},
(Ordering::Less, Ordering::Equal) => {
LineDirection::Horizontal(X::Right)
},
(Ordering::Less, Ordering::Greater) => {
LineDirection::Corner(X::Right, Y::Top)
},
(Ordering::Equal, Ordering::Greater) => {
LineDirection::Vertical(Y::Top)
},
(Ordering::Equal, Ordering::Equal) |
(Ordering::Equal, Ordering::Less) => {
LineDirection::Vertical(Y::Bottom)
},
(Ordering::Greater, Ordering::Less) => {
LineDirection::Corner(X::Left, Y::Bottom)
},
(Ordering::Greater, Ordering::Equal) => {
LineDirection::Horizontal(X::Left)
},
(Ordering::Greater, Ordering::Greater) => {
LineDirection::Corner(X::Left, Y::Top)
},
}
}
}
impl From<Point> for Position {
fn from(point: Point) -> Self {
Self::new(point.horizontal.into(), point.vertical.into())
}
}
impl Parse for Point {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
input.try(|i| {
let x = Component::parse(context, i)?;
let y = Component::parse(context, i)?;
Ok(Self::new(x, y))
})
}
}
impl<S: Side> From<Component<S>> for NumberOrPercentage {
fn from(component: Component<S>) -> Self {
match component {
Component::Center => NumberOrPercentage::Percentage(Percentage::new(0.5)),
Component::Number(number) => number,
Component::Side(side) => {
let p = if side.is_start() { Percentage::zero() } else { Percentage::hundred() };
NumberOrPercentage::Percentage(p)
},
}
}
}
impl<S: Side> From<Component<S>> for PositionComponent<S> {
fn from(component: Component<S>) -> Self {
match component {
Component::Center => {
PositionComponent::Center
},
Component::Number(NumberOrPercentage::Number(number)) => {
PositionComponent::Length(Length::from_px(number.value).into())
},
Component::Number(NumberOrPercentage::Percentage(p)) => {
PositionComponent::Length(p.into())
},
Component::Side(side) => {
PositionComponent::Side(side, None)
},
}
}
}
impl<S: Copy + Side> Component<S> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (NumberOrPercentage::from(*self), NumberOrPercentage::from(*other)) {
(NumberOrPercentage::Percentage(a), NumberOrPercentage::Percentage(b)) => {
a.get().partial_cmp(&b.get())
},
(NumberOrPercentage::Number(a), NumberOrPercentage::Number(b)) => {
a.value.partial_cmp(&b.value)
},
(_, _) => {
None
}
}
}
}
impl<S: Parse> Parse for Component<S> {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
if let Ok(side) = input.try(|i| S::parse(context, i)) {
return Ok(Component::Side(side));
}
if let Ok(number) = input.try(|i| NumberOrPercentage::parse(context, i)) {
return Ok(Component::Number(number));
}
input.try(|i| i.expect_ident_matching("center"))?;
Ok(Component::Center)
}
}
let ident = input.expect_ident_cloned()?;
input.expect_comma()?;
let (kind, reverse_stops) = match_ignore_ascii_case! { &ident,
"linear" => {
let first = Point::parse(context, input)?;
input.expect_comma()?;
let second = Point::parse(context, input)?;
let direction = LineDirection::from_points(first, second);
let kind = GenericGradientKind::Linear(direction);
(kind, false)
},
"radial" => {
let first_point = Point::parse(context, input)?;
input.expect_comma()?;
let first_radius = Number::parse(context, input)?;
input.expect_comma()?;
let second_point = Point::parse(context, input)?;
input.expect_comma()?;
let second_radius = Number::parse(context, input)?;
let (reverse_stops, point, radius) = if second_radius.value >= first_radius.value {
(false, second_point, second_radius)
} else {
(true, first_point, first_radius)
};
let shape = GenericEndingShape::Circle(Circle::Radius(Length::from_px(radius.value)));
let position: Position = point.into();
#[cfg(feature = "gecko")]
{
let kind = GenericGradientKind::Radial(shape, GradientPosition::Modern(position), None);
(kind, reverse_stops)
}
#[cfg(not(feature = "gecko"))]
{
let kind = GenericGradientKind::Radial(shape, position, None);
(kind, reverse_stops)
}
},
_ => return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into()),
};
let mut items = input.try(|i| {
i.expect_comma()?;
i.parse_comma_separated(|i| {
let function = i.expect_function()?.clone();
let (color, mut p) = i.parse_nested_block(|i| {
let p = match_ignore_ascii_case! { &function,
"color-stop" => {
let p = match NumberOrPercentage::parse(context, i)? {
NumberOrPercentage::Number(number) => Percentage::new(number.value),
NumberOrPercentage::Percentage(p) => p,
};
i.expect_comma()?;
p
},
"from" => Percentage::zero(),
"to" => Percentage::hundred(),
_ => return Err(StyleParseError::UnexpectedFunction(function.clone()).into()),
};
let color = Color::parse(context, i)?;
if color == Color::CurrentColor {
return Err(StyleParseError::UnspecifiedError.into());
}
Ok((color.into(), p))
})?;
if reverse_stops {
p.reverse();
}
Ok(GenericGradientItem::ColorStop(GenericColorStop {
color: color,
position: Some(p.into()),
}))
})
}).unwrap_or(vec![]);
if items.is_empty() {
items = vec![
GenericGradientItem::ColorStop(GenericColorStop {
color: Color::transparent().into(),
position: Some(Percentage::zero().into()),
}),
GenericGradientItem::ColorStop(GenericColorStop {
color: Color::transparent().into(),
position: Some(Percentage::hundred().into()),
}),
];
} else if items.len() == 1 {
let first = items[0].clone();
items.push(first);
} else {
items.sort_by(|a, b| {
match (a, b) {
(&GenericGradientItem::ColorStop(ref a), &GenericGradientItem::ColorStop(ref b)) => {
match (&a.position, &b.position) {
(&Some(LengthOrPercentage::Percentage(a)), &Some(LengthOrPercentage::Percentage(b))) => {
return a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal);
},
_ => {},
}
},
_ => {},
}
if reverse_stops {
Ordering::Greater
} else {
Ordering::Less
}
})
}
Ok(GenericGradient {
kind: kind,
items: items,
repeating: false,
compat_mode: CompatMode::Modern,
})
}
}
impl GradientKind {
/// Parses a linear gradient.
/// CompatMode can change during `-moz-` prefixed gradient parsing if it come across a `to` keyword.
fn parse_linear<'i, 't>(context: &ParserContext,
input: &mut Parser<'i, 't>,
compat_mode: &mut CompatMode)
-> Result<Self, ParseError<'i>> {
let direction = if let Ok(d) = input.try(|i| LineDirection::parse(context, i, compat_mode)) {
input.expect_comma()?;
d
} else {
LineDirection::Vertical(Y::Bottom)
};
Ok(GenericGradientKind::Linear(direction))
}
fn parse_radial<'i, 't>(context: &ParserContext,
input: &mut Parser<'i, 't>,
compat_mode: &mut CompatMode)
-> Result<Self, ParseError<'i>> {
let (shape, position, angle, moz_position) = match *compat_mode {
CompatMode::Modern => {
let shape = input.try(|i| EndingShape::parse(context, i, *compat_mode));
let position = input.try(|i| {
i.expect_ident_matching("at")?;
Position::parse(context, i)
});
(shape, position.ok(), None, None)
},
CompatMode::WebKit => {
let position = input.try(|i| Position::parse(context, i));
let shape = input.try(|i| {
if position.is_ok() {
i.expect_comma()?;
}
EndingShape::parse(context, i, *compat_mode)
});
(shape, position.ok(), None, None)
},
// The syntax of `-moz-` prefixed radial gradient is:
// -moz-radial-gradient(
// [ [ <position> || <angle> ]? [ ellipse | [ <length> | <percentage> ]{2} ] , |
// [ <position> || <angle> ]? [ [ circle | ellipse ] | <extent-keyword> ] , |
// ]?
// <color-stop> [ , <color-stop> ]+
// )
// where <extent-keyword> = closest-corner | closest-side | farthest-corner | farthest-side |
// cover | contain
// and <color-stop> = <color> [ <percentage> | <length> ]?
CompatMode::Moz => {
let mut position = input.try(|i| LegacyPosition::parse(context, i));
let angle = input.try(|i| Angle::parse(context, i)).ok();
if position.is_err() {
position = input.try(|i| LegacyPosition::parse(context, i));
}
let shape = input.try(|i| {
if position.is_ok() || angle.is_some() {
i.expect_comma()?;
}
EndingShape::parse(context, i, *compat_mode)
});
(shape, None, angle, position.ok())
}
};
if shape.is_ok() || position.is_some() || angle.is_some() || moz_position.is_some() {
input.expect_comma()?;
}
let shape = shape.unwrap_or({
GenericEndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner))
});
#[cfg(feature = "gecko")]
{
if *compat_mode == CompatMode::Moz {
// If this form can be represented in Modern mode, then convert the compat_mode to Modern.
if angle.is_none() {
*compat_mode = CompatMode::Modern;<|fim▁hole|> }
}
let position = position.unwrap_or(Position::center());
#[cfg(feature = "gecko")]
{
return Ok(GenericGradientKind::Radial(shape, GradientPosition::Modern(position), angle));
}
#[cfg(not(feature = "gecko"))]
{
return Ok(GenericGradientKind::Radial(shape, position, angle));
}
}
}
impl GenericsLineDirection for LineDirection {
fn points_downwards(&self) -> bool {
match *self {
LineDirection::Angle(ref angle) => angle.radians() == PI,
LineDirection::Vertical(Y::Bottom) => true,
_ => false,
}
}
fn to_css<W>(&self, dest: &mut W, compat_mode: CompatMode) -> fmt::Result
where W: fmt::Write
{
match *self {
LineDirection::Angle(angle) => {
angle.to_css(dest)
},
LineDirection::Horizontal(x) => {
if compat_mode == CompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)
},
LineDirection::Vertical(y) => {
if compat_mode == CompatMode::Modern {
dest.write_str("to ")?;
}
y.to_css(dest)
},
LineDirection::Corner(x, y) => {
if compat_mode == CompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)?;
dest.write_str(" ")?;
y.to_css(dest)
},
#[cfg(feature = "gecko")]
LineDirection::MozPosition(ref position, ref angle) => {
let mut need_space = false;
if let Some(ref position) = *position {
position.to_css(dest)?;
need_space = true;
}
if let Some(ref angle) = *angle {
if need_space {
dest.write_str(" ")?;
}
angle.to_css(dest)?;
}
Ok(())
},
}
}
}
impl LineDirection {
fn parse<'i, 't>(context: &ParserContext,
input: &mut Parser<'i, 't>,
compat_mode: &mut CompatMode)
-> Result<Self, ParseError<'i>> {
let mut _angle = if *compat_mode == CompatMode::Moz {
input.try(|i| Angle::parse(context, i)).ok()
} else {
if let Ok(angle) = input.try(|i| Angle::parse_with_unitless(context, i)) {
return Ok(LineDirection::Angle(angle));
}
None
};
input.try(|i| {
let to_ident = i.try(|i| i.expect_ident_matching("to"));
match *compat_mode {
// `to` keyword is mandatory in modern syntax.
CompatMode::Modern => to_ident?,
// Fall back to Modern compatibility mode in case there is a `to` keyword.
// According to Gecko, `-moz-linear-gradient(to ...)` should serialize like
// `linear-gradient(to ...)`.
CompatMode::Moz if to_ident.is_ok() => *compat_mode = CompatMode::Modern,
// There is no `to` keyword in webkit prefixed syntax. If it's consumed,
// parsing should throw an error.
CompatMode::WebKit if to_ident.is_ok() => {
return Err(SelectorParseError::UnexpectedIdent("to".into()).into())
},
_ => {},
}
#[cfg(feature = "gecko")]
{
// `-moz-` prefixed linear gradient can be both Angle and Position.
if *compat_mode == CompatMode::Moz {
let position = i.try(|i| LegacyPosition::parse(context, i)).ok();
if _angle.is_none() {
_angle = i.try(|i| Angle::parse(context, i)).ok();
};
if _angle.is_none() && position.is_none() {
return Err(StyleParseError::UnspecifiedError.into());
}
return Ok(LineDirection::MozPosition(position, _angle));
}
}
if let Ok(x) = i.try(X::parse) {
if let Ok(y) = i.try(Y::parse) {
return Ok(LineDirection::Corner(x, y));
}
return Ok(LineDirection::Horizontal(x));
}
let y = Y::parse(i)?;
if let Ok(x) = i.try(X::parse) {
return Ok(LineDirection::Corner(x, y));
}
Ok(LineDirection::Vertical(y))
})
}
}
#[cfg(feature = "gecko")]
impl ToComputedValue for GradientPosition {
type ComputedValue = ComputedPosition;
fn to_computed_value(&self, context: &Context) -> ComputedPosition {
match *self {
GradientPosition::Modern(ref pos) => pos.to_computed_value(context),
GradientPosition::Legacy(ref pos) => pos.to_computed_value(context),
}
}
fn from_computed_value(computed: &ComputedPosition) -> Self {
GradientPosition::Modern(ToComputedValue::from_computed_value(computed))
}
}
impl EndingShape {
fn parse<'i, 't>(context: &ParserContext,
input: &mut Parser<'i, 't>,
compat_mode: CompatMode)
-> Result<Self, ParseError<'i>> {
if let Ok(extent) = input.try(|i| ShapeExtent::parse_with_compat_mode(i, compat_mode)) {
if input.try(|i| i.expect_ident_matching("circle")).is_ok() {
return Ok(GenericEndingShape::Circle(Circle::Extent(extent)));
}
let _ = input.try(|i| i.expect_ident_matching("ellipse"));
return Ok(GenericEndingShape::Ellipse(Ellipse::Extent(extent)));
}
if input.try(|i| i.expect_ident_matching("circle")).is_ok() {
if let Ok(extent) = input.try(|i| ShapeExtent::parse_with_compat_mode(i, compat_mode)) {
return Ok(GenericEndingShape::Circle(Circle::Extent(extent)));
}
if compat_mode == CompatMode::Modern {
if let Ok(length) = input.try(|i| Length::parse(context, i)) {
return Ok(GenericEndingShape::Circle(Circle::Radius(length)));
}
}
return Ok(GenericEndingShape::Circle(Circle::Extent(ShapeExtent::FarthestCorner)));
}
if input.try(|i| i.expect_ident_matching("ellipse")).is_ok() {
if let Ok(extent) = input.try(|i| ShapeExtent::parse_with_compat_mode(i, compat_mode)) {
return Ok(GenericEndingShape::Ellipse(Ellipse::Extent(extent)));
}
if compat_mode == CompatMode::Modern {
let pair: Result<_, ParseError> = input.try(|i| {
let x = LengthOrPercentage::parse(context, i)?;
let y = LengthOrPercentage::parse(context, i)?;
Ok((x, y))
});
if let Ok((x, y)) = pair {
return Ok(GenericEndingShape::Ellipse(Ellipse::Radii(x, y)));
}
}
return Ok(GenericEndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner)));
}
// -moz- prefixed radial gradient doesn't allow EndingShape's Length or LengthOrPercentage
// to come before shape keyword. Otherwise it conflicts with <position>.
if compat_mode != CompatMode::Moz {
if let Ok(length) = input.try(|i| Length::parse(context, i)) {
if let Ok(y) = input.try(|i| LengthOrPercentage::parse(context, i)) {
if compat_mode == CompatMode::Modern {
let _ = input.try(|i| i.expect_ident_matching("ellipse"));
}
return Ok(GenericEndingShape::Ellipse(Ellipse::Radii(length.into(), y)));
}
if compat_mode == CompatMode::Modern {
let y = input.try(|i| {
i.expect_ident_matching("ellipse")?;
LengthOrPercentage::parse(context, i)
});
if let Ok(y) = y {
return Ok(GenericEndingShape::Ellipse(Ellipse::Radii(length.into(), y)));
}
let _ = input.try(|i| i.expect_ident_matching("circle"));
}
return Ok(GenericEndingShape::Circle(Circle::Radius(length)));
}
}
input.try(|i| {
let x = Percentage::parse(context, i)?;
let y = if let Ok(y) = i.try(|i| LengthOrPercentage::parse(context, i)) {
if compat_mode == CompatMode::Modern {
let _ = i.try(|i| i.expect_ident_matching("ellipse"));
}
y
} else {
if compat_mode == CompatMode::Modern {
i.expect_ident_matching("ellipse")?;
}
LengthOrPercentage::parse(context, i)?
};
Ok(GenericEndingShape::Ellipse(Ellipse::Radii(x.into(), y)))
})
}
}
impl ShapeExtent {
fn parse_with_compat_mode<'i, 't>(input: &mut Parser<'i, 't>,
compat_mode: CompatMode)
-> Result<Self, ParseError<'i>> {
match Self::parse(input)? {
ShapeExtent::Contain | ShapeExtent::Cover if compat_mode == CompatMode::Modern => {
Err(StyleParseError::UnspecifiedError.into())
},
ShapeExtent::Contain => Ok(ShapeExtent::ClosestSide),
ShapeExtent::Cover => Ok(ShapeExtent::FarthestCorner),
keyword => Ok(keyword),
}
}
}
impl GradientItem {
fn parse_comma_separated<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Vec<Self>, ParseError<'i>> {
let mut seen_stop = false;
let items = input.parse_comma_separated(|input| {
if seen_stop {
if let Ok(hint) = input.try(|i| LengthOrPercentage::parse(context, i)) {
seen_stop = false;
return Ok(GenericGradientItem::InterpolationHint(hint));
}
}
seen_stop = true;
ColorStop::parse(context, input).map(GenericGradientItem::ColorStop)
})?;
if !seen_stop || items.len() < 2 {
return Err(StyleParseError::UnspecifiedError.into());
}
Ok(items)
}
}
impl Parse for ColorStop {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
Ok(ColorStop {
color: RGBAColor::parse(context, input)?,
position: input.try(|i| LengthOrPercentage::parse(context, i)).ok(),
})
}
}
impl Parse for PaintWorklet {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.expect_function_matching("paint")?;
input.parse_nested_block(|input| {
let name = Atom::from(&**input.expect_ident()?);
let arguments = input.try(|input| {
input.expect_comma()?;
input.parse_comma_separated(|input| Ok(*SpecifiedValue::parse(context, input)?))
}).unwrap_or(vec![]);
Ok(PaintWorklet {
name: name,
arguments: arguments,
})
})
}
}
impl Parse for MozImageRect {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.try(|i| i.expect_function_matching("-moz-image-rect"))?;
input.parse_nested_block(|i| {
let string = i.expect_url_or_string()?;
let url = SpecifiedUrl::parse_from_string(string.as_ref().to_owned(), context)?;
i.expect_comma()?;
let top = NumberOrPercentage::parse_non_negative(context, i)?;
i.expect_comma()?;
let right = NumberOrPercentage::parse_non_negative(context, i)?;
i.expect_comma()?;
let bottom = NumberOrPercentage::parse_non_negative(context, i)?;
i.expect_comma()?;
let left = NumberOrPercentage::parse_non_negative(context, i)?;
Ok(MozImageRect {
url: url,
top: top,
right: right,
bottom: bottom,
left: left,
})
})
}
}<|fim▁end|> | }
let position = moz_position.unwrap_or(LegacyPosition::center());
return Ok(GenericGradientKind::Radial(shape, GradientPosition::Legacy(position), angle)); |
<|file_name|>display_controller.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/display/display_controller.h"
#include <algorithm>
#include "ash/ash_switches.h"
#include "ash/display/display_manager.h"
#include "ash/root_window_controller.h"
#include "ash/screen_ash.h"
#include "ash/shell.h"
#include "ash/wm/coordinate_conversion.h"
#include "ash/wm/property_util.h"
#include "ash/wm/window_util.h"
#include "base/command_line.h"
#include "base/json/json_value_converter.h"
#include "base/string_piece.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/compositor/dip_util.h"
#include "ui/gfx/display.h"
#include "ui/gfx/screen.h"
#if defined(OS_CHROMEOS)
#include "ash/display/output_configurator_animation.h"
#include "base/chromeos/chromeos_version.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "chromeos/display/output_configurator.h"
#include "ui/base/x/x11_util.h"
#endif // defined(OS_CHROMEOS)
namespace ash {
namespace {
// Primary display stored in global object as it can be
// accessed after Shell is deleted. A separate display instance is created
// during the shutdown instead of always keeping two display instances
// (one here and another one in display_manager) in sync, which is error prone.
int64 primary_display_id = gfx::Display::kInvalidDisplayID;
gfx::Display* primary_display_for_shutdown = NULL;
// Keeps the number of displays during the shutdown after
// ash::Shell:: is deleted.
int num_displays_for_shutdown = -1;
// The maximum value for 'offset' in DisplayLayout in case of outliers. Need
// to change this value in case to support even larger displays.
const int kMaxValidOffset = 10000;
// The number of pixels to overlap between the primary and secondary displays,
// in case that the offset value is too large.
const int kMinimumOverlapForInvalidOffset = 100;
// Specifies how long the display change should have been disabled
// after each display change operations.
// |kCycleDisplayThrottleTimeoutMs| is set to be longer to avoid
// changing the settings while the system is still configurating
// displays. It will be overriden by |kAfterDisplayChangeThrottleTimeoutMs|
// when the display change happens, so the actual timeout is much shorter.
const int64 kAfterDisplayChangeThrottleTimeoutMs = 500;
const int64 kCycleDisplayThrottleTimeoutMs = 4000;
const int64 kSwapDisplayThrottleTimeoutMs = 500;
bool GetPositionFromString(const base::StringPiece& position,
DisplayLayout::Position* field) {
if (position == "top") {
*field = DisplayLayout::TOP;
return true;
} else if (position == "bottom") {
*field = DisplayLayout::BOTTOM;
return true;
} else if (position == "right") {
*field = DisplayLayout::RIGHT;
return true;
} else if (position == "left") {
*field = DisplayLayout::LEFT;
return true;
}
LOG(ERROR) << "Invalid position value: " << position;
return false;
}
std::string GetStringFromPosition(DisplayLayout::Position position) {
switch (position) {
case DisplayLayout::TOP:
return std::string("top");
case DisplayLayout::BOTTOM:
return std::string("bottom");
case DisplayLayout::RIGHT:
return std::string("right");
case DisplayLayout::LEFT:
return std::string("left");
}
return std::string("unknown");
}
internal::DisplayManager* GetDisplayManager() {
return Shell::GetInstance()->display_manager();
}
void SetDisplayPropertiesOnHostWindow(aura::RootWindow* root,
const gfx::Display& display) {
#if defined(OS_CHROMEOS)
// Native window property (Atom in X11) that specifies the display's
// rotation and scale factor. They are read and used by
// touchpad/mouse driver directly on X (contact adlr@ for more
// details on touchpad/mouse driver side). The value of the rotation
// is one of 0 (normal), 1 (90 degrees clockwise), 2 (180 degree) or
// 3 (270 degrees clockwise). The value of the scale factor is in
// percent (100, 140, 200 etc).
const char kRotationProp[] = "_CHROME_DISPLAY_ROTATION";
const char kScaleFactorProp[] = "_CHROME_DISPLAY_SCALE_FACTOR";
const char kCARDINAL[] = "CARDINAL";
CommandLine* command_line = CommandLine::ForCurrentProcess();
int rotation = 0;
if (command_line->HasSwitch(switches::kAshOverrideDisplayOrientation)) {
std::string value = command_line->
GetSwitchValueASCII(switches::kAshOverrideDisplayOrientation);
DCHECK(base::StringToInt(value, &rotation));
DCHECK(0 <= rotation && rotation <= 3) << "Invalid rotation value="
<< rotation;
if (rotation < 0 || rotation > 3)
rotation = 0;
}
gfx::AcceleratedWidget xwindow = root->GetAcceleratedWidget();
ui::SetIntProperty(xwindow, kRotationProp, kCARDINAL, rotation);
ui::SetIntProperty(xwindow,
kScaleFactorProp,
kCARDINAL,
100 * display.device_scale_factor());
#endif
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// DisplayLayout
DisplayLayout::DisplayLayout()
: position(RIGHT),
offset(0) {}
DisplayLayout::DisplayLayout(DisplayLayout::Position position, int offset)
: position(position),
offset(offset) {
DCHECK_LE(TOP, position);
DCHECK_GE(LEFT, position);
// Set the default value to |position| in case position is invalid. DCHECKs
// above doesn't stop in Release builds.
if (TOP > position || LEFT < position)
this->position = RIGHT;
DCHECK_GE(kMaxValidOffset, abs(offset));
}
DisplayLayout DisplayLayout::Invert() const {
Position inverted_position = RIGHT;
switch (position) {
case TOP:
inverted_position = BOTTOM;
break;
case BOTTOM:
inverted_position = TOP;
break;
case RIGHT:
inverted_position = LEFT;
break;
case LEFT:
inverted_position = RIGHT;
break;
}
return DisplayLayout(inverted_position, -offset);
}
// static
bool DisplayLayout::ConvertFromValue(const base::Value& value,
DisplayLayout* layout) {
base::JSONValueConverter<DisplayLayout> converter;
return converter.Convert(value, layout);
}
// static
bool DisplayLayout::ConvertToValue(const DisplayLayout& layout,
base::Value* value) {
base::DictionaryValue* dict_value = NULL;
if (!value->GetAsDictionary(&dict_value) || dict_value == NULL)
return false;
const std::string position_str = GetStringFromPosition(layout.position);
dict_value->SetString("position", position_str);
dict_value->SetInteger("offset", layout.offset);
return true;
}
std::string DisplayLayout::ToString() const {
const std::string position_str = GetStringFromPosition(position);
return StringPrintf("%s, %d", position_str.c_str(), offset);
}
// static
void DisplayLayout::RegisterJSONConverter(
base::JSONValueConverter<DisplayLayout>* converter) {
converter->RegisterCustomField<Position>(
"position", &DisplayLayout::position, &GetPositionFromString);
converter->RegisterIntField("offset", &DisplayLayout::offset);
}
////////////////////////////////////////////////////////////////////////////////
// DisplayChangeLimiter
DisplayController::DisplayChangeLimiter::DisplayChangeLimiter()
: throttle_timeout_(base::Time::Now()) {
}
void DisplayController::DisplayChangeLimiter::SetThrottleTimeout(
int64 throttle_ms) {
throttle_timeout_ =
base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms);
}
bool DisplayController::DisplayChangeLimiter::IsThrottled() const {
return base::Time::Now() < throttle_timeout_;
}
////////////////////////////////////////////////////////////////////////////////
// DisplayController
DisplayController::DisplayController()
: desired_primary_display_id_(gfx::Display::kInvalidDisplayID),
primary_root_window_for_replace_(NULL) {
#if defined(OS_CHROMEOS)
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kAshDisableDisplayChangeLimiter) &&
base::chromeos::IsRunningOnChromeOS())
limiter_.reset(new DisplayChangeLimiter);
#endif
// Reset primary display to make sure that tests don't use
// stale display info from previous tests.
primary_display_id = gfx::Display::kInvalidDisplayID;
delete primary_display_for_shutdown;
primary_display_for_shutdown = NULL;
num_displays_for_shutdown = -1;
Shell::GetScreen()->AddObserver(this);
}
DisplayController::~DisplayController() {
DCHECK(primary_display_for_shutdown);
}
void DisplayController::Shutdown() {
DCHECK(!primary_display_for_shutdown);
primary_display_for_shutdown = new gfx::Display(
GetDisplayManager()->GetDisplayForId(primary_display_id));
num_displays_for_shutdown = GetDisplayManager()->GetNumDisplays();
Shell::GetScreen()->RemoveObserver(this);
// Delete all root window controllers, which deletes root window
// from the last so that the primary root window gets deleted last.
for (std::map<int64, aura::RootWindow*>::const_reverse_iterator it =
root_windows_.rbegin(); it != root_windows_.rend(); ++it) {
internal::RootWindowController* controller =
GetRootWindowController(it->second);
DCHECK(controller);
delete controller;
}
}
// static
const gfx::Display& DisplayController::GetPrimaryDisplay() {
DCHECK_NE(primary_display_id, gfx::Display::kInvalidDisplayID);
if (primary_display_for_shutdown)
return *primary_display_for_shutdown;
return GetDisplayManager()->GetDisplayForId(primary_display_id);
}
// static
int DisplayController::GetNumDisplays() {
if (num_displays_for_shutdown >= 0)
return num_displays_for_shutdown;
return GetDisplayManager()->GetNumDisplays();
}
// static
bool DisplayController::HasPrimaryDisplay() {
return primary_display_id != gfx::Display::kInvalidDisplayID;
}
void DisplayController::InitPrimaryDisplay() {
const gfx::Display* primary_candidate = GetDisplayManager()->GetDisplayAt(0);
#if defined(OS_CHROMEOS)
if (base::chromeos::IsRunningOnChromeOS()) {
internal::DisplayManager* display_manager = GetDisplayManager();
// On ChromeOS device, root windows are stacked vertically, and
// default primary is the one on top.
int count = display_manager->GetNumDisplays();
int y = primary_candidate->bounds_in_pixel().y();
for (int i = 1; i < count; ++i) {
const gfx::Display* display = display_manager->GetDisplayAt(i);
if (display->IsInternal()) {
primary_candidate = display;
break;
} else if (display->bounds_in_pixel().y() < y) {
primary_candidate = display;
y = display->bounds_in_pixel().y();
}
}
}
#endif
primary_display_id = primary_candidate->id();
AddRootWindowForDisplay(*primary_candidate);
UpdateDisplayBoundsForLayout();
}
void DisplayController::InitSecondaryDisplays() {
internal::DisplayManager* display_manager = GetDisplayManager();
for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
const gfx::Display* display = display_manager->GetDisplayAt(i);
if (primary_display_id != display->id()) {
aura::RootWindow* root = AddRootWindowForDisplay(*display);
Shell::GetInstance()->InitRootWindowForSecondaryDisplay(root);
}
}
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kAshSecondaryDisplayLayout)) {
std::string value = command_line->GetSwitchValueASCII(
switches::kAshSecondaryDisplayLayout);
char layout;
int offset;
if (sscanf(value.c_str(), "%c,%d", &layout, &offset) == 2) {
if (layout == 't')
default_display_layout_.position = DisplayLayout::TOP;
else if (layout == 'b')
default_display_layout_.position = DisplayLayout::BOTTOM;
else if (layout == 'r')
default_display_layout_.position = DisplayLayout::RIGHT;
else if (layout == 'l')
default_display_layout_.position = DisplayLayout::LEFT;
default_display_layout_.offset = offset;
}
}
UpdateDisplayBoundsForLayout();
}
void DisplayController::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void DisplayController::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
aura::RootWindow* DisplayController::GetPrimaryRootWindow() {
DCHECK(!root_windows_.empty());
return root_windows_[primary_display_id];
}
aura::RootWindow* DisplayController::GetRootWindowForDisplayId(int64 id) {
return root_windows_[id];
}
void DisplayController::CloseChildWindows() {
for (std::map<int64, aura::RootWindow*>::const_iterator it =
root_windows_.begin(); it != root_windows_.end(); ++it) {
aura::RootWindow* root_window = it->second;
internal::RootWindowController* controller =
GetRootWindowController(root_window);
if (controller) {
controller->CloseChildWindows();
} else {
while (!root_window->children().empty()) {
aura::Window* child = root_window->children()[0];
delete child;
}
}
}
}
std::vector<aura::RootWindow*> DisplayController::GetAllRootWindows() {
std::vector<aura::RootWindow*> windows;
for (std::map<int64, aura::RootWindow*>::const_iterator it =
root_windows_.begin(); it != root_windows_.end(); ++it) {
DCHECK(it->second);
if (GetRootWindowController(it->second))
windows.push_back(it->second);
}
return windows;
}
gfx::Insets DisplayController::GetOverscanInsets(int64 display_id) const {
return GetDisplayManager()->GetOverscanInsets(display_id);
}
void DisplayController::SetOverscanInsets(int64 display_id,
const gfx::Insets& insets_in_dip) {
GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
}
std::vector<internal::RootWindowController*>
DisplayController::GetAllRootWindowControllers() {
std::vector<internal::RootWindowController*> controllers;
for (std::map<int64, aura::RootWindow*>::const_iterator it =
root_windows_.begin(); it != root_windows_.end(); ++it) {
internal::RootWindowController* controller =
GetRootWindowController(it->second);
if (controller)
controllers.push_back(controller);
}
return controllers;
}
void DisplayController::SetDefaultDisplayLayout(const DisplayLayout& layout) {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kAshSecondaryDisplayLayout) &&
(default_display_layout_.position != layout.position ||
default_display_layout_.offset != layout.offset)) {
default_display_layout_ = layout;
NotifyDisplayConfigurationChanging();
UpdateDisplayBoundsForLayout();
}
}
void DisplayController::SetLayoutForDisplayId(int64 id,
const DisplayLayout& layout) {
DisplayLayout& display_for_id = secondary_layouts_[id];
if (display_for_id.position != layout.position ||
display_for_id.offset != layout.offset) {
secondary_layouts_[id] = layout;
NotifyDisplayConfigurationChanging();
UpdateDisplayBoundsForLayout();
}
}
const DisplayLayout& DisplayController::GetLayoutForDisplay(
const gfx::Display& display) const {
std::map<int64, DisplayLayout>::const_iterator it =
secondary_layouts_.find(display.id());
if (it != secondary_layouts_.end())
return it->second;
return default_display_layout_;
}
const DisplayLayout& DisplayController::GetCurrentDisplayLayout() const {
DCHECK_EQ(2U, GetDisplayManager()->GetNumDisplays());
if (GetDisplayManager()->GetNumDisplays() > 1) {
DisplayController* non_const = const_cast<DisplayController*>(this);
return GetLayoutForDisplay(*(non_const->GetSecondaryDisplay()));
}
// On release build, just fallback to default instead of blowing up.
return default_display_layout_;
}
void DisplayController::CycleDisplayMode() {
if (limiter_.get()) {
if (limiter_->IsThrottled())
return;
limiter_->SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs);
}
#if defined(OS_CHROMEOS)
Shell* shell = Shell::GetInstance();
if (!base::chromeos::IsRunningOnChromeOS()) {
internal::DisplayManager::CycleDisplay();
} else if (shell->output_configurator()->connected_output_count() > 1) {
internal::OutputConfiguratorAnimation* animation =
shell->output_configurator_animation();
animation->StartFadeOutAnimation(base::Bind(
base::IgnoreResult(&chromeos::OutputConfigurator::CycleDisplayMode),
base::Unretained(shell->output_configurator())));
}
#endif
}
void DisplayController::SwapPrimaryDisplay() {
if (limiter_.get()) {
if (limiter_->IsThrottled())
return;
limiter_->SetThrottleTimeout(kSwapDisplayThrottleTimeoutMs);
}
if (Shell::GetScreen()->GetNumDisplays() > 1)
SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
}
void DisplayController::SetPrimaryDisplayId(int64 id) {
desired_primary_display_id_ = id;
if (desired_primary_display_id_ == primary_display_id)
return;
internal::DisplayManager* display_manager = GetDisplayManager();
for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
gfx::Display* display = display_manager->GetDisplayAt(i);
if (display->id() == id) {
SetPrimaryDisplay(*display);
break;
}
}
}
void DisplayController::SetPrimaryDisplay(
const gfx::Display& new_primary_display) {
internal::DisplayManager* display_manager = GetDisplayManager();
DCHECK(new_primary_display.is_valid());
DCHECK(display_manager->IsActiveDisplay(new_primary_display));
if (!new_primary_display.is_valid() ||
!display_manager->IsActiveDisplay(new_primary_display)) {
LOG(ERROR) << "Invalid or non-existent display is requested:"
<< new_primary_display.ToString();
return;
}
if (primary_display_id == new_primary_display.id() ||
root_windows_.size() < 2) {
return;
}
aura::RootWindow* non_primary_root = root_windows_[new_primary_display.id()];
LOG_IF(ERROR, !non_primary_root)
<< "Unknown display is requested in SetPrimaryDisplay: id="
<< new_primary_display.id();
if (!non_primary_root)
return;
gfx::Display old_primary_display = GetPrimaryDisplay();
// Swap root windows between current and new primary display.
aura::RootWindow* primary_root = root_windows_[primary_display_id];
DCHECK(primary_root);
DCHECK_NE(primary_root, non_primary_root);
root_windows_[new_primary_display.id()] = primary_root;
primary_root->SetProperty(internal::kDisplayIdKey, new_primary_display.id());
root_windows_[old_primary_display.id()] = non_primary_root;
non_primary_root->SetProperty(internal::kDisplayIdKey,
old_primary_display.id());
primary_display_id = new_primary_display.id();
desired_primary_display_id_ = primary_display_id;
display_manager->UpdateWorkAreaOfDisplayNearestWindow(
primary_root, old_primary_display.GetWorkAreaInsets());
display_manager->UpdateWorkAreaOfDisplayNearestWindow(
non_primary_root, new_primary_display.GetWorkAreaInsets());
// Update the layout.
SetLayoutForDisplayId(old_primary_display.id(),
GetLayoutForDisplay(new_primary_display).Invert());
// Update the dispay manager with new display info.
std::vector<gfx::Display> displays;
displays.push_back(display_manager->GetDisplayForId(primary_display_id));
displays.push_back(*GetSecondaryDisplay());
GetDisplayManager()->set_force_bounds_changed(true);
GetDisplayManager()->UpdateDisplays(displays);
GetDisplayManager()->set_force_bounds_changed(false);
}
gfx::Display* DisplayController::GetSecondaryDisplay() {
internal::DisplayManager* display_manager = GetDisplayManager();
CHECK_EQ(2U, display_manager->GetNumDisplays());
return display_manager->GetDisplayAt(0)->id() == primary_display_id ?
display_manager->GetDisplayAt(1) : display_manager->GetDisplayAt(0);
}
void DisplayController::OnDisplayBoundsChanged(const gfx::Display& display) {
if (limiter_.get())
limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
NotifyDisplayConfigurationChanging();
UpdateDisplayBoundsForLayout();
aura::RootWindow* root = root_windows_[display.id()];
SetDisplayPropertiesOnHostWindow(root, display);
root->SetHostBounds(display.bounds_in_pixel());
}
void DisplayController::OnDisplayAdded(const gfx::Display& display) {
if (limiter_.get())
limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
NotifyDisplayConfigurationChanging();
if (primary_root_window_for_replace_) {
DCHECK(root_windows_.empty());
primary_display_id = display.id();
root_windows_[display.id()] = primary_root_window_for_replace_;
primary_root_window_for_replace_->SetProperty(
internal::kDisplayIdKey, display.id());
primary_root_window_for_replace_ = NULL;
UpdateDisplayBoundsForLayout();
root_windows_[display.id()]->SetHostBounds(display.bounds_in_pixel());
} else {
DCHECK(!root_windows_.empty());
aura::RootWindow* root = AddRootWindowForDisplay(display);
UpdateDisplayBoundsForLayout();
if (desired_primary_display_id_ == display.id())
SetPrimaryDisplay(display);
Shell::GetInstance()->InitRootWindowForSecondaryDisplay(root);
}
}
void DisplayController::OnDisplayRemoved(const gfx::Display& display) {
if (limiter_.get())
limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
aura::RootWindow* root_to_delete = root_windows_[display.id()];
DCHECK(root_to_delete) << display.ToString();
NotifyDisplayConfigurationChanging();
// Display for root window will be deleted when the Primary RootWindow
// is deleted by the Shell.
root_windows_.erase(display.id());
// When the primary root window's display is removed, move the primary
// root to the other display.
if (primary_display_id == display.id()) {
// Temporarily store the primary root window in
// |primary_root_window_for_replace_| when replacing the display.
if (root_windows_.size() == 0) {
primary_display_id = gfx::Display::kInvalidDisplayID;
primary_root_window_for_replace_ = root_to_delete;
return;
}
DCHECK_EQ(1U, root_windows_.size());
primary_display_id = GetSecondaryDisplay()->id();
aura::RootWindow* primary_root = root_to_delete;
// Delete the other root instead.
root_to_delete = root_windows_[primary_display_id];
root_to_delete->SetProperty(internal::kDisplayIdKey, display.id());
// Setup primary root.
root_windows_[primary_display_id] = primary_root;
primary_root->SetProperty(internal::kDisplayIdKey, primary_display_id);
OnDisplayBoundsChanged(
GetDisplayManager()->GetDisplayForId(primary_display_id));
}
internal::RootWindowController* controller =
GetRootWindowController(root_to_delete);
DCHECK(controller);
controller->MoveWindowsTo(GetPrimaryRootWindow());
// Delete most of root window related objects, but don't delete
// root window itself yet because the stack may be using it.
controller->Shutdown();
MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
}
aura::RootWindow* DisplayController::AddRootWindowForDisplay(
const gfx::Display& display) {
aura::RootWindow* root =
GetDisplayManager()->CreateRootWindowForDisplay(display);
root_windows_[display.id()] = root;
SetDisplayPropertiesOnHostWindow(root, display);
#if defined(OS_CHROMEOS)
static bool force_constrain_pointer_to_root =
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAshConstrainPointerToRoot);
if (base::chromeos::IsRunningOnChromeOS() || force_constrain_pointer_to_root)
root->ConfineCursorToWindow();
#endif
return root;
}
void DisplayController::UpdateDisplayBoundsForLayout() {
if (Shell::GetScreen()->GetNumDisplays() <= 1)
return;
DCHECK_EQ(2, Shell::GetScreen()->GetNumDisplays());
const gfx::Rect& primary_bounds = GetPrimaryDisplay().bounds();
gfx::Display* secondary_display = GetSecondaryDisplay();
const gfx::Rect& secondary_bounds = secondary_display->bounds();
gfx::Point new_secondary_origin = primary_bounds.origin();
const DisplayLayout& layout = GetLayoutForDisplay(*secondary_display);
DisplayLayout::Position position = layout.position;
// Ignore the offset in case the secondary display doesn't share edges with
// the primary display.
int offset = layout.offset;
if (position == DisplayLayout::TOP || position == DisplayLayout::BOTTOM) {
offset = std::min(
offset, primary_bounds.width() - kMinimumOverlapForInvalidOffset);
offset = std::max(
offset, -secondary_bounds.width() + kMinimumOverlapForInvalidOffset);
} else {
offset = std::min(
offset, primary_bounds.height() - kMinimumOverlapForInvalidOffset);
offset = std::max(
offset, -secondary_bounds.height() + kMinimumOverlapForInvalidOffset);
}
switch (position) {
case DisplayLayout::TOP:
new_secondary_origin.Offset(offset, -secondary_bounds.height());
break;
case DisplayLayout::RIGHT:
new_secondary_origin.Offset(primary_bounds.width(), offset);
break;
case DisplayLayout::BOTTOM:
new_secondary_origin.Offset(offset, primary_bounds.height());
break;
case DisplayLayout::LEFT:
new_secondary_origin.Offset(-secondary_bounds.width(), offset);<|fim▁hole|> }
gfx::Insets insets = secondary_display->GetWorkAreaInsets();
secondary_display->set_bounds(
gfx::Rect(new_secondary_origin, secondary_bounds.size()));
secondary_display->UpdateWorkAreaFromInsets(insets);
}
void DisplayController::NotifyDisplayConfigurationChanging() {
FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging());
}
} // namespace ash<|fim▁end|> | break; |
<|file_name|>evaluate_quiz.py<|end_file_name|><|fim▁begin|>import os
import sys
import json
from datetime import datetime
from django.db import connection, transaction
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from fly_project import constants
from api.models import QuizSubmission
from api.models import QuestionSubmission
class Command(BaseCommand):
"""
Run in your console:
$ python manage.py evaluate_quiz {{ quiz_submission_id }}
"""
help = _('Command will mark and score the User\'s submitted quiz.')
def add_arguments(self, parser):
parser.add_argument('id', nargs='+')
def handle(self, *args, **options):
# Process all the Quizzes that are inputted into this Command.
for id in options['id']:
try:
submission = QuizSubmission.objects.get(id=id)
self.begin_processing(submission)
except QuizSubmission.DoesNotExist:
pass
def begin_processing(self, submission):
"""
Function will load up the Quiz Submission and iterate through all
Question Submissions and evaluate them for being either correct
or wrong and then assign a mark to them.
"""
# Step 1: Fetch all the submitted Questions for this Quiz.
try:
question_submissions = QuestionSubmission.objects.filter(
quiz=submission.quiz,
user=submission.user,
)
except QuestionSubmission.DoesNotExist:
question_submissions = None
# Step 2: Iterate through all the submitted Questions and mark them
# either right or wrong depending on the correct answer.
for question_submission in question_submissions.all():
is_right = True
question_answer = question_submission.question
# Step 3: If the question is 'Open-ended' then simply give the
# student the mark and finish this function, else then
# evaluate the quiz question.
if question_submission.type == 1:
question_submission.mark = 1
else:
if question_submission.a is not question_answer.a_is_correct:
is_right = False
if question_submission.b is not question_answer.b_is_correct:
is_right = False
if question_submission.c is not question_answer.c_is_correct:
is_right = False<|fim▁hole|> is_right = False
if question_submission.e is not question_answer.e_is_correct:
is_right = False
if question_submission.f is not question_answer.f_is_correct:
is_right = False
if is_right:
question_submission.mark = 1
else:
question_submission.mark = 0
question_submission.save()
# Step 4: Iterate through all the submitted Questions and perform a
# total mark tally of the Quiz and then mark the Quiz either a success
# or a failure.
total_mark = 0
actual_mark = 0
for question_submission in question_submissions.all():
total_mark += 1
actual_mark += question_submission.mark
final_mark = (actual_mark / total_mark) * 100
submission.final_mark = final_mark
submission.save()<|fim▁end|> | if question_submission.d is not question_answer.d_is_correct: |
<|file_name|>assertion_suite_test.go<|end_file_name|><|fim▁begin|>package assertion_test
import (
. "github.com/chai2010/gopkg/database/leveldb/internal/ginkgo"
. "github.com/chai2010/gopkg/database/leveldb/internal/gomega"
"testing"
)
func TestAssertion(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Assertion Suite")<|fim▁hole|><|fim▁end|> | } |
<|file_name|>issue-3860.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.
struct Foo { x: int }
impl Foo {
pub fn stuff<'a>(&'a mut self) -> &'a mut Foo {<|fim▁hole|>}
pub fn main() {
let x = @mut Foo { x: 3 };
// Neither of the next two lines should cause an error
let _ = x.stuff();
x.stuff();
}<|fim▁end|> | return self;
} |
<|file_name|>getters.js<|end_file_name|><|fim▁begin|>export default {
// 购物车的商品数量<|fim▁hole|> cartCommodityCount: state => {
const totalCount = state.cartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
},
removeCommodityCount: state => {
const totalCount = state.removeCartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
}
}<|fim▁end|> | |
<|file_name|>common.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011-2013 Martijn Kaijser
#
# 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 xbmc
import xbmcaddon
### get addon info
__addon__ = xbmcaddon.Addon(id='script.artwork.downloader')<|fim▁hole|>__version__ = __addon__.getAddonInfo('version')
__addonpath__ = __addon__.getAddonInfo('path')
__addonprofile__= xbmc.translatePath(__addon__.getAddonInfo('profile')).decode('utf-8')
__icon__ = __addon__.getAddonInfo('icon')
__localize__ = __addon__.getLocalizedString<|fim▁end|> | __addonid__ = __addon__.getAddonInfo('id')
__addonname__ = __addon__.getAddonInfo('name')
__author__ = __addon__.getAddonInfo('author') |
<|file_name|>TermsAndConditionsAcceptanceStatusCollectionPage.java<|end_file_name|><|fim▁begin|>// Template Source: BaseEntityCollectionPage.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.TermsAndConditionsAcceptanceStatus;
import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionRequestBuilder;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionResponse;
import com.microsoft.graph.http.BaseCollectionPage;
<|fim▁hole|>// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Terms And Conditions Acceptance Status Collection Page.
*/
public class TermsAndConditionsAcceptanceStatusCollectionPage extends BaseCollectionPage<TermsAndConditionsAcceptanceStatus, TermsAndConditionsAcceptanceStatusCollectionRequestBuilder> {
/**
* A collection page for TermsAndConditionsAcceptanceStatus
*
* @param response the serialized TermsAndConditionsAcceptanceStatusCollectionResponse from the service
* @param builder the request builder for the next collection page
*/
public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final TermsAndConditionsAcceptanceStatusCollectionResponse response, @Nonnull final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder builder) {
super(response, builder);
}
/**
* Creates the collection page for TermsAndConditionsAcceptanceStatus
*
* @param pageContents the contents of this page
* @param nextRequestBuilder the request builder for the next page
*/
public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final java.util.List<TermsAndConditionsAcceptanceStatus> pageContents, @Nullable final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder nextRequestBuilder) {
super(pageContents, nextRequestBuilder);
}
}<|fim▁end|> | |
<|file_name|>fleetworkspace.go<|end_file_name|><|fim▁begin|>/*
Copyright 2021 Rancher Labs, 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.
*/
// Code generated by main. DO NOT EDIT.
package v3
import (
"context"
"time"
"github.com/rancher/lasso/pkg/client"
"github.com/rancher/lasso/pkg/controller"
v3 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
"github.com/rancher/wrangler/pkg/apply"
"github.com/rancher/wrangler/pkg/condition"
"github.com/rancher/wrangler/pkg/generic"
"github.com/rancher/wrangler/pkg/kv"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
)
type FleetWorkspaceHandler func(string, *v3.FleetWorkspace) (*v3.FleetWorkspace, error)
type FleetWorkspaceController interface {
generic.ControllerMeta
FleetWorkspaceClient
OnChange(ctx context.Context, name string, sync FleetWorkspaceHandler)
OnRemove(ctx context.Context, name string, sync FleetWorkspaceHandler)
Enqueue(name string)
EnqueueAfter(name string, duration time.Duration)
Cache() FleetWorkspaceCache
}
type FleetWorkspaceClient interface {
Create(*v3.FleetWorkspace) (*v3.FleetWorkspace, error)
Update(*v3.FleetWorkspace) (*v3.FleetWorkspace, error)
UpdateStatus(*v3.FleetWorkspace) (*v3.FleetWorkspace, error)
Delete(name string, options *metav1.DeleteOptions) error
Get(name string, options metav1.GetOptions) (*v3.FleetWorkspace, error)
List(opts metav1.ListOptions) (*v3.FleetWorkspaceList, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v3.FleetWorkspace, err error)
}
type FleetWorkspaceCache interface {
Get(name string) (*v3.FleetWorkspace, error)
List(selector labels.Selector) ([]*v3.FleetWorkspace, error)
AddIndexer(indexName string, indexer FleetWorkspaceIndexer)
GetByIndex(indexName, key string) ([]*v3.FleetWorkspace, error)
}
type FleetWorkspaceIndexer func(obj *v3.FleetWorkspace) ([]string, error)
type fleetWorkspaceController struct {
controller controller.SharedController
client *client.Client
gvk schema.GroupVersionKind
groupResource schema.GroupResource
}
func NewFleetWorkspaceController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) FleetWorkspaceController {
c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced)
return &fleetWorkspaceController{
controller: c,
client: c.Client(),
gvk: gvk,
groupResource: schema.GroupResource{
Group: gvk.Group,
Resource: resource,
},
}
}
func FromFleetWorkspaceHandlerToHandler(sync FleetWorkspaceHandler) generic.Handler {
return func(key string, obj runtime.Object) (ret runtime.Object, err error) {
var v *v3.FleetWorkspace
if obj == nil {
v, err = sync(key, nil)
} else {
v, err = sync(key, obj.(*v3.FleetWorkspace))
}
if v == nil {
return nil, err
}
return v, err
}
}
func (c *fleetWorkspaceController) Updater() generic.Updater {
return func(obj runtime.Object) (runtime.Object, error) {
newObj, err := c.Update(obj.(*v3.FleetWorkspace))
if newObj == nil {
return nil, err
}
return newObj, err
}
}
func UpdateFleetWorkspaceDeepCopyOnChange(client FleetWorkspaceClient, obj *v3.FleetWorkspace, handler func(obj *v3.FleetWorkspace) (*v3.FleetWorkspace, error)) (*v3.FleetWorkspace, error) {
if obj == nil {
return obj, nil
}
copyObj := obj.DeepCopy()
newObj, err := handler(copyObj)
if newObj != nil {
copyObj = newObj
}
if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) {
return client.Update(copyObj)
}
return copyObj, err
}
func (c *fleetWorkspaceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) {
c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler))
}
func (c *fleetWorkspaceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) {
c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler))
}
func (c *fleetWorkspaceController) OnChange(ctx context.Context, name string, sync FleetWorkspaceHandler) {
c.AddGenericHandler(ctx, name, FromFleetWorkspaceHandlerToHandler(sync))
}
func (c *fleetWorkspaceController) OnRemove(ctx context.Context, name string, sync FleetWorkspaceHandler) {
c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromFleetWorkspaceHandlerToHandler(sync)))
}
func (c *fleetWorkspaceController) Enqueue(name string) {
c.controller.Enqueue("", name)
}
func (c *fleetWorkspaceController) EnqueueAfter(name string, duration time.Duration) {
c.controller.EnqueueAfter("", name, duration)
}
func (c *fleetWorkspaceController) Informer() cache.SharedIndexInformer {
return c.controller.Informer()
}
func (c *fleetWorkspaceController) GroupVersionKind() schema.GroupVersionKind {
return c.gvk
}
func (c *fleetWorkspaceController) Cache() FleetWorkspaceCache {<|fim▁hole|> }
}
func (c *fleetWorkspaceController) Create(obj *v3.FleetWorkspace) (*v3.FleetWorkspace, error) {
result := &v3.FleetWorkspace{}
return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{})
}
func (c *fleetWorkspaceController) Update(obj *v3.FleetWorkspace) (*v3.FleetWorkspace, error) {
result := &v3.FleetWorkspace{}
return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{})
}
func (c *fleetWorkspaceController) UpdateStatus(obj *v3.FleetWorkspace) (*v3.FleetWorkspace, error) {
result := &v3.FleetWorkspace{}
return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{})
}
func (c *fleetWorkspaceController) Delete(name string, options *metav1.DeleteOptions) error {
if options == nil {
options = &metav1.DeleteOptions{}
}
return c.client.Delete(context.TODO(), "", name, *options)
}
func (c *fleetWorkspaceController) Get(name string, options metav1.GetOptions) (*v3.FleetWorkspace, error) {
result := &v3.FleetWorkspace{}
return result, c.client.Get(context.TODO(), "", name, result, options)
}
func (c *fleetWorkspaceController) List(opts metav1.ListOptions) (*v3.FleetWorkspaceList, error) {
result := &v3.FleetWorkspaceList{}
return result, c.client.List(context.TODO(), "", result, opts)
}
func (c *fleetWorkspaceController) Watch(opts metav1.ListOptions) (watch.Interface, error) {
return c.client.Watch(context.TODO(), "", opts)
}
func (c *fleetWorkspaceController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v3.FleetWorkspace, error) {
result := &v3.FleetWorkspace{}
return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...)
}
type fleetWorkspaceCache struct {
indexer cache.Indexer
resource schema.GroupResource
}
func (c *fleetWorkspaceCache) Get(name string) (*v3.FleetWorkspace, error) {
obj, exists, err := c.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(c.resource, name)
}
return obj.(*v3.FleetWorkspace), nil
}
func (c *fleetWorkspaceCache) List(selector labels.Selector) (ret []*v3.FleetWorkspace, err error) {
err = cache.ListAll(c.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v3.FleetWorkspace))
})
return ret, err
}
func (c *fleetWorkspaceCache) AddIndexer(indexName string, indexer FleetWorkspaceIndexer) {
utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{
indexName: func(obj interface{}) (strings []string, e error) {
return indexer(obj.(*v3.FleetWorkspace))
},
}))
}
func (c *fleetWorkspaceCache) GetByIndex(indexName, key string) (result []*v3.FleetWorkspace, err error) {
objs, err := c.indexer.ByIndex(indexName, key)
if err != nil {
return nil, err
}
result = make([]*v3.FleetWorkspace, 0, len(objs))
for _, obj := range objs {
result = append(result, obj.(*v3.FleetWorkspace))
}
return result, nil
}
type FleetWorkspaceStatusHandler func(obj *v3.FleetWorkspace, status v3.FleetWorkspaceStatus) (v3.FleetWorkspaceStatus, error)
type FleetWorkspaceGeneratingHandler func(obj *v3.FleetWorkspace, status v3.FleetWorkspaceStatus) ([]runtime.Object, v3.FleetWorkspaceStatus, error)
func RegisterFleetWorkspaceStatusHandler(ctx context.Context, controller FleetWorkspaceController, condition condition.Cond, name string, handler FleetWorkspaceStatusHandler) {
statusHandler := &fleetWorkspaceStatusHandler{
client: controller,
condition: condition,
handler: handler,
}
controller.AddGenericHandler(ctx, name, FromFleetWorkspaceHandlerToHandler(statusHandler.sync))
}
func RegisterFleetWorkspaceGeneratingHandler(ctx context.Context, controller FleetWorkspaceController, apply apply.Apply,
condition condition.Cond, name string, handler FleetWorkspaceGeneratingHandler, opts *generic.GeneratingHandlerOptions) {
statusHandler := &fleetWorkspaceGeneratingHandler{
FleetWorkspaceGeneratingHandler: handler,
apply: apply,
name: name,
gvk: controller.GroupVersionKind(),
}
if opts != nil {
statusHandler.opts = *opts
}
controller.OnChange(ctx, name, statusHandler.Remove)
RegisterFleetWorkspaceStatusHandler(ctx, controller, condition, name, statusHandler.Handle)
}
type fleetWorkspaceStatusHandler struct {
client FleetWorkspaceClient
condition condition.Cond
handler FleetWorkspaceStatusHandler
}
func (a *fleetWorkspaceStatusHandler) sync(key string, obj *v3.FleetWorkspace) (*v3.FleetWorkspace, error) {
if obj == nil {
return obj, nil
}
origStatus := obj.Status.DeepCopy()
obj = obj.DeepCopy()
newStatus, err := a.handler(obj, obj.Status)
if err != nil {
// Revert to old status on error
newStatus = *origStatus.DeepCopy()
}
if a.condition != "" {
if errors.IsConflict(err) {
a.condition.SetError(&newStatus, "", nil)
} else {
a.condition.SetError(&newStatus, "", err)
}
}
if !equality.Semantic.DeepEqual(origStatus, &newStatus) {
if a.condition != "" {
// Since status has changed, update the lastUpdatedTime
a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339))
}
var newErr error
obj.Status = newStatus
newObj, newErr := a.client.UpdateStatus(obj)
if err == nil {
err = newErr
}
if newErr == nil {
obj = newObj
}
}
return obj, err
}
type fleetWorkspaceGeneratingHandler struct {
FleetWorkspaceGeneratingHandler
apply apply.Apply
opts generic.GeneratingHandlerOptions
gvk schema.GroupVersionKind
name string
}
func (a *fleetWorkspaceGeneratingHandler) Remove(key string, obj *v3.FleetWorkspace) (*v3.FleetWorkspace, error) {
if obj != nil {
return obj, nil
}
obj = &v3.FleetWorkspace{}
obj.Namespace, obj.Name = kv.RSplit(key, "/")
obj.SetGroupVersionKind(a.gvk)
return nil, generic.ConfigureApplyForObject(a.apply, obj, &a.opts).
WithOwner(obj).
WithSetID(a.name).
ApplyObjects()
}
func (a *fleetWorkspaceGeneratingHandler) Handle(obj *v3.FleetWorkspace, status v3.FleetWorkspaceStatus) (v3.FleetWorkspaceStatus, error) {
objs, newStatus, err := a.FleetWorkspaceGeneratingHandler(obj, status)
if err != nil {
return newStatus, err
}
return newStatus, generic.ConfigureApplyForObject(a.apply, obj, &a.opts).
WithOwner(obj).
WithSetID(a.name).
ApplyObjects(objs...)
}<|fim▁end|> | return &fleetWorkspaceCache{
indexer: c.Informer().GetIndexer(),
resource: c.groupResource, |
<|file_name|>dist.py<|end_file_name|><|fim▁begin|>"""distutils.dist
Provides the Distribution class, which represents the module distribution
being built/installed/distributed.
"""
import sys, os, re
try:
import warnings
except ImportError:
warnings = None
from distutils.errors import *
from distutils.fancy_getopt import FancyGetopt, translate_longopt
from distutils.util import check_environ, strtobool, rfc822_escape
from distutils import log
from distutils.debug import DEBUG
# Regex to define acceptable Distutils command names. This is not *quite*
# the same as a Python NAME -- I don't allow leading underscores. The fact
# that they're very similar is no coincidence; the default naming scheme is
# to look for a Python module named after the command.
command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
class Distribution:
"""The core of the Distutils. Most of the work hiding behind 'setup'
is really done within a Distribution instance, which farms the work out
to the Distutils commands specified on the command line.
Setup scripts will almost never instantiate Distribution directly,
unless the 'setup()' function is totally inadequate to their needs.
However, it is conceivable that a setup script might wish to subclass
Distribution for some specialized purpose, and then pass the subclass
to 'setup()' as the 'distclass' keyword argument. If so, it is
necessary to respect the expectations that 'setup' has of Distribution.
See the code for 'setup()', in core.py, for details.
"""
# 'global_options' describes the command-line options that may be
# supplied to the setup script prior to any actual commands.
# Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
# these global options. This list should be kept to a bare minimum,
# since every global option is also valid as a command option -- and we
# don't want to pollute the commands with too many options that they
# have minimal control over.
# The fourth entry for verbose means that it can be repeated.
global_options = [('verbose', 'v', "run verbosely (default)", 1),
('quiet', 'q', "run quietly (turns verbosity off)"),
('dry-run', 'n', "don't actually do anything"),
('help', 'h', "show detailed help message"),
]
# 'common_usage' is a short (2-3 line) string describing the common
# usage of the setup script.
common_usage = """\
Common commands: (see '--help-commands' for more)
setup.py build will build the package underneath 'build/'
setup.py install will install the package
"""
# options that are not propagated to the commands
display_options = [
('help-commands', None,
"list all available commands"),
('name', None,
"print package name"),
('version', 'V',
"print package version"),
('fullname', None,
"print <package name>-<version>"),
('author', None,
"print the author's name"),
('author-email', None,
"print the author's email address"),
('maintainer', None,
"print the maintainer's name"),
('maintainer-email', None,
"print the maintainer's email address"),
('contact', None,
"print the maintainer's name if known, else the author's"),
('contact-email', None,
"print the maintainer's email address if known, else the author's"),
('url', None,
"print the URL for this package"),
('license', None,
"print the license of the package"),
('licence', None,
"alias for --license"),
('description', None,
"print the package description"),
('long-description', None,
"print the long package description"),
('platforms', None,
"print the list of platforms"),
('classifiers', None,
"print the list of classifiers"),
('keywords', None,
"print the list of keywords"),
('provides', None,
"print the list of packages/modules provided"),
('requires', None,
"print the list of packages/modules required"),
('obsoletes', None,
"print the list of packages/modules made obsolete")
]
display_option_names = [translate_longopt(x[0]) for x in display_options]
# negative options are options that exclude other options
negative_opt = {'quiet': 'verbose'}
# -- Creation/initialization methods -------------------------------
def __init__ (self, attrs=None):
"""Construct a new Distribution instance: initialize all the
attributes of a Distribution, and then use 'attrs' (a dictionary
mapping attribute names to values) to assign some of those
attributes their "real" values. (Any attributes not mentioned in
'attrs' will be assigned to some null value: 0, None, an empty list
or dictionary, etc.) Most importantly, initialize the
'command_obj' attribute to the empty dictionary; this will be
filled in with real command objects by 'parse_command_line()'.
"""
# Default values for our command-line options
self.verbose = 1
self.dry_run = 0
self.help = 0
for attr in self.display_option_names:
setattr(self, attr, 0)
# Store the distribution meta-data (name, version, author, and so
# forth) in a separate object -- we're getting to have enough
# information here (and enough command-line options) that it's
# worth it. Also delegate 'get_XXX()' methods to the 'metadata'
# object in a sneaky and underhanded (but efficient!) way.
self.metadata = DistributionMetadata()
for basename in self.metadata._METHOD_BASENAMES:
method_name = "get_" + basename
setattr(self, method_name, getattr(self.metadata, method_name))
# 'cmdclass' maps command names to class objects, so we
# can 1) quickly figure out which class to instantiate when
# we need to create a new command object, and 2) have a way
# for the setup script to override command classes
self.cmdclass = {}
# 'command_packages' is a list of packages in which commands
# are searched for. The factory for command 'foo' is expected
# to be named 'foo' in the module 'foo' in one of the packages
# named here. This list is searched from the left; an error
# is raised if no named package provides the command being
# searched for. (Always access using get_command_packages().)
self.command_packages = None
# 'script_name' and 'script_args' are usually set to sys.argv[0]
# and sys.argv[1:], but they can be overridden when the caller is
# not necessarily a setup script run from the command-line.
self.script_name = None
self.script_args = None
# 'command_options' is where we store command options between
# parsing them (from config files, the command-line, etc.) and when
# they are actually needed -- ie. when the command in question is
# instantiated. It is a dictionary of dictionaries of 2-tuples:
# command_options = { command_name : { option : (source, value) } }
self.command_options = {}
# 'dist_files' is the list of (command, pyversion, file) that
# have been created by any dist commands run so far. This is
# filled regardless of whether the run is dry or not. pyversion
# gives sysconfig.get_python_version() if the dist file is
# specific to a Python version, 'any' if it is good for all
# Python versions on the target platform, and '' for a source
# file. pyversion should not be used to specify minimum or
# maximum required Python versions; use the metainfo for that
# instead.
self.dist_files = []
# These options are really the business of various commands, rather
# than of the Distribution itself. We provide aliases for them in
# Distribution as a convenience to the developer.
self.packages = None
self.package_data = {}
self.package_dir = None
self.py_modules = None
self.libraries = None
self.headers = None
self.ext_modules = None
self.ext_package = None
self.include_dirs = None
self.extra_path = None
self.scripts = None
self.data_files = None
self.password = ''
# And now initialize bookkeeping stuff that can't be supplied by
# the caller at all. 'command_obj' maps command names to
# Command instances -- that's how we enforce that every command
# class is a singleton.
self.command_obj = {}
# 'have_run' maps command names to boolean values; it keeps track
# of whether we have actually run a particular command, to make it
# cheap to "run" a command whenever we think we might need to -- if
# it's already been done, no need for expensive filesystem
# operations, we just check the 'have_run' dictionary and carry on.
# It's only safe to query 'have_run' for a command class that has
# been instantiated -- a false value will be inserted when the
# command object is created, and replaced with a true value when
# the command is successfully run. Thus it's probably best to use
# '.get()' rather than a straight lookup.
self.have_run = {}
# Now we'll use the attrs dictionary (ultimately, keyword args from
# the setup script) to possibly override any or all of these
# distribution options.
if attrs:
# Pull out the set of command options and work on them
# specifically. Note that this order guarantees that aliased
# command options will override any supplied redundantly
# through the general options dictionary.
options = attrs.get('options')
if options is not None:
del attrs['options']
for (command, cmd_options) in options.items():
opt_dict = self.get_option_dict(command)
for (opt, val) in cmd_options.items():
opt_dict[opt] = ("setup script", val)
if 'licence' in attrs:
attrs['license'] = attrs['licence']
del attrs['licence']
msg = "'licence' distribution option is deprecated; use 'license'"
if warnings is not None:
warnings.warn(msg)
else:
sys.stderr.write(msg + "\n")
# Now work on the rest of the attributes. Any attribute that's
# not already defined is invalid!
for (key, val) in attrs.items():
if hasattr(self.metadata, "set_" + key):
getattr(self.metadata, "set_" + key)(val)
elif hasattr(self.metadata, key):
setattr(self.metadata, key, val)
elif hasattr(self, key):
setattr(self, key, val)
else:
msg = "Unknown distribution option: %s" % repr(key)
if warnings is not None:
warnings.warn(msg)
else:
sys.stderr.write(msg + "\n")
self.finalize_options()
def get_option_dict(self, command):
"""Get the option dictionary for a given command. If that
command's option dictionary hasn't been created yet, then create it
and return the new dictionary; otherwise, return the existing
option dictionary.
"""
dict = self.command_options.get(command)
if dict is None:
dict = self.command_options[command] = {}
return dict
def dump_option_dicts(self, header=None, commands=None, indent=""):
from pprint import pformat
if commands is None: # dump all command option dicts
commands = sorted(self.command_options.keys())
if header is not None:
self.announce(indent + header)
indent = indent + " "
if not commands:
self.announce(indent + "no commands known yet")
return
for cmd_name in commands:
opt_dict = self.command_options.get(cmd_name)
if opt_dict is None:
self.announce(indent +
"no option dict for '%s' command" % cmd_name)
else:
self.announce(indent +
"option dict for '%s' command:" % cmd_name)
out = pformat(opt_dict)
for line in out.split('\n'):
self.announce(indent + " " + line)
# -- Config file finding/parsing methods ---------------------------
def find_config_files(self):
"""Find as many configuration files as should be processed for this
platform, and return a list of filenames in the order in which they
should be parsed. The filenames returned are guaranteed to exist
(modulo nasty race conditions).
There are three possible config files: distutils.cfg in the
Distutils installation directory (ie. where the top-level
Distutils __inst__.py file lives), a file in the user's home
directory named .pydistutils.cfg on Unix and pydistutils.cfg
on Windows/Mac, and setup.cfg in the current directory.
"""
files = []
check_environ()
# Where to look for the system-wide Distutils config file
sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
# Look for the system config file
sys_file = os.path.join(sys_dir, "distutils.cfg")
if os.path.isfile(sys_file):
files.append(sys_file)
# What to call the per-user config file
if os.name == 'posix':
user_filename = ".pydistutils.cfg"
else:
user_filename = "pydistutils.cfg"
# And look for the user config file
user_file = os.path.join(os.path.expanduser('~'), user_filename)
if os.path.isfile(user_file):
files.append(user_file)
# All platforms support local setup.cfg
local_file = "setup.cfg"
if os.path.isfile(local_file):
files.append(local_file)
return files
def parse_config_files(self, filenames=None):
from configparser import ConfigParser
if filenames is None:
filenames = self.find_config_files()
if DEBUG:
self.announce("Distribution.parse_config_files():")
parser = ConfigParser()
for filename in filenames:
if DEBUG:
self.announce(" reading %s" % filename)
parser.read(filename)
for section in parser.sections():
options = parser.options(section)
opt_dict = self.get_option_dict(section)
for opt in options:
if opt != '__name__':
val = parser.get(section,opt)
opt = opt.replace('-', '_')
opt_dict[opt] = (filename, val)
# Make the ConfigParser forget everything (so we retain
# the original filenames that options come from)
parser.__init__()
# If there was a "global" section in the config file, use it
# to set Distribution options.
if 'global' in self.command_options:
for (opt, (src, val)) in self.command_options['global'].items():
alias = self.negative_opt.get(opt)
try:
if alias:
setattr(self, alias, not strtobool(val))
elif opt in ('verbose', 'dry_run'): # ugh!
setattr(self, opt, strtobool(val))
else:
setattr(self, opt, val)
except ValueError as msg:
raise DistutilsOptionError(msg)
# -- Command-line parsing methods ----------------------------------
def parse_command_line(self):
"""Parse the setup script's command line, taken from the
'script_args' instance attribute (which defaults to 'sys.argv[1:]'
-- see 'setup()' in core.py). This list is first processed for
"global options" -- options that set attributes of the Distribution
instance. Then, it is alternately scanned for Distutils commands
and options for that command. Each new command terminates the
options for the previous command. The allowed options for a
command are determined by the 'user_options' attribute of the
command class -- thus, we have to be able to load command classes
in order to parse the command line. Any error in that 'options'
attribute raises DistutilsGetoptError; any error on the
command-line raises DistutilsArgError. If no Distutils commands
were found on the command line, raises DistutilsArgError. Return
true if command-line was successfully parsed and we should carry
on with executing commands; false if no errors but we shouldn't
execute commands (currently, this only happens if user asks for
help).
"""
#
# We now have enough information to show the Macintosh dialog
# that allows the user to interactively specify the "command line".
#
toplevel_options = self._get_toplevel_options()
# We have to parse the command line a bit at a time -- global
# options, then the first command, then its options, and so on --
# because each command will be handled by a different class, and
# the options that are valid for a particular class aren't known
# until we have loaded the command class, which doesn't happen
# until we know what the command is.
self.commands = []
parser = FancyGetopt(toplevel_options + self.display_options)
parser.set_negative_aliases(self.negative_opt)
parser.set_aliases({'licence': 'license'})
args = parser.getopt(args=self.script_args, object=self)
option_order = parser.get_option_order()
log.set_verbosity(self.verbose)
# for display options we return immediately
if self.handle_display_options(option_order):
return
while args:
args = self._parse_command_opts(parser, args)
if args is None: # user asked for help (and got it)
return
# Handle the cases of --help as a "global" option, ie.
# "setup.py --help" and "setup.py --help command ...". For the
# former, we show global options (--verbose, --dry-run, etc.)
# and display-only options (--name, --version, etc.); for the
# latter, we omit the display-only options and show help for
# each command listed on the command line.
if self.help:
self._show_help(parser,
display_options=len(self.commands) == 0,
commands=self.commands)
return
# Oops, no commands found -- an end-user error
if not self.commands:
raise DistutilsArgError("no commands supplied")
# All is well: return true
return True
def _get_toplevel_options(self):
"""Return the non-display options recognized at the top level.
This includes options that are recognized *only* at the top
level as well as options recognized for commands.
"""
return self.global_options + [
("command-packages=", None,
"list of packages that provide distutils commands"),
]
def _parse_command_opts(self, parser, args):
"""Parse the command-line options for a single command.
'parser' must be a FancyGetopt instance; 'args' must be the list
of arguments, starting with the current command (whose options
we are about to parse). Returns a new version of 'args' with
the next command at the front of the list; will be the empty
list if there are no more commands on the command line. Returns
None if the user asked for help on this command.
"""
# late import because of mutual dependence between these modules
from distutils.cmd import Command
# Pull the current command from the head of the command line
command = args[0]
if not command_re.match(command):
raise SystemExit("invalid command name '%s'" % command)
self.commands.append(command)
# Dig up the command class that implements this command, so we
# 1) know that it's a valid command, and 2) know which options
# it takes.
try:
cmd_class = self.get_command_class(command)
except DistutilsModuleError as msg:
raise DistutilsArgError(msg)
# Require that the command class be derived from Command -- want
# to be sure that the basic "command" interface is implemented.
if not issubclass(cmd_class, Command):
raise DistutilsClassError(
"command class %s must subclass Command" % cmd_class)
# Also make sure that the command object provides a list of its
# known options.
if not (hasattr(cmd_class, 'user_options') and
isinstance(cmd_class.user_options, list)):
raise DistutilsClassError(("command class %s must provide " +
"'user_options' attribute (a list of tuples)") % \
cmd_class)
# If the command class has a list of negative alias options,
# merge it in with the global negative aliases.
negative_opt = self.negative_opt
if hasattr(cmd_class, 'negative_opt'):
negative_opt = negative_opt.copy()
negative_opt.update(cmd_class.negative_opt)
# Check for help_options in command class. They have a different
# format (tuple of four) so we need to preprocess them here.
if (hasattr(cmd_class, 'help_options') and
isinstance(cmd_class.help_options, list)):
help_options = fix_help_options(cmd_class.help_options)
else:
help_options = []
# All commands support the global options too, just by adding
# in 'global_options'.
parser.set_option_table(self.global_options +
cmd_class.user_options +
help_options)
parser.set_negative_aliases(negative_opt)
(args, opts) = parser.getopt(args[1:])
if hasattr(opts, 'help') and opts.help:
self._show_help(parser, display_options=0, commands=[cmd_class])
return
if (hasattr(cmd_class, 'help_options') and
isinstance(cmd_class.help_options, list)):
help_option_found=0
for (help_option, short, desc, func) in cmd_class.help_options:
if hasattr(opts, parser.get_attr_name(help_option)):
help_option_found=1
if hasattr(func, '__call__'):
func()
else:
raise DistutilsClassError(
"invalid help function %r for help option '%s': "
"must be a callable object (function, etc.)"
% (func, help_option))
if help_option_found:
return
# Put the options from the command-line into their official
# holding pen, the 'command_options' dictionary.
opt_dict = self.get_option_dict(command)
for (name, value) in vars(opts).items():
opt_dict[name] = ("command line", value)
return args
def finalize_options(self):
"""Set final values for all the options on the Distribution
instance, analogous to the .finalize_options() method of Command
objects.
"""
for attr in ('keywords', 'platforms'):
value = getattr(self.metadata, attr)
if value is None:
continue
if isinstance(value, str):
value = [elm.strip() for elm in value.split(',')]
setattr(self.metadata, attr, value)
def _show_help(self, parser, global_options=1, display_options=1,
commands=[]):
"""Show help for the setup script command-line in the form of
several lists of command-line options. 'parser' should be a
FancyGetopt instance; do not expect it to be returned in the
same state, as its option table will be reset to make it
generate the correct help text.
If 'global_options' is true, lists the global options:
--verbose, --dry-run, etc. If 'display_options' is true, lists
the "display-only" options: --name, --version, etc. Finally,
lists per-command help for every command name or command class
in 'commands'.
"""
# late import because of mutual dependence between these modules
from distutils.core import gen_usage
from distutils.cmd import Command
if global_options:
if display_options:
options = self._get_toplevel_options()
else:
options = self.global_options
parser.set_option_table(options)
parser.print_help(self.common_usage + "\nGlobal options:")
print('')
if display_options:
parser.set_option_table(self.display_options)
parser.print_help(
"Information display options (just display " +
"information, ignore any commands)")
print('')
for command in self.commands:
if isinstance(command, type) and issubclass(command, Command):
klass = command
else:
klass = self.get_command_class(command)
if (hasattr(klass, 'help_options') and
isinstance(klass.help_options, list)):
parser.set_option_table(klass.user_options +
fix_help_options(klass.help_options))
else:
parser.set_option_table(klass.user_options)
parser.print_help("Options for '%s' command:" % klass.__name__)
print('')
print(gen_usage(self.script_name))
def handle_display_options(self, option_order):
"""If there were any non-global "display-only" options
(--help-commands or the metadata display options) on the command
line, display the requested info and return true; else return
false.
"""
from distutils.core import gen_usage
# User just wants a list of commands -- we'll print it out and stop
# processing now (ie. if they ran "setup --help-commands foo bar",
# we ignore "foo bar").
if self.help_commands:
self.print_commands()
print('')
print(gen_usage(self.script_name))
return 1
# If user supplied any of the "display metadata" options, then
# display that metadata in the order in which the user supplied the
# metadata options.
any_display_options = 0
is_display_option = {}
for option in self.display_options:
is_display_option[option[0]] = 1
for (opt, val) in option_order:
if val and is_display_option.get(opt):
opt = translate_longopt(opt)
value = getattr(self.metadata, "get_"+opt)()
if opt in ['keywords', 'platforms']:
print(','.join(value))
elif opt in ('classifiers', 'provides', 'requires',
'obsoletes'):
print('\n'.join(value))
else:
print(value)
any_display_options = 1
return any_display_options
def print_command_list(self, commands, header, max_length):
"""Print a subset of the list of all commands -- used by
'print_commands()'.
"""
print(header + ":")
for cmd in commands:
klass = self.cmdclass.get(cmd)
if not klass:
klass = self.get_command_class(cmd)
try:
description = klass.description
except AttributeError:
description = "(no description available)"
print(" %-*s %s" % (max_length, cmd, description))
def print_commands(self):
"""Print out a help message listing all available commands with a
description of each. The list is divided into "standard commands"
(listed in distutils.command.__all__) and "extra commands"
(mentioned in self.cmdclass, but not a standard command). The
descriptions come from the command class attribute
'description'.
"""
import distutils.command
std_commands = distutils.command.__all__
is_std = {}
for cmd in std_commands:
is_std[cmd] = 1
extra_commands = []
for cmd in self.cmdclass.keys():
if not is_std.get(cmd):
extra_commands.append(cmd)
max_length = 0
for cmd in (std_commands + extra_commands):
if len(cmd) > max_length:
max_length = len(cmd)
self.print_command_list(std_commands,
"Standard commands",
max_length)
if extra_commands:
print()
self.print_command_list(extra_commands,
"Extra commands",
max_length)
def get_command_list(self):
"""Get a list of (command, description) tuples.
The list is divided into "standard commands" (listed in
distutils.command.__all__) and "extra commands" (mentioned in
self.cmdclass, but not a standard command). The descriptions come
from the command class attribute 'description'.
"""
# Currently this is only used on Mac OS, for the Mac-only GUI
# Distutils interface (by Jack Jansen)
import distutils.command
std_commands = distutils.command.__all__
is_std = {}
for cmd in std_commands:
is_std[cmd] = 1
extra_commands = []
for cmd in self.cmdclass.keys():
if not is_std.get(cmd):
extra_commands.append(cmd)
rv = []
for cmd in (std_commands + extra_commands):
klass = self.cmdclass.get(cmd)
if not klass:
klass = self.get_command_class(cmd)
try:
description = klass.description
except AttributeError:
description = "(no description available)"
rv.append((cmd, description))
return rv
# -- Command class/object methods ----------------------------------
def get_command_packages(self):
"""Return a list of packages from which commands are loaded."""
pkgs = self.command_packages
if not isinstance(pkgs, list):
if pkgs is None:
pkgs = ''
pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
if "distutils.command" not in pkgs:
pkgs.insert(0, "distutils.command")
self.command_packages = pkgs
return pkgs
def get_command_class(self, command):
"""Return the class that implements the Distutils command named by
'command'. First we check the 'cmdclass' dictionary; if the
command is mentioned there, we fetch the class object from the
dictionary and return it. Otherwise we load the command module
("distutils.command." + command) and fetch the command class from
the module. The loaded class is also stored in 'cmdclass'
to speed future calls to 'get_command_class()'.
Raises DistutilsModuleError if the expected module could not be
found, or if that module does not define the expected class.
"""
klass = self.cmdclass.get(command)
if klass:
return klass
for pkgname in self.get_command_packages():
module_name = "%s.%s" % (pkgname, command)
klass_name = command
try:
__import__ (module_name)
module = sys.modules[module_name]
except ImportError:
continue
try:
klass = getattr(module, klass_name)
except AttributeError:
raise DistutilsModuleError(
"invalid command '%s' (no class '%s' in module '%s')"
% (command, klass_name, module_name))
self.cmdclass[command] = klass
return klass
raise DistutilsModuleError("invalid command '%s'" % command)
def get_command_obj(self, command, create=1):
"""Return the command object for 'command'. Normally this object
is cached on a previous call to 'get_command_obj()'; if no command
object for 'command' is in the cache, then we either create and
return it (if 'create' is true) or return None.
"""
cmd_obj = self.command_obj.get(command)
if not cmd_obj and create:
if DEBUG:
self.announce("Distribution.get_command_obj(): " \
"creating '%s' command object" % command)
klass = self.get_command_class(command)
cmd_obj = self.command_obj[command] = klass(self)
self.have_run[command] = 0
# Set any options that were supplied in config files
# or on the command line. (NB. support for error
# reporting is lame here: any errors aren't reported
# until 'finalize_options()' is called, which means
# we won't report the source of the error.)
options = self.command_options.get(command)
if options:
self._set_command_options(cmd_obj, options)
return cmd_obj
def _set_command_options(self, command_obj, option_dict=None):
"""Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a Command instance. If 'option_dict' is not
supplied, uses the standard option dictionary for this command
(from 'self.command_options').
"""
command_name = command_obj.get_command_name()
if option_dict is None:
option_dict = self.get_option_dict(command_name)
if DEBUG:
self.announce(" setting options for '%s' command:" % command_name)
for (option, (source, value)) in option_dict.items():
if DEBUG:
self.announce(" %s = %s (from %s)" % (option, value,
source))
try:
bool_opts = [translate_longopt(o)
for o in command_obj.boolean_options]
except AttributeError:
bool_opts = []
try:
neg_opt = command_obj.negative_opt
except AttributeError:
neg_opt = {}
try:
is_string = isinstance(value, str)
if option in neg_opt and is_string:
setattr(command_obj, neg_opt[option], not strtobool(value))
elif option in bool_opts and is_string:
setattr(command_obj, option, strtobool(value))
elif hasattr(command_obj, option):
setattr(command_obj, option, value)
else:
raise DistutilsOptionError(
"error in %s: command '%s' has no such option '%s'"
% (source, command_name, option))
except ValueError as msg:
raise DistutilsOptionError(msg)
def reinitialize_command(self, command, reinit_subcommands=0):
"""Reinitializes a command to the state it was in when first
returned by 'get_command_obj()': ie., initialized but not yet
finalized. This provides the opportunity to sneak option
values in programmatically, overriding or supplementing
user-supplied values from the config files and command line.
You'll have to re-finalize the command object (by calling
'finalize_options()' or 'ensure_finalized()') before using it for
real.
'command' should be a command name (string) or command object. If
'reinit_subcommands' is true, also reinitializes the command's
sub-commands, as declared by the 'sub_commands' class attribute (if
it has one). See the "install" command for an example. Only
reinitializes the sub-commands that actually matter, ie. those
whose test predicates return true.
Returns the reinitialized command object.
"""
from distutils.cmd import Command
if not isinstance(command, Command):
command_name = command
command = self.get_command_obj(command_name)
else:
command_name = command.get_command_name()
if not command.finalized:
return command
command.initialize_options()
command.finalized = 0
self.have_run[command_name] = 0
self._set_command_options(command)
if reinit_subcommands:
for sub in command.get_sub_commands():
self.reinitialize_command(sub, reinit_subcommands)
return command
# -- Methods that operate on the Distribution ----------------------
def announce(self, msg, level=log.INFO):
log.log(level, msg)
def run_commands(self):
"""Run each command that was seen on the setup script command line.
Uses the list of commands found and cache of command objects
created by 'get_command_obj()'.
"""
for cmd in self.commands:
self.run_command(cmd)
# -- Methods that operate on its Commands --------------------------
def run_command(self, command):
"""Do whatever it takes to run a command (including nothing at all,
if the command has already been run). Specifically: if we have
already created and run the command named by 'command', return
silently without doing anything. If the command named by 'command'
doesn't even have a command object yet, create one. Then invoke
'run()' on that command object (or an existing one).
"""
# Already been here, done that? then return silently.
if self.have_run.get(command):
return
log.info("running %s", command)
cmd_obj = self.get_command_obj(command)
cmd_obj.ensure_finalized()
cmd_obj.run()
self.have_run[command] = 1
# -- Distribution query methods ------------------------------------
def has_pure_modules(self):
return len(self.packages or self.py_modules or []) > 0
def has_ext_modules(self):
return self.ext_modules and len(self.ext_modules) > 0
def has_c_libraries(self):
return self.libraries and len(self.libraries) > 0
def has_modules(self):
return self.has_pure_modules() or self.has_ext_modules()
def has_headers(self):
return self.headers and len(self.headers) > 0
def has_scripts(self):
return self.scripts and len(self.scripts) > 0
def has_data_files(self):
return self.data_files and len(self.data_files) > 0
def is_pure(self):
return (self.has_pure_modules() and
not self.has_ext_modules() and
not self.has_c_libraries())
# -- Metadata query methods ----------------------------------------
# If you're looking for 'get_name()', 'get_version()', and so forth,
# they are defined in a sneaky way: the constructor binds self.get_XXX
# to self.metadata.get_XXX. The actual code is in the
# DistributionMetadata class, below.
class DistributionMetadata:
"""Dummy class to hold the distribution meta-data: name, version,
author, and so forth.
"""
_METHOD_BASENAMES = ("name", "version", "author", "author_email",
"maintainer", "maintainer_email", "url",
"license", "description", "long_description",
"keywords", "platforms", "fullname", "contact",
"contact_email", "license", "classifiers",
"download_url",
# PEP 314
"provides", "requires", "obsoletes",
)
def __init__ (self):
self.name = None
self.version = None
self.author = None
self.author_email = None
self.maintainer = None
self.maintainer_email = None
self.url = None
self.license = None
self.description = None
self.long_description = None
self.keywords = None
self.platforms = None
self.classifiers = None
self.download_url = None
# PEP 314
self.provides = None
self.requires = None
self.obsoletes = None
def write_pkg_info(self, base_dir):
"""Write the PKG-INFO file into the release tree.
"""
pkg_info = open(os.path.join(base_dir, 'PKG-INFO'), 'w')
try:
self.write_pkg_file(pkg_info)
finally:
pkg_info.close()
def write_pkg_file(self, file):
"""Write the PKG-INFO format data to a file object.
"""
version = '1.0'
if self.provides or self.requires or self.obsoletes:
version = '1.1'
file.write('Metadata-Version: %s\n' % version)
file.write('Name: %s\n' % self.get_name() )
file.write('Version: %s\n' % self.get_version() )
file.write('Summary: %s\n' % self.get_description() )
file.write('Home-page: %s\n' % self.get_url() )
file.write('Author: %s\n' % self.get_contact() )
file.write('Author-email: %s\n' % self.get_contact_email() )
file.write('License: %s\n' % self.get_license() )
if self.download_url:
file.write('Download-URL: %s\n' % self.download_url)
long_desc = rfc822_escape(self.get_long_description())
file.write('Description: %s\n' % long_desc)
keywords = ','.join(self.get_keywords())
if keywords:
file.write('Keywords: %s\n' % keywords )
self._write_list(file, 'Platform', self.get_platforms())
self._write_list(file, 'Classifier', self.get_classifiers())
# PEP 314
self._write_list(file, 'Requires', self.get_requires())
self._write_list(file, 'Provides', self.get_provides())
self._write_list(file, 'Obsoletes', self.get_obsoletes())
def _write_list(self, file, name, values):
for value in values:
file.write('%s: %s\n' % (name, value))
# -- Metadata query methods ----------------------------------------
def get_name(self):
return self.name or "UNKNOWN"
def get_version(self):
return self.version or "0.0.0"
def get_fullname(self):
return "%s-%s" % (self.get_name(), self.get_version())
def get_author(self):
return self.author or "UNKNOWN"
def get_author_email(self):
return self.author_email or "UNKNOWN"
def get_maintainer(self):
return self.maintainer or "UNKNOWN"
def get_maintainer_email(self):
return self.maintainer_email or "UNKNOWN"
def get_contact(self):
return self.maintainer or self.author or "UNKNOWN"
def get_contact_email(self):
return self.maintainer_email or self.author_email or "UNKNOWN"
def get_url(self):
return self.url or "UNKNOWN"
def get_license(self):
return self.license or "UNKNOWN"
get_licence = get_license
def get_description(self):
return self.description or "UNKNOWN"
def get_long_description(self):
return self.long_description or "UNKNOWN"
def get_keywords(self):
return self.keywords or []
def get_platforms(self):
return self.platforms or ["UNKNOWN"]
def get_classifiers(self):
return self.classifiers or []
def get_download_url(self):
return self.download_url or "UNKNOWN"
# PEP 314
def get_requires(self):
return self.requires or []
def set_requires(self, value):
import distutils.versionpredicate
for v in value:
distutils.versionpredicate.VersionPredicate(v)
self.requires = value
def get_provides(self):
return self.provides or []
def set_provides(self, value):
<|fim▁hole|> value = [v.strip() for v in value]
for v in value:
import distutils.versionpredicate
distutils.versionpredicate.split_provision(v)
self.provides = value
def get_obsoletes(self):
return self.obsoletes or []
def set_obsoletes(self, value):
import distutils.versionpredicate
for v in value:
distutils.versionpredicate.VersionPredicate(v)
self.obsoletes = value
def fix_help_options(options):
"""Convert a 4-tuple 'help_options' list as found in various command
classes to the 3-tuple form required by FancyGetopt.
"""
new_options = []
for help_tuple in options:
new_options.append(help_tuple[0:3])
return new_options<|fim▁end|> | |
<|file_name|>memo-card-test.js<|end_file_name|><|fim▁begin|>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('memo-card', 'Integration | Component | memo card', {
integration: true
});
test('it renders', function(assert) {
assert.expect(2);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{memo-card}}`);
assert.equal(this.$().text().trim(), '');<|fim▁hole|> template block text
{{/memo-card}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});<|fim▁end|> |
// Template block usage:
this.render(hbs`
{{#memo-card}} |
<|file_name|>countDenormalization.ts<|end_file_name|><|fim▁begin|>/*
Copyright 2017 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.
*/
import {
Article,
} from '../../models';
import { Category } from '../../models';
export async function denormalizeCommentCountsForCategory(category: Category) {
const query = { where: { categoryId: category.id } };
const [
allCount,
unprocessedCount,
unmoderatedCount,
moderatedCount,
highlightedCount,
approvedCount,
rejectedCount,
deferredCount,
flaggedCount,
batchedCount,
] = await Promise.all([
Article.sum('allCount', query),<|fim▁hole|> Article.sum('highlightedCount', query),
Article.sum('approvedCount', query),
Article.sum('rejectedCount', query),
Article.sum('deferredCount', query),
Article.sum('flaggedCount', query),
Article.sum('batchedCount', query),
]);
return category.update({
allCount,
unprocessedCount,
unmoderatedCount,
moderatedCount,
highlightedCount,
approvedCount,
rejectedCount,
deferredCount,
flaggedCount,
batchedCount,
});
}<|fim▁end|> | Article.sum('unprocessedCount', query),
Article.sum('unmoderatedCount', query),
Article.sum('moderatedCount', query), |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict';<|fim▁hole|>module.exports = (str, count, indent) => indentString(stripIndent(str), count || 0, indent);<|fim▁end|> | const stripIndent = require('strip-indent');
const indentString = require('indent-string');
|
<|file_name|>newchannel.go<|end_file_name|><|fim▁begin|><|fim▁hole|>
// Newchannel triggered when a new channel is created.
type Newchannel struct {
Privilege []string
Channel string `AMI:"Channel"`
ChannelState string `AMI:"Channelstate"`
ChannelStateDesc string `AMI:"Channelstatedesc"`
CallerIDNum string `AMI:"Calleridnum"`
CallerIDName string `AMI:"Calleridname"`
AccountCode string `AMI:"Accountcode"`
UniqueID string `AMI:"Uniqueid"`
Context string `AMI:"Context"`
Extension string `AMI:"Exten"`
}
func init() {
eventTrap["Newchannel"] = Newchannel{}
}<|fim▁end|> | // Package event for AMI
package event |
<|file_name|>multifilereader.rs<|end_file_name|><|fim▁begin|>use std;
use std::io;
use std::io::BufReader;
use std::fs::File;
use std::vec::Vec;
pub enum InputSource<'a> {
FileName(&'a str),
Stdin,
#[allow(dead_code)]
Stream(Box<io::Read>),
}
// MultifileReader - concatenate all our input, file or stdin.
pub struct MultifileReader<'a> {
ni: Vec<InputSource<'a>>,
curr_file: Option<Box<io::Read>>,
any_err: bool,
}
pub trait HasError {
fn has_error(&self) -> bool;
}
impl<'b> MultifileReader<'b> {
pub fn new<'a>(fnames: Vec<InputSource<'a>>) -> MultifileReader<'a> {
let mut mf = MultifileReader {
ni: fnames,
curr_file: None, // normally this means done; call next_file()
any_err: false,
};
mf.next_file();
mf
}
fn next_file(&mut self) {
// loop retries with subsequent files if err - normally 'loops' once
loop {
if self.ni.len() == 0 {
self.curr_file = None;
break;
}
match self.ni.remove(0) {
InputSource::Stdin => {
self.curr_file = Some(Box::new(BufReader::new(std::io::stdin())));
break;
}
InputSource::FileName(fname) => {
match File::open(fname) {
Ok(f) => {
self.curr_file = Some(Box::new(BufReader::new(f)));<|fim▁hole|> // If any file can't be opened,
// print an error at the time that the file is needed,
// then move on the the next file.
// This matches the behavior of the original `od`
eprintln!(
"{}: '{}': {}",
executable!().split("::").next().unwrap(), // remove module
fname,
e
);
self.any_err = true
}
}
}
InputSource::Stream(s) => {
self.curr_file = Some(s);
break;
}
}
}
}
}
impl<'b> io::Read for MultifileReader<'b> {
// Fill buf with bytes read from the list of files
// Returns Ok(<number of bytes read>)
// Handles io errors itself, thus always returns OK
// Fills the provided buffer completely, unless it has run out of input.
// If any call returns short (< buf.len()), all subsequent calls will return Ok<0>
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut xfrd = 0;
// while buffer we are filling is not full.. May go thru several files.
'fillloop: while xfrd < buf.len() {
match self.curr_file {
None => break,
Some(ref mut curr_file) => {
loop {
// stdin may return on 'return' (enter), even though the buffer isn't full.
xfrd += match curr_file.read(&mut buf[xfrd..]) {
Ok(0) => break,
Ok(n) => n,
Err(e) => {
eprintln!(
"{}: I/O: {}",
executable!().split("::").next().unwrap(), // remove module
e
);
self.any_err = true;
break;
}
};
if xfrd == buf.len() {
// transferred all that was asked for.
break 'fillloop;
}
}
}
}
self.next_file();
}
Ok(xfrd)
}
}
impl<'b> HasError for MultifileReader<'b> {
fn has_error(&self) -> bool {
self.any_err
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Cursor, ErrorKind, Read};
use mockstream::*;
#[test]
fn test_multi_file_reader_one_read() {
let mut inputs = Vec::new();
inputs.push(InputSource::Stream(Box::new(Cursor::new(&b"abcd"[..]))));
inputs.push(InputSource::Stream(Box::new(Cursor::new(&b"ABCD"[..]))));
let mut v = [0; 10];
let mut sut = MultifileReader::new(inputs);
assert_eq!(sut.read(v.as_mut()).unwrap(), 8);
assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41, 0x42, 0x43, 0x44, 0, 0]);
assert_eq!(sut.read(v.as_mut()).unwrap(), 0);
}
#[test]
fn test_multi_file_reader_two_reads() {
let mut inputs = Vec::new();
inputs.push(InputSource::Stream(Box::new(Cursor::new(&b"abcd"[..]))));
inputs.push(InputSource::Stream(Box::new(Cursor::new(&b"ABCD"[..]))));
let mut v = [0; 5];
let mut sut = MultifileReader::new(inputs);
assert_eq!(sut.read(v.as_mut()).unwrap(), 5);
assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41]);
assert_eq!(sut.read(v.as_mut()).unwrap(), 3);
assert_eq!(v, [0x42, 0x43, 0x44, 0x64, 0x41]); // last two bytes are not overwritten
}
#[test]
fn test_multi_file_reader_read_error() {
let c = Cursor::new(&b"1234"[..])
.chain(FailingMockStream::new(ErrorKind::Other, "Failing", 1))
.chain(Cursor::new(&b"5678"[..]));
let mut inputs = Vec::new();
inputs.push(InputSource::Stream(Box::new(c)));
inputs.push(InputSource::Stream(Box::new(Cursor::new(&b"ABCD"[..]))));
let mut v = [0; 5];
let mut sut = MultifileReader::new(inputs);
assert_eq!(sut.read(v.as_mut()).unwrap(), 5);
assert_eq!(v, [49, 50, 51, 52, 65]);
assert_eq!(sut.read(v.as_mut()).unwrap(), 3);
assert_eq!(v, [66, 67, 68, 52, 65]); // last two bytes are not overwritten
// note: no retry on i/o error, so 5678 is missing
}
#[test]
fn test_multi_file_reader_read_error_at_start() {
let mut inputs = Vec::new();
inputs.push(InputSource::Stream(Box::new(FailingMockStream::new(
ErrorKind::Other,
"Failing",
1,
))));
inputs.push(InputSource::Stream(Box::new(Cursor::new(&b"abcd"[..]))));
inputs.push(InputSource::Stream(Box::new(FailingMockStream::new(
ErrorKind::Other,
"Failing",
1,
))));
inputs.push(InputSource::Stream(Box::new(Cursor::new(&b"ABCD"[..]))));
inputs.push(InputSource::Stream(Box::new(FailingMockStream::new(
ErrorKind::Other,
"Failing",
1,
))));
let mut v = [0; 5];
let mut sut = MultifileReader::new(inputs);
assert_eq!(sut.read(v.as_mut()).unwrap(), 5);
assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41]);
assert_eq!(sut.read(v.as_mut()).unwrap(), 3);
assert_eq!(v, [0x42, 0x43, 0x44, 0x64, 0x41]); // last two bytes are not overwritten
}
}<|fim▁end|> | break;
}
Err(e) => { |
<|file_name|>PreReadDatabaseEvent.java<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.metastore.events;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hive.metastore.IHMSHandler;
import org.apache.hadoop.hive.metastore.api.Database;
/**
* Database read event
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class PreReadDatabaseEvent extends PreEventContext {
private final Database db;
public PreReadDatabaseEvent(Database db, IHMSHandler handler) {
super(PreEventType.READ_DATABASE, handler);
this.db = db;
}<|fim▁hole|> /**
* @return the db
*/
public Database getDatabase() {
return db;
}
}<|fim▁end|> | |
<|file_name|>GoogleCloudDialogflowV2ImportConversationDataOperationMetadata.java<|end_file_name|><|fim▁begin|>/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dialogflow.v3beta1.model;
/**
* Metadata for a ConversationDatasets.ImportConversationData operation.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2ImportConversationDataOperationMetadata extends com.google.api.client.json.GenericJson {
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String conversationDataset;
/**<|fim▁hole|> * The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String createTime;
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleRpcStatus> partialFailures;
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* @return value or {@code null} for none
*/
public java.lang.String getConversationDataset() {
return conversationDataset;
}
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* @param conversationDataset conversationDataset or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setConversationDataset(java.lang.String conversationDataset) {
this.conversationDataset = conversationDataset;
return this;
}
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* @return value or {@code null} for none
*/
public String getCreateTime() {
return createTime;
}
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* @param createTime createTime or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setCreateTime(String createTime) {
this.createTime = createTime;
return this;
}
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* @return value or {@code null} for none
*/
public java.util.List<GoogleRpcStatus> getPartialFailures() {
return partialFailures;
}
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* @param partialFailures partialFailures or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setPartialFailures(java.util.List<GoogleRpcStatus> partialFailures) {
this.partialFailures = partialFailures;
return this;
}
@Override
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata set(String fieldName, Object value) {
return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata clone() {
return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.clone();
}
}<|fim▁end|> | * Timestamp when import conversation data request was created. The time is measured on server
* side. |
<|file_name|>coordinate.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied 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.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import hashlib
import itertools
import numpy
from nupic.bindings.math import Random
from nupic.encoders.base import Encoder
class CoordinateEncoder(Encoder):
"""
Given a coordinate in an N-dimensional space, and a radius around
that coordinate, the Coordinate Encoder returns an SDR representation
of that position.
The Coordinate Encoder uses an N-dimensional integer coordinate space.
For example, a valid coordinate in this space is (150, -49, 58), whereas
an invalid coordinate would be (55.4, -5, 85.8475).
It uses the following algorithm:
1. Find all the coordinates around the input coordinate, within the
specified radius.
2. For each coordinate, use a uniform hash function to
deterministically map it to a real number between 0 and 1. This is the
"order" of the coordinate.<|fim▁hole|> 3. Of these coordinates, pick the top W by order, where W is the
number of active bits desired in the SDR.
4. For each of these W coordinates, use a uniform hash function to
deterministically map it to one of the bits in the SDR. Make this bit active.
5. This results in a final SDR with exactly W bits active
(barring chance hash collisions).
"""
def __init__(self,
w=21,
n=1000,
name=None,
verbosity=0):
"""
See `nupic.encoders.base.Encoder` for more information.
@param name An optional string which will become part of the description
"""
# Validate inputs
if (w <= 0) or (w % 2 == 0):
raise ValueError("w must be an odd positive integer")
if (n <= 6 * w) or (not isinstance(n, int)):
raise ValueError("n must be an int strictly greater than 6*w. For "
"good results we recommend n be strictly greater "
"than 11*w")
self.w = w
self.n = n
self.verbosity = verbosity
self.encoders = None
if name is None:
name = "[%s:%s]" % (self.n, self.w)
self.name = name
def getWidth(self):
"""See `nupic.encoders.base.Encoder` for more information."""
return self.n
def getDescription(self):
"""See `nupic.encoders.base.Encoder` for more information."""
return [('coordinate', 0), ('radius', 1)]
def getScalars(self, inputData):
"""See `nupic.encoders.base.Encoder` for more information."""
return numpy.array([0]*len(inputData))
def encodeIntoArray(self, inputData, output):
"""
See `nupic.encoders.base.Encoder` for more information.
@param inputData (tuple) Contains coordinate (numpy.array)
and radius (float)
@param output (numpy.array) Stores encoded SDR in this numpy array
"""
(coordinate, radius) = inputData
neighbors = self._neighbors(coordinate, radius)
winners = self._topWCoordinates(neighbors, self.w)
bitFn = lambda coordinate: self._bitForCoordinate(coordinate, self.n)
indices = numpy.array([bitFn(w) for w in winners])
output[:] = 0
output[indices] = 1
@staticmethod
def _neighbors(coordinate, radius):
"""
Returns coordinates around given coordinate, within given radius.
Includes given coordinate.
@param coordinate (numpy.array) Coordinate whose neighbors to find
@param radius (float) Radius around `coordinate`
@return (numpy.array) List of coordinates
"""
ranges = [range(n-radius, n+radius+1) for n in coordinate.tolist()]
return numpy.array(list(itertools.product(*ranges)))
@classmethod
def _topWCoordinates(cls, coordinates, w):
"""
Returns the top W coordinates by order.
@param coordinates (numpy.array) A 2D numpy array, where each element
is a coordinate
@param w (int) Number of top coordinates to return
@return (numpy.array) A subset of `coordinates`, containing only the
top ones by order
"""
orders = numpy.array([cls._orderForCoordinate(c)
for c in coordinates.tolist()])
indices = numpy.argsort(orders)[-w:]
return coordinates[indices]
@staticmethod
def _hashCoordinate(coordinate):
"""Hash a coordinate to a 64 bit integer."""
coordinateStr = ",".join(str(v) for v in coordinate)
# Compute the hash and convert to 64 bit int.
hash = int(int(hashlib.md5(coordinateStr).hexdigest(), 16) % (2 ** 64))
return hash
@classmethod
def _orderForCoordinate(cls, coordinate):
"""
Returns the order for a coordinate.
@param coordinate (numpy.array) Coordinate
@return (float) A value in the interval [0, 1), representing the
order of the coordinate
"""
seed = cls._hashCoordinate(coordinate)
rng = Random(seed)
return rng.getReal64()
@classmethod
def _bitForCoordinate(cls, coordinate, n):
"""
Maps the coordinate to a bit in the SDR.
@param coordinate (numpy.array) Coordinate
@param n (int) The number of available bits in the SDR
@return (int) The index to a bit in the SDR
"""
seed = cls._hashCoordinate(coordinate)
rng = Random(seed)
return rng.getUInt32(n)
def dump(self):
print "CoordinateEncoder:"
print " w: %d" % self.w
print " n: %d" % self.n
@classmethod
def read(cls, proto):
encoder = object.__new__(cls)
encoder.w = proto.w
encoder.n = proto.n
encoder.verbosity = proto.verbosity
encoder.name = proto.name
return encoder
def write(self, proto):
proto.w = self.w
proto.n = self.n
proto.verbosity = self.verbosity
proto.name = self.name<|fim▁end|> | |
<|file_name|>descrobject.rs<|end_file_name|><|fim▁begin|>use libc::{c_char, c_int, c_void};
use crate::methodobject::PyMethodDef;
use crate::object::{PyObject, PyTypeObject, Py_TYPE};
use crate::structmember::PyMemberDef;
pub type getter = unsafe extern "C" fn(slf: *mut PyObject, closure: *mut c_void) -> *mut PyObject;
pub type setter =
unsafe extern "C" fn(slf: *mut PyObject, value: *mut PyObject, closure: *mut c_void) -> c_int;
#[repr(C)]
#[derive(Copy)]
pub struct PyGetSetDef {
pub name: *mut c_char,
pub get: Option<getter>,
pub set: Option<setter>,
pub doc: *mut c_char,
pub closure: *mut c_void,
}
impl Clone for PyGetSetDef {
#[inline]
fn clone(&self) -> PyGetSetDef {
*self
}
}
pub type wrapperfunc = unsafe extern "C" fn(
slf: *mut PyObject,
args: *mut PyObject,
wrapped: *mut c_void,
) -> *mut PyObject;
pub type wrapperfunc_kwds = unsafe extern "C" fn(
slf: *mut PyObject,
args: *mut PyObject,
wrapped: *mut c_void,
kwds: *mut PyObject,
) -> *mut PyObject;
#[repr(C)]
#[derive(Copy)]
pub struct wrapperbase {
pub name: *mut c_char,
pub offset: c_int,
pub function: *mut c_void,
pub wrapper: Option<wrapperfunc>,
pub doc: *mut c_char,
pub flags: c_int,
pub name_strobj: *mut PyObject,
}
impl Clone for wrapperbase {
#[inline]<|fim▁hole|>
pub const PyWrapperFlag_KEYWORDS: c_int = 1;
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub static mut PyWrapperDescr_Type: PyTypeObject;
pub static mut PyDictProxy_Type: PyTypeObject;
pub static mut PyGetSetDescr_Type: PyTypeObject;
pub static mut PyMemberDescr_Type: PyTypeObject;
pub static mut PyProperty_Type: PyTypeObject;
pub fn PyDescr_NewMethod(arg1: *mut PyTypeObject, arg2: *mut PyMethodDef) -> *mut PyObject;
pub fn PyDescr_NewClassMethod(arg1: *mut PyTypeObject, arg2: *mut PyMethodDef)
-> *mut PyObject;
pub fn PyDescr_NewMember(arg1: *mut PyTypeObject, arg2: *mut PyMemberDef) -> *mut PyObject;
pub fn PyDescr_NewGetSet(arg1: *mut PyTypeObject, arg2: *mut PyGetSetDef) -> *mut PyObject;
pub fn PyDescr_NewWrapper(
arg1: *mut PyTypeObject,
arg2: *mut wrapperbase,
arg3: *mut c_void,
) -> *mut PyObject;
}
#[inline(always)]
pub unsafe fn PyDescr_IsData(d: *mut PyObject) -> c_int {
(*Py_TYPE(d)).tp_descr_set.is_some() as c_int
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
ignore! {
// PyDictProxy_New is also defined in dictobject.h
pub fn PyDictProxy_New(arg1: *mut PyObject) -> *mut PyObject;
}
pub fn PyWrapper_New(arg1: *mut PyObject, arg2: *mut PyObject) -> *mut PyObject;
}<|fim▁end|> | fn clone(&self) -> wrapperbase {
*self
}
} |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|>"""A very simple logger that tries to be concurrency-safe."""
import os, sys
import time
import traceback
import subprocess
import select
LOG_FILE = '/var/log/nodemanager.func'
# basically define 3 levels
LOG_NONE=0
LOG_NODE=1
LOG_VERBOSE=2
# default is to log a reasonable amount of stuff for when running on operational nodes
LOG_LEVEL=1
def set_level(level):
global LOG_LEVEL
assert level in [LOG_NONE,LOG_NODE,LOG_VERBOSE]
LOG_LEVEL=level
def verbose(msg):
log('(v) '+msg,LOG_VERBOSE)
def log(msg,level=LOG_NODE):
"""Write <msg> to the log file if level >= current log level (default LOG_NODE)."""
if (level > LOG_LEVEL):
return
try:<|fim▁hole|> os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
os.close(fd)
except OSError:
sys.stderr.write(msg)
sys.stderr.flush()
def log_exc(msg="",name=None):
"""Log the traceback resulting from an exception."""
if name:
log("%s: EXCEPTION caught <%s> \n %s" %(name, msg, traceback.format_exc()))
else:
log("EXCEPTION caught <%s> \n %s" %(msg, traceback.format_exc()))
#################### child processes
# avoid waiting until the process returns;
# that makes debugging of hanging children hard
class Buffer:
def __init__ (self,message='log_call: '):
self.buffer=''
self.message=message
def add (self,c):
self.buffer += c
if c=='\n': self.flush()
def flush (self):
if self.buffer:
log (self.message + self.buffer)
self.buffer=''
# time out in seconds - avoid hanging subprocesses - default is 5 minutes
default_timeout_minutes=5
# returns a bool that is True when everything goes fine and the retcod is 0
def log_call(command,timeout=default_timeout_minutes*60,poll=1):
message=" ".join(command)
log("log_call: running command %s" % message)
verbose("log_call: timeout=%r s" % timeout)
verbose("log_call: poll=%r s" % poll)
trigger=time.time()+timeout
result = False
try:
child = subprocess.Popen(command, bufsize=1,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
buffer = Buffer()
while True:
# see if anything can be read within the poll interval
(r,w,x)=select.select([child.stdout],[],[],poll)
if r: buffer.add(child.stdout.read(1))
# is process over ?
returncode=child.poll()
# yes
if returncode != None:
buffer.flush()
# child is done and return 0
if returncode == 0:
log("log_call:end command (%s) completed" % message)
result=True
break
# child has failed
else:
log("log_call:end command (%s) returned with code %d" %(message,returncode))
break
# no : still within timeout ?
if time.time() >= trigger:
buffer.flush()
child.terminate()
log("log_call:end terminating command (%s) - exceeded timeout %d s"%(message,timeout))
break
except: log_exc("failed to run command %s" % message)
return result<|fim▁end|> | fd = os.open(LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
if not msg.endswith('\n'): msg += '\n' |
<|file_name|>[email protected]<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="sr@latin">
<context>
<name>ConfigPanelDialog</name>
<message>
<location filename="../config/configpaneldialog.cpp" line="80"/>
<location filename="../config/configpaneldialog.cpp" line="86"/>
<source>Configure Panel</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ConfigPanelWidget</name>
<message>
<location filename="../config/configpaneldialog.ui" line="20"/>
<source>Configure panel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="32"/>
<source>Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="41"/>
<source>Size:</source>
<translation type="unfinished"></translation>
</message><|fim▁hole|> <source> px</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="58"/>
<source>Icon size:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="65"/>
<source>Length:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="110"/>
<source><p>Negative pixel value sets the panel length to that many pixels less than available screen space.</p><p/><p><i>E.g. "Length" set to -100px, screen size is 1000px, then real panel length will be 900 px.</i></p></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="124"/>
<source>%</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="129"/>
<source>px</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="140"/>
<source>Rows count:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="172"/>
<source>Alignment && position</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="182"/>
<location filename="../config/configpaneldialog.cpp" line="229"/>
<source>Left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="187"/>
<location filename="../config/configpaneldialog.cpp" line="230"/>
<location filename="../config/configpaneldialog.cpp" line="236"/>
<source>Center</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="192"/>
<location filename="../config/configpaneldialog.cpp" line="231"/>
<source>Right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="200"/>
<source>Alignment:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="210"/>
<source>Position:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="226"/>
<source>Styling</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="232"/>
<source>Custom font color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="239"/>
<source>Custom background image:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="253"/>
<source>Custom background color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.ui" line="344"/>
<source>Opacity</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="195"/>
<source>Top of desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="196"/>
<source>Left of desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="197"/>
<source>Right of desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="198"/>
<source>Bottom of desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="207"/>
<source>Top of desktop %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="208"/>
<source>Left of desktop %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="209"/>
<source>Right of desktop %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="210"/>
<source>Bottom of desktop %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="235"/>
<source>Top</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="237"/>
<source>Bottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="391"/>
<location filename="../config/configpaneldialog.cpp" line="405"/>
<source>Pick color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../config/configpaneldialog.cpp" line="425"/>
<source>Images (*.png *.gif *.jpg)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>LxQtPanel</name>
<message>
<location filename="../lxqtpanel.cpp" line="605"/>
<source>Add Panel Widgets</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqtpanel.cpp" line="929"/>
<location filename="../lxqtpanel.cpp" line="948"/>
<source>Panel</source>
<translation>Automatsko suspendovanje</translation>
</message>
<message>
<location filename="../lxqtpanel.cpp" line="950"/>
<source>Configure Panel...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqtpanel.cpp" line="955"/>
<source>Add Panel Widgets...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqtpanel.cpp" line="960"/>
<source>Add Panel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqtpanel.cpp" line="966"/>
<source>Remove Panel</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Plugin</name>
<message>
<location filename="../plugin.cpp" line="309"/>
<source>Configure "%1"</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../plugin.cpp" line="314"/>
<source>Move "%1"</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../plugin.cpp" line="320"/>
<source>Remove "%1"</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS><|fim▁end|> | <message>
<location filename="../config/configpaneldialog.ui" line="48"/>
<location filename="../config/configpaneldialog.ui" line="82"/> |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)
from homeassistant.helpers import state as state_helper
from homeassistant.helpers.event import track_point_in_time
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'emoncms_history'
CONF_INPUTNODE = 'inputnode'<|fim▁hole|> vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_INPUTNODE): cv.positive_int,
vol.Required(CONF_WHITELIST): cv.entity_ids,
vol.Optional(CONF_SCAN_INTERVAL, default=30): cv.positive_int,
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up the Emoncms history component."""
conf = config[DOMAIN]
whitelist = conf.get(CONF_WHITELIST)
def send_data(url, apikey, node, payload):
"""Send payload data to Emoncms."""
try:
fullurl = '{}/input/post.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
timeout=5)
except requests.exceptions.RequestException:
_LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl)
else:
if req.status_code != 200:
_LOGGER.error(
"Error saving data %s to %s (http status code = %d)",
payload, fullurl, req.status_code)
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
continue
try:
payload_dict[entity_id] = state_helper.state_as_number(state)
except ValueError:
continue
if payload_dict:
payload = "{%s}" % ",".join("{}:{}".format(key, val)
for key, val in
payload_dict.items())
send_data(conf.get(CONF_URL), conf.get(CONF_API_KEY),
str(conf.get(CONF_INPUTNODE)), payload)
track_point_in_time(hass, update_emoncms, time +
timedelta(seconds=conf.get(CONF_SCAN_INTERVAL)))
update_emoncms(dt_util.utcnow())
return True<|fim▁end|> |
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({ |
<|file_name|>test_linesearch.py<|end_file_name|><|fim▁begin|>"""
Tests for line search routines
"""
from __future__ import division, print_function, absolute_import
from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
assert_array_almost_equal_nulp, assert_warns,
suppress_warnings)
import scipy.optimize.linesearch as ls
from scipy.optimize.linesearch import LineSearchWarning
import numpy as np
def assert_wolfe(s, phi, derphi, c1=1e-4, c2=0.9, err_msg=""):
"""
Check that strong Wolfe conditions apply
"""
phi1 = phi(s)
phi0 = phi(0)
derphi0 = derphi(0)
derphi1 = derphi(s)
msg = "s = %s; phi(0) = %s; phi(s) = %s; phi'(0) = %s; phi'(s) = %s; %s" % (
s, phi0, phi1, derphi0, derphi1, err_msg)
assert_(phi1 <= phi0 + c1*s*derphi0, "Wolfe 1 failed: " + msg)
assert_(abs(derphi1) <= abs(c2*derphi0), "Wolfe 2 failed: " + msg)
def assert_armijo(s, phi, c1=1e-4, err_msg=""):
"""
Check that Armijo condition applies
"""
phi1 = phi(s)
phi0 = phi(0)
msg = "s = %s; phi(0) = %s; phi(s) = %s; %s" % (s, phi0, phi1, err_msg)
assert_(phi1 <= (1 - c1*s)*phi0, msg)
def assert_line_wolfe(x, p, s, f, fprime, **kw):
assert_wolfe(s, phi=lambda sp: f(x + p*sp),
derphi=lambda sp: np.dot(fprime(x + p*sp), p), **kw)
def assert_line_armijo(x, p, s, f, **kw):
assert_armijo(s, phi=lambda sp: f(x + p*sp), **kw)
def assert_fp_equal(x, y, err_msg="", nulp=50):
"""Assert two arrays are equal, up to some floating-point rounding error"""
try:
assert_array_almost_equal_nulp(x, y, nulp)
except AssertionError as e:
raise AssertionError("%s\n%s" % (e, err_msg))
class TestLineSearch(object):
# -- scalar functions; must have dphi(0.) < 0
def _scalar_func_1(self, s):
self.fcount += 1
p = -s - s**3 + s**4
dp = -1 - 3*s**2 + 4*s**3
return p, dp
def _scalar_func_2(self, s):
self.fcount += 1
p = np.exp(-4*s) + s**2
dp = -4*np.exp(-4*s) + 2*s
return p, dp
def _scalar_func_3(self, s):
self.fcount += 1
p = -np.sin(10*s)
dp = -10*np.cos(10*s)
return p, dp
# -- n-d functions
def _line_func_1(self, x):
self.fcount += 1
f = np.dot(x, x)
df = 2*x
return f, df
def _line_func_2(self, x):
self.fcount += 1
f = np.dot(x, np.dot(self.A, x)) + 1
df = np.dot(self.A + self.A.T, x)
return f, df
# --
def setup_method(self):
self.scalar_funcs = []
self.line_funcs = []
self.N = 20
self.fcount = 0
def bind_index(func, idx):
# Remember Python's closure semantics!
return lambda *a, **kw: func(*a, **kw)[idx]
for name in sorted(dir(self)):
if name.startswith('_scalar_func_'):
value = getattr(self, name)
self.scalar_funcs.append(
(name, bind_index(value, 0), bind_index(value, 1)))
elif name.startswith('_line_func_'):
value = getattr(self, name)
self.line_funcs.append(
(name, bind_index(value, 0), bind_index(value, 1)))
np.random.seed(1234)
self.A = np.random.randn(self.N, self.N)
def scalar_iter(self):
for name, phi, derphi in self.scalar_funcs:
for old_phi0 in np.random.randn(3):
yield name, phi, derphi, old_phi0
def line_iter(self):
for name, f, fprime in self.line_funcs:
k = 0
while k < 9:
x = np.random.randn(self.N)
p = np.random.randn(self.N)
if np.dot(p, fprime(x)) >= 0:
# always pick a descent direction
continue
k += 1
old_fv = float(np.random.randn())
yield name, f, fprime, x, p, old_fv
# -- Generic scalar searches
def test_scalar_search_wolfe1(self):
c = 0
for name, phi, derphi, old_phi0 in self.scalar_iter():
c += 1
s, phi1, phi0 = ls.scalar_search_wolfe1(phi, derphi, phi(0),
old_phi0, derphi(0))
assert_fp_equal(phi0, phi(0), name)
assert_fp_equal(phi1, phi(s), name)
assert_wolfe(s, phi, derphi, err_msg=name)
assert_(c > 3) # check that the iterator really works...
def test_scalar_search_wolfe2(self):
for name, phi, derphi, old_phi0 in self.scalar_iter():
s, phi1, phi0, derphi1 = ls.scalar_search_wolfe2(
phi, derphi, phi(0), old_phi0, derphi(0))
assert_fp_equal(phi0, phi(0), name)
assert_fp_equal(phi1, phi(s), name)
if derphi1 is not None:
assert_fp_equal(derphi1, derphi(s), name)
assert_wolfe(s, phi, derphi, err_msg="%s %g" % (name, old_phi0))
def test_scalar_search_wolfe2_with_low_amax(self):
def phi(alpha):
return (alpha - 5) ** 2
def derphi(alpha):
return 2 * (alpha - 5)
s, _, _, _ = assert_warns(LineSearchWarning,
ls.scalar_search_wolfe2, phi, derphi, amax=0.001)
assert_(s is None)
def test_scalar_search_armijo(self):
for name, phi, derphi, old_phi0 in self.scalar_iter():
s, phi1 = ls.scalar_search_armijo(phi, phi(0), derphi(0))
assert_fp_equal(phi1, phi(s), name)
assert_armijo(s, phi, err_msg="%s %g" % (name, old_phi0))
# -- Generic line searches
def test_line_search_wolfe1(self):
c = 0
smax = 100
for name, f, fprime, x, p, old_f in self.line_iter():
f0 = f(x)
g0 = fprime(x)
self.fcount = 0
s, fc, gc, fv, ofv, gv = ls.line_search_wolfe1(f, fprime, x, p,
g0, f0, old_f,
amax=smax)
assert_equal(self.fcount, fc+gc)
assert_fp_equal(ofv, f(x))
if s is None:
continue
assert_fp_equal(fv, f(x + s*p))
assert_array_almost_equal(gv, fprime(x + s*p), decimal=14)
if s < smax:
c += 1
assert_line_wolfe(x, p, s, f, fprime, err_msg=name)
assert_(c > 3) # check that the iterator really works...
def test_line_search_wolfe2(self):
c = 0
smax = 512
for name, f, fprime, x, p, old_f in self.line_iter():
f0 = f(x)
g0 = fprime(x)
self.fcount = 0
with suppress_warnings() as sup:
sup.filter(LineSearchWarning,
"The line search algorithm could not find a solution")
sup.filter(LineSearchWarning,
"The line search algorithm did not converge")
s, fc, gc, fv, ofv, gv = ls.line_search_wolfe2(f, fprime, x, p,
g0, f0, old_f,
amax=smax)
assert_equal(self.fcount, fc+gc)
assert_fp_equal(ofv, f(x))
assert_fp_equal(fv, f(x + s*p))
if gv is not None:
assert_array_almost_equal(gv, fprime(x + s*p), decimal=14)
if s < smax:<|fim▁hole|>
def test_line_search_wolfe2_bounds(self):
# See gh-7475
# For this f and p, starting at a point on axis 0, the strong Wolfe
# condition 2 is met if and only if the step length s satisfies
# |x + s| <= c2 * |x|
f = lambda x: np.dot(x, x)
fp = lambda x: 2 * x
p = np.array([1, 0])
# Smallest s satisfying strong Wolfe conditions for these arguments is 30
x = -60 * p
c2 = 0.5
s, _, _, _, _, _ = ls.line_search_wolfe2(f, fp, x, p, amax=30, c2=c2)
assert_line_wolfe(x, p, s, f, fp)
s, _, _, _, _, _ = assert_warns(LineSearchWarning,
ls.line_search_wolfe2, f, fp, x, p,
amax=29, c2=c2)
assert_(s is None)
# s=30 will only be tried on the 6th iteration, so this won't converge
assert_warns(LineSearchWarning, ls.line_search_wolfe2, f, fp, x, p,
c2=c2, maxiter=5)
def test_line_search_armijo(self):
c = 0
for name, f, fprime, x, p, old_f in self.line_iter():
f0 = f(x)
g0 = fprime(x)
self.fcount = 0
s, fc, fv = ls.line_search_armijo(f, x, p, g0, f0)
c += 1
assert_equal(self.fcount, fc)
assert_fp_equal(fv, f(x + s*p))
assert_line_armijo(x, p, s, f, err_msg=name)
assert_(c >= 9)
# -- More specific tests
def test_armijo_terminate_1(self):
# Armijo should evaluate the function only once if the trial step
# is already suitable
count = [0]
def phi(s):
count[0] += 1
return -s + 0.01*s**2
s, phi1 = ls.scalar_search_armijo(phi, phi(0), -1, alpha0=1)
assert_equal(s, 1)
assert_equal(count[0], 2)
assert_armijo(s, phi)
def test_wolfe_terminate(self):
# wolfe1 and wolfe2 should also evaluate the function only a few
# times if the trial step is already suitable
def phi(s):
count[0] += 1
return -s + 0.05*s**2
def derphi(s):
count[0] += 1
return -1 + 0.05*2*s
for func in [ls.scalar_search_wolfe1, ls.scalar_search_wolfe2]:
count = [0]
r = func(phi, derphi, phi(0), None, derphi(0))
assert_(r[0] is not None, (r, func))
assert_(count[0] <= 2 + 2, (count, func))
assert_wolfe(r[0], phi, derphi, err_msg=str(func))<|fim▁end|> | c += 1
assert_line_wolfe(x, p, s, f, fprime, err_msg=name)
assert_(c > 3) # check that the iterator really works... |
<|file_name|>utf_8.py<|end_file_name|><|fim▁begin|># uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: utf_8.py
""" Python 'utf-8' Codec<|fim▁hole|>
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs
encode = codecs.utf_8_encode
def decode(input, errors='strict'):
return codecs.utf_8_decode(input, errors, True)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.utf_8_encode(input, self.errors)[0]
class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
_buffer_decode = codecs.utf_8_decode
class StreamWriter(codecs.StreamWriter):
encode = codecs.utf_8_encode
class StreamReader(codecs.StreamReader):
decode = codecs.utf_8_decode
def getregentry():
return codecs.CodecInfo(name='utf-8', encode=encode, decode=decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter)<|fim▁end|> |
Written by Marc-Andre Lemburg ([email protected]). |
<|file_name|>recipe-580709-1.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# <https://code.activestate.com/recipes/580709-lines-of-code-loc/>
# Basic Lines-Of-Code counter in Python source files, reporting the
# number of blank, comment and source code lines and total number of
# lines in all Python files scanned.
# Usage example:
# % python locs.py -rec ~/Projects
# 8691 *.py files: 365038 blank (14.0%), 212100 comment (8.1%),
# 2030198 source (77.9%), 2607336 total lines
# (2.739 secs, 951872 lines/sec)
# % python3 locs.py -rec ~/Projects
# 8691 *.py files: 365037 blank (14.0%), 212100 comment (8.1%),
# 2030198 source (77.9%), 2607335 total lines
# (2.599 secs, 1003158 lines/sec)
# % python3 locs.py -h
# usage: locs.py [-help] [-recurse] [-verbose] <file_or_dir_name> ...
# Tested with 64-bit Python 2.7.10 and 3.5.1 on MacOS 10.11.6 only.
from glob import iglob
from os.path import basename, exists, isdir, join
from time import time
__all__ = ('Loc',)
__version__ = '16.10.25'
class Loc(object):
'''Lines-Of-Code accumulator.
'''
blank = 42
comment = 0
files = 0
source = 0
ext = '.py'
_time0 = 0
_recurse = False # process dirs
_verbose = False # print details
def __init__(self, recurse=False, verbose=False):
if recurse:
self._recurse = recurse
if verbose:
self._verbose = verbose
self._time0 = time()
def __str__(self):
s = time() - self._time0
n = self.source + self.comment + self.blank
p = int(n / s) if n > s > 0 else '-'
t = ['%s *%s files:' % (self.files, self.ext),
self._bcst(self.blank, self.comment, self.source),
'(%.3f secs, %s lines/sec)' % (s, p)]
return ' '.join(t)
def _bcst(self, blank, comment, source):
t, n = [], blank + comment + source
for a, v in (('blank', blank),
('comment', comment),
('source', source)):
p = ' (%.1f%%)' % ((v * 100.0) / n,) if n > 0 else ''
t.append('%s %s%s' % (v, a, p))
t.append('%s total lines' % (n,))
return ', '.join(t)
def adir(self, name):
'''Process a directory.
'''
if self._recurse:
if self._verbose:
print(' dir %s: %s' % (name, '...'))
b, c, s = self.blank, self.comment, self.source
self.aglob(join(name, '*'))
b = self.blank - b
c = self.comment - c
s = self.source - s
t = name, self._bcst(b, c, s)
print(' dir %s: %s' % t)
else:
self.aglob(join(name, '*'))
def afile(self, name):
'''Process a file.
'''
if name.endswith(self.ext) and exists(name):
b = c = s = 0
with open(name, 'rb') as f:
for t in f.readlines():
t = t.lstrip()
if not t:
b += 1
elif t.startswith(b'#'): # Python 3+
c += 1
else:
s += 1
self.blank += b
self.comment += c
self.source += s
self.files += 1
if self._verbose:
t = self.files, name, self._bcst(b, c, s)
print('file %s %s: %s' % t)
def aglob(self, wild):
'''Process a possible wildcard.
'''
for t in iglob(wild):
if isdir(t):
self.adir(t)
else:
self.afile(t)
if __name__ == '__main__':
import sys
argv0 = basename(sys.argv[0])<|fim▁hole|> try:
for arg in sys.argv[1:]:
if not arg.startswith('-'):
loc.aglob(arg)
elif '-help'.startswith(arg):
print('usage: %s [-help] [-recurse] [-verbose] <file_or_dir_name> ...' % (argv0,))
sys.exit(0)
elif '-recurse'.startswith(arg):
loc._recurse = True
elif '-verbose'.startswith(arg):
loc._verbose = True
elif arg != '--':
print('%s: invalid option: %r' % (argv0, arg))
sys.exit(1)
except KeyboardInterrupt:
print('')
print('%s' % (loc,))<|fim▁end|> |
loc = Loc() |
<|file_name|>ActionOutilTrait.java<|end_file_name|><|fim▁begin|>package controler;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.Observable;
import java.util.Observer;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
// INTERNE
import model.Model;
import ressources.URLIcons;
/**
* Listener pour le bouton trait.
*
<|fim▁hole|> * @author Pierre-Édouard Caron
*
* @version 0.4 finale
*/
public class ActionOutilTrait extends AbstractAction implements Observer {
private Model model;
private JButton bouton;
/**
* Ne comporte pas de nom, autrement
* l'affichage ne s'effectuerait pas correctement
*
* @param model Modèle du MVC
*/
public ActionOutilTrait(Model model, JButton bouton) {
this.model = model;
model.addObserver(this);
this.bouton = bouton;
// Values
this.putValue(SHORT_DESCRIPTION, "Sélectionne l'outil trait");
this.putValue(SMALL_ICON, new ImageIcon(URLIcons.CRAYON));
}
/**
* Sélectionne l'outil trait dans le modèle.
*/
public void actionPerformed(ActionEvent e) {
model.setObjetCourant("trait");
model.deselectionnerToutesLesFormes();
}
/**
* Crée des bordures lorsque cet outil est sélectionné dans le modèle.
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(Observable arg0, Object arg1) {
if (model.getObjetCourant().equals("trait")) {
bouton.setBackground(new Color(220, 220, 220));
bouton.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.GRAY));
} else {
bouton.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY));
bouton.setBackground(Color.WHITE);
}
}
}<|fim▁end|> | * @author Alexandre Thorez
* @author Fabien Huitelec
|
<|file_name|>lightstreamer-adapter.js<|end_file_name|><|fim▁begin|>/*
Copyright (c) Lightstreamer Srl
Licensed under the Apache License, Version 2.0 (the "License");<|fim▁hole|>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Module DataProvider export.
*
* @ignore
*/
exports.DataProvider = require('./dataprovider').DataProvider;
/**
* Module MetadataProvider export.
*
* @ignore
*/
exports.MetadataProvider = require('./metadataprovider').MetadataProvider;<|fim▁end|> | 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 |
<|file_name|>HistoryComplete.java<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.data.history;
/**
* History that records a data from a simulation. When existing space
* is insufficient to hold new data, the array to hold the data is doubled
* in length.
*
* @author Andrew Schultz
*/
public class HistoryComplete implements History {
public HistoryComplete() {this(100);}
public HistoryComplete(int n) {
setHistoryLength(n);
reset();
doCollapseOnReset = true;
}
/**
* Sets the number of values kept in the history.
*/
public void setHistoryLength(int n) {
int originalLength = history.length;
if (n < cursor) {
throw new IllegalArgumentException("decreasing history length would clobber data");
}
if (n==originalLength) return;
double[] temp = new double[n];
System.arraycopy(xValues,0,temp,0,cursor);
xValues = temp;
for (int i = cursor; i<n; i++) {
xValues[i] = Double.NaN;
}
temp = new double[n];
System.arraycopy(history,0,temp,0,cursor);
history = temp;
for (int i = cursor; i<n; i++) {
history[i] = Double.NaN;
}
}
public int getHistoryLength() {
return history.length;
}
public int getSampleCount() {
return cursor;
}
/**
* Removes entire history, setting all values to NaN.
*/
public void reset() {
int nValues = getHistoryLength();
if (doCollapseOnReset && nValues > 100) {
xValues = new double[100];
history = new double[100];
}
for(int i=0; i<nValues; i++) {
xValues[i] = Double.NaN;
history[i] = Double.NaN;
}
cursor = 0;
}
public double[] getXValues() {
return xValues;
}
public boolean addValue(double x, double y) {
if (cursor == history.length) {
int newLength = history.length*2;
if (newLength == 0) {
newLength = 1;
}
setHistoryLength(newLength);
}
xValues[cursor] = x;
history[cursor] = y;
cursor++;
return true;
}
/**
* Returns an the history
*/
public double[] getHistory() {<|fim▁hole|> return history;
}
/**
* Sets a flag that determines if the history is collapsed (to 100 data
* points) when reset is called. If the current history length is less
* than 100, the history length is unchanged.
*/
public void setCollapseOnReset(boolean flag) {
doCollapseOnReset = flag;
}
/**
* Returns true if the history is collapsed (to 100 data points) when reset
* is called. If the current history length is less than 100, the history
* length is unchanged.
*/
public boolean isCollapseOnReset() {
return doCollapseOnReset;
}
public boolean willDiscardNextData() {
return false;
}
private double[] history = new double[0];
private double[] xValues = new double[0];
private int cursor;
private boolean doCollapseOnReset;
}<|fim▁end|> | |
<|file_name|>dicts.js<|end_file_name|><|fim▁begin|>module.exports = {
'ar': require('../../i18n/ar.json'),
'da': require('../../i18n/da.json'),
'de': require('../../i18n/de.json'),
'en': require('../../i18n/en.json'),
'es': require('../../i18n/es.json'),
'fr': require('../../i18n/fr-FR.json'),
'fr-FR': require('../../i18n/fr-FR.json'),
'he': require('../../i18n/he.json'),
'it': require('../../i18n/it.json'),
'ja': require('../../i18n/ja.json'),
'ko': require('../../i18n/ko.json'),
'nb-NO': require('../../i18n/nb-NO.json'),
'nl': require('../../i18n/nl-NL.json'),
'nl-NL': require('../../i18n/nl-NL.json'),<|fim▁hole|> 'tlh': require('../../i18n/tlh.json'),
'tr': require('../../i18n/tr.json'),
'zh': require('../../i18n/zh.json'),
'zh-TW': require('../../i18n/zh-TW.json')
}<|fim▁end|> | 'pt': require('../../i18n/pt.json'),
'pt-BR': require('../../i18n/pt-BR.json'),
'ru': require('../../i18n/ru.json'),
'sv': require('../../i18n/sv.json'), |
<|file_name|>autofill_profile.cc<|end_file_name|><|fim▁begin|>// Copyright 2013 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 "components/autofill/core/browser/autofill_profile.h"
#include <algorithm>
#include <functional>
#include <map>
#include <ostream>
#include <set>
#include "base/basictypes.h"
#include "base/guid.h"
#include "base/i18n/case_conversion.h"
#include "base/i18n/char_iterator.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/sha1.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/address.h"
#include "components/autofill/core/browser/address_i18n.h"
#include "components/autofill/core/browser/autofill_country.h"
#include "components/autofill/core/browser/autofill_field.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/contact_info.h"
#include "components/autofill/core/browser/phone_number.h"
#include "components/autofill/core/browser/phone_number_i18n.h"
#include "components/autofill/core/browser/state_names.h"
#include "components/autofill/core/browser/validation.h"
#include "components/autofill/core/common/autofill_l10n_util.h"
#include "components/autofill/core/common/form_field_data.h"
#include "grit/components_strings.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/libaddressinput/chromium/addressinput_util.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_metadata.h"
#include "ui/base/l10n/l10n_util.h"
using base::ASCIIToUTF16;
using base::UTF16ToUTF8;
using i18n::addressinput::AddressData;
using i18n::addressinput::AddressField;
namespace autofill {
namespace {
// Like |AutofillType::GetStorableType()|, but also returns |NAME_FULL| for
// first, middle, and last name field types, and groups phone number types
// similarly.
ServerFieldType GetStorableTypeCollapsingGroups(ServerFieldType type) {
ServerFieldType storable_type = AutofillType(type).GetStorableType();
if (AutofillType(storable_type).group() == NAME)
return NAME_FULL;
if (AutofillType(storable_type).group() == PHONE_HOME)
return PHONE_HOME_WHOLE_NUMBER;
return storable_type;
}
// Returns a value that represents specificity/privacy of the given type. This
// is used for prioritizing which data types are shown in inferred labels. For
// example, if the profile is going to fill ADDRESS_HOME_ZIP, it should
// prioritize showing that over ADDRESS_HOME_STATE in the suggestion sublabel.
int SpecificityForType(ServerFieldType type) {
switch (type) {
case ADDRESS_HOME_LINE1:
return 1;
case ADDRESS_HOME_LINE2:
return 2;
case EMAIL_ADDRESS:
return 3;
case PHONE_HOME_WHOLE_NUMBER:
return 4;
case NAME_FULL:
return 5;
case ADDRESS_HOME_ZIP:
return 6;
case ADDRESS_HOME_SORTING_CODE:
return 7;
case COMPANY_NAME:
return 8;
case ADDRESS_HOME_CITY:
return 9;
case ADDRESS_HOME_STATE:
return 10;
case ADDRESS_HOME_COUNTRY:
return 11;
default:
break;
}
// The priority of other types is arbitrary, but deterministic.
return 100 + type;
}
bool CompareSpecificity(ServerFieldType type1, ServerFieldType type2) {
return SpecificityForType(type1) < SpecificityForType(type2);
}
// Fills |distinguishing_fields| with a list of fields to use when creating
// labels that can help to distinguish between two profiles. Draws fields from
// |suggested_fields| if it is non-NULL; otherwise returns a default list.
// If |suggested_fields| is non-NULL, does not include |excluded_field| in the
// list. Otherwise, |excluded_field| is ignored, and should be set to
// |UNKNOWN_TYPE| by convention. The resulting list of fields is sorted in
// decreasing order of importance.
void GetFieldsForDistinguishingProfiles(
const std::vector<ServerFieldType>* suggested_fields,
ServerFieldType excluded_field,
std::vector<ServerFieldType>* distinguishing_fields) {
static const ServerFieldType kDefaultDistinguishingFields[] = {
NAME_FULL,
ADDRESS_HOME_LINE1,
ADDRESS_HOME_LINE2,
ADDRESS_HOME_DEPENDENT_LOCALITY,
ADDRESS_HOME_CITY,
ADDRESS_HOME_STATE,
ADDRESS_HOME_ZIP,
ADDRESS_HOME_SORTING_CODE,
ADDRESS_HOME_COUNTRY,
EMAIL_ADDRESS,
PHONE_HOME_WHOLE_NUMBER,
COMPANY_NAME,
};
std::vector<ServerFieldType> default_fields;
if (!suggested_fields) {
default_fields.assign(
kDefaultDistinguishingFields,
kDefaultDistinguishingFields + arraysize(kDefaultDistinguishingFields));
if (excluded_field == UNKNOWN_TYPE) {
distinguishing_fields->swap(default_fields);
return;
}
suggested_fields = &default_fields;
}
// Keep track of which fields we've seen so that we avoid duplicate entries.
// Always ignore fields of unknown type and the excluded field.
std::set<ServerFieldType> seen_fields;
seen_fields.insert(UNKNOWN_TYPE);
seen_fields.insert(GetStorableTypeCollapsingGroups(excluded_field));
distinguishing_fields->clear();
for (const ServerFieldType& it : *suggested_fields) {
ServerFieldType suggested_type = GetStorableTypeCollapsingGroups(it);
if (seen_fields.insert(suggested_type).second)
distinguishing_fields->push_back(suggested_type);
}
std::sort(distinguishing_fields->begin(), distinguishing_fields->end(),
CompareSpecificity);
// Special case: If the excluded field is a partial name (e.g. first name) and
// the suggested fields include other name fields, include |NAME_FULL| in the
// list of distinguishing fields as a last-ditch fallback. This allows us to
// distinguish between profiles that are identical except for the name.
ServerFieldType effective_excluded_type =
GetStorableTypeCollapsingGroups(excluded_field);
if (excluded_field != effective_excluded_type) {
for (const ServerFieldType& it : *suggested_fields) {
if (it != excluded_field &&
GetStorableTypeCollapsingGroups(it) == effective_excluded_type) {
distinguishing_fields->push_back(effective_excluded_type);
break;
}
}
}
}
// Collapse compound field types to their "full" type. I.e. First name
// collapses to full name, area code collapses to full phone, etc.
void CollapseCompoundFieldTypes(ServerFieldTypeSet* type_set) {
ServerFieldTypeSet collapsed_set;
for (const auto& it : *type_set) {
switch (it) {
case NAME_FIRST:
case NAME_MIDDLE:
case NAME_LAST:
case NAME_MIDDLE_INITIAL:
case NAME_FULL:
case NAME_SUFFIX:
collapsed_set.insert(NAME_FULL);
break;
case PHONE_HOME_NUMBER:
case PHONE_HOME_CITY_CODE:
case PHONE_HOME_COUNTRY_CODE:
case PHONE_HOME_CITY_AND_NUMBER:
case PHONE_HOME_WHOLE_NUMBER:
collapsed_set.insert(PHONE_HOME_WHOLE_NUMBER);
break;
default:
collapsed_set.insert(it);
}
}
std::swap(*type_set, collapsed_set);
}
class FindByPhone {
public:
FindByPhone(const base::string16& phone,
const std::string& country_code,
const std::string& app_locale)
: phone_(phone),
country_code_(country_code),
app_locale_(app_locale) {}
bool operator()(const base::string16& phone) {
return i18n::PhoneNumbersMatch(phone, phone_, country_code_, app_locale_);
}
private:
base::string16 phone_;
std::string country_code_;
std::string app_locale_;
};
} // namespace
AutofillProfile::AutofillProfile(const std::string& guid,
const std::string& origin)
: AutofillDataModel(guid, origin),
record_type_(LOCAL_PROFILE),
phone_number_(this) {
}
AutofillProfile::AutofillProfile(RecordType type, const std::string& server_id)
: AutofillDataModel(base::GenerateGUID(), std::string()),
record_type_(type),
phone_number_(this),
server_id_(server_id) {
DCHECK(type == SERVER_PROFILE);
}
AutofillProfile::AutofillProfile()
: AutofillDataModel(base::GenerateGUID(), std::string()),
record_type_(LOCAL_PROFILE),
phone_number_(this) {
}
AutofillProfile::AutofillProfile(const AutofillProfile& profile)
: AutofillDataModel(std::string(), std::string()), phone_number_(this) {
operator=(profile);
}
AutofillProfile::~AutofillProfile() {
}
AutofillProfile& AutofillProfile::operator=(const AutofillProfile& profile) {
set_use_count(profile.use_count());
set_use_date(profile.use_date());
set_modification_date(profile.modification_date());
if (this == &profile)
return *this;
set_guid(profile.guid());
set_origin(profile.origin());
record_type_ = profile.record_type_;
name_ = profile.name_;
email_ = profile.email_;
company_ = profile.company_;
phone_number_ = profile.phone_number_;
phone_number_.set_profile(this);
address_ = profile.address_;
set_language_code(profile.language_code());
server_id_ = profile.server_id();
return *this;
}
void AutofillProfile::GetMatchingTypes(
const base::string16& text,
const std::string& app_locale,
ServerFieldTypeSet* matching_types) const {
FormGroupList info = FormGroups();
for (const auto& it : info) {
it->GetMatchingTypes(text, app_locale, matching_types);
}
}
base::string16 AutofillProfile::GetRawInfo(ServerFieldType type) const {
const FormGroup* form_group = FormGroupForType(AutofillType(type));
if (!form_group)
return base::string16();
return form_group->GetRawInfo(type);
}
void AutofillProfile::SetRawInfo(ServerFieldType type,
const base::string16& value) {
FormGroup* form_group = MutableFormGroupForType(AutofillType(type));
if (form_group)
form_group->SetRawInfo(type, value);
}
base::string16 AutofillProfile::GetInfo(const AutofillType& type,
const std::string& app_locale) const {
if (type.html_type() == HTML_TYPE_FULL_ADDRESS) {
scoped_ptr<AddressData> address_data =
i18n::CreateAddressDataFromAutofillProfile(*this, app_locale);
if (!addressinput::HasAllRequiredFields(*address_data))
return base::string16();
std::vector<std::string> lines;
::i18n::addressinput::GetFormattedNationalAddress(*address_data, &lines);
return base::UTF8ToUTF16(base::JoinString(lines, "\n"));
}
const FormGroup* form_group = FormGroupForType(type);
if (!form_group)
return base::string16();
return form_group->GetInfo(type, app_locale);
}
bool AutofillProfile::SetInfo(const AutofillType& type,
const base::string16& value,
const std::string& app_locale) {
FormGroup* form_group = MutableFormGroupForType(type);
if (!form_group)
return false;
base::string16 trimmed_value;
base::TrimWhitespace(value, base::TRIM_ALL, &trimmed_value);
return form_group->SetInfo(type, trimmed_value, app_locale);
}
bool AutofillProfile::IsEmpty(const std::string& app_locale) const {
ServerFieldTypeSet types;
GetNonEmptyTypes(app_locale, &types);
return types.empty();
}
bool AutofillProfile::IsPresentButInvalid(ServerFieldType type) const {
std::string country = UTF16ToUTF8(GetRawInfo(ADDRESS_HOME_COUNTRY));
base::string16 data = GetRawInfo(type);
if (data.empty())
return false;
switch (type) {
case ADDRESS_HOME_STATE:
return country == "US" && !IsValidState(data);
case ADDRESS_HOME_ZIP:
return country == "US" && !IsValidZip(data);
case PHONE_HOME_WHOLE_NUMBER:
return !i18n::PhoneObject(data, country).IsValidNumber();
case EMAIL_ADDRESS:
return !IsValidEmailAddress(data);
default:
NOTREACHED();
return false;
}
}
int AutofillProfile::Compare(const AutofillProfile& profile) const {
const ServerFieldType types[] = {
NAME_FULL,
NAME_FIRST,
NAME_MIDDLE,
NAME_LAST,
COMPANY_NAME,
ADDRESS_HOME_STREET_ADDRESS,
ADDRESS_HOME_DEPENDENT_LOCALITY,
ADDRESS_HOME_CITY,
ADDRESS_HOME_STATE,
ADDRESS_HOME_ZIP,
ADDRESS_HOME_SORTING_CODE,
ADDRESS_HOME_COUNTRY,
EMAIL_ADDRESS,
PHONE_HOME_WHOLE_NUMBER,
};
for (size_t i = 0; i < arraysize(types); ++i) {
int comparison = GetRawInfo(types[i]).compare(profile.GetRawInfo(types[i]));
if (comparison != 0) {
return comparison;
}
}
return 0;
}
bool AutofillProfile::EqualsSansOrigin(const AutofillProfile& profile) const {
return guid() == profile.guid() &&
language_code() == profile.language_code() &&
Compare(profile) == 0;
}
bool AutofillProfile::EqualsForSyncPurposes(const AutofillProfile& profile)
const {
return use_count() == profile.use_count() &&
use_date() == profile.use_date() &&
EqualsSansGuid(profile);
}
bool AutofillProfile::operator==(const AutofillProfile& profile) const {
return guid() == profile.guid() && EqualsSansGuid(profile);
}
bool AutofillProfile::operator!=(const AutofillProfile& profile) const {
return !operator==(profile);
}
const base::string16 AutofillProfile::PrimaryValue() const {
return GetRawInfo(ADDRESS_HOME_LINE1) + GetRawInfo(ADDRESS_HOME_CITY);
}
bool AutofillProfile::IsSubsetOf(const AutofillProfile& profile,
const std::string& app_locale) const {
ServerFieldTypeSet types;
GetSupportedTypes(&types);
return IsSubsetOfForFieldSet(profile, app_locale, types);
}
bool AutofillProfile::IsSubsetOfForFieldSet(
const AutofillProfile& profile,
const std::string& app_locale,
const ServerFieldTypeSet& types) const {
scoped_ptr<l10n::CaseInsensitiveCompare> compare;
for (ServerFieldType type : types) {
base::string16 value = GetRawInfo(type);
if (value.empty())
continue;
if (type == NAME_FULL || type == ADDRESS_HOME_STREET_ADDRESS) {
// Ignore the compound "full name" field type. We are only interested in
// comparing the constituent parts. For example, if |this| has a middle
// name saved, but |profile| lacks one, |profile| could still be a subset
// of |this|. Likewise, ignore the compound "street address" type, as we
// are only interested in matching line-by-line.
continue;
} else if (AutofillType(type).group() == PHONE_HOME) {
// Phone numbers should be canonicalized prior to being compared.
if (type != PHONE_HOME_WHOLE_NUMBER) {
continue;
} else if (!i18n::PhoneNumbersMatch(
value, profile.GetRawInfo(type),
base::UTF16ToASCII(GetRawInfo(ADDRESS_HOME_COUNTRY)),
app_locale)) {
return false;
}
} else {
if (!compare)
compare.reset(new l10n::CaseInsensitiveCompare());
if (!compare->StringsEqual(value, profile.GetRawInfo(type)))
return false;
}
}
return true;
}
bool AutofillProfile::OverwriteName(const NameInfo& imported_name,
const std::string& app_locale) {
if (name_.ParsedNamesAreEqual(imported_name)) {
if (name_.GetRawInfo(NAME_FULL).empty() &&
!imported_name.GetRawInfo(NAME_FULL).empty()) {
name_.SetRawInfo(NAME_FULL, imported_name.GetRawInfo(NAME_FULL));
return true;
}
return false;
}
l10n::CaseInsensitiveCompare compare;
AutofillType type = AutofillType(NAME_FULL);
base::string16 full_name = name_.GetInfo(type, app_locale);
if (compare.StringsEqual(full_name,
imported_name.GetInfo(type, app_locale))) {
// The imported name has the same full name string as the name for this
// profile. Because full names are _heuristically_ parsed into
// {first, middle, last} name components, it's possible that either the
// existing name or the imported name was misparsed. Prefer to keep the
// name whose {first, middle, last} components do not match those computed
// by the heuristic parse, as this more likely represents the correct,
// user-input parse of the name.
NameInfo heuristically_parsed_name;
heuristically_parsed_name.SetInfo(type, full_name, app_locale);
if (imported_name.ParsedNamesAreEqual(heuristically_parsed_name))
return false;
}
name_ = imported_name;
return true;
}
bool AutofillProfile::OverwriteWith(const AutofillProfile& profile,
const std::string& app_locale) {
// Verified profiles should never be overwritten with unverified data.
DCHECK(!IsVerified() || profile.IsVerified());
set_origin(profile.origin());
set_language_code(profile.language_code());
set_use_count(profile.use_count() + use_count());
if (profile.use_date() > use_date())
set_use_date(profile.use_date());
ServerFieldTypeSet field_types;
profile.GetNonEmptyTypes(app_locale, &field_types);
// Only transfer "full" types (e.g. full name) and not fragments (e.g.
// first name, last name).
CollapseCompoundFieldTypes(&field_types);
// Remove ADDRESS_HOME_STREET_ADDRESS to ensure a merge of the address line by
// line. See comment below.
field_types.erase(ADDRESS_HOME_STREET_ADDRESS);
l10n::CaseInsensitiveCompare compare;
// Special case for addresses. With the whole address comparison, it is now
// necessary to make sure to keep the best address format: both lines used.
// This is because some sites might not have an address line 2 and the
// previous value should not be replaced with an empty string in that case.
if (compare.StringsEqual(
CanonicalizeProfileString(
profile.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)),
CanonicalizeProfileString(GetRawInfo(ADDRESS_HOME_STREET_ADDRESS))) &&
!GetRawInfo(ADDRESS_HOME_LINE2).empty() &&
profile.GetRawInfo(ADDRESS_HOME_LINE2).empty()) {
field_types.erase(ADDRESS_HOME_LINE1);
field_types.erase(ADDRESS_HOME_LINE2);
}
bool did_overwrite = false;
for (ServerFieldTypeSet::const_iterator iter = field_types.begin();
iter != field_types.end(); ++iter) {
FieldTypeGroup group = AutofillType(*iter).group();
// Special case names.
if (group == NAME) {
did_overwrite = OverwriteName(profile.name_, app_locale) || did_overwrite;
continue;
}
base::string16 new_value = profile.GetRawInfo(*iter);
if (!compare.StringsEqual(GetRawInfo(*iter), new_value)) {
SetRawInfo(*iter, new_value);
did_overwrite = true;
}
}
return did_overwrite;
}
bool AutofillProfile::SaveAdditionalInfo(const AutofillProfile& profile,
const std::string& app_locale) {
ServerFieldTypeSet field_types, other_field_types;
GetNonEmptyTypes(app_locale, &field_types);
profile.GetNonEmptyTypes(app_locale, &other_field_types);
// The address needs to be compared line by line to take into account the
// logic for empty fields implemented in the loop.
field_types.erase(ADDRESS_HOME_STREET_ADDRESS);
l10n::CaseInsensitiveCompare compare;
for (ServerFieldType field_type : field_types) {
if (other_field_types.count(field_type)) {
AutofillType type = AutofillType(field_type);
// Special cases for name and phone. If the whole/full value matches, skip
// the individual fields comparison.
if (type.group() == NAME &&
compare.StringsEqual(
profile.GetInfo(AutofillType(NAME_FULL), app_locale),
GetInfo(AutofillType(NAME_FULL), app_locale))) {
continue;
}
if (type.group() == PHONE_HOME &&
i18n::PhoneNumbersMatch(
GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
base::UTF16ToASCII(GetRawInfo(ADDRESS_HOME_COUNTRY)),
app_locale)) {
continue;
}
// Special case for the address because the comparison uses canonicalized
// values. Start by comparing the address line by line. If it fails, make
// sure that the address as a whole is different before returning false.
// It is possible that the user put the info from line 2 on line 1 because
// of a certain form for example.
if (field_type == ADDRESS_HOME_LINE1 ||
field_type == ADDRESS_HOME_LINE2) {
if (!compare.StringsEqual(
CanonicalizeProfileString(profile.GetRawInfo(field_type)),
CanonicalizeProfileString(GetRawInfo(field_type))) &&
!compare.StringsEqual(CanonicalizeProfileString(profile.GetRawInfo(
ADDRESS_HOME_STREET_ADDRESS)),
CanonicalizeProfileString(GetRawInfo(
ADDRESS_HOME_STREET_ADDRESS)))) {
return false;
}
continue;
}
// Special case for the state to support abbreviations. Currently only the
// US states are supported.
if (field_type == ADDRESS_HOME_STATE) {
base::string16 full, abbreviation;
state_names::GetNameAndAbbreviation(GetRawInfo(ADDRESS_HOME_STATE),
&full, &abbreviation);
if (compare.StringsEqual(profile.GetRawInfo(ADDRESS_HOME_STATE),
full) ||
compare.StringsEqual(profile.GetRawInfo(ADDRESS_HOME_STATE),
abbreviation))
continue;
}
if (!compare.StringsEqual(profile.GetRawInfo(field_type),
GetRawInfo(field_type))) {
return false;
}
}
}
if (!IsVerified() || profile.IsVerified()) {
if (OverwriteWith(profile, app_locale)) {
AutofillMetrics::LogProfileActionOnFormSubmitted(
AutofillMetrics::EXISTING_PROFILE_UPDATED);
} else {
AutofillMetrics::LogProfileActionOnFormSubmitted(
AutofillMetrics::EXISTING_PROFILE_USED);
}
}
return true;
}
// static
bool AutofillProfile::SupportsMultiValue(ServerFieldType type) {
FieldTypeGroup group = AutofillType(type).group();
return group == NAME ||
group == NAME_BILLING ||
group == EMAIL ||
group == PHONE_HOME ||
group == PHONE_BILLING;
}
// static
void AutofillProfile::CreateDifferentiatingLabels(
const std::vector<AutofillProfile*>& profiles,
const std::string& app_locale,
std::vector<base::string16>* labels) {
const size_t kMinimalFieldsShown = 2;
CreateInferredLabels(profiles, NULL, UNKNOWN_TYPE, kMinimalFieldsShown,
app_locale, labels);
DCHECK_EQ(profiles.size(), labels->size());
}<|fim▁hole|> const std::vector<ServerFieldType>* suggested_fields,
ServerFieldType excluded_field,
size_t minimal_fields_shown,
const std::string& app_locale,
std::vector<base::string16>* labels) {
std::vector<ServerFieldType> fields_to_use;
GetFieldsForDistinguishingProfiles(suggested_fields, excluded_field,
&fields_to_use);
// Construct the default label for each profile. Also construct a map that
// associates each label with the profiles that have this label. This map is
// then used to detect which labels need further differentiating fields.
std::map<base::string16, std::list<size_t> > labels_to_profiles;
for (size_t i = 0; i < profiles.size(); ++i) {
base::string16 label =
profiles[i]->ConstructInferredLabel(fields_to_use,
minimal_fields_shown,
app_locale);
labels_to_profiles[label].push_back(i);
}
labels->resize(profiles.size());
for (auto& it : labels_to_profiles) {
if (it.second.size() == 1) {
// This label is unique, so use it without any further ado.
base::string16 label = it.first;
size_t profile_index = it.second.front();
(*labels)[profile_index] = label;
} else {
// We have more than one profile with the same label, so add
// differentiating fields.
CreateInferredLabelsHelper(profiles, it.second, fields_to_use,
minimal_fields_shown, app_locale, labels);
}
}
}
void AutofillProfile::GenerateServerProfileIdentifier() {
DCHECK_EQ(SERVER_PROFILE, record_type());
base::string16 contents = GetRawInfo(NAME_FIRST);
contents.append(GetRawInfo(NAME_MIDDLE));
contents.append(GetRawInfo(NAME_LAST));
contents.append(GetRawInfo(EMAIL_ADDRESS));
contents.append(GetRawInfo(COMPANY_NAME));
contents.append(GetRawInfo(ADDRESS_HOME_STREET_ADDRESS));
contents.append(GetRawInfo(ADDRESS_HOME_DEPENDENT_LOCALITY));
contents.append(GetRawInfo(ADDRESS_HOME_CITY));
contents.append(GetRawInfo(ADDRESS_HOME_STATE));
contents.append(GetRawInfo(ADDRESS_HOME_ZIP));
contents.append(GetRawInfo(ADDRESS_HOME_SORTING_CODE));
contents.append(GetRawInfo(ADDRESS_HOME_COUNTRY));
contents.append(GetRawInfo(PHONE_HOME_WHOLE_NUMBER));
std::string contents_utf8 = UTF16ToUTF8(contents);
contents_utf8.append(language_code());
server_id_ = base::SHA1HashString(contents_utf8);
}
void AutofillProfile::RecordAndLogUse() {
UMA_HISTOGRAM_COUNTS_1000("Autofill.DaysSinceLastUse.Profile",
(base::Time::Now() - use_date()).InDays());
RecordUse();
}
// static
base::string16 AutofillProfile::CanonicalizeProfileString(
const base::string16& str) {
base::string16 ret;
ret.reserve(str.size());
bool previous_was_whitespace = false;
// This algorithm isn't designed to be perfect, we could get arbitrarily
// fancy here trying to canonicalize address lines. Instead, this is designed
// to handle common cases for all types of data (addresses and names)
// without the need of domain-specific logic.
base::i18n::UTF16CharIterator iter(&str);
while (!iter.end()) {
switch (u_charType(iter.get())) {
case U_DASH_PUNCTUATION:
case U_START_PUNCTUATION:
case U_END_PUNCTUATION:
case U_CONNECTOR_PUNCTUATION:
case U_OTHER_PUNCTUATION:
// Convert punctuation to spaces. This will convert "Mid-Island Plz."
// -> "Mid Island Plz" (the trailing space will be trimmed off at the
// end of the loop).
if (!previous_was_whitespace) {
ret.push_back(' ');
previous_was_whitespace = true;
}
break;
case U_CONTROL_CHAR: // To escape the '\n' character.
case U_SPACE_SEPARATOR:
case U_LINE_SEPARATOR:
case U_PARAGRAPH_SEPARATOR:
// Convert sequences of spaces to single spaces.
if (!previous_was_whitespace) {
ret.push_back(' ');
previous_was_whitespace = true;
}
break;
case U_UPPERCASE_LETTER:
case U_TITLECASE_LETTER:
previous_was_whitespace = false;
base::WriteUnicodeCharacter(u_tolower(iter.get()), &ret);
break;
default:
previous_was_whitespace = false;
base::WriteUnicodeCharacter(iter.get(), &ret);
break;
}
iter.Advance();
}
// Trim off trailing whitespace if we left one.
if (previous_was_whitespace)
ret.resize(ret.size() - 1);
return ret;
}
// static
bool AutofillProfile::AreProfileStringsSimilar(const base::string16& a,
const base::string16& b) {
return CanonicalizeProfileString(a) == CanonicalizeProfileString(b);
}
void AutofillProfile::GetSupportedTypes(
ServerFieldTypeSet* supported_types) const {
FormGroupList info = FormGroups();
for (const auto& it : info) {
it->GetSupportedTypes(supported_types);
}
}
base::string16 AutofillProfile::ConstructInferredLabel(
const std::vector<ServerFieldType>& included_fields,
size_t num_fields_to_use,
const std::string& app_locale) const {
// TODO(estade): use libaddressinput?
base::string16 separator =
l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESS_SUMMARY_SEPARATOR);
AutofillType region_code_type(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE);
const base::string16& profile_region_code =
GetInfo(region_code_type, app_locale);
std::string address_region_code = UTF16ToUTF8(profile_region_code);
// A copy of |this| pruned down to contain only data for the address fields in
// |included_fields|.
AutofillProfile trimmed_profile(guid(), origin());
trimmed_profile.SetInfo(region_code_type, profile_region_code, app_locale);
trimmed_profile.set_language_code(language_code());
std::vector<ServerFieldType> remaining_fields;
for (std::vector<ServerFieldType>::const_iterator it =
included_fields.begin();
it != included_fields.end() && num_fields_to_use > 0;
++it) {
AddressField address_field;
if (!i18n::FieldForType(*it, &address_field) ||
!::i18n::addressinput::IsFieldUsed(
address_field, address_region_code) ||
address_field == ::i18n::addressinput::COUNTRY) {
remaining_fields.push_back(*it);
continue;
}
AutofillType autofill_type(*it);
const base::string16& field_value = GetInfo(autofill_type, app_locale);
if (field_value.empty())
continue;
trimmed_profile.SetInfo(autofill_type, field_value, app_locale);
--num_fields_to_use;
}
scoped_ptr<AddressData> address_data =
i18n::CreateAddressDataFromAutofillProfile(trimmed_profile, app_locale);
std::string address_line;
::i18n::addressinput::GetFormattedNationalAddressLine(
*address_data, &address_line);
base::string16 label = base::UTF8ToUTF16(address_line);
for (std::vector<ServerFieldType>::const_iterator it =
remaining_fields.begin();
it != remaining_fields.end() && num_fields_to_use > 0;
++it) {
const base::string16& field_value = GetInfo(AutofillType(*it), app_locale);
if (field_value.empty())
continue;
if (!label.empty())
label.append(separator);
label.append(field_value);
--num_fields_to_use;
}
// If country code is missing, libaddressinput won't be used to format the
// address. In this case the suggestion might include a multi-line street
// address which needs to be flattened.
base::ReplaceChars(label, base::ASCIIToUTF16("\n"), separator, &label);
return label;
}
// static
void AutofillProfile::CreateInferredLabelsHelper(
const std::vector<AutofillProfile*>& profiles,
const std::list<size_t>& indices,
const std::vector<ServerFieldType>& fields,
size_t num_fields_to_include,
const std::string& app_locale,
std::vector<base::string16>* labels) {
// For efficiency, we first construct a map of fields to their text values and
// each value's frequency.
std::map<ServerFieldType,
std::map<base::string16, size_t> > field_text_frequencies_by_field;
for (const ServerFieldType& field : fields) {
std::map<base::string16, size_t>& field_text_frequencies =
field_text_frequencies_by_field[field];
for (const auto& it : indices) {
const AutofillProfile* profile = profiles[it];
base::string16 field_text =
profile->GetInfo(AutofillType(field), app_locale);
// If this label is not already in the map, add it with frequency 0.
if (!field_text_frequencies.count(field_text))
field_text_frequencies[field_text] = 0;
// Now, increment the frequency for this label.
++field_text_frequencies[field_text];
}
}
// Now comes the meat of the algorithm. For each profile, we scan the list of
// fields to use, looking for two things:
// 1. A (non-empty) field that differentiates the profile from all others
// 2. At least |num_fields_to_include| non-empty fields
// Before we've satisfied condition (2), we include all fields, even ones that
// are identical across all the profiles. Once we've satisfied condition (2),
// we only include fields that that have at last two distinct values.
for (const auto& it : indices) {
const AutofillProfile* profile = profiles[it];
std::vector<ServerFieldType> label_fields;
bool found_differentiating_field = false;
for (std::vector<ServerFieldType>::const_iterator field = fields.begin();
field != fields.end(); ++field) {
// Skip over empty fields.
base::string16 field_text =
profile->GetInfo(AutofillType(*field), app_locale);
if (field_text.empty())
continue;
std::map<base::string16, size_t>& field_text_frequencies =
field_text_frequencies_by_field[*field];
found_differentiating_field |=
!field_text_frequencies.count(base::string16()) &&
(field_text_frequencies[field_text] == 1);
// Once we've found enough non-empty fields, skip over any remaining
// fields that are identical across all the profiles.
if (label_fields.size() >= num_fields_to_include &&
(field_text_frequencies.size() == 1))
continue;
label_fields.push_back(*field);
// If we've (1) found a differentiating field and (2) found at least
// |num_fields_to_include| non-empty fields, we're done!
if (found_differentiating_field &&
label_fields.size() >= num_fields_to_include)
break;
}
(*labels)[it] = profile->ConstructInferredLabel(
label_fields, label_fields.size(), app_locale);
}
}
AutofillProfile::FormGroupList AutofillProfile::FormGroups() const {
FormGroupList v(5);
v[0] = &name_;
v[1] = &email_;
v[2] = &company_;
v[3] = &phone_number_;
v[4] = &address_;
return v;
}
const FormGroup* AutofillProfile::FormGroupForType(
const AutofillType& type) const {
return const_cast<AutofillProfile*>(this)->MutableFormGroupForType(type);
}
FormGroup* AutofillProfile::MutableFormGroupForType(const AutofillType& type) {
switch (type.group()) {
case NAME:
case NAME_BILLING:
return &name_;
case EMAIL:
return &email_;
case COMPANY:
return &company_;
case PHONE_HOME:
case PHONE_BILLING:
return &phone_number_;
case ADDRESS_HOME:
case ADDRESS_BILLING:
return &address_;
case NO_GROUP:
case CREDIT_CARD:
case PASSWORD_FIELD:
case USERNAME_FIELD:
case TRANSACTION:
return NULL;
}
NOTREACHED();
return NULL;
}
bool AutofillProfile::EqualsSansGuid(const AutofillProfile& profile) const {
return origin() == profile.origin() &&
language_code() == profile.language_code() &&
Compare(profile) == 0;
}
// So we can compare AutofillProfiles with EXPECT_EQ().
std::ostream& operator<<(std::ostream& os, const AutofillProfile& profile) {
return os << profile.guid() << " " << profile.origin() << " "
<< UTF16ToUTF8(profile.GetRawInfo(NAME_FIRST)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(NAME_MIDDLE)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(NAME_LAST)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(EMAIL_ADDRESS)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(COMPANY_NAME)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_LINE1)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_LINE2)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_DEPENDENT_LOCALITY))
<< " " << UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_CITY)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_STATE)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_ZIP)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_SORTING_CODE)) << " "
<< UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY)) << " "
<< profile.language_code() << " "
<< UTF16ToUTF8(profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER));
}
} // namespace autofill<|fim▁end|> |
// static
void AutofillProfile::CreateInferredLabels(
const std::vector<AutofillProfile*>& profiles, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.