code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
import WordSearch from './word-search';
describe('single line grids', () => {
test('Should accept an initial game grid', () => {
const grid = ['jefblpepre'];
const wordSearch = new WordSearch(grid);
expect(wordSearch instanceof WordSearch).toEqual(true);
});
xtest('can accept a target search word', () => {
const grid = ['jefblpepre'];
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['glasnost'])).toEqual({ glasnost: undefined });
});
xtest('should locate a word written left to right', () => {
const grid = ['clojurermt'];
const expectedResults = {
clojure: {
start: [1, 1],
end: [1, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a different position', () => {
const grid = ['mtclojurer'];
const expectedResults = {
clojure: {
start: [1, 3],
end: [1, 9],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a different left to right word', () => {
const grid = ['coffeelplx'];
const expectedResults = {
coffee: {
start: [1, 1],
end: [1, 6],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['coffee'])).toEqual(expectedResults);
});
xtest('can locate that different left to right word in a different position', () => {
const grid = ['xcoffeezlp'];
const expectedResults = {
coffee: {
start: [1, 2],
end: [1, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['coffee'])).toEqual(expectedResults);
});
});
describe('multi line grids', () => {
xtest('can locate a left to right word in a two line grid', () => {
const grid = ['jefblpepre', 'clojurermt'];
const expectedResults = {
clojure: {
start: [2, 1],
end: [2, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a different position in a two line grid', () => {
const grid = ['jefblpepre', 'tclojurerm'];
const expectedResults = {
clojure: {
start: [2, 2],
end: [2, 8],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a three line grid', () => {
const grid = ['camdcimgtc', 'jefblpepre', 'clojurermt'];
const expectedResults = {
clojure: {
start: [3, 1],
end: [3, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a ten line grid', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a different position in a ten line grid', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'clojurermt',
'jalaycalmp',
];
const expectedResults = {
clojure: {
start: [9, 1],
end: [9, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a different left to right word in a ten line grid', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'clojurermt',
'jalaycalmp',
];
const expectedResults = {
scree: {
start: [7, 1],
end: [7, 5],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['scree'])).toEqual(expectedResults);
});
});
describe('can find multiple words', () => {
xtest('can find two words written left to right', () => {
const grid = [
'aefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
'xjavamtzlp',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
java: {
start: [11, 2],
end: [11, 5],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['java', 'clojure'])).toEqual(expectedResults);
});
});
describe('different directions', () => {
xtest('should locate a single word written right to left', () => {
const grid = ['rixilelhrs'];
const expectedResults = {
elixir: {
start: [1, 6],
end: [1, 1],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['elixir'])).toEqual(expectedResults);
});
xtest('should locate multiple words written in different horizontal directions', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['elixir', 'clojure'])).toEqual(expectedResults);
});
});
describe('vertical directions', () => {
xtest('should locate words written top to bottom', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['elixir', 'clojure', 'ecmascript'])).toEqual(
expectedResults
);
});
xtest('should locate words written bottom to top', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find(['elixir', 'clojure', 'ecmascript', 'rust'])
).toEqual(expectedResults);
});
xtest('should locate words written top left to bottom right', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find(['clojure', 'elixir', 'ecmascript', 'rust', 'java'])
).toEqual(expectedResults);
});
xtest('should locate words written bottom right to top left', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
lua: {
start: [9, 8],
end: [7, 6],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find([
'clojure',
'elixir',
'ecmascript',
'rust',
'java',
'lua',
])
).toEqual(expectedResults);
});
xtest('should locate words written bottom left to top right', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
lua: {
start: [9, 8],
end: [7, 6],
},
lisp: {
start: [6, 3],
end: [3, 6],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find([
'clojure',
'elixir',
'ecmascript',
'rust',
'java',
'lua',
'lisp',
])
).toEqual(expectedResults);
});
xtest('should locate words written top right to bottom left', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
lua: {
start: [9, 8],
end: [7, 6],
},
lisp: {
start: [6, 3],
end: [3, 6],
},
ruby: {
start: [6, 8],
end: [9, 5],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find([
'clojure',
'elixir',
'ecmascript',
'rust',
'java',
'lua',
'lisp',
'ruby',
])
).toEqual(expectedResults);
});
describe("word doesn't exist", () => {
xtest('should fail to locate a word that is not in the puzzle', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
fail: undefined,
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['fail'])).toEqual(expectedResults);
});
});
});
| exercism/xecmascript | exercises/practice/word-search/word-search.spec.js | JavaScript | mit | 12,331 |
using System;
using System.Linq;
using System.Collections.Generic;
namespace Abnaki.Windows.Software.Wpf.Ultimate
{
/// <summary>
/// Starts Ultimate MainWindow where a Tcontrol occupies all the useful space
/// </summary>
/// <typeparam name="Tcontrol">
/// </typeparam>
public class UltimateStarter<Tcontrol>
where Tcontrol : System.Windows.UIElement, Abnaki.Windows.GUI.IMainControl, new()
{
public static int Start(string[] args)
{
return Starter.Start(args, InitWindow);
}
static MainWindow InitWindow()
{
MainWindow mw = new MainWindow();
Tcontrol child = new Tcontrol();
mw.SetMainControl(child);
// Icon: alphabetically first embedded resource .ico
System.Reflection.Assembly a = child.GetType().Assembly;
string icname = a.GetManifestResourceNames().OrderBy(n => n).FirstOrDefault(n => n.EndsWith(".ico"));
if (icname != null)
mw.Icon = System.Windows.Media.Imaging.BitmapFrame.Create(a.GetManifestResourceStream(icname));
return mw;
}
}
}
| abnaki/windows | Library/Software/WpfApplication/Ultimate/UltimateStarter.cs | C# | mit | 1,221 |
'use strict';
/* Controllers */
angular.module('myApp.controllers')
.controller('DatepickerDemoCtrl', ['$scope','$timeout',function($scope, $timeout) {
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.showWeeks = true;
$scope.toggleWeeks = function () {
$scope.showWeeks = ! $scope.showWeeks;
};
$scope.clear = function () {
$scope.dt = null;
};
// Disable weekend selection
$scope.disabled = function(date, mode) {
return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
};
$scope.toggleMin = function() {
$scope.minDate = ( $scope.minDate ) ? null : new Date();
};
$scope.toggleMin();
$scope.open = function() {
$timeout(function() {
$scope.opened = true;
});
};
$scope.dateOptions = {
'year-format': "'yy'",
'starting-day': 1
};
}])
| Jeffwan/friendsDoc | app/js/controllers/datepickerDemoCtrl.js | JavaScript | mit | 1,071 |
# -*- coding: utf-8 -*-
class Courier::SubscriptionType::Base < ActiveRecord::Base
INTERPOLATION_PATTERN = Regexp.new /%\{([a-z|0-9\._]+)\}/
self.table_name = :courier_subscription_types
serialize :properties
has_many :log_entities, :foreign_key => :subscription_type_id, :class_name => 'Courier::LogEntity'
before_save do
self.subject = self.description if self.subject.blank?
self.properties = {} unless self.properties
end
# Запускаем рассылку по указанному ресурсу.
# В параметрах можно передать send_at для запуска рассылки в определенное время.
#
def notify subscription_list, resource, params={}
if use_delay?
send_at = params.delete(:send_at) || Time.zone.now
self.delay(run_at: send_at).real_notify(subscription_list, resource, params)
else
real_notify subscription_list, resource, params
end
end
def real_notify subscription_list, resource = nil, params={}
list = subscription_list.collect_subscriptions resource, params
list.each do |subscription|
safe_send_mail context( resource, subscription, params )
subscription.deactivate if subscription.temporary?
end
end
def context resource, subscription, params
context = OpenStruct.new params.merge(
:subscription_type => self,
:resource => resource,
:subscription => subscription,
:to => subscription.to,
:from => from
)
context.subject = get_subject(context)
context
end
def send_mail context
# Подготавливаем сообщение
message = mailer_class.send context.subscription_type.name, context
transaction do
lock!(true)
log_and_deliver message, context
end
end
def log_and_deliver message, context
begin
Courier::LogEntity.save_mail message, context
message.deliver
rescue ActiveRecord::RecordInvalid => e
logger.warn "Дупликат или ошибка логирования, не отправляю: #{context.to}/#{self}/#{context.object}: #{e.message}" # / #{e.record.errors.full_messages}"
end
end
def safe_send_mail context
begin
send_mail context
rescue Exception => e
# TODO Log error
if Rails.env.production?
Airbrake.notify(e) if defined?(Airbrake)
else
raise(e)
end
end
end
def use_delay?
not (Rails.env.test? or Rails.env.development?)
end
def mailer_class
Courier::Mailer::Common
end
def get_subject object = nil
interpolate subject, object || self
end
def to_s
name
end
private
# TODO Вынести в отдельный класс
def interpolate string, object
string.gsub(INTERPOLATION_PATTERN) do |match|
if match == '%%'
'%'
else
v = object
$1.split('.').each do |m|
unless v.respond_to? m
v="No such method #{m} if object #{v}"
break
end
v = v.send m
end
v.to_s
end
end
end
end
| BrandyMint/courier | app/models/courier/subscription_type/base.rb | Ruby | mit | 3,123 |
<body style="background-color: #4CAF50">
<ul class="menu-area">
<li class="menu-part-area"><a class="menu-link-area" href="<?php echo site_url('welcome/index') ?>">Domov</a></li>
</ul>
<form action="<?php echo site_url('reservation/writeplace');?>" method="post">
<div class="dark-form">
Vyberte si čas a dĺžku rezervácie. <br>
Rezervácia pre dátum <?php echo $date ?> <br> <br>
Rezervované časy: <br>
<?php
foreach($query as $row){
?>
<?php echo substr($row->start, -8,5); ?> - <?php echo substr($row->end, -8,5);?>
<br>
<?php }
?>
<br>
<input type="hidden" name="id" value="<?php echo $id ?>">
<input type="hidden" name="date" value="<?php echo $date ?>">
Začiatok rezervácie: <br><input type="time" required name="start" min="06:00" max="23:00" value="06:00" step="3600" style="color: black"> <br><br>
Koniec rezervácie: <br><input type="time" required name="end" min="07:00" max="23:00" value="07:00" step="3600" style="color: black"> <br><br>
<input type="submit" name="potvrd" value="Pokračovať" style="color: black">
</div>
</form>
<body> | Laope94/sportcomplex | application/views/choose_time.php | PHP | mit | 1,208 |
//Draw at the console a filled square of size n like in the example:
//--------
//-\/\/\/-
//-\/\/\/-
//--------
namespace Draw_a_Filled_Square
{
using System;
class DrawAFilledSquare
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
PrintHeaderRow(n);
for (int i = 0; i < n-2; i++)
{
PrintBody(n);
}
PrintHeaderRow(n);
}
private static void PrintBody(int n)
{
Console.Write('-');
for (int i = 1; i < n; i++)
{
Console.Write("\\/");
}
Console.WriteLine('-');
}
static void PrintHeaderRow(int n)
{
Console.WriteLine(new string('-', 2 * n));
}
}
}
| NikolaySpasov/Softuni | Programming Fundamentals/03.Methods - Defining and Calling Methods/4. Draw a Filled Square/DrawAFilledSquare.cs | C# | mit | 837 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sk" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About StreamCoin</source>
<translation>O StreamCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>StreamCoin</b> version</source>
<translation><b>StreamCoin</b> verzia</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 (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The StreamCoin 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ár</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dvojklikom editovať adresu alebo popis</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Vytvoriť novú adresu</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopírovať práve zvolenú adresu do systémového klipbordu</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nová adresa</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your StreamCoin 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>Toto sú Vaše StreamCoin adresy pre prijímanie platieb. Môžete dať každému odosielateľovi inú rôznu adresu a tak udržiavať prehľad o platbách.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopírovať adresu</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Zobraz &QR Kód</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a StreamCoin address</source>
<translation>Podpísať správu a dokázať že vlastníte túto adresu</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Podpísať &správu</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>Exportovať tento náhľad do súboru</translation>
</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 StreamCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Zmazať</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your StreamCoin 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>Kopírovať &popis</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Upraviť</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>Exportovať dáta z adresára</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Čiarkou oddelený súbor (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Chyba exportu.</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nedalo sa zapisovať do súboru %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Popis</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresa</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(bez popisu)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Zadajte heslo</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nové heslo</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Zopakujte nové heslo</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>Zadajte nové heslo k peňaženke.<br/>Prosím použite heslo s dĺžkou aspon <b>10 alebo viac náhodných znakov</b>, alebo <b>8 alebo viac slov</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Zašifrovať peňaženku</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Táto operácia potrebuje heslo k vašej peňaženke aby ju mohla dešifrovať.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Odomknúť peňaženku</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Táto operácia potrebuje heslo k vašej peňaženke na dešifrovanie peňaženky.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dešifrovať peňaženku</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Zmena hesla</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Zadajte staré a nové heslo k peňaženke.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Potvrďte šifrovanie peňaženky</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>Varovanie: Ak zašifrujete peňaženku a stratíte heslo, <b>STRATÍTE VŠETKY VAŠE LITECOINY</b>!⏎</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Ste si istí, že si želáte zašifrovať peňaženku?</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>Varovanie: Caps Lock je zapnutý</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Peňaženka zašifrovaná</translation>
</message>
<message>
<location line="-56"/>
<source>StreamCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your streamcoins from being stolen by malware infecting your computer.</source>
<translation>StreamCoin sa teraz ukončí pre dokončenie procesu šifrovania. Pamätaj že šifrovanie peňaženky Ťa nemôže úplne ochrániť pred kráďežou streamcoinov pomocou škodlivého software.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Šifrovanie peňaženky zlyhalo</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Šifrovanie peňaženky zlyhalo kôli internej chybe. Vaša peňaženka nebola zašifrovaná.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Zadané heslá nesúhlasia.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Odomykanie peňaženky zlyhalo</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Zadané heslo pre dešifrovanie peňaženky bolo nesprávne.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Zlyhalo šifrovanie peňaženky.</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Heslo k peňaženke bolo úspešne zmenené.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Podpísať &správu...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronizácia so sieťou...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Prehľad</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Zobraziť celkový prehľad o peňaženke</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transakcie</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Prechádzať históriu transakcií</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Editovať zoznam uložených adries a popisov</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Zobraziť zoznam adries pre prijímanie platieb.</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>U&končiť</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Ukončiť program</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about StreamCoin</source>
<translation>Zobraziť informácie o StreamCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>O &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Zobrazit informácie o Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Možnosti...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Zašifrovať Peňaženku...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup peňaženku...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Zmena Hesla...</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 StreamCoin address</source>
<translation>Poslať streamcoins na adresu</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for StreamCoin</source>
<translation>Upraviť možnosti nastavenia pre streamcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Zálohovať peňaženku na iné miesto</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Zmeniť heslo použité na šifrovanie peňaženky</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Okno pre ladenie</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Otvor konzolu pre ladenie a diagnostiku</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>StreamCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Peňaženka</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 StreamCoin</source>
<translation>&O StreamCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</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 StreamCoin 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 StreamCoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Súbor</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Nastavenia</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Pomoc</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Lišta záložiek</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testovacia sieť]</translation>
</message>
<message>
<location line="+47"/>
<source>StreamCoin client</source>
<translation>StreamCoin klient</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to StreamCoin network</source>
<translation><numerusform>%n aktívne spojenie v StreamCoin sieti</numerusform><numerusform>%n aktívne spojenia v StreamCoin sieti</numerusform><numerusform>%n aktívnych spojení v Bitconi sieti</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>Aktualizovaný</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Sťahujem...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Potvrď poplatok za transakciu.</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Odoslané transakcie</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Prijaté transakcie</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dátum: %1
Suma: %2
Typ: %3
Adresa: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid StreamCoin 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>Peňaženka je <b>zašifrovaná</b> a momentálne <b>odomknutá</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Peňaženka je <b>zašifrovaná</b> a momentálne <b>zamknutá</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. StreamCoin 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 type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Upraviť adresu</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Popis</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Popis priradený k tomuto záznamu v adresári</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresa</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>Adresa spojená s týmto záznamom v adresári. Možno upravovať len pre odosielajúce adresy.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nová adresa pre prijímanie</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nová adresa pre odoslanie</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Upraviť prijímacie adresy</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Upraviť odosielaciu adresu</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Vložená adresa "%1" sa už nachádza v adresári.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid StreamCoin address.</source>
<translation>Vložená adresa "%1" nieje platnou adresou streamcoin.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Nepodarilo sa odomknúť peňaženku.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generovanie nového kľúča zlyhalo.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>StreamCoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>verzia</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Použitie:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI možnosti</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Spustiť minimalizované</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>Možnosti</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Hlavné</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>Zaplatiť transakčné &poplatky</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start StreamCoin after logging in to the system.</source>
<translation>Automaticky spustiť StreamCoin po zapnutí počítača</translation>
</message>
<message>
<location line="+3"/>
<source>&Start StreamCoin on system login</source>
<translation>&Spustiť StreamCoin pri spustení systému správy okien</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 type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the StreamCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automaticky otvorit port pre StreamCoin na routeri. Toto funguje len ak router podporuje UPnP a je táto podpora aktivovaná.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapovať port pomocou &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the StreamCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Pripojiť do siete StreamCoin cez SOCKS proxy (napr. keď sa pripájate cez Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Pripojiť cez SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP addresa proxy (napr. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port proxy (napr. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Zobraziť len ikonu na lište po minimalizovaní okna.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>Zobraziť len ikonu na lište po minimalizovaní okna.</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>Minimalizovat namiesto ukončenia aplikácie keď sa okno zavrie. Keď je zvolená táto možnosť, aplikácia sa zavrie len po zvolení Ukončiť v menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimalizovať pri zavretí</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Displej</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting StreamCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Zobrazovať hodnoty v jednotkách:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show StreamCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Zobraziť adresy zo zoznamu transakcií</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</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>Varovanie</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting StreamCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</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 StreamCoin 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>Zostatok:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Nepotvrdené:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Peňaženka</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</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>Nedávne transakcie</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Váš súčasný zostatok</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>Suma transakcií ktoré ešte neboli potvrdené a nezapočítavaju sa do celkového zostatku.</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 streamcoin: 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 type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Vyžiadať platbu</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Suma:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Popis:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Správa:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Uložiť ako...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Chyba v zakódovaní URI do QR kódu</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Výsledné URI príliš dlhé, skráť text pre názov / správu.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Ukladanie QR kódu</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG obrázky (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Meno klienta</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>nie je k dispozícii</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Verzia klienta</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Sieť</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Počet pripojení</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Na testovacej sieti</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Reťazec blokov</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Aktuálny počet blokov</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 type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the StreamCoin-Qt help message to get a list with possible StreamCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>StreamCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>StreamCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the StreamCoin 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 type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the StreamCoin 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>Poslať StreamCoins</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Poslať viacerým príjemcom naraz</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Pridať príjemcu</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Odobrať všetky políčka transakcie</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Zmazať &všetko</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Zostatok:</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>Potvrďte odoslanie</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Odoslať</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> do %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Potvrdiť odoslanie streamcoins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ste si istí, že chcete odoslať %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> a</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresa príjemcu je neplatná, prosím, overte ju.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Suma na úhradu musí byť väčšia ako 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Suma je vyššia ako Váš zostatok.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Suma celkom prevyšuje Váš zostatok ak sú započítané %1 transakčné poplatky.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplikát adresy objavený, je možné poslať na každú adresu len raz v jednej odchádzajúcej transakcii.</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>Chyba: Transakcia bola odmietnutá. Toto sa môže stať ak niektoré z mincí vo vašej peňaženke boli už utratené, napríklad ak používaš kópiu wallet.dat a mince označené v druhej kópií neboli označené ako utratené v tejto.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Su&ma:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Zapla&tiť:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</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>Vložte popis pre túto adresu aby sa pridala do adresára</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Popis:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Zvoľte adresu z adresára</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>Vložiť adresu z klipbordu</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>Odstrániť tohto príjemcu</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a StreamCoin address (e.g. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</source>
<translation>Zadajte StreamCoin adresu (napr. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</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>&Podpísať Správu</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>Môžete podpísať správy svojou adresou a dokázať, že ju vlastníte. Buďte opatrní a podpíšte len prehlásenia s ktorými plne súhlasíte, nakoľko útoky typu "phishing" Vás môžu lákať k ich podpísaniu.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</source>
<translation>Zadajte StreamCoin adresu (napr. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Zvoľte adresu z adresára</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>Vložte adresu z klipbordu</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>Sem vložte správu ktorú chcete podpísať</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 StreamCoin address</source>
<translation>Podpíšte správu aby ste dokázali že vlastníte túto adresu</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>Zmazať &všetko</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</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. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</source>
<translation>Zadajte StreamCoin adresu (napr. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified StreamCoin address</source>
<translation type="unfinished"/>
</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 StreamCoin address (e.g. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</source>
<translation>Zadajte StreamCoin adresu (napr. Ser4Ac2awZmCQrGFP2W34PM2UAlC8ax3)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Kliknite "Podpísať Správu" na získanie podpisu</translation>
</message>
<message>
<location line="+3"/>
<source>Enter StreamCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The StreamCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testovacia sieť]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Otvorené do %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nepotvrdené</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 potvrdení</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Stav</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>Dátum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>od</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>popis</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</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>neprijaté</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transakčný poplatok</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Suma netto</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Správa</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Komentár</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID transakcie</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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transakcie</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 type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ešte nebola úspešne odoslaná</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>neznámy</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detaily transakcie</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Táto časť obrazovky zobrazuje detailný popis transakcie</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresa</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Hodnota</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>Otvorené do %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 potvrdení)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Nepotvrdené (%1 z %2 potvrdení)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Potvrdené (%1 potvrdení)</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>Ten blok nebol prijatý žiadnou inou nódou a pravdepodobne nebude akceptovaný!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Vypočítané ale neakceptované</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Prijaté s</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Prijaté od:</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Odoslané na</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Platba sebe samému</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Vyfárané</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Status transakcie. Pohybujte myšou nad týmto poľom a zjaví sa počet potvrdení.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Dátum a čas prijatia transakcie.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Typ transakcie.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Cieľová adresa transakcie.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Suma pridaná alebo odobraná k zostatku.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Všetko</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Dnes</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Tento týždeň</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Tento mesiac</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Minulý mesiac</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Tento rok</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rozsah...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Prijaté s</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Odoslané na</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Samému sebe</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Vyfárané</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Iné</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Vložte adresu alebo popis pre vyhľadávanie</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min množstvo</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopírovať adresu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopírovať popis</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopírovať sumu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editovať popis</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportovať transakčné dáta</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Čiarkou oddelovaný súbor (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Potvrdené</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Popis</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresa</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>Chyba exportu</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nedalo sa zapisovať do súboru %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rozsah:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>do</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Poslať StreamCoins</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>Exportovať tento náhľad do súboru</translation>
</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>StreamCoin version</source>
<translation>StreamCoin verzia</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Použitie:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or streamcoind</source>
<translation>Odoslať príkaz -server alebo streamcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Zoznam príkazov</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Dostať pomoc pre príkaz</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Možnosti:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: streamcoin.conf)</source>
<translation>Určiť súbor s nastaveniami (predvolené: streamcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: streamcoind.pid)</source>
<translation>Určiť súbor pid (predvolené: streamcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Určiť priečinok s dátami</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Veľkosť vyrovnávajúcej pamäte pre databázu v megabytoch (predvolené:25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Načúvať spojeniam na <port> (prednastavené: 9333 alebo testovacia sieť: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Udržiavať maximálne <n> spojení (predvolené: 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>Hranica pre odpojenie zle sa správajúcich peerov (predvolené: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Počet sekúnd kedy sa zabráni zle sa správajúcim peerom znovupripojenie (predvolené: 86400)</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: 9332 or testnet: 19332)</source>
<translation>Počúvať JSON-RPC spojeniam na <port> (predvolené: 9332 or testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Prijímať príkazy z príkazového riadku a JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Bežať na pozadí ako démon a prijímať príkazy</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Použiť testovaciu sieť</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=streamcoinrpc
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 "StreamCoin Alert" admin@foo.com
</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. StreamCoin 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>Varovanie: -paytxfee je nastavené veľmi vysoko. Toto sú transakčné poplatky ktoré zaplatíte ak odošlete transakciu.</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 StreamCoin will not work properly.</source>
<translation type="unfinished"/>
</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>Pripojiť sa len k určenej nóde</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>Neplatná adresa tor: '%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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</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>Produkovať extra ladiace informácie. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Pridať na začiatok ladiaceho výstupu časový údaj</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the StreamCoin Wiki for SSL setup instructions)</source>
<translation>SSL možnosť: (pozrite StreamCoin Wiki pre návod na nastavenie SSL)</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>Odoslať trace/debug informácie na konzolu namiesto debug.info žurnálu</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Odoslať trace/debug informácie do ladiaceho programu</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>Určiť aut spojenia v milisekundách (predvolené: 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>Skúsiť použiť UPnP pre mapovanie počúvajúceho portu (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Skúsiť použiť UPnP pre mapovanie počúvajúceho portu (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>Užívateľské meno pre JSON-RPC spojenia</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>Heslo pre JSON-rPC spojenia</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Povoliť JSON-RPC spojenia z určenej IP adresy.</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Poslať príkaz nóde bežiacej na <ip> (predvolené: 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>Vykonaj príkaz, ak zmeny v najlepšom bloku (%s v príkaze nahradí blok hash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Aktualizuj peňaženku na najnovší formát.</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Nastaviť zásobu adries na <n> (predvolené: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Znovu skenovať reťaz blokov pre chýbajúce transakcie</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Použiť OpenSSL (https) pre JSON-RPC spojenia</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Súbor s certifikátom servra (predvolené: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Súkromný kľúč servra (predvolené: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Prijateľné šifry (predvolené: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Táto pomocná správa</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Pripojenie cez socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Povoliť vyhľadávanie DNS pre pridanie nódy a spojenie</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Načítavanie adries...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Chyba načítania wallet.dat: Peňaženka je poškodená</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of StreamCoin</source>
<translation>Chyba načítania wallet.dat: Peňaženka vyžaduje novšiu verziu StreamCoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart StreamCoin to complete</source>
<translation>Bolo potrebné prepísať peňaženku: dokončite reštartovaním StreamCoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Chyba načítania wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Neplatná adresa proxy: '%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>Neplatná suma pre -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Neplatná suma</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Nedostatok prostriedkov</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Načítavanie zoznamu blokov...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Pridať nód na pripojenie a pokus o udržanie pripojenia otvoreného</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. StreamCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Poplatok za kB ktorý treba pridať k odoslanej transakcii</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Načítavam peňaženku...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Nie je možné prejsť na nižšiu verziu peňaženky</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Nie je možné zapísať predvolenú adresu.</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Dokončené načítavanie</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Použiť %s možnosť.</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Chyba</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>Musíš nastaviť rpcpassword=<heslo> v konfiguračnom súbore:
%s
Ak súbor neexistuje, vytvor ho s oprávnením pre čítanie len vlastníkom (owner-readable-only)</translation>
</message>
</context>
</TS> | streamcoin/streamcoin-master | src/qt/locale/bitcoin_sk.ts | TypeScript | mit | 106,581 |
using System;
using Newtonsoft.Json;
using VkNet.Enums;
using VkNet.Enums.Filters;
using VkNet.Enums.SafetyEnums;
using VkNet.Utils.JsonConverter;
namespace VkNet.Model.RequestParams
{
/// <summary>
/// Параметры метода users.search
/// </summary>
[Serializable]
public class UserSearchParams
{
/// <summary>
/// Строка поискового запроса. Например, Вася Бабич.
/// </summary>
public string Query { get; set; }
/// <summary>
/// Сортировка результатов.
/// </summary>
[JsonConverter(typeof(SafetyEnumJsonConverter))]
public UserSort Sort { get; set; }
/// <summary>
/// Смещение относительно первого найденного пользователя для выборки определенного
/// подмножества.
/// </summary>
public uint? Offset { get; set; }
/// <summary>
/// Количество возвращаемых пользователей. Обратите внимание — даже при
/// использовании параметра offset для получения
/// информации доступны только первые 1000 результатов.
/// </summary>
public uint? Count { get; set; }
/// <summary>
/// Список дополнительных полей, которые необходимо вернуть.
/// </summary>
public ProfileFields Fields { get; set; }
/// <summary>
/// Идентификатор города.
/// </summary>
public int? City { get; set; }
/// <summary>
/// Идентификатор страны.
/// </summary>
public int? Country { get; set; }
/// <summary>
/// Название города строкой.
/// </summary>
public string Hometown { get; set; }
/// <summary>
/// Идентификатор страны, в которой пользователи закончили ВУЗ.
/// </summary>
public int? UniversityCountry { get; set; }
/// <summary>
/// Идентификатор ВУЗа.
/// </summary>
public int? University { get; set; }
/// <summary>
/// Год окончания ВУЗа.
/// </summary>
public uint? UniversityYear { get; set; }
/// <summary>
/// Идентификатор факультета.
/// </summary>
public int? UniversityFaculty { get; set; }
/// <summary>
/// Идентификатор кафедры.
/// </summary>
public int? UniversityChair { get; set; }
/// <summary>
/// Пол.
/// </summary>
public Sex Sex { get; set; }
/// <summary>
/// Семейное положение.
/// </summary>
public MaritalStatus? Status { get; set; }
/// <summary>
/// Начиная с какого возраста.
/// </summary>
public ushort? AgeFrom { get; set; }
/// <summary>
/// До какого возраста.
/// </summary>
public ushort? AgeTo { get; set; }
/// <summary>
/// День рождения.
/// </summary>
public ushort? BirthDay { get; set; }
/// <summary>
/// Месяц рождения.
/// </summary>
public ushort? BirthMonth { get; set; }
/// <summary>
/// Год рождения.
/// </summary>
public uint? BirthYear { get; set; }
/// <summary>
/// <c> true </c> — только в сети, <c> false </c> — все пользователи. флаг.
/// </summary>
public bool? Online { get; set; }
/// <summary>
/// <c> true </c> — только с фотографией, <c> false </c> — все пользователи. флаг.
/// </summary>
public bool? HasPhoto { get; set; }
/// <summary>
/// Идентификатор страны, в которой пользователи закончили школу.
/// </summary>
public int? SchoolCountry { get; set; }
/// <summary>
/// Идентификатор города, в котором пользователи закончили школу.
/// </summary>
public int? SchoolCity { get; set; }
/// <summary>
/// Класс в школе.
/// </summary>
public int? SchoolClass { get; set; }
/// <summary>
/// Идентификатор школы, которую закончили пользователи.
/// </summary>
public int? School { get; set; }
/// <summary>
/// Год окончания школы.
/// </summary>
public uint? SchoolYear { get; set; }
/// <summary>
/// Религиозные взгляды.
/// </summary>
public string Religion { get; set; }
/// <summary>
/// Интересы.
/// </summary>
public string Interests { get; set; }
/// <summary>
/// Название компании, в которой работают пользователи.
/// </summary>
public string Company { get; set; }
/// <summary>
/// Название должности.
/// </summary>
public string Position { get; set; }
/// <summary>
/// Идентификатор группы, среди пользователей которой необходимо проводить поиск.
/// </summary>
public ulong? GroupId { get; set; }
/// <summary>
/// Разделы среди которых нужно осуществить поиск.
/// </summary>
[JsonConverter(typeof(SafetyEnumJsonConverter))]
public UserSection FromList { get; set; }
}
} | vknet/vk | VkNet/Model/RequestParams/Users/UserSearchParams.cs | C# | mit | 5,434 |
package smash.data.tweets.pojo;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yikai Gong
*/
public class TweetCoordinates implements Serializable {
private String type;
// Order in lon-lat. Follow the GeoJSON/WKT standard which JTS is holing on
// Ref: http://www.macwright.org/lonlat/
// and http://docs.geotools.org/latest/userguide/library/referencing/epsg.html
private List<BigDecimal> coordinates;
public TweetCoordinates() {
}
public TweetCoordinates(Double lon, Double lat) {
this();
type = "point";
List<BigDecimal> l = new ArrayList<>();
l.add(0, BigDecimal.valueOf(lon));
l.add(1, BigDecimal.valueOf(lat));
coordinates = l;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<BigDecimal> getCoordinates() {
return coordinates;
}
public void setCoordinates(List<BigDecimal> coordinates) {
this.coordinates = coordinates;
}
public BigDecimal getLon() {
return coordinates.get(0);
}
public BigDecimal getLat() {
return coordinates.get(1);
}
}
| project-rhd/smash-app | smash-tweets/smash-tweets-data/src/main/java/smash/data/tweets/pojo/TweetCoordinates.java | Java | mit | 1,190 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DockSample
{
public partial class SplashScreen : Form
{
public SplashScreen()
{
InitializeComponent();
}
}
}
| thijse/dockpanelsuite | DockSample/SplashScreen.cs | C# | mit | 355 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._test_base import TestBase
__all__ = ['TestBase']
| Azure/azure-sdk-for-python | sdk/testbase/azure-mgmt-testbase/azure/mgmt/testbase/aio/__init__.py | Python | mit | 524 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Poseidon.Energy.Core.DL
{
using Poseidon.Base.Framework;
using Poseidon.Base.Utility;
/// <summary>
/// 能源计量总类
/// </summary>
public class Measure : BusinessEntity
{
#region Property
/// <summary>
/// 名称
/// </summary>
[Display(Name = "名称")]
public string Name { get; set; }
/// <summary>
/// 年度
/// </summary>
[Display(Name = "年度")]
public int Year { get; set; }
/// <summary>
/// 归属时间
/// </summary>
[Display(Name = "归属时间")]
public string BelongTime { get; set; }
/// <summary>
/// 起始时间
/// </summary>
[Display(Name = "起始时间")]
public DateTime StartTime { get; set; }
/// <summary>
/// 截至时间
/// </summary>
[Display(Name = "截至时间")]
public DateTime EndTime { get; set; }
/// <summary>
/// 能源类型
/// </summary>
[Display(Name = "能源类型")]
public int EnergyType { get; set; }
/// <summary>
/// 是否计入合计
/// </summary>
[Display(Name = "是否计入合计")]
public bool Included { get; set; }
#endregion //Property
}
} | robertzml/Poseidon.Energy | Poseidon.Energy.Core/DL/Measure.cs | C# | mit | 1,522 |
//////////////////////////////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2017-present, cyder.org
// All rights reserved.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////////////////
/**
* An IOErrorEvent object is emitted when an error causes input or output operations to fail.
*/
class IOErrorEvent extends Event {
/**
* Emitted when an error causes input or output operations to fail.
*/
public static readonly IO_ERROR:string = "ioError";
/**
* Creates an Event object that contains specific information about ioError events. Event objects are passed as
* parameters to Event listeners.
* @param type The type of the event.
* @param cancelable Determine whether the Event object can be canceled. The default value is false.
* @param text Text to be displayed as an error message.
*/
public constructor(type:string, cancelable?:boolean, text:string = "") {
super(type, cancelable);
this.text = text;
}
/**
* Text to be displayed as an error message.
*/
public text:string;
} | cyderjs/cyder | scripts/src/events/IOErrorEvent.ts | TypeScript | mit | 2,265 |
import {Manager} from './manager'
export {Filterer} from './filter';
export {Logger} from './logger';
export {Manager};
var logging = new Manager();
export default logging;
| smialy/sjs-logging | src/index.js | JavaScript | mit | 175 |
# Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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.
import collections
import threading
import logging
import Queue
from ant.base.ant import Ant
from ant.base.message import Message
from ant.easy.channel import Channel
from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special
_logger = logging.getLogger("garmin.ant.easy.node")
class Node():
def __init__(self):
self._responses_cond = threading.Condition()
self._responses = collections.deque()
self._event_cond = threading.Condition()
self._events = collections.deque()
self._datas = Queue.Queue()
self.channels = {}
self.ant = Ant()
self._running = True
self._worker_thread = threading.Thread(target=self._worker, name="ant.easy")
self._worker_thread.start()
def new_channel(self, ctype):
channel = Channel(0, self, self.ant)
self.channels[0] = channel
channel._assign(ctype, 0x00)
return channel
def request_message(self, messageId):
_logger.debug("requesting message %#02x", messageId)
self.ant.request_message(0, messageId)
_logger.debug("done requesting message %#02x", messageId)
return self.wait_for_special(messageId)
def set_network_key(self, network, key):
self.ant.set_network_key(network, key)
return self.wait_for_response(Message.ID.SET_NETWORK_KEY)
def wait_for_event(self, ok_codes):
return wait_for_event(ok_codes, self._events, self._event_cond)
def wait_for_response(self, event_id):
return wait_for_response(event_id, self._responses, self._responses_cond)
def wait_for_special(self, event_id):
return wait_for_special(event_id, self._responses, self._responses_cond)
def _worker_response(self, channel, event, data):
self._responses_cond.acquire()
self._responses.append((channel, event, data))
self._responses_cond.notify()
self._responses_cond.release()
def _worker_event(self, channel, event, data):
if event == Message.Code.EVENT_RX_BURST_PACKET:
self._datas.put(('burst', channel, data))
elif event == Message.Code.EVENT_RX_BROADCAST:
self._datas.put(('broadcast', channel, data))
else:
self._event_cond.acquire()
self._events.append((channel, event, data))
self._event_cond.notify()
self._event_cond.release()
def _worker(self):
self.ant.response_function = self._worker_response
self.ant.channel_event_function = self._worker_event
# TODO: check capabilities
self.ant.start()
def _main(self):
while self._running:
try:
(data_type, channel, data) = self._datas.get(True, 1.0)
self._datas.task_done()
if data_type == 'broadcast':
self.channels[channel].on_broadcast_data(data)
elif data_type == 'burst':
self.channels[channel].on_burst_data(data)
else:
_logger.warning("Unknown data type '%s': %r", data_type, data)
except Queue.Empty as e:
pass
def start(self):
self._main()
def stop(self):
if self._running:
_logger.debug("Stoping ant.easy")
self._running = False
self.ant.stop()
self._worker_thread.join()
| ddboline/Garmin-Forerunner-610-Extractor_fork | ant/easy/node.py | Python | mit | 4,653 |
import os
from ConfigParser import ConfigParser
from amlib import argp
tmp_conf = ConfigParser()
tmp_path = os.path.dirname(os.path.abspath(__file__)) # /base/lib/here
tmp_path = tmp_path.split('/')
conf_path = '/'.join(tmp_path[0:-1]) # /base/lib
tmp_conf.read(conf_path+'/ampush.conf')
c = {}
c.update(tmp_conf.items('default'))
# select target AD container: default or user-specified with --mode?
if argp.a['mode'] is not None:
try:
container_conf_key = 'am_container_' + argp.a['mode']
c['am_container'] = c[container_conf_key]
except KeyError:
log_msg = 'Terminating. No such parameter in ampush.conf: ' + \
container_conf_key
raise Exception(log_msg)
else:
c['am_container'] = c['am_container_default']
# select alternate flat file automount maps: default or user-specified
# set passed via --source?
if argp.a['source'] is not None:
try:
ff_map_dir_conf_key = 'flat_file_map_dir_' + argp.a['source']
c['flat_file_map_dir'] = c[ff_map_dir_conf_key]
except KeyError:
log_msg = 'Terminating. No such parameter in ampush.conf: ' + \
ff_map_dir_conf_key
raise Exception(log_msg)
else:
c['flat_file_map_dir'] = c['flat_file_map_dir_default']
| sfu-rcg/ampush | amlib/conf.py | Python | mit | 1,274 |
/**
* Created by larry on 2017/1/6.
*/
import React from 'react';
import Todo from './Todo';
//圆括号里面要写大括号
const TodoList = ({todos, onTodoClick}) => {
return (
<ul>
{
todos.map
(
todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)
}
</ul>
)
};
export default TodoList; | lingxiao-Zhu/react-redux-demo | src/components/TodoList.js | JavaScript | mit | 568 |
package com.bellini.recipecatalog.exception.recipe;
public class NotExistingRecipeException extends RuntimeException {
private static final long serialVersionUID = 2975419159984559986L;
private Long id;
public NotExistingRecipeException(Long id) {
super();
if (id == null) {
throw new IllegalArgumentException("Null object used as initializer of the exception");
}
this.id = id;
}
@Override
public String getMessage() {
return "Recipe " + id + " not found in database";
}
}
| riccardobellini/recipecatalog-backend-java | src/main/java/com/bellini/recipecatalog/exception/recipe/NotExistingRecipeException.java | Java | mit | 559 |
package biz.golek.whattodofordinner.view.activities;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.greenrobot.eventbus.Subscribe;
import java.util.List;
import biz.golek.whattodofordinner.R;
import biz.golek.whattodofordinner.business.contract.request_data.GeneratePromptsRequestData;
import biz.golek.whattodofordinner.business.contract.response_data.DinnerListItem;
import biz.golek.whattodofordinner.view.ActivityDependencyProvider;
import biz.golek.whattodofordinner.view.adapters.DinnerListItemArrayAdapter;
import biz.golek.whattodofordinner.view.awareness.IActivityDependencyProviderAware;
import biz.golek.whattodofordinner.view.messages.DinnerDeletedMessage;
import biz.golek.whattodofordinner.view.messages.DinnerUpdatedMessage;
import biz.golek.whattodofordinner.view.view_models.PromptsActivityViewModel;
public class PromptsActivity extends AppCompatActivity implements IActivityDependencyProviderAware {
private String PROMPTS_LIST_VIEW_MODEL = "promptsListViewModel";
private PromptsActivityViewModel viewModel;
private ActivityDependencyProvider activityDependencyProvider;
private ArrayAdapter adapter;
private ListView listView;
private DinnerListItem nonOfThisListItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prompts);
setupActionBar();
if (savedInstanceState != null)
viewModel = (PromptsActivityViewModel) savedInstanceState.getSerializable(PROMPTS_LIST_VIEW_MODEL);
else
viewModel = (PromptsActivityViewModel)getIntent().getSerializableExtra("VIEW_MODEL");
listView = (ListView) findViewById(R.id.prompts_list);
List<DinnerListItem> prompts = viewModel.prompts;
nonOfThisListItem = new DinnerListItem();
nonOfThisListItem.id = -1L;
nonOfThisListItem.name = getResources().getString(R.string.non_of_this);
prompts.add(nonOfThisListItem);
adapter = new DinnerListItemArrayAdapter(this, prompts);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DinnerListItem item = (DinnerListItem)listView.getItemAtPosition(position);
if (item == nonOfThisListItem)
activityDependencyProvider.getGeneratePromptsController().Run(getDenyRequestData());
else
activityDependencyProvider.getDinnerChosenController().Run(item.id, item.name);
}
});
registerForContextMenu(listView);
activityDependencyProvider.getEventBusProvider().get().register(this);
}
@Subscribe
public void onDinnerDeleteMessage(DinnerDeletedMessage event) {
DinnerListItem dinner = null;
for (DinnerListItem d : viewModel.prompts)
if (d.id.equals(event.getId()))
dinner = d;
if (dinner != null)
viewModel.prompts.remove(dinner);
adapter.notifyDataSetChanged();
}
@Subscribe
public void onDinnerUpdatedMessage(DinnerUpdatedMessage event) {
boolean updated = false;
for (DinnerListItem dinner : viewModel.prompts) {
if (dinner.id.equals(event.getId())) {
dinner.id = event.getId();
dinner.name = event.getName();
updated = true;
}
}
if (updated)
adapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
activityDependencyProvider.getEventBusProvider().get().unregister(this);
}
@NonNull
private GeneratePromptsRequestData getDenyRequestData() {
GeneratePromptsRequestData rd = new GeneratePromptsRequestData();
rd.soup_profile = viewModel.getSoupProfile();
rd.vegetarian_profile = viewModel.getVegetarianProfile();
rd.maximum_duration = viewModel.getMaximumDuration();
Long[] oldExcludes = viewModel.getExcludes();
List<DinnerListItem> prompts = viewModel.prompts;
int oldExcludesLength = oldExcludes!= null ? oldExcludes.length : 0;
int promptsSize = prompts != null ? prompts.size() : 0;
if (oldExcludesLength + promptsSize > 0)
{
Long[] excludes = new Long[oldExcludesLength + promptsSize];
Integer index = 0;
if (oldExcludes != null)
{
for (Long id: oldExcludes) {
excludes[index++] = id;
}
}
if (prompts != null)
{
for (DinnerListItem dli: prompts) {
excludes[index++] = dli.id;
}
}
rd.excludes = excludes;
}
return rd;
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.prompts_list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position);
if (dinnerListItem != nonOfThisListItem)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dinner_list_item_menu, menu);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position);
switch(item.getItemId()) {
case R.id.dinner_list_item_menu_edit:
activityDependencyProvider.getEditDinnerController().Run(dinnerListItem.id);
return true;
case R.id.dinner_list_item_menu_delete:
activityDependencyProvider.getDeleteDinnerController().Run(dinnerListItem.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable(PROMPTS_LIST_VIEW_MODEL, viewModel);
super.onSaveInstanceState(outState);
}
@Override
public void Set(ActivityDependencyProvider item) {
activityDependencyProvider = item;
}
}
| bartoszgolek/whattodofordinner | app/src/main/java/biz/golek/whattodofordinner/view/activities/PromptsActivity.java | Java | mit | 7,640 |
Gem.find_files('slackbot_frd/**/*.rb').each do |path|
require path.gsub(/\.rb$/, '') unless path =~ /bot.*cli/
end
| FreedomBen/slackbot_frd | lib/slackbot_frd.rb | Ruby | mit | 117 |
# encoding: utf-8
from __future__ import unicode_literals
import operator
import pytest
from marrow.mongo import Filter
from marrow.schema.compat import odict, py3
@pytest.fixture
def empty_ops(request):
return Filter()
@pytest.fixture
def single_ops(request):
return Filter({'roll': 27})
def test_ops_iteration(single_ops):
assert list(iter(single_ops)) == ['roll']
class TestOpsMapping(object):
def test_getitem(self, empty_ops, single_ops):
with pytest.raises(KeyError):
empty_ops['roll']
assert single_ops['roll'] == 27
def test_setitem(self, empty_ops):
assert repr(empty_ops) == "Filter([])"
empty_ops['meaning'] = 42
if py3:
assert repr(empty_ops) == "Filter([('meaning', 42)])"
else:
assert repr(empty_ops) == "Filter([(u'meaning', 42)])"
def test_delitem(self, empty_ops, single_ops):
with pytest.raises(KeyError):
del empty_ops['roll']
if py3:
assert repr(single_ops) == "Filter([('roll', 27)])"
else:
assert repr(single_ops) == "Filter([(u'roll', 27)])"
del single_ops['roll']
assert repr(single_ops) == "Filter([])"
def test_length(self, empty_ops, single_ops):
assert len(empty_ops) == 0
assert len(single_ops) == 1
def test_keys(self, empty_ops, single_ops):
assert list(empty_ops.keys()) == []
assert list(single_ops.keys()) == ['roll']
def test_items(self, empty_ops, single_ops):
assert list(empty_ops.items()) == []
assert list(single_ops.items()) == [('roll', 27)]
def test_values(self, empty_ops, single_ops):
assert list(empty_ops.values()) == []
assert list(single_ops.values()) == [27]
def test_contains(self, single_ops):
assert 'foo' not in single_ops
assert 'roll' in single_ops
def test_equality_inequality(self, empty_ops, single_ops):
assert empty_ops == {}
assert empty_ops != {'roll': 27}
assert single_ops != {}
assert single_ops == {'roll': 27}
def test_get(self, single_ops):
assert single_ops.get('foo') is None
assert single_ops.get('foo', 42) == 42
assert single_ops.get('roll') == 27
def test_clear(self, single_ops):
assert len(single_ops.operations) == 1
single_ops.clear()
assert len(single_ops.operations) == 0
def test_pop(self, single_ops):
assert len(single_ops.operations) == 1
with pytest.raises(KeyError):
single_ops.pop('foo')
assert single_ops.pop('foo', 42) == 42
assert len(single_ops.operations) == 1
assert single_ops.pop('roll') == 27
assert len(single_ops.operations) == 0
def test_popitem(self, single_ops):
assert len(single_ops.operations) == 1
assert single_ops.popitem() == ('roll', 27)
assert len(single_ops.operations) == 0
with pytest.raises(KeyError):
single_ops.popitem()
def test_update(self, empty_ops, single_ops):
assert len(empty_ops.operations) == 0
empty_ops.update(name="Bob Dole")
assert len(empty_ops.operations) == 1
if py3:
assert repr(empty_ops) == "Filter([('name', 'Bob Dole')])"
else:
assert repr(empty_ops) == "Filter([('name', u'Bob Dole')])"
assert len(single_ops.operations) == 1
if py3:
assert repr(single_ops) == "Filter([('roll', 27)])"
else:
assert repr(single_ops) == "Filter([(u'roll', 27)])"
single_ops.update([('name', "Bob Dole")])
assert len(single_ops.operations) == 2
if py3:
assert repr(single_ops) in ("Filter([('roll', 27), ('name', 'Bob Dole')])", "Filter([('name', 'Bob Dole'), ('roll', 27)])")
else:
assert repr(single_ops) in ("Filter([(u'roll', 27), (u'name', u'Bob Dole')])", "Filter([(u'name', u'Bob Dole'), (u'roll', 27)])")
def test_setdefault(self, empty_ops):
assert len(empty_ops.operations) == 0
empty_ops.setdefault('fnord', 42)
assert len(empty_ops.operations) == 1
assert empty_ops.operations['fnord'] == 42
empty_ops.setdefault('fnord', 27)
assert len(empty_ops.operations) == 1
assert empty_ops.operations['fnord'] == 42
def test_ops_shallow_copy(self, single_ops):
assert single_ops.operations == single_ops.copy().operations
class TestOperationsCombination(object):
def test_operations_and_clean_merge(self):
comb = Filter({'roll': 27}) & Filter({'foo': 42})
assert comb.as_query == {'roll': 27, 'foo': 42}
def test_operations_and_operator_overlap(self):
comb = Filter({'roll': {'$gte': 27}}) & Filter({'roll': {'$lte': 42}})
assert comb.as_query == {'roll': {'$gte': 27, '$lte': 42}}
def test_paradoxical_condition(self):
comb = Filter({'roll': 27}) & Filter({'roll': {'$lte': 42}})
assert comb.as_query == {'roll': {'$eq': 27, '$lte': 42}}
comb = Filter({'roll': {'$gte': 27}}) & Filter({'roll': 42})
assert list(comb.as_query['roll'].items()) in ([('$gte', 27), ('$eq', 42)], [('$eq', 42), ('$gte', 27)])
def test_operations_or_clean_merge(self):
comb = Filter({'roll': 27}) | Filter({'foo': 42})
assert comb.as_query == {'$or': [{'roll': 27}, {'foo': 42}]}
comb = comb | Filter({'bar': 'baz'})
assert comb.as_query == {'$or': [{'roll': 27}, {'foo': 42}, {'bar': 'baz'}]}
def test_operations_hard_and(self):
comb = Filter({'$and': [{'a': 1}, {'b': 2}]}) & Filter({'$and': [{'c': 3}]})
assert comb.as_query == {'$and': [{'a': 1}, {'b': 2}, {'c': 3}]}
def test_operations_soft_and(self):
comb = Filter({'$and': [{'a': 1}, {'b': 2}]}) & Filter({'c': 3})
assert comb.as_query == {'$and': [{'a': 1}, {'b': 2}], 'c': 3}
| marrow/mongo | test/query/test_ops.py | Python | mit | 5,358 |
<?php
namespace SVG\Nodes\Filters;
use SVG\Nodes\SVGNodeContainer;
use SVG\Rasterization\SVGRasterizer;
/**
* Represents the SVG tag 'feComponentTransfer'.
*/
class SVGFEComponentTransfer extends SVGNodeContainer
{
const TAG_NAME = 'feComponentTransfer';
public function __construct()
{
parent::__construct();
}
/**
* @inheritdoc
*/
public function rasterize(SVGRasterizer $rasterizer)
{
// Nothing to rasterize.
}
}
| JangoBrick/php-svg | src/Nodes/Filters/SVGFEComponentTransfer.php | PHP | mit | 482 |
export { default } from 'ember-fhir/serializers/timing-repeat'; | davekago/ember-fhir | app/serializers/timing-repeat.js | JavaScript | mit | 63 |
import { Route } from '@angular/router';
import { LoginComponent } from './index';
export const LoginRoutes: Route[] = [
{
path: 'login',
component: LoginComponent
}
];
| AnnaCasper/finance-tool | src/client/app/login/login.routes.ts | TypeScript | mit | 186 |
require File.expand_path(File.join(File.dirname(__FILE__), "test_helper"))
require 'onelogin/ruby-saml/slo_logoutresponse'
class SloLogoutresponseTest < Minitest::Test
describe "SloLogoutresponse" do
let(:settings) { OneLogin::RubySaml::Settings.new }
let(:logout_request) { OneLogin::RubySaml::SloLogoutrequest.new(logout_request_document) }
before do
settings.idp_entity_id = 'https://app.onelogin.com/saml/metadata/SOMEACCOUNT'
settings.idp_slo_service_url = "http://unauth.com/logout"
settings.name_identifier_value = "f00f00"
settings.compress_request = true
settings.certificate = ruby_saml_cert_text
settings.private_key = ruby_saml_key_text
logout_request.settings = settings
end
it "create the deflated SAMLResponse URL parameter" do
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id)
assert_match /^http:\/\/unauth\.com\/logout\?SAMLResponse=/, unauth_url
inflated = decode_saml_response_payload(unauth_url)
assert_match /^<samlp:LogoutResponse/, inflated
end
it "support additional params" do
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, nil, { :hello => nil })
assert_match /&hello=$/, unauth_url
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, nil, { :foo => "bar" })
assert_match /&foo=bar$/, unauth_url
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, nil, { :RelayState => "http://idp.example.com" })
assert_match /&RelayState=http%3A%2F%2Fidp.example.com$/, unauth_url
end
it "RelayState cases" do
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, nil, { :RelayState => nil })
assert !unauth_url.include?('RelayState')
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, nil, { :RelayState => "http://example.com" })
assert unauth_url.include?('&RelayState=http%3A%2F%2Fexample.com')
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, nil, { 'RelayState' => nil })
assert !unauth_url.include?('RelayState')
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, nil, { 'RelayState' => "http://example.com" })
assert unauth_url.include?('&RelayState=http%3A%2F%2Fexample.com')
end
it "set InResponseTo to the ID from the logout request" do
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id)
inflated = decode_saml_response_payload(unauth_url)
assert_match /InResponseTo='_c0348950-935b-0131-1060-782bcb56fcaa'/, inflated
end
it "set a custom successful logout message on the response" do
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id, "Custom Logout Message")
inflated = decode_saml_response_payload(unauth_url)
assert_match /<samlp:StatusMessage>Custom Logout Message<\/samlp:StatusMessage>/, inflated
end
it "set a custom logout message and an status on the response" do
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, nil, "Custom Logout Message", {}, "urn:oasis:names:tc:SAML:2.0:status:PartialLogout")
inflated = decode_saml_response_payload(unauth_url)
assert_match /<samlp:StatusMessage>Custom Logout Message<\/samlp:StatusMessage>/, inflated
assert_match /<samlp:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:PartialLogout/, inflated
end
it "uses the response location when set" do
settings.idp_slo_response_service_url = "http://unauth.com/logout/return"
unauth_url = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request.id)
assert_match /^http:\/\/unauth\.com\/logout\/return\?SAMLResponse=/, unauth_url
inflated = decode_saml_response_payload(unauth_url)
assert_match /Destination='http:\/\/unauth.com\/logout\/return'/, inflated
end
describe "playgin with preix" do
it "creates request with ID prefixed with default '_'" do
request = OneLogin::RubySaml::SloLogoutresponse.new
assert_match /^_/, request.uuid
end
it "creates request with ID is prefixed, when :id_prefix is passed" do
OneLogin::RubySaml::Utils::set_prefix("test")
request = OneLogin::RubySaml::SloLogoutresponse.new
assert_match /^test/, request.uuid
OneLogin::RubySaml::Utils::set_prefix("_")
end
end
describe "signing with HTTP-POST binding" do
before do
settings.idp_sso_service_binding = :redirect
settings.idp_slo_service_binding = :post
settings.compress_response = false
settings.security[:logout_responses_signed] = true
end
it "doesn't sign through create_xml_document" do
unauth_res = OneLogin::RubySaml::SloLogoutresponse.new
inflated = unauth_res.create_xml_document(settings).to_s
refute_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], inflated
refute_match %r[<ds:SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1'/>], inflated
refute_match %r[<ds:DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>], inflated
end
it "sign unsigned request" do
unauth_res = OneLogin::RubySaml::SloLogoutresponse.new
unauth_res_doc = unauth_res.create_xml_document(settings)
inflated = unauth_res_doc.to_s
refute_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], inflated
refute_match %r[<ds:SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1'/>], inflated
refute_match %r[<ds:DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>], inflated
inflated = unauth_res.sign_document(unauth_res_doc, settings).to_s
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], inflated
assert_match %r[<ds:SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1'/>], inflated
assert_match %r[<ds:DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>], inflated
end
it "signs through create_logout_response_xml_doc" do
unauth_res = OneLogin::RubySaml::SloLogoutresponse.new
inflated = unauth_res.create_logout_response_xml_doc(settings).to_s
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], inflated
assert_match %r[<ds:SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1'/>], inflated
assert_match %r[<ds:DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>], inflated
end
it "create a signed logout response" do
logout_request.settings = settings
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message")
response_xml = Base64.decode64(params["SAMLResponse"])
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], response_xml
assert_match /<ds:SignatureMethod Algorithm='http:\/\/www.w3.org\/2000\/09\/xmldsig#rsa-sha1'\/>/, response_xml
assert_match /<ds:DigestMethod Algorithm='http:\/\/www.w3.org\/2000\/09\/xmldsig#sha1'\/>/, response_xml
end
it "create a signed logout response with 256 digest and signature methods" do
settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA256
settings.security[:digest_method] = XMLSecurity::Document::SHA256
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message")
response_xml = Base64.decode64(params["SAMLResponse"])
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], response_xml
assert_match /<ds:SignatureMethod Algorithm='http:\/\/www.w3.org\/2001\/04\/xmldsig-more#rsa-sha256'\/>/, response_xml
assert_match /<ds:DigestMethod Algorithm='http:\/\/www.w3.org\/2001\/04\/xmlenc#sha256'\/>/, response_xml
end
it "create a signed logout response with 512 digest and signature method RSA_SHA384" do
settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA384
settings.security[:digest_method] = XMLSecurity::Document::SHA512
logout_request.settings = settings
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message")
response_xml = Base64.decode64(params["SAMLResponse"])
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], response_xml
assert_match /<ds:SignatureMethod Algorithm='http:\/\/www.w3.org\/2001\/04\/xmldsig-more#rsa-sha384'\/>/, response_xml
assert_match /<ds:DigestMethod Algorithm='http:\/\/www.w3.org\/2001\/04\/xmlenc#sha512'\/>/, response_xml
end
end
describe "signing with HTTP-Redirect binding" do
let(:cert) { OpenSSL::X509::Certificate.new(ruby_saml_cert_text) }
before do
settings.idp_sso_service_binding = :post
settings.idp_slo_service_binding = :redirect
settings.compress_response = false
settings.security[:logout_responses_signed] = true
end
it "create a signature parameter with RSA_SHA1 and validate it" do
settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA1
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message", :RelayState => 'http://example.com')
assert params['SAMLResponse']
assert params[:RelayState]
assert params['Signature']
assert_equal params['SigAlg'], XMLSecurity::Document::RSA_SHA1
query_string = "SAMLResponse=#{CGI.escape(params['SAMLResponse'])}"
query_string << "&RelayState=#{CGI.escape(params[:RelayState])}"
query_string << "&SigAlg=#{CGI.escape(params['SigAlg'])}"
signature_algorithm = XMLSecurity::BaseDocument.new.algorithm(params['SigAlg'])
assert_equal signature_algorithm, OpenSSL::Digest::SHA1
assert cert.public_key.verify(signature_algorithm.new, Base64.decode64(params['Signature']), query_string)
end
it "create a signature parameter with RSA_SHA256 /SHA256 and validate it" do
settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA256
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message", :RelayState => 'http://example.com')
assert params['SAMLResponse']
assert params[:RelayState]
assert params['Signature']
assert_equal params['SigAlg'], XMLSecurity::Document::RSA_SHA256
query_string = "SAMLResponse=#{CGI.escape(params['SAMLResponse'])}"
query_string << "&RelayState=#{CGI.escape(params[:RelayState])}"
query_string << "&SigAlg=#{CGI.escape(params['SigAlg'])}"
signature_algorithm = XMLSecurity::BaseDocument.new.algorithm(params['SigAlg'])
assert_equal signature_algorithm, OpenSSL::Digest::SHA256
assert cert.public_key.verify(signature_algorithm.new, Base64.decode64(params['Signature']), query_string)
end
it "create a signature parameter with RSA_SHA384 / SHA384 and validate it" do
settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA384
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message", :RelayState => 'http://example.com')
assert params['SAMLResponse']
assert params[:RelayState]
assert params['Signature']
assert_equal params['SigAlg'], XMLSecurity::Document::RSA_SHA384
query_string = "SAMLResponse=#{CGI.escape(params['SAMLResponse'])}"
query_string << "&RelayState=#{CGI.escape(params[:RelayState])}"
query_string << "&SigAlg=#{CGI.escape(params['SigAlg'])}"
signature_algorithm = XMLSecurity::BaseDocument.new.algorithm(params['SigAlg'])
assert_equal signature_algorithm, OpenSSL::Digest::SHA384
assert cert.public_key.verify(signature_algorithm.new, Base64.decode64(params['Signature']), query_string)
end
it "create a signature parameter with RSA_SHA512 / SHA512 and validate it" do
settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA512
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message", :RelayState => 'http://example.com')
assert params['SAMLResponse']
assert params[:RelayState]
assert params['Signature']
assert_equal params['SigAlg'], XMLSecurity::Document::RSA_SHA512
query_string = "SAMLResponse=#{CGI.escape(params['SAMLResponse'])}"
query_string << "&RelayState=#{CGI.escape(params[:RelayState])}"
query_string << "&SigAlg=#{CGI.escape(params['SigAlg'])}"
signature_algorithm = XMLSecurity::BaseDocument.new.algorithm(params['SigAlg'])
assert_equal signature_algorithm, OpenSSL::Digest::SHA512
assert cert.public_key.verify(signature_algorithm.new, Base64.decode64(params['Signature']), query_string)
end
end
describe "DEPRECATED: signing with HTTP-POST binding via :embed_sign" do
before do
settings.compress_response = false
settings.security[:logout_responses_signed] = true
settings.security[:embed_sign] = true
end
it "doesn't sign through create_xml_document" do
unauth_res = OneLogin::RubySaml::SloLogoutresponse.new
inflated = unauth_res.create_xml_document(settings).to_s
refute_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], inflated
refute_match %r[<ds:SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1'/>], inflated
refute_match %r[<ds:DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>], inflated
end
it "sign unsigned request" do
unauth_res = OneLogin::RubySaml::SloLogoutresponse.new
unauth_res_doc = unauth_res.create_xml_document(settings)
inflated = unauth_res_doc.to_s
refute_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], inflated
refute_match %r[<ds:SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1'/>], inflated
refute_match %r[<ds:DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>], inflated
inflated = unauth_res.sign_document(unauth_res_doc, settings).to_s
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], inflated
assert_match %r[<ds:SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1'/>], inflated
assert_match %r[<ds:DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>], inflated
end
end
describe "DEPRECATED: signing with HTTP-Redirect binding via :embed_sign" do
let(:cert) { OpenSSL::X509::Certificate.new(ruby_saml_cert_text) }
before do
settings.compress_response = false
settings.security[:logout_responses_signed] = true
settings.security[:embed_sign] = false
end
it "create a signature parameter with RSA_SHA1 and validate it" do
settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA1
params = OneLogin::RubySaml::SloLogoutresponse.new.create_params(settings, logout_request.id, "Custom Logout Message", :RelayState => 'http://example.com')
assert params['SAMLResponse']
assert params[:RelayState]
assert params['Signature']
assert_equal params['SigAlg'], XMLSecurity::Document::RSA_SHA1
query_string = "SAMLResponse=#{CGI.escape(params['SAMLResponse'])}"
query_string << "&RelayState=#{CGI.escape(params[:RelayState])}"
query_string << "&SigAlg=#{CGI.escape(params['SigAlg'])}"
signature_algorithm = XMLSecurity::BaseDocument.new.algorithm(params['SigAlg'])
assert_equal signature_algorithm, OpenSSL::Digest::SHA1
assert cert.public_key.verify(signature_algorithm.new, Base64.decode64(params['Signature']), query_string)
end
end
describe "#manipulate response_id" do
it "be able to modify the response id" do
logoutresponse = OneLogin::RubySaml::SloLogoutresponse.new
response_id = logoutresponse.response_id
assert_equal response_id, logoutresponse.uuid
logoutresponse.uuid = "new_uuid"
assert_equal logoutresponse.response_id, logoutresponse.uuid
assert_equal "new_uuid", logoutresponse.response_id
end
end
end
end
| onelogin/ruby-saml | test/slo_logoutresponse_test.rb | Ruby | mit | 16,979 |
<?php
//2382364672-2399141887
$ranges=Array(
"2382430208" => array("2382495743","CA"),
"2382495744" => array("2382561279","CA"),
"2382561280" => array("2382626815","CA"),
"2382626816" => array("2382692351","CA"),
"2382692352" => array("2382757887","CA"),
"2382757888" => array("2382823423","CA"),
"2382823424" => array("2382888959","CA"),
"2382888960" => array("2382954495","CA"),
"2382954496" => array("2383020031","CA"),
"2383020032" => array("2383085567","CA"),
"2383151104" => array("2383216639","CA"),
"2383216640" => array("2383282175","CA"),
"2383282176" => array("2383347711","CA"),
"2383347712" => array("2383413247","CA"),
"2383413248" => array("2383478783","CA"),
"2383478784" => array("2383544319","CA"),
"2383544320" => array("2383609855","CA"),
"2383609856" => array("2383675391","CA"),
"2383675392" => array("2383740927","CA"),
"2383740928" => array("2383806463","CA"),
"2383806464" => array("2383871999","CA"),
"2383872000" => array("2383937535","CA"),
"2383937536" => array("2384003071","CA"),
"2384003072" => array("2384068607","CA"),
"2384068608" => array("2384134143","CA"),
"2384134144" => array("2384199679","CA"),
"2384199680" => array("2384265215","CA"),
"2384265216" => array("2384330751","CA"),
"2384330752" => array("2384396287","CA"),
"2384396288" => array("2384461823","CA"),
"2384461824" => array("2384527359","CA"),
"2384527360" => array("2384592895","CA"),
"2384592896" => array("2384658431","CA"),
"2384658432" => array("2384723967","CA"),
"2384723968" => array("2384789503","CA"),
"2384789504" => array("2384855039","CA"),
"2384855040" => array("2384920575","CA"),
"2384920576" => array("2384986111","CA"),
"2384986112" => array("2385051647","CA"),
"2385051648" => array("2385117183","CA"),
"2385117184" => array("2385182719","CA"),
"2385182720" => array("2385248255","CA"),
"2385248256" => array("2385313791","CA"),
"2385313792" => array("2385707007","CA"),
"2385707008" => array("2385772543","CA"),
"2385772544" => array("2385838079","CA"),
"2385838080" => array("2385903615","CA"),
"2385903616" => array("2385969151","CA"),
"2385969152" => array("2386034687","CA"),
"2386034688" => array("2386100223","CA"),
"2386100224" => array("2386165759","CA"),
"2386165760" => array("2386231295","CA"),
"2386231296" => array("2386296831","CA"),
"2386296832" => array("2386362367","CA"),
"2386362368" => array("2386427903","CA"),
"2386427904" => array("2386493439","CA"),
"2386493440" => array("2386558975","CA"),
"2386558976" => array("2386624511","CA"),
"2386624512" => array("2386690047","US"),
"2386690048" => array("2386755583","CA"),
"2386755584" => array("2386821119","CA"),
"2386821120" => array("2386886655","CA"),
"2386886656" => array("2386952191","CA"),
"2386952192" => array("2387017727","CA"),
"2387017728" => array("2387083263","CA"),
"2387083264" => array("2387148799","CA"),
"2387148800" => array("2387214335","CA"),
"2387214336" => array("2387279871","CA"),
"2387279872" => array("2387345407","CA"),
"2387345408" => array("2387410943","CA"),
"2387410944" => array("2387476479","US"),
"2387476480" => array("2387542015","CA"),
"2387542016" => array("2387607551","US"),
"2387607552" => array("2388000767","CA"),
"2388000768" => array("2388066303","CA"),
"2388066304" => array("2388131839","CA"),
"2388131840" => array("2388197375","CA"),
"2388197376" => array("2388262911","CA"),
"2388262912" => array("2388328447","CA"),
"2388393984" => array("2388459519","CA"),
"2388459520" => array("2388525055","CA"),
"2388525056" => array("2388590591","CA"),
"2388590592" => array("2388656127","CA"),
"2388656128" => array("2388721663","CA"),
"2388721664" => array("2388787199","CA"),
"2388787200" => array("2388852735","CA"),
"2388852736" => array("2388918271","CA"),
"2388918272" => array("2388983807","CA"),
"2388983808" => array("2389049343","CA"),
"2389049344" => array("2389114879","CA"),
"2389114880" => array("2389180415","CA"),
"2389180416" => array("2389245951","CA"),
"2389311488" => array("2389377023","CA"),
"2389377024" => array("2389442559","CA"),
"2389442560" => array("2389508095","CA"),
"2389508096" => array("2389573631","CA"),
"2389573632" => array("2389639167","CA"),
"2389704704" => array("2390753279","CA"),
"2390753280" => array("2390818815","CA"),
"2390884352" => array("2390949887","CA"),
"2390949888" => array("2391015423","CA"),
"2391015424" => array("2391080959","CA"),
"2391080960" => array("2391146495","CA"),
"2391146496" => array("2391212031","CA"),
"2391212032" => array("2391277567","CA"),
"2391343104" => array("2391408639","CA"),
"2391408640" => array("2391474175","CA"),
"2391474176" => array("2391539711","CA"),
"2391539712" => array("2391605247","CA"),
"2391605248" => array("2391670783","CA"),
"2391670784" => array("2391736319","CA"),
"2391736320" => array("2391801855","CA"),
"2391801856" => array("2391867391","CA"),
"2391867392" => array("2391932927","CA"),
"2391932928" => array("2391998463","CA"),
"2391998464" => array("2392063999","CA"),
"2392064000" => array("2392096767","CA"),
"2392096768" => array("2392129535","CA"),
"2392129536" => array("2392195071","CA"),
"2392195072" => array("2392260607","CA"),
"2392260608" => array("2392326143","CA"),
"2392326144" => array("2392391679","CA"),
"2392391680" => array("2392457215","CA"),
"2392457216" => array("2392522751","CA"),
"2392522752" => array("2392588287","CA"),
"2392588288" => array("2392653823","CA"),
"2392653824" => array("2392719359","CA"),
"2392719360" => array("2392784895","CA"),
"2392784896" => array("2392850431","CA"),
"2392850432" => array("2392915967","CA"),
"2392915968" => array("2392981503","CA"),
"2392981504" => array("2393047039","CA"),
"2393047040" => array("2393112575","CA"),
"2393112576" => array("2393178111","CA"),
"2393178112" => array("2393243647","CA"),
"2393243648" => array("2393309183","CA"),
"2393309184" => array("2393374719","CA"),
"2393374720" => array("2393440255","CA"),
"2393440256" => array("2393505791","CA"),
"2393505792" => array("2393571327","CA"),
"2393571328" => array("2393636863","CA"),
"2393636864" => array("2393702399","CA"),
"2393702400" => array("2393767935","CA"),
"2393767936" => array("2393833471","CA"),
"2393833472" => array("2393899007","CA"),
"2393899008" => array("2393964543","CA"),
"2393964544" => array("2394030079","CA"),
"2394030080" => array("2394095615","CA"),
"2394095616" => array("2394161151","CA"),
"2394161152" => array("2394226687","CA"),
"2394226688" => array("2394292223","CA"),
"2394292224" => array("2394357759","CA"),
"2394357760" => array("2394423295","CA"),
"2394423296" => array("2394488831","CA"),
"2394488832" => array("2394554367","CA"),
"2394554368" => array("2394619903","CA"),
"2394619904" => array("2394685439","CA"),
"2394685440" => array("2394750975","CA"),
"2394750976" => array("2394816511","CA"),
"2394816512" => array("2394882047","CA"),
"2394882048" => array("2394947583","CA"),
"2394947584" => array("2395013119","US"),
"2395013120" => array("2395078655","CA"),
"2395078656" => array("2395144191","CA"),
"2395144192" => array("2395209727","CA"),
"2395340800" => array("2395406335","CA"),
"2395406336" => array("2395471871","CA"),
"2395471872" => array("2395537407","CA"),
"2395537408" => array("2395602943","CA"),
"2395602944" => array("2395668479","CA"),
"2395668480" => array("2395734015","CA"),
"2395734016" => array("2395799551","CA"),
"2395799552" => array("2395865087","CA"),
"2395865088" => array("2395930623","CA"),
"2395930624" => array("2395996159","CA"),
"2395996160" => array("2396061695","CA"),
"2396061696" => array("2396127231","CA"),
"2396127232" => array("2396192767","CA"),
"2396192768" => array("2396258303","CA"),
"2396258304" => array("2396323839","CA"),
"2396323840" => array("2396389375","CA"),
"2396389376" => array("2396454911","CA"),
"2396454912" => array("2396520447","CA"),
"2396520448" => array("2396585983","CA"),
"2396585984" => array("2396651519","CA"),
"2396651520" => array("2396717055","CA"),
"2396717056" => array("2396782591","CA"),
"2396782592" => array("2396848127","CA"),
"2396848128" => array("2396913663","CA"),
"2396913664" => array("2396979199","CA"),
"2396979200" => array("2397044735","CA"),
"2397044736" => array("2397110271","CA"),
"2397110272" => array("2397175807","CA"),
"2397175808" => array("2397241343","CA"),
"2397241344" => array("2397306879","CA"),
"2397306880" => array("2397372415","CA"),
"2397372416" => array("2397437951","CA"),
"2397437952" => array("2397503487","CA"),
"2397503488" => array("2397569023","CA"),
"2397569024" => array("2397634559","CA"),
"2397634560" => array("2397700095","CA"),
"2397765632" => array("2397831167","CA"),
"2397831168" => array("2397896703","CA"),
"2397896704" => array("2397962239","CA"),
"2397962240" => array("2398027775","CA"),
"2398027776" => array("2398093311","CA"),
"2398093312" => array("2398158847","CA"),
"2398158848" => array("2398224383","CA"),
"2398224384" => array("2398289919","CA"),
"2398289920" => array("2398355455","CA"),
"2398355456" => array("2398420991","CA"),
"2398420992" => array("2398486527","CA"),
"2398486528" => array("2398552063","CA"),
"2398552064" => array("2398617599","CA"),
"2398617600" => array("2398683135","CA"),
"2398683136" => array("2398748671","CA"),
"2398945280" => array("2399010815","CA"),
);
?> | NikoRoberts/BuzzerBeaterStats | scripts/c_ip/142.php | PHP | mit | 9,164 |
package twg2.template.codeTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @param <T> the {@link ClassInfo} to build
*
* @author TeamworkGuy2
* @since 2015-1-24
*/
public final class ClassTemplateBuilder<T extends ClassInfo> {
private T tmpl;
public ClassTemplateBuilder(T tmpl) {
this.tmpl = tmpl;
}
public ClassTemplateBuilder(T tmpl, String className, String packageName) {
this.tmpl = tmpl;
tmpl.setClassName(className);
tmpl.setPackageName(packageName);
}
public ClassTemplateBuilder<T> setPackageName(String packageName) {
tmpl.setPackageName(packageName);
return this;
}
/** Alias for {@link #addImportStatement(Class...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> imports(Class<?>... importStatements) {
return addImportStatement(importStatements);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImportStatement(Class<?>... importStatements) {
List<String> statements = tmpl.getImportStatements();
if(statements == null) {
statements = new ArrayList<>();
tmpl.setImportStatements(statements);
}
if(importStatements == null) {
return this;
}
for(Class<?> importStatement : importStatements) {
statements.add(importStatement.getCanonicalName());
}
return this;
}
/** Alias for {@link #addImportStatement(String...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> imports(String... importStatements) {
return addImportStatement(importStatements);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImportStatement(String... importStatements) {
List<String> imports = tmpl.getImportStatements();
if(imports == null) {
imports = new ArrayList<>();
tmpl.setImportStatements(imports);
}
if(importStatements == null) {
return this;
}
for(String importStatement : importStatements) {
imports.add(importStatement);
}
return this;
}
public ClassTemplateBuilder<T> setClassModifier(String classAccessModifier) {
tmpl.setClassModifier(classAccessModifier);
return this;
}
public ClassTemplateBuilder<T> setClassType(String classType) {
tmpl.setClassType(classType);
return this;
}
public ClassTemplateBuilder<T> addTypeParameters(Iterable<? extends Map.Entry<String, String>> classParameterNamesAndTypes) {
for(Map.Entry<String, String> classParam : classParameterNamesAndTypes) {
addTypeParameter(classParam.getKey(), classParam.getValue());
}
return this;
}
public ClassTemplateBuilder<T> addTypeParameter(String classParameterName, String classTypeParameterDefinition) {
if(tmpl.getClassTypeParameterDefinitions() == null) {
tmpl.setClassTypeParameterDefinitions(new ArrayList<>());
}
if(tmpl.getClassTypeParameterNames() == null) {
tmpl.setClassTypeParameterNames(new ArrayList<>());
}
tmpl.getClassTypeParameterNames().add(classParameterName);
tmpl.getClassTypeParameterDefinitions().add(classTypeParameterDefinition);
return this;
}
public ClassTemplateBuilder<T> setClassName(String className) {
tmpl.setClassName(className);
return this;
}
/** Alias for {@link #setExtendClassName(Class)} */
public ClassTemplateBuilder<T> extend(Class<?> extendClassName) {
return setExtendClassName(extendClassName);
}
public ClassTemplateBuilder<T> setExtendClassName(Class<?> extendClassName) {
tmpl.setExtendClassName(extendClassName.getCanonicalName().replace("java.lang.", ""));
return this;
}
/** Alias for {@link #setExtendClassName(String)} */
public ClassTemplateBuilder<T> extend(String extendClassName) {
return setExtendClassName(extendClassName);
}
public ClassTemplateBuilder<T> setExtendClassName(String extendClassName) {
tmpl.setExtendClassName(extendClassName);
return this;
}
/** Alias for {@link #addImplementClassNames(String...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> implement(String... implementClassNames) {
return addImplementClassNames(implementClassNames);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImplementClassNames(String... implementClassNames) {
List<String> implementNames = tmpl.getImplementClassNames();
if(implementNames == null) {
implementNames = new ArrayList<>();
tmpl.setImplementClassNames(implementNames);
}
if(implementClassNames == null) {
return this;
}
for(String implementClassName : implementClassNames) {
implementNames.add(implementClassName);
}
return this;
}
/** Alias for {@link #addImplementClassNames(Class...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> implement(Class<?>... implementClassNames) {
return addImplementClassNames(implementClassNames);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImplementClassNames(Class<?>... implementClassNames) {
List<String> implementNames = tmpl.getImplementClassNames();
if(implementNames == null) {
implementNames = new ArrayList<>();
tmpl.setImplementClassNames(implementNames);
}
if(implementClassNames == null) {
return this;
}
for(Class<?> implementClassName : implementClassNames) {
implementNames.add(implementClassName.getCanonicalName().replace("java.lang.", ""));
}
return this;
}
public T getTemplate() {
return tmpl;
}
public static ClassTemplateBuilder<ClassInfo> newInst() {
return new ClassTemplateBuilder<ClassInfo>(new ClassTemplate());
}
public static <T extends ClassInfo> ClassTemplateBuilder<T> of(T inst) {
return new ClassTemplateBuilder<>(inst);
}
public static <T extends ClassInfo> ClassTemplateBuilder<T> of(T inst, String className, String packageName) {
return new ClassTemplateBuilder<>(inst, className, packageName);
}
public static ClassTemplateBuilder<ClassTemplate> of(String className) {
return of(className, null);
}
public static ClassTemplateBuilder<ClassTemplate> of(String className, String packageName) {
return new ClassTemplateBuilder<>(new ClassTemplate(), className, packageName);
}
}
| TeamworkGuy2/JTwg2Templating | src/twg2/template/codeTemplate/ClassTemplateBuilder.java | Java | mit | 5,967 |
<?php
get_header();
$sidebar = ot_get_option( 'search_page_sidebar', 'yes' );
$content_class = 'sixteen';
if ( $sidebar == 'yes' )
$content_class = 'eleven';
$cat_title = single_cat_title( '', false );
$cat_id = get_query_var( 'cat' );
$count = 0;
global $paged;
?>
<div class="pageTitle">
<div class="container">
<div class="sixteen columns"><h1><?php printf( __( 'Search for: %s', 'localization' ), get_search_query() ); ?></h1></div>
</div>
</div><!-- .pageTitle -->
<div class="pageContent">
<div class="container">
<div class="<?php echo $content_class; ?> columns content">
<?php if ( have_posts()) : while ( have_posts()) : the_post(); $count++; ?>
<?php if ( $count == 1 && $paged == 0 ) : ?>
<div class="categoryFeatured clearfix">
<div class="four columns alpha categoryFeaturedThumb">
<?php if(get_field('custom_post_link', $thePostID ) != '') { ?><a target="_blank" href="<?php the_field('custom_post_link', $thePostID ); ?>"><?php } else { ?><a href="<?php the_permalink(); ?>"><?php } ?><?php the_post_thumbnail( 'post-medium' ); ?></a>
</div>
<?php if ( $sidebar == 'yes') : ?>
<div class="seven columns omega">
<?php else : ?>
<div class="twelve columns omega">
<?php endif; ?>
<div class="categoryFeaturedInfo">
<h1><?php if(get_field('custom_post_link', $thePostID ) != '') { ?><a target="_blank" href="<?php the_field('custom_post_link', $thePostID ); ?>"><?php } else { ?><a href="<?php the_permalink(); ?>"><?php } ?><?php the_title(); ?></a></h1>
<?php the_excerpt(); ?>
<ul>
<li><a class="author" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>"><i class="icon-user"></i><?php the_author(); ?></a></li>
<?php if ( has_tag() ) : ?>
<li><a class="tags" href="#"><i class="icon-tag"></i></a><?php the_tags('', ', ', ''); ?> </li>
<?php endif; ?>
<li><a class="comments" href="<?php comments_link(); ?> "><i class="icon-comment"></i> <?php comments_number( __( '0 comments', 'localization' ), __( '1 comment', 'localization' ), __( '% comments', 'localization' ) ); ?> </a></li>
</ul>
</div>
</div>
</div><!-- .categoryFeatured -->
<?php endif; ?>
<?php if ( $count > 1 || $paged != 0 ) : ?>
<?php if ( ( $count == 2 && $paged == 0 ) || ( $count == 1 && $paged != 0 ) ) : ?><ul class="categoryPosts"><?php endif; ?>
<li <?php post_class( 'categoryPost' ); ?>>
<?php if( has_post_thumbnail() ) : ?>
<div class="two columns alpha categoryPostsThumbs">
<?php if(get_field('custom_post_link', $thePostID ) != '') { ?><a target="_blank" href="<?php the_field('custom_post_link', $thePostID ); ?>"><?php } else { ?><a href="<?php the_permalink(); ?>"><?php } ?><?php the_post_thumbnail( 'post-regular' ); ?></a>
</div>
<?php if ( $sidebar == 'yes') : ?>
<div class="eight columns omega">
<?php else : ?>
<div class="thirteen columns omega">
<?php endif; ?>
<?php else : ?>
<?php if ( $sidebar == 'yes') : ?>
<div class="ten columns omega">
<?php else : ?>
<div class="fifteen columns omega">
<?php endif; ?>
<?php endif; ?>
<div class="categoryPostsInfo">
<h1><?php if(get_field('custom_post_link', $thePostID ) != '') { ?><a target="_blank" href="<?php the_field('custom_post_link', $thePostID ); ?>"><?php } else { ?><a href="<?php the_permalink(); ?>"><?php } ?><?php the_title(); ?></a><span class="categoryBadge category-<?php echo $cat_id; ?>"><?php the_category(', ');?></span></h1>
<?php the_excerpt(); ?>
<ul>
<li><a class="author" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>"><i class="icon-user"></i><?php the_author(); ?></a></li>
<?php if ( has_tag() ) : ?>
<li><a class="tags" href="#"><i class="icon-tag"></i></a><?php the_tags('', ', ', ''); ?> </li>
<?php endif; ?>
<li><a class="comments" href="<?php comments_link(); ?> "><i class="icon-comment"></i> <?php comments_number( __( '0 comments', 'localization' ), __( '1 comment', 'localization' ), __( '% comments', 'localization' ) ); ?> </a></li>
</ul>
</div><!-- .categoryPostsInfo -->
</div><!-- .columns.omega -->
<div class="one column">
<?php if(get_field('custom_post_link', $thePostID ) != '') { ?><a target="_blank" href="<?php the_field('custom_post_link', $thePostID ); ?>" class="categoryPostBtn"><?php } else { ?><a href="<?php the_permalink(); ?>" class="categoryPostBtn"><?php } ?><i class="icon-right-open"></i></a>
</div>
</li>
<?php endif; ?>
<?php endwhile; else :?>
<div class="pageContent">
<h4 style="margin-top: 0; margin-bottom: 10px;"><?php _e('THERE IS NO POST AVAILABLE', 'localization'); ?></h4>
<a href="<?php echo home_url(); ?>" class="back-to-home"><?php _e('Go Back To Homepage', 'localization'); ?> →</a>
</div>
<?php endif; ?>
</ul><!-- .categoryPosts -->
<?php kriesi_pagination( $wp_query->max_num_pages, 500 ); ?>
<?php dd_load_more_button(); ?>
</div><!-- .content -->
<ul class="sidebar four columns clearfix sidebarone">
<?php if ( function_exists( 'dynamic_sidebar' ) && dynamic_sidebar( 'sidebar-4' ) ) : else : ?>
<p><strong>Home Sidebar 1</strong> widget section is empty.</p>
<p>Go to WP Admin → Appearance → Widgets and add the widgets you want.</p>
<?php endif; ?>
</ul>
<?php// if ( $sidebar == 'yes' ) get_sidebar( 'archives' ); ?>
</div><!-- .container -->
</div><!-- .pageContent -->
<?php get_footer(); ?> | mandino/www.bloggingshakespeare.com | reviewing-shakespeare/wp-content/themes/reviewing-shakespeare/search.php | PHP | mit | 5,913 |
$(document).ready(function() {
//Note: default min/max ranges are defined outside of this JS file
//include "js/BoulderRouteGradingSystems.js" before running this script
//generate Bouldering rating selection upon click
//Find which boulder grading system is selected and update the difficulty range
//**********************************************
$("select[name='boulder-rating-select']").click(function()
{
var boulderGradingSelect = document.getElementById("boulder-rating-select");
boulderGradingID = boulderGradingSelect.options[boulderGradingSelect.selectedIndex].value;
console.log(boulderGradingID);
var maxBoulder = boulderRatings[boulderGradingID].length - 1;
var boulderingMinRange = "<div id='boulderprefs'><p>Minimum bouldering rating: <select name='minBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==selectMinBoulder) {
boulderingMinRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMinRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMinRange += "</option></select>";
//get max value of bouldering range
var boulderingMaxRange = "<p>Maximum bouldering rating: <select name='maxBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==Math.min(maxBoulder,selectMaxBoulder)) {
boulderingMaxRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMaxRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMaxRange += "</option></select></div>";
document.getElementById("boulderprefs").innerHTML =
boulderingMinRange + boulderingMaxRange;
});
//**********************************************
//initialize the boulder grading system
var maxBoulder = boulderRatings[boulderGradingID].length - 1;
var boulderingMinRange = "<div id='boulderprefs'><p>Minimum bouldering rating: <select name='minBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==selectMinBoulder) {
boulderingMinRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMinRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMinRange += "</option></select>";
//get max value of bouldering range
var boulderingMaxRange = "<p>Maximum bouldering rating: <select name='maxBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==Math.min(maxBoulder,selectMaxBoulder)) {
boulderingMaxRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMaxRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMaxRange += "</option></select></div>";
//************************
//Update TR and lead when clicked
//******************************
$("select[name='route-rating-select']").click(function()
{
var routeGradingSelect = document.getElementById("route-rating-select");
routeGradingID = routeGradingSelect.options[routeGradingSelect.selectedIndex].value;
console.log(routeGradingID);
var maxRoute = routeRatings[routeGradingID].length - 1;
//generate TR rating selection
var TRMinRange = "<div id='trprefs'><p>Minimum top-rope rating: <select name='minTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinTR) {
TRMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMinRange += "</option></select>";
var TRMaxRange = "<p>Maximum top-rope rating: <select name='maxTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxTR)) {
TRMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMaxRange += "</option></select></div>";
//generate lead rating selection
var LeadMinRange = "<div id='leadprefs'><p>Minimum lead rating: <select name='minLeadRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinL) {
LeadMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMinRange += "</option></select>";
var LeadMaxRange = "<p>Maximum lead rating: <select name='maxLeadRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxL)) {
LeadMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMaxRange += "</option></select></div>";
document.getElementById("trprefs").innerHTML = TRMinRange + TRMaxRange;
document.getElementById("leadprefs").innerHTML =
LeadMinRange + LeadMaxRange;
});
//**********************************
//Initialize TR and Lead selections
var maxRoute = routeRatings[routeGradingID].length - 1;
//generate TR rating selection
var TRMinRange = "<div id='trprefs'><p>Minimum top-rope rating: <select name='minTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinTR) {
TRMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMinRange += "</option></select>";
var TRMaxRange = "<p>Maximum top-rope rating: <select name='maxTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxTR)) {
TRMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMaxRange += "</option></select></div>";
//generate lead rating selection
var LeadMinRange = "<div id='leadprefs'><p>Minimum lead rating: <select name='minLeadRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinL) {
LeadMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMinRange += "</option></select>";
var LeadMaxRange = "<p>Maximum lead rating: <select name='maxLeadRange' class='form-control' id='rating-range-select'> ";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxL)) {
LeadMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMaxRange += "</option></select></div>";
//write rating preferences to html
document.getElementById("ratingrange").innerHTML =
boulderingMinRange + boulderingMaxRange + TRMinRange + TRMaxRange +
LeadMinRange + LeadMaxRange;
$("select[name='country-select']").click(function()
{
//get country value
var country = document.getElementById("country-select");
var countryID = country.options[country.selectedIndex].value;
console.log(countryID);
//determine best guess for grading system?
});
$("input[name='showBoulder']").click(function()
{
if ($(this).is(':checked')) {
$("#boulderprefs").show();
}
else {
$("#boulderprefs").hide();
}
});
$("input[name='showTR']").click(function()
{
if ($(this).is(':checked')) {
$("#trprefs").show();
}
else {
$("#trprefs").hide();
}
});
$("input[name='showLead']").click(function()
{
if ($(this).is(':checked')) {
$("#leadprefs").show();
}
else {
$("#leadprefs").hide();
}
});
});
| shimizust/trackyourclimb | js/preferences.js | JavaScript | mit | 8,494 |
<?php
declare(strict_types=1);
namespace App\Persistence\Query\Constraint;
class Lt extends FieldValue
{
const OP = '<';
} | kilahm/minutes | back/Persistence/Query/Constraint/Lt.php | PHP | mit | 128 |
'use strict';
jQuery(document).ready(function ($) {
var lastId,
topMenu = $("#top-navigation"),
topMenuHeight = topMenu.outerHeight(),
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function () {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
//Get width of container
var containerWidth = $('.section .container').width();
//Resize animated triangle
$(".triangle").css({
"border-left": containerWidth / 2 + 'px outset transparent',
"border-right": containerWidth / 2 + 'px outset transparent'
});
//resize
$(window).resize(function () {
containerWidth = $('.container').width();
$(".triangle").css({
"border-left": containerWidth / 2 + 'px outset transparent',
"border-right": containerWidth / 2 + 'px outset transparent'
});
});
//mask
$('.has-mask').each( function() {
var $this = $( this ),
mask = $this.data( 'aria-mask' );
$this.mask( mask );
});
//Initialize header slider.
$('#da-slider').cslider();
//Initial mixitup, used for animated filtering portgolio.
$('#portfolio-grid').mixitup({
'onMixStart': function (config) {
$('div.toggleDiv').hide();
}
});
//Initial Out clients slider in client section
$('#clint-slider').bxSlider({
pager: false,
minSlides: 1,
maxSlides: 5,
moveSlides: 2,
slideWidth: 210,
slideMargin: 25,
prevSelector: $('#client-prev'),
nextSelector: $('#client-next'),
prevText: '<i class="icon-left-open"></i>',
nextText: '<i class="icon-right-open"></i>'
});
$('input, textarea').placeholder();
// Bind to scroll
$(window).scroll(function () {
//Display or hide scroll to top button
if ($(this).scrollTop() > 100) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
if ($(this).scrollTop() > 100) {
$('.navbar').addClass('navbar-fixed-top animated fadeInDown');
} else {
$('.navbar').removeClass('navbar-fixed-top animated fadeInDown');
}
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight + 10;
// Get id of current scroll item
var cur = scrollItems.map(function () {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
/*
Function for scroliing to top
************************************/
$('.scrollup').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
/*
Sand newsletter
**********************************************************************/
$('#subscribe').click(function () {
var error = false;
var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field
if (email == "" || email == " " || !emailCompare.test(email)) {
$('#err-subscribe').show(500);
$('#err-subscribe').delay(4000);
$('#err-subscribe').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
if (error === false) {
$.ajax({
type: 'POST',
url: 'php/newsletter.php',
data: {
email: $('#nlmail').val()
},
error: function (request, error) {
alert("An error occurred");
},
success: function (response) {
if (response == 'OK') {
$('#success-subscribe').show();
$('#nlmail').val('')
} else {
alert("An error occurred");
}
}
});
}
return false;
});
/*
Sand mail
**********************************************************************/
$("#send-mail").click(function () {
var name = $('input#name').val(); // get the value of the input field
var error = false;
if (name == "" || name == " ") {
$('#err-name').show(500);
$('#err-name').delay(4000);
$('#err-name').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
var email = $('input#email').val().toLowerCase(); // get the value of the input field
if (email == "" || email == " " || !emailCompare.test(email)) {
$('#err-email').show(500);
$('#err-email').delay(4000);
$('#err-email').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var comment = $('textarea#comment').val(); // get the value of the input field
if (comment == "" || comment == " ") {
$('#err-comment').show(500);
$('#err-comment').delay(4000);
$('#err-comment').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
if (error == false) {
var dataString = $('#contact-form').serialize(); // Collect data from form
$.ajax({
type: "POST",
url: $('#contact-form').attr('action'),
data: dataString,
timeout: 6000,
error: function (request, error) {
},
success: function (response) {
response = $.parseJSON(response);
if (response.success) {
$('#successSend').show();
$("#name").val('');
$("#email").val('');
$("#comment").val('');
} else {
$('#errorSend').show();
}
}
});
return false;
}
return false; // stops user browser being directed to the php file
});
//Function for show or hide portfolio desctiption.
$.fn.showHide = function (options) {
var defaults = {
speed: 1000,
easing: '',
changeText: 0,
showText: 'Show',
hideText: 'Hide'
};
var options = $.extend(defaults, options);
$(this).click(function () {
$('.toggleDiv').slideUp(options.speed, options.easing);
var toggleClick = $(this);
var toggleDiv = $(this).attr('rel');
$(toggleDiv).slideToggle(options.speed, options.easing, function () {
if (options.changeText == 1) {
$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
}
});
return false;
});
};
//Initial Show/Hide portfolio element.
$('div.toggleDiv').hide();
/************************
Animate elements
*************************/
//Animate thumbnails
jQuery('.thumbnail').one('inview', function (event, visible) {
if (visible == true) {
jQuery(this).addClass("animated fadeInDown");
} else {
jQuery(this).removeClass("animated fadeInDown");
}
});
//Animate triangles
jQuery('.triangle').bind('inview', function (event, visible) {
if (visible == true) {
jQuery(this).addClass("animated fadeInDown");
} else {
jQuery(this).removeClass("animated fadeInDown");
}
});
//animate first team member
jQuery('#first-person').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('#first-person').addClass("animated pulse");
} else {
jQuery('#first-person').removeClass("animated pulse");
}
});
//animate sectond team member
jQuery('#second-person').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('#second-person').addClass("animated pulse");
} else {
jQuery('#second-person').removeClass("animated pulse");
}
});
//animate thrid team member
jQuery('#third-person').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('#third-person').addClass("animated pulse");
} else {
jQuery('#third-person').removeClass("animated pulse");
}
});
//Animate price columns
jQuery('.price-column, .testimonial').bind('inview', function (event, visible) {
if (visible == true) {
jQuery(this).addClass("animated fadeInDown");
} else {
jQuery(this).removeClass("animated fadeInDown");
}
});
//Animate contact form
jQuery('.contact-form').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('.contact-form').addClass("animated bounceIn");
} else {
jQuery('.contact-form').removeClass("animated bounceIn");
}
});
//Animate skill bars
jQuery('.skills > li > span').one('inview', function (event, visible) {
if (visible == true) {
jQuery(this).each(function () {
jQuery(this).animate({
width: jQuery(this).attr('data-width')
}, 3000);
});
}
});
//initialize pluging
$("a[rel^='prettyPhoto']").prettyPhoto();
//contact form
function enviainfocurso()
{
$.ajax({
type: "POST",
url: "php/phpscripts/infocurso.php",
async: true,
data: $('form.informacao').serialize(),
});
alert('Entraremos em breve em contato com você');
}
//analytics
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-62932901-1', 'auto');
ga('send', 'pageview');
}); // end ready()
$(window).load(function () {
function filterPath(string) {
return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, '');
}
$('a[href*=#]').each(function () {
if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) {
var $targetId = $(this.hash),
$targetAnchor = $('[name=' + this.hash.slice(1) + ']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ( $target ) {
$(this).click(function (e) {
e.preventDefault();
//Hack collapse top navigation after clicking
// topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation
$('.navbar .btn-navbar').addClass('collapsed');
var targetOffset = $target.offset().top - 63;
$('html, body').animate({
scrollTop: targetOffset
}, 800);
return false;
});
}
}
});
});
//Initialize google map for contact setion with your location.
function initializeMap() {
if( $("#map-canvas").length ) {
var lat = '-8.0618743';//-8.055967'; //Set your latitude.
var lon = '-34.8734548';//'-34.896303'; //Set your longitude.
var centerLon = lon - 0.0105;
var myOptions = {
scrollwheel: false,
draggable: false,
disableDefaultUI: true,
center: new google.maps.LatLng(lat, centerLon),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Bind map to elemet with id map-canvas
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lon),
});
//var infowindow = new google.maps.InfoWindow();
//google.maps.event.addListener(marker, 'click', function () {
// infowindow.open(map, marker);
//});
// infowindow.open(map, marker);
}
} | SamuelRocha2015/ch-v3 | assets/js/app.js | JavaScript | mit | 14,062 |
require 'simplecov'
require 'coveralls'
Coveralls.wear!
SimpleCov.start 'rails' do
SimpleCov.formatters = [
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
add_filter '/spec/'
end
require 'lita-wit'
require 'lita/rspec'
require 'lita_config'
# A compatibility mode is provided for older plugins upgrading from Lita 3. Since this plugin
# was generated with Lita 4, the compatibility mode should be left disabled.
Lita.version_3_compatibility_mode = false
require 'vcr'
require 'webmock/rspec'
VCR.configure do |config|
config.cassette_library_dir = 'spec/support/vcr_cassettes'
config.ignore_localhost = true
config.hook_into :webmock
config.configure_rspec_metadata!
end
SESSION_ID = 'unique-1234'
| dbastin/lita-wit | spec/spec_helper.rb | Ruby | mit | 753 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class LoadBalancersOperations:
"""LoadBalancersOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2016_09_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _delete_initial(
self,
resource_group_name: str,
load_balancer_name: str,
**kwargs: Any
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2016-09-01"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
load_balancer_name: str,
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes the specified load balancer.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param load_balancer_name: The name of the load balancer.
:type load_balancer_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
load_balancer_name=load_balancer_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore
async def get(
self,
resource_group_name: str,
load_balancer_name: str,
expand: Optional[str] = None,
**kwargs: Any
) -> "_models.LoadBalancer":
"""Gets the specified load balancer.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param load_balancer_name: The name of the load balancer.
:type load_balancer_name: str
:param expand: Expands referenced resources.
:type expand: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: LoadBalancer, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2016_09_01.models.LoadBalancer
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancer"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2016-09-01"
accept = "application/json, text/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('LoadBalancer', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
load_balancer_name: str,
parameters: "_models.LoadBalancer",
**kwargs: Any
) -> "_models.LoadBalancer":
cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancer"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2016-09-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json, text/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'LoadBalancer')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('LoadBalancer', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('LoadBalancer', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
load_balancer_name: str,
parameters: "_models.LoadBalancer",
**kwargs: Any
) -> AsyncLROPoller["_models.LoadBalancer"]:
"""Creates or updates a load balancer.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param load_balancer_name: The name of the load balancer.
:type load_balancer_name: str
:param parameters: Parameters supplied to the create or update load balancer operation.
:type parameters: ~azure.mgmt.network.v2016_09_01.models.LoadBalancer
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either LoadBalancer or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2016_09_01.models.LoadBalancer]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancer"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
load_balancer_name=load_balancer_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('LoadBalancer', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore
def list_all(
self,
**kwargs: Any
) -> AsyncIterable["_models.LoadBalancerListResult"]:
"""Gets all the load balancers in a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either LoadBalancerListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2016_09_01.models.LoadBalancerListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancerListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2016-09-01"
accept = "application/json, text/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_all.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('LoadBalancerListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers'} # type: ignore
def list(
self,
resource_group_name: str,
**kwargs: Any
) -> AsyncIterable["_models.LoadBalancerListResult"]:
"""Gets all the load balancers in a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either LoadBalancerListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2016_09_01.models.LoadBalancerListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancerListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2016-09-01"
accept = "application/json, text/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('LoadBalancerListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers'} # type: ignore
| Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2016_09_01/aio/operations/_load_balancers_operations.py | Python | mit | 23,464 |
<?php
abstract class BaseGgSettingsPeer {
const DATABASE_NAME = 'propel';
const TABLE_NAME = 'gg_settings';
const CLASS_DEFAULT = 'lib.model.GgSettings';
const NUM_COLUMNS = 3;
const NUM_LAZY_LOAD_COLUMNS = 0;
const ID = 'gg_settings.ID';
const PARAM = 'gg_settings.PARAM';
const VALUE = 'gg_settings.VALUE';
private static $phpNameMap = null;
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('Id', 'Param', 'Value', ),
BasePeer::TYPE_COLNAME => array (GgSettingsPeer::ID, GgSettingsPeer::PARAM, GgSettingsPeer::VALUE, ),
BasePeer::TYPE_FIELDNAME => array ('id', 'param', 'value', ),
BasePeer::TYPE_NUM => array (0, 1, 2, )
);
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'Param' => 1, 'Value' => 2, ),
BasePeer::TYPE_COLNAME => array (GgSettingsPeer::ID => 0, GgSettingsPeer::PARAM => 1, GgSettingsPeer::VALUE => 2, ),
BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'param' => 1, 'value' => 2, ),
BasePeer::TYPE_NUM => array (0, 1, 2, )
);
public static function getMapBuilder()
{
include_once 'lib/model/map/GgSettingsMapBuilder.php';
return BasePeer::getMapBuilder('lib.model.map.GgSettingsMapBuilder');
}
public static function getPhpNameMap()
{
if (self::$phpNameMap === null) {
$map = GgSettingsPeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
static public function translateFieldName($name, $fromType, $toType)
{
$toNames = self::getFieldNames($toType);
$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, self::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
}
return self::$fieldNames[$type];
}
public static function alias($alias, $column)
{
return str_replace(GgSettingsPeer::TABLE_NAME.'.', $alias.'.', $column);
}
public static function addSelectColumns(Criteria $criteria)
{
$criteria->addSelectColumn(GgSettingsPeer::ID);
$criteria->addSelectColumn(GgSettingsPeer::PARAM);
$criteria->addSelectColumn(GgSettingsPeer::VALUE);
}
const COUNT = 'COUNT(gg_settings.ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT gg_settings.ID)';
public static function doCount(Criteria $criteria, $distinct = false, $con = null)
{
$criteria = clone $criteria;
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(GgSettingsPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(GgSettingsPeer::COUNT);
}
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$rs = GgSettingsPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
return 0;
}
}
public static function doSelectOne(Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = GgSettingsPeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
public static function doSelect(Criteria $criteria, $con = null)
{
return GgSettingsPeer::populateObjects(GgSettingsPeer::doSelectRS($criteria, $con));
}
public static function doSelectRS(Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if (!$criteria->getSelectColumns()) {
$criteria = clone $criteria;
GgSettingsPeer::addSelectColumns($criteria);
}
$criteria->setDbName(self::DATABASE_NAME);
return BasePeer::doSelect($criteria, $con);
}
public static function populateObjects(ResultSet $rs)
{
$results = array();
$cls = GgSettingsPeer::getOMClass();
$cls = Propel::import($cls);
while($rs->next()) {
$obj = new $cls();
$obj->hydrate($rs);
$results[] = $obj;
}
return $results;
}
public static function getTableMap()
{
return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
}
public static function getOMClass()
{
return GgSettingsPeer::CLASS_DEFAULT;
}
public static function doInsert($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; } else {
$criteria = $values->buildCriteria(); }
$criteria->remove(GgSettingsPeer::ID);
$criteria->setDbName(self::DATABASE_NAME);
try {
$con->begin();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch(PropelException $e) {
$con->rollback();
throw $e;
}
return $pk;
}
public static function doUpdate($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$selectCriteria = new Criteria(self::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values;
$comparison = $criteria->getComparison(GgSettingsPeer::ID);
$selectCriteria->add(GgSettingsPeer::ID, $criteria->remove(GgSettingsPeer::ID), $comparison);
} else { $criteria = $values->buildCriteria(); $selectCriteria = $values->buildPkeyCriteria(); }
$criteria->setDbName(self::DATABASE_NAME);
return BasePeer::doUpdate($selectCriteria, $criteria, $con);
}
public static function doDeleteAll($con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$affectedRows = 0; try {
$con->begin();
$affectedRows += BasePeer::doDeleteAll(GgSettingsPeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
public static function doDelete($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(GgSettingsPeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; } elseif ($values instanceof GgSettings) {
$criteria = $values->buildPkeyCriteria();
} else {
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(GgSettingsPeer::ID, (array) $values, Criteria::IN);
}
$criteria->setDbName(self::DATABASE_NAME);
$affectedRows = 0;
try {
$con->begin();
$affectedRows += BasePeer::doDelete($criteria, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
public static function doValidate(GgSettings $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(GgSettingsPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(GgSettingsPeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach($cols as $colName) {
if ($tableMap->containsColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
return BasePeer::doValidate(GgSettingsPeer::DATABASE_NAME, GgSettingsPeer::TABLE_NAME, $columns);
}
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(GgSettingsPeer::DATABASE_NAME);
$criteria->add(GgSettingsPeer::ID, $pk);
$v = GgSettingsPeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
public static function retrieveByPKs($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria();
$criteria->add(GgSettingsPeer::ID, $pks, Criteria::IN);
$objs = GgSettingsPeer::doSelect($criteria, $con);
}
return $objs;
}
}
if (Propel::isInit()) {
try {
BaseGgSettingsPeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
require_once 'lib/model/map/GgSettingsMapBuilder.php';
Propel::registerMapBuilder('lib.model.map.GgSettingsMapBuilder');
}
| vincent03460/fxcmiscc-partner | lib/model/om/BaseGgSettingsPeer.php | PHP | mit | 9,104 |
/*
* Globalcode - "The Developers Company"
*
* Academia do Java
*
*/
public abstract class Agencia {
private String numero;
private Banco banco;
/**
* @param num
* Numero da agencia
* @param bc
* banco ao qual a agencia pertence
*/
public Agencia(String num, Banco bc) {
numero = num;
banco = bc;
}
/**
* @return numero do banco
*/
public Banco getBanco() {
return banco;
}
/**
* @return numero da agencia
*/
public String getNumero() {
return numero;
}
/**
* @param b
* banco
*/
public void setBanco(Banco b) {
banco = b;
}
/**
* @param num
* numero da agencia
*/
public void setNumero(String num) {
numero = num;
}
/**
* Metodo para impressao de todos os dados da classe
*/
public void imprimeDados() {
System.out.println("Agencia no. " + numero);
banco.imprimeDados();
}
public void ajustarLimites(ContaEspecial[] contasEspeciais) {
System.out.println("===================================================================");
System.out.println("Agencia: " + this.getNumero() + " ajustando limites");
for (int i = 0; i < contasEspeciais.length; i++) {
ContaEspecial ce = contasEspeciais[i];
if (ce != null) {
if (ce.getAgencia() != this) {
System.out.println("A conta " + ce.getNumero() + " nao pertence a esta agencia");
} else {
double limiteAntigo = ce.getLimite();
ajustarLimiteIndividual(ce);
double limiteAjustado = ce.getLimite();
System.out.println("conta " + ce.getNumero() +
"\tlimite antigo: " + limiteAntigo +
"\tlimite ajustado: " + limiteAjustado);
}
}
}
System.out.println("limites ajustados");
System.out.println("===================================================================");
}
protected abstract void ajustarLimiteIndividual(ContaEspecial contaEspecial);
public Conta abrirConta(Cliente titular, double saldoInicial) {
String numeroConta = "" + (int) (Math.random() * 9999999);
if (saldoInicial <= 500) {
return new Conta(saldoInicial, numeroConta, titular, this);
} else if (saldoInicial > 500 && saldoInicial <= 1000) {
String hoje = "" + new java.util.Date();
return new ContaPoupanca(saldoInicial, numeroConta, titular, this, hoje);
} else {
return null;
}
}
} | andersonsilvade/workspacejava | engsoft1globalcode/aj2lab10_02/src/Agencia.java | Java | mit | 2,802 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.Rabbits
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
var rabbitAnswers = input.Split(' ').Select(int.Parse).ToList();
rabbitAnswers.RemoveAt(rabbitAnswers.Count - 1);
int minRabbotsCount = FindMinRabbitsCount(rabbitAnswers);
Console.WriteLine(minRabbotsCount);
}
private static int FindMinRabbitsCount(List<int> rabbitAnswers)
{
// Key - group size
// Value - count of rabbits in a group
var groups = new Dictionary<int, int>();
foreach (var answer in rabbitAnswers)
{
if (!groups.ContainsKey(answer + 1))
{
groups.Add(answer + 1, 0);
}
groups[answer + 1]++;
}
var rabbits = 0;
foreach (var group in groups)
{
int groupSize = group.Key;
int rabbitsInGroupCount = group.Value;
if (rabbitsInGroupCount <= groupSize)
{
rabbits += groupSize;
}
else
{
int minNumberOfGroupsToContainTheRabbits = (int)Math.Ceiling(rabbitsInGroupCount / (double)groupSize);
rabbits += minNumberOfGroupsToContainTheRabbits * groupSize;
}
}
return rabbits;
}
}
}
| TsvetanRazsolkov/Telerik-Academy | Homeworks/Programming/DSA/17.Workshop-Strings-Greedy-2015.11.27/02.Rabbits/Program.cs | C# | mit | 1,645 |
/*
* Globalize Culture co
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd.
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "co", "default", {
name: "co",
englishName: "Corsican",
nativeName: "Corsu",
language: "co",
numberFormat: {
",": " ",
".": ",",
"NaN": "Mica numericu",
negativeInfinity: "-Infinitu",
positiveInfinity: "+Infinitu",
percent: {
",": " ",
".": ","
},
currency: {
pattern: ["-n $","n $"],
",": " ",
".": ",",
symbol: "€"
}
},
calendars: {
standard: {
firstDay: 1,
days: {
names: ["dumenica","luni","marti","mercuri","ghjovi","venderi","sabbatu"],
namesAbbr: ["dum.","lun.","mar.","mer.","ghj.","ven.","sab."],
namesShort: ["du","lu","ma","me","gh","ve","sa"]
},
months: {
names: ["ghjennaghju","ferraghju","marzu","aprile","maghju","ghjunghju","lugliu","aostu","settembre","ottobre","nuvembre","dicembre",""],
namesAbbr: ["ghje","ferr","marz","apri","magh","ghju","lugl","aost","sett","otto","nuve","dice",""]
},
AM: null,
PM: null,
eras: [{"name":"dopu J-C","start":null,"offset":0}],
patterns: {
d: "dd/MM/yyyy",
D: "dddd d MMMM yyyy",
t: "HH:mm",
T: "HH:mm:ss",
f: "dddd d MMMM yyyy HH:mm",
F: "dddd d MMMM yyyy HH:mm:ss",
M: "d MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
| bevacqua/jscharting | bundle/JSC/cultures/globalize.culture.co.js | JavaScript | mit | 1,986 |
package com.ccsi.commons.dto.tenant;
/**
* @author mbmartinez
*/
public class BaseCcsiInfo {
protected Long id;
protected String name;
protected String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| lordmarkm/ccsi | ccsi-commons/src/main/java/com/ccsi/commons/dto/tenant/BaseCcsiInfo.java | Java | mit | 595 |
// TriAppSkeleton.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <GL/glew.h>
#include "AppSkeleton.h"
#include "GL/GLUtils.h"
#include "GL/ShaderFunctions.h"
#include "MatrixMath.h"
#include "utils/Logger.h"
#include "paramgl.h"
#include "TriAppSkeleton.h"
TriAppSkeleton::TriAppSkeleton()
: AppSkeleton()
, which_button(-1)
{
g_cameraLocation = make_float3(0.0f, -3.0f, 0.0f);
g_lookVector = make_float3(0.0f, 1.0f, 0.0f);
g_upVector = make_float3(0.0f, 0.0f, 1.0f);
g_rotation = make_float3(0.0f, 90.0f, 0.0f);
g_distance = 0.0f;
g_viewAngle = 45.0;
which_button = -1;
modifier_mode = 0;
g_progBasic = 0;
g_progOverlay = 0;
}
TriAppSkeleton::~TriAppSkeleton()
{
}
bool TriAppSkeleton::initGL(int argc, char **argv)
{
bool ret = AppSkeleton::initGL(argc, argv); /// calls _InitShaders
return ret;
}
/// Shaders must be created *after* the OpenGL context is created.
/// This virtual function will be called by AppSkeleton::initGL.
void TriAppSkeleton::_InitShaders()
{
// InitShaders()
LOG_INFO("Initializing shaders.");
{
g_progBasic = makeShaderByName("basic");
g_progOverlay = makeShaderByName("overlay");
}
}
void TriAppSkeleton::drawObject() const
{
GLfloat vVertices[] = { 0.0f, 0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f };
GLfloat vColors[] = { 1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f };
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, vColors);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
CHECK_GL_ERROR_MACRO();
}
void TriAppSkeleton::display() const
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glUseProgram(g_progBasic);
{
/// Set up our 3D transformation matrices
float modelviewMatrix[16];
float projectionMatrix[16];
float3 origin = g_cameraLocation + g_lookVector;
glhLookAtf2(modelviewMatrix,
g_cameraLocation,
origin,
g_upVector);
glhTranslate(modelviewMatrix, 0.0f, g_distance, 0.0f);
glhRotate(modelviewMatrix, g_rotation.x, 0.0f, 0.0f, 1.0f);
glhRotate(modelviewMatrix, g_rotation.y, 1.0f, 0.0f, 0.0f);
glhPerspectivef2(projectionMatrix, g_viewAngle, (float)g_windowWidth/(float)g_windowHeight, 0.004, 500.0);
glUniformMatrix4fv(getUniLoc(g_progBasic, "mvmtx"), 1, false, modelviewMatrix);
glUniformMatrix4fv(getUniLoc(g_progBasic, "prmtx"), 1, false, projectionMatrix);
drawObject();
}
glUseProgram(0);
CHECK_GL_ERROR_MACRO();
}
void TriAppSkeleton::mouseDown(int button, int state, int x, int y)
{
which_button = button;
oldx = newx = x;
oldy = newy = y;
if (state == 0) // 0 == GLFW_RELEASE
{
which_button = -1;
}
}
void TriAppSkeleton::mouseMove(int x, int y)
{
int mmx, mmy;
float thresh = 4;
if (modifier_mode & GLUT_ACTIVE_SHIFT) { thresh /= 0.01f; }
oldx = newx;
oldy = newy;
newx = x;
newy = y;
mmx = x-oldx;
mmy = y-oldy;
if (which_button == GLUT_LEFT_BUTTON) //GLFW_MOUSE_BUTTON_1
{
g_rotation.x += (float)mmx/thresh;
g_rotation.y += (float)mmy/thresh;
}
else if (which_button == GLUT_RIGHT_BUTTON)
{
g_distance += (float)mmx/thresh;
}
}
void TriAppSkeleton::keyboard(int key, int x, int y)
{
AppSkeleton::keyboard(key, x, y);
}
| jimbo00000/OpenGLMultiSkeleton | src/appskeleton/TriAppSkeleton.cpp | C++ | mit | 3,856 |
// 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 "sync/test/fake_server/bookmark_entity.h"
#include <string>
#include "base/basictypes.h"
#include "base/guid.h"
#include "sync/internal_api/public/base/model_type.h"
#include "sync/protocol/sync.pb.h"
#include "sync/test/fake_server/fake_server_entity.h"
using std::string;
namespace fake_server {
namespace {
// Returns true if and only if |client_entity| is a bookmark.
bool IsBookmark(const sync_pb::SyncEntity& client_entity) {
return syncer::GetModelType(client_entity) == syncer::BOOKMARKS;
}
} // namespace
BookmarkEntity::~BookmarkEntity() { }
// static
scoped_ptr<FakeServerEntity> BookmarkEntity::CreateNew(
const sync_pb::SyncEntity& client_entity,
const string& parent_id,
const string& client_guid) {
CHECK(client_entity.version() == 0) << "New entities must have version = 0.";
CHECK(IsBookmark(client_entity)) << "The given entity must be a bookmark.";
const string id =
FakeServerEntity::CreateId(syncer::BOOKMARKS, base::GenerateGUID());
const string originator_cache_guid = client_guid;
const string originator_client_item_id = client_entity.id_string();
return scoped_ptr<FakeServerEntity>(new BookmarkEntity(
id, client_entity.version(), client_entity.name(), originator_cache_guid,
originator_client_item_id, client_entity.unique_position(),
client_entity.specifics(), client_entity.folder(), parent_id,
client_entity.ctime(), client_entity.mtime()));
}
// static
scoped_ptr<FakeServerEntity> BookmarkEntity::CreateUpdatedVersion(
const sync_pb::SyncEntity& client_entity,
const FakeServerEntity& current_server_entity,
const string& parent_id) {
CHECK(client_entity.version() != 0) << "Existing entities must not have a "
<< "version = 0.";
CHECK(IsBookmark(client_entity)) << "The given entity must be a bookmark.";
const BookmarkEntity& current_bookmark_entity =
static_cast<const BookmarkEntity&>(current_server_entity);
const string originator_cache_guid =
current_bookmark_entity.originator_cache_guid_;
const string originator_client_item_id =
current_bookmark_entity.originator_client_item_id_;
return scoped_ptr<FakeServerEntity>(new BookmarkEntity(
client_entity.id_string(), client_entity.version(), client_entity.name(),
originator_cache_guid, originator_client_item_id,
client_entity.unique_position(), client_entity.specifics(),
client_entity.folder(), parent_id, client_entity.ctime(),
client_entity.mtime()));
}
BookmarkEntity::BookmarkEntity(
const string& id,
int64 version,
const string& name,
const string& originator_cache_guid,
const string& originator_client_item_id,
const sync_pb::UniquePosition& unique_position,
const sync_pb::EntitySpecifics& specifics,
bool is_folder,
const string& parent_id,
int64 creation_time,
int64 last_modified_time)
: FakeServerEntity(id, syncer::BOOKMARKS, version, name),
originator_cache_guid_(originator_cache_guid),
originator_client_item_id_(originator_client_item_id),
unique_position_(unique_position),
is_folder_(is_folder),
parent_id_(parent_id),
creation_time_(creation_time),
last_modified_time_(last_modified_time) {
SetSpecifics(specifics);
}
void BookmarkEntity::SetParentId(const string& parent_id) {
parent_id_ = parent_id;
}
string BookmarkEntity::GetParentId() const {
return parent_id_;
}
void BookmarkEntity::SerializeAsProto(sync_pb::SyncEntity* proto) const {
FakeServerEntity::SerializeBaseProtoFields(proto);
proto->set_originator_cache_guid(originator_cache_guid_);
proto->set_originator_client_item_id(originator_client_item_id_);
proto->set_parent_id_string(parent_id_);
proto->set_ctime(creation_time_);
proto->set_mtime(last_modified_time_);
sync_pb::UniquePosition* unique_position = proto->mutable_unique_position();
unique_position->CopyFrom(unique_position_);
}
bool BookmarkEntity::IsFolder() const {
return is_folder_;
}
} // namespace fake_server
| Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/sync/test/fake_server/bookmark_entity.cc | C++ | mit | 4,239 |
(function () {
'use strict';
angular.module('customers')
.controller('OneCustomerCtrl', function ($scope, customers, $stateParams) {
var cid = $stateParams.cid;
$scope.customer=_.find(customers, function (customer) {
return customer.profile.userName===cid;
});
console.log($scope.customer);
});
})();
| SvitlanaShepitsena/remax16 | app/scripts/customers/controllers/OneCustomerCtrl.js | JavaScript | mit | 393 |
var exptemplate = require('../prepublic/javascripts/exptemplate');
module.exports = exptemplate;
| addrummond/nodeibexfarm | lib/exptemplate.js | JavaScript | mit | 97 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Validation Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Validation Data")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6041a5c8-5e7b-4340-a90c-5c7a99de96ce")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| BlueDress/School | C# OOP Basics/Encapsulation/Validation Data/Properties/AssemblyInfo.cs | C# | mit | 1,406 |
using System.Collections.Generic;
using BEPUphysics.Constraints.SolverGroups;
using BEPUphysics.Constraints.TwoEntity.Motors;
using BEPUphysics.Entities.Prefabs;
using BEPUutilities;
using BEPUphysics.Entities;
using BEPUphysics.CollisionRuleManagement;
using Microsoft.Xna.Framework.Input;
using System;
using BEPUphysics.BroadPhaseEntries;
namespace BEPUphysicsDemos.Demos
{
/// <summary>
/// A robot with multiple individually controllable legs qwops around.
/// </summary>
/// <remarks>
/// This demo type is initially excluded from the main list in the DemosGame.
/// To access it while playing the demos, add an entry to the demoTypes array for this demo.
/// </remarks>
public class SpiderDemo : StandardDemo
{
private List<RevoluteJoint> legJoints;
/// <summary>
/// Constructs a new demo.
/// </summary>
/// <param name="game">Game owning this demo.</param>
public SpiderDemo(DemosGame game)
: base(game)
{
game.Camera.Position = new Vector3(0, 2, 15);
Space.Add(new Box(new Vector3(0, -5, 0), 20, 1, 20));
BuildBot(new Vector3(0, 3, 0), out legJoints);
//x and y, in terms of heightmaps, refer to their local x and y coordinates. In world space, they correspond to x and z.
//Setup the heights of the terrain.
int xLength = 180;
int zLength = 180;
float xSpacing = 8f;
float zSpacing = 8f;
var heights = new float[xLength, zLength];
for (int i = 0; i < xLength; i++)
{
for (int j = 0; j < zLength; j++)
{
float x = i - xLength / 2;
float z = j - zLength / 2;
//heights[i,j] = (float)(x * y / 1000f);
heights[i, j] = (float)(10 * (Math.Sin(x / 8) + Math.Sin(z / 8)));
//heights[i,j] = 3 * (float)Math.Sin(x * y / 100f);
//heights[i,j] = (x * x * x * y - y * y * y * x) / 1000f;
}
}
//Create the terrain.
var terrain = new Terrain(heights, new AffineTransform(
new Vector3(xSpacing, 1, zSpacing),
Quaternion.Identity,
new Vector3(-xLength * xSpacing / 2, -10, -zLength * zSpacing / 2)));
//terrain.Thickness = 5; //Uncomment this and shoot some things at the bottom of the terrain! They'll be sucked up through the ground.
Space.Add(terrain);
game.ModelDrawer.Add(terrain);
}
void BuildBot(Vector3 position, out List<RevoluteJoint> legJoints)
{
var body = new Box(position + new Vector3(0, 2.5f, 0), 2, 3, 2, 30);
Space.Add(body);
legJoints = new List<RevoluteJoint>();
//Plop four legs on the spider.
BuildLeg(body, new RigidTransform(body.Position + new Vector3(-.8f, -1, -.8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4 * 3)), legJoints);
BuildLeg(body, new RigidTransform(body.Position + new Vector3(-.8f, -1, .8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4 * 5)), legJoints);
BuildLeg(body, new RigidTransform(body.Position + new Vector3(.8f, -1, -.8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4)), legJoints);
BuildLeg(body, new RigidTransform(body.Position + new Vector3(.8f, -1, .8f), Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.PiOver4 * 7)), legJoints);
}
void BuildLeg(Entity body, RigidTransform legTransform, List<RevoluteJoint> legJoints)
{
//Build the leg in local space.
var upperLeg = new Box(new Vector3(.75f, 0, 0), 1.5f, .6f, .6f, 7);
var lowerLeg = new Box(new Vector3(1.2f, -.75f, 0), .6f, 1.5f, .6f, 7);
//Increase the feetfriction to make walking easier.
lowerLeg.Material.KineticFriction = 3;
lowerLeg.Material.StaticFriction = 3;
Space.Add(upperLeg);
Space.Add(lowerLeg);
//Pull the leg entities into world space.
upperLeg.WorldTransform *= legTransform.Matrix;
lowerLeg.WorldTransform *= legTransform.Matrix;
//Don't let the leg pieces interact with each other.
CollisionRules.AddRule(upperLeg, body, CollisionRule.NoBroadPhase);
CollisionRules.AddRule(upperLeg, lowerLeg, CollisionRule.NoBroadPhase);
//Connect the body to the upper leg.
var bodyToUpper = new RevoluteJoint(body, upperLeg, legTransform.Position, legTransform.OrientationMatrix.Forward);
//Both the motor and limit need to be activated for this leg.
bodyToUpper.Limit.IsActive = true;
//While the angular joint doesn't need any extra configuration, the limit does in order to ensure that its interpretation of angles matches ours.
bodyToUpper.Limit.LocalTestAxis = Vector3.Left;
bodyToUpper.Limit.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Left);
bodyToUpper.Limit.MinimumAngle = -MathHelper.PiOver4;
bodyToUpper.Limit.MaximumAngle = MathHelper.PiOver4;
//Similarly, the motor needs configuration.
bodyToUpper.Motor.IsActive = true;
bodyToUpper.Motor.LocalTestAxis = Vector3.Left;
bodyToUpper.Motor.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Left);
bodyToUpper.Motor.Settings.Mode = MotorMode.Servomechanism;
//Weaken the spring to prevent it from launching too much.
bodyToUpper.Motor.Settings.Servo.SpringSettings.Stiffness *= .01f;
bodyToUpper.Motor.Settings.Servo.SpringSettings.Damping *= .01f;
Space.Add(bodyToUpper);
//Connect the upper leg to the lower leg.
var upperToLower = new RevoluteJoint(upperLeg, lowerLeg, legTransform.Position - legTransform.OrientationMatrix.Left * 1.2f, legTransform.OrientationMatrix.Forward);
//Both the motor and limit need to be activated for this leg.
upperToLower.Limit.IsActive = true;
//While the angular joint doesn't need any extra configuration, the limit does in order to ensure that its interpretation of angles matches ours.
upperToLower.Limit.LocalTestAxis = Vector3.Down;
upperToLower.Limit.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Down);
upperToLower.Limit.MinimumAngle = -MathHelper.PiOver4;
upperToLower.Limit.MaximumAngle = MathHelper.PiOver4;
//Similarly, the motor needs configuration.
upperToLower.Motor.IsActive = true;
upperToLower.Motor.LocalTestAxis = Vector3.Down;
upperToLower.Motor.Basis.SetWorldAxes(legTransform.OrientationMatrix.Forward, legTransform.OrientationMatrix.Down);
upperToLower.Motor.Settings.Mode = MotorMode.Servomechanism;
//Weaken the spring to prevent it from launching too much.
upperToLower.Motor.Settings.Servo.SpringSettings.Stiffness *= .01f;
upperToLower.Motor.Settings.Servo.SpringSettings.Damping *= .01f;
Space.Add(upperToLower);
legJoints.Add(upperToLower);
legJoints.Add(bodyToUpper);
}
/// <summary>
/// Gets the name of the simulation.
/// </summary>
public override string Name
{
get { return "QWOPbot"; }
}
public override void DrawUI()
{
base.DrawUI();
Game.DataTextDrawer.Draw("QWRT to retract, OPKL to extend. Good luck!", new Microsoft.Xna.Framework.Vector2(50, 50));
}
public override void Update(float dt)
{
//Extend the legs!
if (Game.KeyboardInput.IsKeyDown(Keys.Q))
{
Extend(legJoints[0], dt);
Extend(legJoints[1], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.W))
{
Extend(legJoints[2], dt);
Extend(legJoints[3], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.R))
{
Extend(legJoints[4], dt);
Extend(legJoints[5], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.T))
{
Extend(legJoints[6], dt);
Extend(legJoints[7], dt);
}
//Retract the legs!
if (Game.KeyboardInput.IsKeyDown(Keys.O))
{
Retract(legJoints[0], dt);
Retract(legJoints[1], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.P))
{
Retract(legJoints[2], dt);
Retract(legJoints[3], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.K))
{
Retract(legJoints[4], dt);
Retract(legJoints[5], dt);
}
if (Game.KeyboardInput.IsKeyDown(Keys.L))
{
Retract(legJoints[6], dt);
Retract(legJoints[7], dt);
}
base.Update(dt);
}
void Extend(RevoluteJoint joint, float dt)
{
float extensionSpeed = 2;
joint.Motor.Settings.Servo.Goal = MathHelper.Clamp(joint.Motor.Settings.Servo.Goal + extensionSpeed * dt, joint.Limit.MinimumAngle, joint.Limit.MaximumAngle);
}
void Retract(RevoluteJoint joint, float dt)
{
float retractionSpeed = 2;
joint.Motor.Settings.Servo.Goal = MathHelper.Clamp(joint.Motor.Settings.Servo.Goal - retractionSpeed * dt, joint.Limit.MinimumAngle, joint.Limit.MaximumAngle);
}
}
} | karrtmomil/coms437_assignment2 | 3DAsteroids/3DAsteroids/BEPUphysicsDemos/BEPUphysicsDemos/Demos/SpiderDemo.cs | C# | mit | 10,023 |
/**
* Created by jsturtevant on 1/18/14
*/
var DEFAULT_SHORTCUT_KEY = 'ctrl+shift+k';
var LOCAL_STORAGE_KEY = 'optionsStore'
var defaultOptions = {
shortcuts: [
{key: "", value:""}
],
cssSelectors: [{value:""}],
shortcutKey: DEFAULT_SHORTCUT_KEY,
includeIFrames: true
};
var optionsApp = angular.module('optionsApp', []);
optionsApp.factory('OptionsData', function() {
var optionsJSON = localStorage[LOCAL_STORAGE_KEY];
if (!optionsJSON){
return defaultOptions;
}
else{
return JSON.parse(optionsJSON);
}
});
optionsApp.directive("showhide", function() {
return function(scope, element, attrs) {
var bodyelement =angular.element(document.getElementById(attrs.showhide));
element.bind("mouseover", function() {
element.css("cursor", "pointer");
element.css('color', attrs.togglecolor);
})
element.bind("mouseleave", function() {
if (bodyelement.hasClass('hidden')){
element.css('color', "");
}
});
element.bind("click", function() {
angular.element(bodyelement).toggleClass('hidden');
element.css('color', attrs.togglecolor);
});
};
});
function OptionsCtrl($scope, OptionsData, $timeout){
$scope.options = OptionsData;
$scope.AddShortcut = function(){
$scope.options.shortcuts.push({key: "", value:""})
};
$scope.AddSelector = function(){
if (!$scope.options.cssSelectors){
$scope.options.cssSelectors = defaultOptions.cssSelectors;
}
$scope.options.cssSelectors.push({value: ""})
};
$scope.Save = function(){
localStorage[LOCAL_STORAGE_KEY] = JSON.stringify($scope.options);
$scope.message = 'Changes saved!';
$timeout(function() {
$scope.message = null;
}, 5 * 1000);
};
$scope.Delete = function (index){
$scope.options.shortcuts.splice(index,1);
};
$scope.DeleteSelector = function (index){
$scope.options.cssSelectors.splice(index,1);
};
};
| jsturtevant/expander | app/scripts/options.js | JavaScript | mit | 2,125 |
package flow;
/**
* This interface is used to define the name of variables that are
* declared in the call flow. All variables are defined as
* <code>public static final String</code>, which allows user-defined
* code to reference variable names by the Java variable name.
* Last generated by Orchestration Designer at: 2013-FEB-03 08:27:04 PM
*/
public interface IProjectVariables {
//{{START:PROJECT:VARIABLES
/**
* This is a reserved block of variable name definitions.
* The variable names defined here can be used as the key
* to get the <code>com.avaya.sce.runtime.Variable</code>
* from the <code>SCESession</code> at runtime.<br>
*
* For example, given a variable name <code>phoneNum</code>,
* user-defined code should access the variable in this format:<PRE>
* Variable phNum = mySession.getVariable(IProjectVariables.PHONE_NUM);
* if ( phNum != null ) {
* // do something with the variable
* }</PRE>
*
* This block of code is generated automatically by Orchestration Designer and should not
* be manually edited as changes may be overwritten by future code generation.
* Last generated by Orchestration Designer at: 2013-JUN-19 09:09:36 PM
*/
public static final String MAIN_MENU = "MainMenu";
public static final String BLIND_TRANSFER = "BlindTransfer";
public static final String TIME = "time";
public static final String REDIRECTINFO = "redirectinfo";
public static final String MAIN_MENU_TEXT = "MainMenuText";
public static final String SESSION = "session";
public static final String DD_LAST_EXCEPTION = "ddLastException";
public static final String DATE = "date";
public static final String SHAREDUUI = "shareduui";
//}}END:PROJECT:VARIABLES
//{{START:PROJECT:VARIABLEFIELDS
public static final String MAIN_MENU_FIELD_COLUMN_0 = "Column0";
public static final String MAIN_MENU_FIELD_CONFIDENCE = "confidence";
public static final String MAIN_MENU_FIELD_INPUTMODE = "inputmode";
public static final String MAIN_MENU_FIELD_INTERPRETATION = "interpretation";
public static final String MAIN_MENU_FIELD_NOINPUTCOUNT = "noinputcount";
public static final String MAIN_MENU_FIELD_NOMATCHCOUNT = "nomatchcount";
public static final String MAIN_MENU_FIELD_UTTERANCE = "utterance";
public static final String MAIN_MENU_FIELD_VALUE = "value";
public static final String TIME_FIELD_AUDIO = "audio";
public static final String TIME_FIELD_HOUR = "hour";
public static final String TIME_FIELD_MILLISECOND = "millisecond";
public static final String TIME_FIELD_MINUTE = "minute";
public static final String TIME_FIELD_SECOND = "second";
public static final String TIME_FIELD_TIMEZONE = "timezone";
public static final String REDIRECTINFO_FIELD_PRESENTATIONINFO = "presentationinfo";
public static final String REDIRECTINFO_FIELD_REASON = "reason";
public static final String REDIRECTINFO_FIELD_SCREENINGINFO = "screeninginfo";
public static final String REDIRECTINFO_FIELD_URI = "uri";
public static final String SESSION_FIELD_AAI = "aai";
public static final String SESSION_FIELD_ANI = "ani";
public static final String SESSION_FIELD_CALLTAG = "calltag";
public static final String SESSION_FIELD_CHANNEL = "channel";
public static final String SESSION_FIELD_CONVERSEFIRST = "conversefirst";
public static final String SESSION_FIELD_CONVERSESECOND = "conversesecond";
public static final String SESSION_FIELD_CURRENTLANGUAGE = "currentlanguage";
public static final String SESSION_FIELD_DNIS = "dnis";
public static final String SESSION_FIELD_EXIT_CUSTOMER_ID = "exitCustomerId";
public static final String SESSION_FIELD_EXIT_INFO_1 = "exitInfo1";
public static final String SESSION_FIELD_EXIT_INFO_2 = "exitInfo2";
public static final String SESSION_FIELD_EXIT_PREFERRED_PATH = "exitPreferredPath";
public static final String SESSION_FIELD_EXIT_REASON = "exitReason";
public static final String SESSION_FIELD_EXIT_TOPIC = "exitTopic";
public static final String SESSION_FIELD_LASTERROR = "lasterror";
public static final String SESSION_FIELD_MEDIATYPE = "mediatype";
public static final String SESSION_FIELD_MESSAGE_TYPE = "messageType";
public static final String SESSION_FIELD_PROTOCOLNAME = "protocolname";
public static final String SESSION_FIELD_PROTOCOLVERSION = "protocolversion";
public static final String SESSION_FIELD_SESSIONID = "sessionid";
public static final String SESSION_FIELD_SESSIONLABEL = "sessionlabel";
public static final String SESSION_FIELD_SHAREDMODE = "sharedmode";
public static final String SESSION_FIELD_UCID = "ucid";
public static final String SESSION_FIELD_UUI = "uui";
public static final String SESSION_FIELD_VIDEOBITRATE = "videobitrate";
public static final String SESSION_FIELD_VIDEOCODEC = "videocodec";
public static final String SESSION_FIELD_VIDEOENABLED = "videoenabled";
public static final String SESSION_FIELD_VIDEOFARFMTP = "videofarfmtp";
public static final String SESSION_FIELD_VIDEOFORMAT = "videoformat";
public static final String SESSION_FIELD_VIDEOFPS = "videofps";
public static final String SESSION_FIELD_VIDEOHEIGHT = "videoheight";
public static final String SESSION_FIELD_VIDEONEARFMTP = "videonearfmtp";
public static final String SESSION_FIELD_VIDEOWIDTH = "videowidth";
public static final String SESSION_FIELD_VPCALLEDEXTENSION = "vpcalledextension";
public static final String SESSION_FIELD_VPCONVERSEONDATA = "vpconverseondata";
public static final String SESSION_FIELD_VPCOVERAGEREASON = "vpcoveragereason";
public static final String SESSION_FIELD_VPCOVERAGETYPE = "vpcoveragetype";
public static final String SESSION_FIELD_VPRDNIS = "vprdnis";
public static final String SESSION_FIELD_VPREPORTURL = "vpreporturl";
public static final String DD_LAST_EXCEPTION_FIELD_ERRORCODE = "errorcode";
public static final String DD_LAST_EXCEPTION_FIELD_MESSAGE = "message";
public static final String DD_LAST_EXCEPTION_FIELD_OBJECT = "object";
public static final String DD_LAST_EXCEPTION_FIELD_STACKTRACE = "stacktrace";
public static final String DD_LAST_EXCEPTION_FIELD_TYPE = "type";
public static final String DATE_FIELD_AUDIO = "audio";
public static final String DATE_FIELD_DAYOFMONTH = "dayofmonth";
public static final String DATE_FIELD_DAYOFWEEK = "dayofweek";
public static final String DATE_FIELD_DAYOFWEEKNUM = "dayofweeknum";
public static final String DATE_FIELD_DAYOFYEAR = "dayofyear";
public static final String DATE_FIELD_MONTH = "month";
public static final String DATE_FIELD_MONTHINYEAR = "monthinyear";
public static final String DATE_FIELD_YEAR = "year";
public static final String SHAREDUUI_FIELD_ID = "id";
public static final String SHAREDUUI_FIELD_VALUE = "value";
//}}END:PROJECT:VARIABLEFIELDS
}
| RadishSystems/choiceview-webapi-avaya-demo | RadishTest/WEB-INF/src/flow/IProjectVariables.java | Java | mit | 6,735 |
<?php
/* To jest proba*/
namespace Mcc\Bundle\ASMemberBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('MccASMemberBundle:Default:index.html.twig', array('name' => $name));
}
}
| KonradMasalski/ASMember | src/Mcc/ASMemberBundle/Controller/DefaultController.php | PHP | mit | 330 |
/*
GWEN
Copyright (c) 2012 Facepunch Studios
See license in Gwen.h
*/
#include <rose/Rose.hpp>
#include <rose/Utility.hpp>
#include <rose/Skin.hpp>
#include <rose/ctl/PageControl.hpp>
#include <rose/ctl/Controls.hpp>
using namespace rose;
using namespace rose::ctl;
GWEN_CONTROL_CONSTRUCTOR(PageControl)
{
m_iPages = 0;
m_iCurrentPage = 0;
SetUseFinishButton(true);
for(int i = 0; i < MaxPages; i++)
{
m_pPages[i] = NULL;
}
Widget* pControls = new Widget(this);
pControls->Dock(EWP_BOTTOM);
pControls->SetSize(24, 24);
pControls->SetMargin(Margin(10, 10, 10, 10));
m_Finish = new ctl::Button(pControls);
m_Finish->SetText("Finish");
m_Finish->Dock(EWP_RIGHT);
m_Finish->onPress.Add(this, &ThisClass::Finish);
m_Finish->SetSize(70);
m_Finish->SetMargin(Margin(4, 0, 0, 0));
m_Finish->Hide();
m_Next = new ctl::Button(pControls);
m_Next->SetText("Next >");
m_Next->Dock(EWP_RIGHT);
m_Next->onPress.Add(this, &ThisClass::NextPage);
m_Next->SetSize(70);
m_Next->SetMargin(Margin(4, 0, 0, 0));
m_Back = new ctl::Button(pControls);
m_Back->SetText("< Back");
m_Back->Dock(EWP_RIGHT);
m_Back->onPress.Add(this, &ThisClass::PreviousPage);
m_Back->SetSize(70);
m_Label = new ctl::Label(pControls);
m_Label->Dock(EWP_FILL);
m_Label->SetAlignment(EWP_LEFT | EWP_CENTERV);
m_Label->SetText("Page 1 or 2");
}
void PageControl::SetPageCount(unsigned int iNum)
{
if(iNum >= MaxPages)
{
iNum = MaxPages;
}
for(unsigned int i = 0; i < iNum; i++)
{
if(!m_pPages[i])
{
m_pPages[i] = new ctl::Widget(this);
m_pPages[i]->Dock(EWP_FILL);
}
}
m_iPages = iNum;
// Setting to -1 to force the page to change
m_iCurrentPage = -1;
HideAll();
ShowPage(0);
}
void PageControl::HideAll()
{
for(int i = 0; i < MaxPages; i++)
{
if(!m_pPages[i])
{
continue;
}
m_pPages[i]->Hide();
}
}
void PageControl::ShowPage(unsigned int i)
{
if(m_iCurrentPage == i)
{
return;
}
if(m_pPages[i])
{
m_pPages[i]->Show();
m_pPages[i]->Dock(EWP_FILL);
}
m_iCurrentPage = i;
m_Back->SetDisabled(m_iCurrentPage == 0);
m_Next->SetDisabled(m_iCurrentPage >= m_iPages);
m_Label->SetText(Utility::Format("Page %i of %i", m_iCurrentPage + 1, m_iPages));
if(GetUseFinishButton())
{
bool bFinished = m_iCurrentPage >= m_iPages - 1;
m_Next->SetHidden(bFinished);
m_Finish->SetHidden(!bFinished);
}
{
EventInfo info;
info.Integer = i;
info.Control = m_pPages[i];
onPageChanged.Call(this, info);
}
}
ctl::Widget* PageControl::GetPage(unsigned int i)
{
return m_pPages[i];
}
ctl::Widget * PageControl::GetCurrentPage()
{
return GetPage(GetPageNumber());
}
void PageControl::NextPage()
{
if(m_iCurrentPage >= m_iPages - 1)
{
return;
}
if(m_pPages[m_iCurrentPage])
{
m_pPages[m_iCurrentPage]->Dock(EWP_NONE);
//Anim::Add(m_pPages[m_iCurrentPage], new Anim::Pos::X(m_pPages[m_iCurrentPage]->X(), Width() * -1, 0.2f, true, 0.0f, -1));
}
ShowPage(m_iCurrentPage + 1);
if(m_pPages[m_iCurrentPage])
{
m_pPages[m_iCurrentPage]->Dock(EWP_NONE);
//Anim::Add(m_pPages[m_iCurrentPage], new Anim::Pos::X(Width(), 0, 0.2f, false, 0.0f, -1));
}
}
void PageControl::PreviousPage()
{
if(m_iCurrentPage == 0)
{
return;
}
if(m_pPages[m_iCurrentPage])
{
m_pPages[m_iCurrentPage]->Dock(EWP_NONE);
//Anim::Add(m_pPages[m_iCurrentPage], new Anim::Pos::X(m_pPages[m_iCurrentPage]->X(), Width(), 0.3f, true, 0.0f, -1));
}
ShowPage(m_iCurrentPage - 1);
if(m_pPages[m_iCurrentPage])
{
m_pPages[m_iCurrentPage]->Dock(EWP_NONE);
//Anim::Add(m_pPages[m_iCurrentPage], new Anim::Pos::X(Width() * -1, 0, 0.3f, false, 0.0f, -1));
}
}
void PageControl::Finish()
{
onFinish.Call(this);
}
| FRex/rose | src/rose/PageControl.cpp | C++ | mit | 4,144 |
import { BecauseError } from "../../errors";
import { Response } from "../../response";
import { parse_response } from "../../parse";
import { JWT, LazyJWT } from "./jwt";
class TokenParseError extends BecauseError {
}
// https://github.com/boundlessgeo/bcs/blob/master/bcs-token-service
// /src/main/java/com/boundlessgeo/bcs/data/ApiKeyResponse.java
class ApiKeyData {
key: string;
domain: string;
issued: Date;
expires: Date;
}
// ref OAuthTokenResponse in
// https://github.com/boundlessgeo/bcs/blob/master/bcs-token-service
// /src/main/java/com/boundlessgeo/bcs/data/OAuthTokenResponse.java
class OAuthTokenData {
access_token: string;
token_type: string;
expires_in: number;
}
// ref TokenRequest in
// https://github.com/boundlessgeo/bcs/blob/master/bcs-token-service
// /src/main/java/com/boundlessgeo/bcs/data/TokenRequest.java
class TokenRequest {
username: string;
password: string;
}
/**
* Structure of JSON body of token responses.
*
* See also:
* https://github.com/boundlessgeo/bcs/blob/master/bcs-token-service
* /src/main/java/com/boundlessgeo/bcs/data/BCSToken.java
*/
export class TokenData {
token: string;
errorCode: number | undefined;
errorMessage: string | undefined;
}
/**
* Structure of object under 'app_metadata' in a parsed JWT.
*/
export class AppMetadata {
SiteRole: string;
}
/**
* Structure of a JWT, after the base64 blob is parsed.
*/
export class JWTData {
name: string;
email: string;
email_verified: boolean;
app_metadata: AppMetadata;
iss: string;
sub: string;
aud: string;
exp: number;
iat: number;
// Not in the actual response, but added by parser for convenience
token: string | undefined;
}
/**
* Extract a token blob from a response.
*
* This does not parse any of the JWT structure implicit in the blob.
*/
export function response_to_blob(response: Response): string {
const data = parse_response<TokenData>(response);
if (!data.token) {
throw new Error("no token blob");
}
return data.token;
}
/**
* Extract JWT metadata from the given blob.
*/
export function blob_to_data(blob: string): JWTData {
if (!blob) {
throw new Error("empty token blob");
}
const parts = blob.split(".");
if (parts.length !== 3) {
throw new Error("cannot parse token blob into parts");
}
const middle = parts[1];
// TODO: Node compatibility here...
const payload = window.atob(middle);
const parsed = JSON.parse(payload);
return parsed;
}
/**
* Extract JWT metadata from the given response.
*
* This means what you get back is a lower-level object directly reflecting the
* JSON that was base64 encoded.
*/
export function response_to_data(response: Response): JWTData {
const blob = response_to_blob(response);
const data = blob_to_data(blob);
// Add the token in case caller doesn't have it
return {...data, "token": data.token || ""};
}
/**
* Extract a JWT object from the given response.
*
* This means what you get back is a higher-level object that's easier for
* humans to read and write programs against.
*/
export function response_to_jwt(response: Response): JWT {
const blob = response_to_blob(response);
const data = blob_to_data(blob);
// Use LazyJWT to parse this, so I don't have to duplicate the parsing
// methods right now. But return a nice browsable JWT.
const lazy = new LazyJWT(data);
return new JWT(
lazy.name,
lazy.email,
lazy.email_verified,
lazy.roles,
lazy.issuer,
lazy.subject,
lazy.audience,
lazy.expiration,
lazy.issued_at,
blob,
);
}
| harts-boundless/because.js | src/services/token/parse.ts | TypeScript | mit | 3,733 |
package piskvork;
/**
* Root interface for a Piskvork command. A command must provide a string to
* send to the AI, and a method to validate the response.
*/
public interface PiskvorkCommand {
/**
* Get the string for this command to send to the AI.
* @return String identifier of the command, e.g. TURN or MESSAGE, plus
* any other parameters to send to the AI.
*/
String getCommandString();
/**
* Return whether or not this command requires a response.
* @return True by default, overridden to false if required.
*/
default boolean requiresResponse() {
return true;
}
/**
* Validate a response for this command.
* @param response Response to validate
* @return Boolean representing whether this response is valid
*/
default boolean validateResponse(String response) {
return true;
}
}
| haslam22/gomoku | src/main/java/piskvork/PiskvorkCommand.java | Java | mit | 898 |
/* Copyright (C) 2001, 2008 United States Government as represented by
the Administrator of the National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.render;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.render.airspaces.*;
import javax.media.opengl.*;
/**
* @author brownrigg
* @version $Id: SurfaceCircle2.java 9230 2009-03-06 05:36:26Z dcollins $
*/
public class SurfaceCircle2 extends CappedCylinder
{
public SurfaceCircle2(LatLon location, double radius)
{
super(location, radius);
}
public SurfaceCircle2(AirspaceAttributes shapeAttributes)
{
super(shapeAttributes);
}
public SurfaceCircle2()
{
super();
}
protected void doRenderGeometry(DrawContext dc, String drawStyle)
{
beginDrawShape(dc);
super.doRenderGeometry(dc, drawStyle);
endDrawShape(dc);
}
protected void beginDrawShape(DrawContext dc)
{
// Modify the projection transform to shift the depth values slightly toward the camera in order to
// ensure the shape is selected during depth buffering.
GL gl = dc.getGL();
float[] pm = new float[16];
gl.glGetFloatv(GL.GL_PROJECTION_MATRIX, pm, 0);
pm[10] *= .8; // TODO: See Lengyel 2 ed. Section 9.1.2 to compute optimal/minimal offset
gl.glPushAttrib(GL.GL_TRANSFORM_BIT);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadMatrixf(pm, 0);
}
protected void endDrawShape(DrawContext dc)
{
GL gl = dc.getGL();
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPopMatrix();
gl.glPopAttrib();
}
}
| caadxyz/Macro-Thinking-Micro-action | experimental/gov/nasa/worldwind/render/SurfaceCircle2.java | Java | mit | 1,719 |
// MIT License
//
// Copyright (c) 2016 Fingercomp
//
// 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.
#include <iostream>
#include <cmath>
#include <map>
#include <string>
#include <vector>
#include <SFML/Graphics.hpp>
#include "board.hpp"
#include "graphics.hpp"
#include "main.hpp"
void resizeWindow(sf::RenderWindow &window, sf::Vector2u &windowSize, float zoom) {
sf::FloatRect visibleArea(0, 0, zoom * static_cast<float>(windowSize.x), zoom * static_cast<float>(windowSize.y));
window.setView(sf::View(visibleArea));
}
inline void resizeTilemap(CellTilemap &cellTilemap, sf::Vector2u &windowSize, float zoom) {
cellTilemap.resize(ceil(zoom * static_cast<float>(windowSize.x) / graphicsSettings::cellWidth), ceil(zoom * static_cast<float>(windowSize.y) / graphicsSettings::cellHeight));
}
int main() {
Board board(10, 10);
CellTilemap cellTilemap(board);
sf::Texture texture;
std::vector<std::pair<Tile, sf::Color>> tilesetNumbers;
sf::Uint8 *tilesetBytes = nullptr;
createTileset(graphicsSettings::colors, tilesetNumbers, tilesetBytes, texture);
Tilemap tilemap(cellTilemap, texture, tilesetNumbers);
sf::RenderWindow window(sf::VideoMode(800, 600), "Game of Life");
window.setFramerateLimit(30); // no need for high FPS
int zoomPos = 4; // 1.0f
float zoom = graphicsSettings::zoomLevels.at(zoomPos);
sf::Vector2u windowSize = window.getSize();
cellTilemap.resize(ceil(zoom * static_cast<float>(windowSize.x) / graphicsSettings::cellWidth), ceil(zoom * static_cast<float>(windowSize.y) / graphicsSettings::cellHeight));
resizeWindow(window, windowSize, zoom);
State state = State::PAUSED;
int speed = 7;
sf::Time updateInterval = graphicsSettings::speed.at(speed);
sf::Clock clock;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::Resized: {
sf::Vector2u windowSize(event.size.width, event.size.height);
resizeWindow(window, windowSize, zoom);
resizeTilemap(cellTilemap, windowSize, zoom);
}
case sf::Event::MouseButtonPressed: {
switch (event.mouseButton.button) {
case sf::Mouse::Left: {
sf::Vector2i point(event.mouseButton.x, event.mouseButton.y);
sf::Vector2f pos = window.mapPixelToCoords(point);
int x = static_cast<int>(pos.x);
int y = static_cast<int>(pos.y);
x /= graphicsSettings::cellWidth;
y /= graphicsSettings::cellHeight;
if (x >= 0 && y >= 0 && x < cellTilemap.getWidth() && y < cellTilemap.getHeight()) {
cellTilemap.set(x, y, true);
}
break;
}
case sf::Mouse::Right: {
sf::Vector2i point(event.mouseButton.x, event.mouseButton.y);
sf::Vector2f pos = window.mapPixelToCoords(point);
int x = static_cast<int>(pos.x);
int y = static_cast<int>(pos.y);
x /= graphicsSettings::cellWidth;
y /= graphicsSettings::cellHeight;
if (x >= 0 && y >= 0 && x < cellTilemap.getWidth() && y < cellTilemap.getHeight()) {
cellTilemap.set(x, y, false);
}
break;
}
case sf::Mouse::Middle: {
sf::Vector2i point(event.mouseButton.x, event.mouseButton.y);
sf::Vector2f pos = window.mapPixelToCoords(point);
int x = static_cast<int>(pos.x);
int y = static_cast<int>(pos.y);
x /= graphicsSettings::cellWidth;
y /= graphicsSettings::cellHeight;
if (x >= 0 && y >= 0 && x < cellTilemap.getWidth() && y < cellTilemap.getHeight()) {
std::cout << "DEBUG INFO FOR {x=" << x << ", y=" << y << "}:\n";
std::cout << "Neighbors: " << board.getNeighborCount(x, y) << "\n";
}
break;
}
default:
break;
}
}
case sf::Event::KeyPressed: {
switch (event.key.code) {
case sf::Keyboard::Space:
if (state == State::PAUSED) {
state = State::RUNNING;
} else if (state == State::RUNNING) {
state = State::PAUSED;
}
break;
case sf::Keyboard::Period:
// Speed +
if (speed != 0) {
--speed;
updateInterval = graphicsSettings::speed.at(speed);
}
break;
case sf::Keyboard::Comma:
// Speed -
if (speed + 1 != static_cast<int>(graphicsSettings::speed.size())) {
++speed;
updateInterval = graphicsSettings::speed.at(speed);
}
break;
case sf::Keyboard::PageUp:
// Zoom In
if (zoomPos != 0) {
--zoomPos;
zoom = graphicsSettings::zoomLevels[zoomPos];
sf::Vector2u windowSize = window.getSize();
resizeWindow(window, windowSize, zoom);
resizeTilemap(cellTilemap, windowSize, zoom);
}
break;
case sf::Keyboard::PageDown:
// Zoom Out
if (zoomPos < static_cast<int>(graphicsSettings::zoomLevels.size()) - 1) {
++zoomPos;
zoom = graphicsSettings::zoomLevels[zoomPos];
sf::Vector2u windowSize = window.getSize();
resizeWindow(window, windowSize, zoom);
resizeTilemap(cellTilemap, windowSize, zoom);
}
break;
case sf::Keyboard::BackSpace:
// Clear
board.clear();
break;
case sf::Keyboard::Return:
// Pause and step
if (state == State::RUNNING) {
state = State::PAUSED;
}
board.step();
clock.restart();
default:
break;
}
break;
}
case sf::Event::MouseMoved: {
if (sf::Mouse::isButtonPressed(sf::Mouse::Left) ||
sf::Mouse::isButtonPressed(sf::Mouse::Right) ||
sf::Mouse::isButtonPressed(sf::Mouse::Middle)) {
sf::Vector2i point(event.mouseMove.x, event.mouseMove.y);
sf::Vector2f pos = window.mapPixelToCoords(point);
int x = static_cast<int>(pos.x);
int y = static_cast<int>(pos.y);
x /= graphicsSettings::cellWidth;
y /= graphicsSettings::cellHeight;
if (x >= 0 && y >= 0 && x < cellTilemap.getWidth() && y < cellTilemap.getHeight()) {
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
cellTilemap.set(x, y, true);
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
cellTilemap.set(x, y, false);
}
}
}
}
default:
break;
}
}
if (state == State::RUNNING) {
if (clock.getElapsedTime() >= updateInterval) {
board.step();
clock.restart();
}
}
window.clear();
if (board.modified()) {
tilemap.update();
board.modified(true);
}
window.draw(tilemap);
window.display();
}
delete[] tilesetBytes;
return 0;
}
| Fingercomp/game-of-life | src/main.cpp | C++ | mit | 10,463 |
import { fromJS, OrderedMap } from 'immutable';
const vaccines = fromJS([
{
name: 'AVA (BioThrax)',
id: '8b013618-439e-4829-b88f-98a44b420ee8',
diseases: ['Anthrax'],
},
{
name: 'VAR (Varivax)',
id: 'f3e08a56-003c-4b46-9dea-216298401ca0',
diseases: ['Varicella (Chickenpox)'],
},
{
name: 'MMRV (ProQuad)',
id: '3373721d-3d14-490c-9fa9-69a223888322',
diseases: [
'Varicella (Chickenpox)',
'Measles',
'Mumps',
'Rubella (German Measles)',
],
},
{
name: 'HepA (Havrix, Vaqta)',
id: 'a9144edf-13a2-4ce5-b6af-14eb38fd848c',
diseases: ['Hepatitis A'],
},
{
name: 'HepA-HepB (Twinrix)',
id: '6888fd1a-af4f-4f33-946d-40d4c473c9cc',
diseases: ['Hepatitis A', 'Hepatitis B'],
},
{
name: 'HepB (Engerix-B, Recombivax HB)',
id: 'ca079856-a561-4bc9-9bef-e62429ed3a38',
diseases: ['Hepatitis B'],
},
{
name: 'Hib-HepB (Comvax)',
id: '7305d769-0d1e-4bef-bd09-6998dc839825',
diseases: ['Hepatitis B', 'Haemophilus influenzae type b (Hib)'],
},
{
name: 'Hib (ActHIB, PedvaxHIB, Hiberix)',
id: 'd241f0c7-9920-4bc6-8f34-288a13e03f4d',
diseases: ['Haemophilus influenzae type b (Hib)'],
},
{
name: 'HPV4 (Gardasil)',
id: 'c2fef03c-db7f-483b-af70-50560712b189',
diseases: ['Human Papillomavirus (HPV)'],
},
{
name: 'HPV2 (Cervarix)',
id: '286f55e4-e727-4fc4-86b0-5a08ea712a77',
diseases: ['Human Papillomavirus (HPV)'],
},
{
name: 'TIV (Afluria, Agriflu, FluLaval, Fluarix, Fluvirin, Fluzone, Fluzone High-Dose, Fluzone Intradermal)', // eslint-disable-line max-len
id: '60e85a31-6a54-48e1-b0b7-deb28120675b',
diseases: ['Seasonal Influenza (Flu)'],
},
{
name: 'LAIV (FluMist)',
id: '9e67e321-9a7f-426f-ba9b-28885f93f9b9',
diseases: ['Seasonal Influenza (Flu)'],
},
{
name: 'JE (Ixiaro)',
id: '5ce00584-3350-442d-ac6c-7f19567eff8a',
diseases: ['Japanese Encephalitis'],
},
{
name: 'MMR (M-M-R II)',
id: 'd10b7bf0-d51e-4117-a6a4-08bdb5cb682a',
diseases: ['Measles', 'Mumps', 'Rubella (German Measles)'],
},
{
name: 'MCV4 (Menactra)',
id: '6295fe11-f0ce-4967-952c-f271416cc300',
diseases: ['Meningococcal'],
},
{
name: 'MPSV4 (Menomune)',
id: '65f6d6d0-6dd8-49c9-95da-ed9fa403ae96',
diseases: ['Meningococcal'],
},
{
name: 'MODC (Menveo)',
id: 'be10b480-7934-46be-a488-66540aac2881',
diseases: ['Meningococcal'],
},
{
name: 'Tdap (Adacel, Boostrix)',
id: '0c6c33fb-f4dc-44c6-8684-625099f6fa21',
diseases: ['Pertussis (Whooping Cough)', 'Tetanus (Lockjaw)', 'Diphtheria'],
},
{
name: 'PCV13 (Prevnar13)',
id: 'd8c5a723-21e2-49a6-a921-705da16563e1',
diseases: ['Pneumococcal'],
},
{
name: 'PPSV23 (Pneumovax 23)',
id: '4005de2f-8e6d-40ae-bb5f-068ac56885b8',
diseases: ['Pneumococcal'],
},
{
name: 'Polio (Ipol)',
id: '9c1582f2-8a7b-4bae-8ba5-656efe33fb29',
diseases: ['Polio'],
},
{
name: 'Rabies (Imovax Rabies, RabAvert)',
id: '2bfeeb1f-b7a7-4ce6-aae1-72e840a93e2e',
diseases: ['Rabies'],
},
{
name: 'RV1 (Rotarix)',
id: '8ddfa840-7558-469a-a53b-19a40d016518',
diseases: ['Rotavirus'],
},
{
name: 'RV5 (RotaTeq)',
id: '9281ddcb-5ef3-47e6-a249-6b2b8bee1e7f',
diseases: ['Rotavirus'],
},
{
name: 'ZOS (Zostavax)',
id: '2921b034-8a4c-46f5-9753-70a112dfec3f',
diseases: ['Shingles (Herpes Zoster)'],
},
{
name: 'Vaccinia (ACAM2000)',
id: 'e26378f4-5d07-4b5f-9c93-53816c0faf9f',
diseases: ['Smallpox'],
},
{
name: 'DTaP (Daptacel, Infanrix)',
id: 'b23e765e-a05b-4a24-8095-03d79e47a8aa',
diseases: [
'Tetanus (Lockjaw)',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'Td (Decavac, generic)',
id: '1af45230-cb2a-4242-81ac-2430cd64f8ce',
diseases: ['Tetanus (Lockjaw)', 'Diphtheria'],
},
{
name: 'DT (-generic-)',
id: '6eb77e28-aaa1-4e29-b124-5793a4bd6f1f',
diseases: ['Tetanus (Lockjaw)', 'Diphtheria'],
},
{
name: 'TT (-generic-)',
id: 'd6cf7277-831c-43c6-a1fa-7109d3325168',
diseases: ['Tetanus (Lockjaw)'],
},
{
name: 'DTaP-IPV (Kinrix)',
id: 'a8ecfef5-5f09-442c-84c3-4dfbcd99b3b8',
diseases: [
'Tetanus (Lockjaw)',
'Polio',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'DTaP-HepB-IPV (Pediarix)',
id: '10bc0626-7b0a-4a42-b1bf-2742f0435c37',
diseases: [
'Tetanus (Lockjaw)',
'Polio',
'Hepatitis B',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'DTaP-IPV/Hib (Pentacel)',
id: 'dcbb9691-1544-44fc-a9ca-351946010876',
diseases: [
'Tetanus (Lockjaw)',
'Polio',
'Haemophilus influenzae type b (Hib)',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'DTaP/Hib',
id: 'e817c55d-e3db-4963-9fec-04d5823f6915',
diseases: [
'Tetanus (Lockjaw)',
'Diphtheria',
'Haemophilus influenzae type b (Hib)',
'Pertussis (Whooping Cough)',
],
},
{
name: 'BCG (TICE BCG, Mycobax)',
id: '8f2049a1-a1e3-44e1-947e-debbf3cafecc',
diseases: ['Tuberculosis (TB)'],
},
{
name: 'Typhoid Oral (Vivotif)',
id: '060f44be-e1e7-4575-ba0f-62611f03384b',
diseases: ['Typhoid Fever'],
},
{
name: 'Typhoid Polysaccharide (Typhim Vi)',
id: '87009829-1a48-4330-91e1-6bcd7ab04ee1',
diseases: ['Typhoid Fever'],
},
{
name: 'YF (YF-Vax)',
id: '24d5bfc4-d69a-4311-bb10-8980dddafa20',
diseases: ['Yellow Fever'],
},
]);
const keyedVaccines = vaccines.reduce((result, item) => (
result.set(item.get('id'), item)
), OrderedMap());
export default keyedVaccines.sortBy(vaccine => vaccine.get('name').toLowerCase());
| nikgraf/CarteJaune | constants/vaccines.js | JavaScript | mit | 5,870 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "strlcpy.h"
#include "addrman.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
void ThreadOpenConnections2(void* parg);
void ThreadOpenAddedConnections2(void* parg);
#ifdef USE_UPNP
void ThreadMapPort2(void* parg);
#endif
void ThreadDNSAddressSeed2(void* parg);
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fClient = false;
bool fDiscover = true;
bool fUseUPnP = false;
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64 nLocalHostNonce = 0;
array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64> mapAlreadyAskedFor;
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
loop
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
if (fShutdown)
return false;
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
Sleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore;
info.nPort = addr.GetPort() + (fAlready ? 1 : 0);
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their webserver that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
}
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to nonblocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
vRecv.clear();
}
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: local node %s misbehaving\n", addrName.c_str());
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
printf("Disconnected %s for misbehavior (score=%d)\n", addrName.c_str(), nMisbehavior);
return true;
}
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nReleaseTime);
X(nStartingHeight);
X(nMisbehavior);
}
#undef X
void ThreadSocketHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
// Make this thread recognisable as the networking thread
RenameThread("bitcoin-net");
try
{
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
ThreadSocketHandler2(parg);
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
PrintException(&e, "ThreadSocketHandler()");
} catch (...) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
throw; // support pthread_cancel()
}
printf("ThreadSocketHandler exited\n");
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_mapRequests, lockReq);
if (lockReq)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSend.empty())
FD_SET(pnode->hSocket, &fdsetSend);
}
}
}
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
if (fShutdown)
return;
if (nSelect == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (hSocketMax != INVALID_SOCKET)
{
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
Sleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("warning: unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", WSAGetLastError());
}
else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (fShutdown)
return;
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
CDataStream& vRecv = pnode->vRecv;
unsigned int nPos = vRecv.size();
if (nPos > ReceiveBufferSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());
pnode->CloseSocketDisconnect();
}
else {
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
vRecv.resize(nPos + nBytes);
memcpy(&vRecv[nPos], pchBuf, nBytes);
pnode->nLastRecv = GetTime();
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
CDataStream& vSend = pnode->vSend;
if (!vSend.empty())
{
int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0)
{
vSend.erase(vSend.begin(), vSend.begin() + nBytes);
pnode->nLastSend = GetTime();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Inactivity checking
//
if (pnode->vSend.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
Sleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadMapPort(parg));
// Make this thread recognisable as the UPnP thread
RenameThread("bitcoin-UPnP");
try
{
vnThreadsRunning[THREAD_UPNP]++;
ThreadMapPort2(parg);
vnThreadsRunning[THREAD_UPNP]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(&e, "ThreadMapPort()");
} catch (...) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(NULL, "ThreadMapPort()");
}
printf("ThreadMapPort exited\n");
}
void ThreadMapPort2(void* parg)
{
printf("ThreadMapPort started\n");
char port[6];
sprintf(port, "%d", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "LeproCoin " + FormatFullVersion();
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");
int i = 1;
loop {
if (fShutdown || !fUseUPnP)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port, "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
return;
}
if (i % 600 == 0) // Refresh every 20 minutes
{
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
}
Sleep(2000);
i++;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
loop {
if (fShutdown || !fUseUPnP)
return;
Sleep(2000);
}
}
}
void MapPort()
{
if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
{
if (!CreateThread(ThreadMapPort, NULL))
printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
}
}
#else
void MapPort()
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strDNSSeed[][2] = {
//{"litecoinpool.org", "dnsseed.litecoinpool.org"},
//{"bytesized-vps.com", "dnsseed.bytesized-vps.com"},
//{"xurious.com", "dnsseed.ltc.xurious.com"},
};
void ThreadDNSAddressSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDNSAddressSeed(parg));
// Make this thread recognisable as the DNS seeding thread
RenameThread("bitcoin-dnsseed");
try
{
vnThreadsRunning[THREAD_DNSSEED]++;
ThreadDNSAddressSeed2(parg);
vnThreadsRunning[THREAD_DNSSEED]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_DNSSEED]--;
PrintException(&e, "ThreadDNSAddressSeed()");
} catch (...) {
vnThreadsRunning[THREAD_DNSSEED]--;
throw; // support pthread_cancel()
}
printf("ThreadDNSAddressSeed exited\n");
}
void ThreadDNSAddressSeed2(void* parg)
{
printf("ThreadDNSAddressSeed started\n");
int found = 0;
if (!fTestNet)
{
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
if (GetNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
0x2EFDCB71, 0xCC1B3AD6, 0xADA77149,
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void ThreadDumpAddress2(void* parg)
{
vnThreadsRunning[THREAD_DUMPADDRESS]++;
while (!fShutdown)
{
DumpAddresses();
vnThreadsRunning[THREAD_DUMPADDRESS]--;
Sleep(100000);
vnThreadsRunning[THREAD_DUMPADDRESS]++;
}
vnThreadsRunning[THREAD_DUMPADDRESS]--;
}
void ThreadDumpAddress(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDumpAddress(parg));
// Make this thread recognisable as the address dumping thread
RenameThread("bitcoin-adrdump");
try
{
ThreadDumpAddress2(parg);
}
catch (std::exception& e) {
PrintException(&e, "ThreadDumpAddress()");
}
printf("ThreadDumpAddress exited\n");
}
void ThreadOpenConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
ThreadOpenConnections2(parg);
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(&e, "ThreadOpenConnections()");
} catch (...) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(NULL, "ThreadOpenConnections()");
}
printf("ThreadOpenConnections exited\n");
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections2(void* parg)
{
printf("ThreadOpenConnections started\n");
// Connect to specific addresses
if (mapArgs.count("-connect"))
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
Sleep(500);
if (fShutdown)
return;
}
}
}
}
// Initiate network connections
int64 nStart = GetTime();
loop
{
ProcessOneShot();
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
Sleep(500);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CSemaphoreGrant grant(*semOutbound);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
nTries++;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
ThreadOpenAddedConnections2(parg);
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(&e, "ThreadOpenAddedConnections()");
} catch (...) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(NULL, "ThreadOpenAddedConnections()");
}
printf("ThreadOpenAddedConnections exited\n");
}
void ThreadOpenAddedConnections2(void* parg)
{
printf("ThreadOpenAddedConnections started\n");
if (mapArgs.count("-addnode") == 0)
return;
if (GetNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
Sleep(500);
}
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
}
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
loop
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = vservConnectAddresses.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
Sleep(500);
if (fShutdown)
return;
}
if (fShutdown)
return;
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
if (fShutdown)
return;
}
}
// if succesful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
if (fShutdown)
return false;
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CNode* pnode = ConnectNode(addrConnect, strDest);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return false;
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
// Make this thread recognisable as the message handling thread
RenameThread("bitcoin-msghand");
try
{
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
ThreadMessageHandler2(parg);
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(&e, "ThreadMessageHandler()");
} catch (...) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(NULL, "ThreadMessageHandler()");
}
printf("ThreadMessageHandler exited\n");
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
// Receive messages
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
ProcessMessages(pnode);
}
if (fShutdown)
return;
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
if (fShutdown)
return;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
// Wait and allow messages to bunch up.
// Reduce vnThreadsRunning so StopNode has permission to exit while
// we're sleeping, but we must always check fShutdown after doing this.
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
Sleep(100);
if (fRequestShutdown)
StartShutdown();
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
if (fShutdown)
return;
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
#endif
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to nonblocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. LeproCoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host ip
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
CreateThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(void* parg)
{
// Make this thread recognisable as the startup thread
RenameThread("bitcoin-start");
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
if (!CreateThread(ThreadDNSAddressSeed, NULL))
printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n");
// Map ports with UPnP
if (fUseUPnP)
MapPort();
// Get addresses from IRC and advertise ours
if (!CreateThread(ThreadIRCSeed, NULL))
printf("Error: CreateThread(ThreadIRCSeed) failed\n");
// Send and receive from sockets, accept connections
if (!CreateThread(ThreadSocketHandler, NULL))
printf("Error: CreateThread(ThreadSocketHandler) failed\n");
// Initiate outbound connections from -addnode
if (!CreateThread(ThreadOpenAddedConnections, NULL))
printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n");
// Initiate outbound connections
if (!CreateThread(ThreadOpenConnections, NULL))
printf("Error: CreateThread(ThreadOpenConnections) failed\n");
// Process messages
if (!CreateThread(ThreadMessageHandler, NULL))
printf("Error: CreateThread(ThreadMessageHandler) failed\n");
// Dump network addresses
if (!CreateThread(ThreadDumpAddress, NULL))
printf("Error; CreateThread(ThreadDumpAddress) failed\n");
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
int64 nStart = GetTime();
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
do
{
int nThreadsRunning = 0;
for (int n = 0; n < THREAD_MAX; n++)
nThreadsRunning += vnThreadsRunning[n];
if (nThreadsRunning == 0)
break;
if (GetTime() - nStart > 20)
break;
Sleep(20);
} while(true);
if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n");
if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
#ifdef USE_UPNP
if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
#endif
if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
Sleep(20);
Sleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
| deemkeen/leprocoin | src/net.cpp | C++ | mit | 57,969 |
export class Entry {
title: string;
photo: string;
description: string;
comments: any[];
} | TechGladiator/Treehouse | angular-basics/src/app/entries/shared/entry.model.ts | TypeScript | mit | 98 |
##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
module Twilio
module REST
class Chat < Domain
##
# Initialize the Chat Domain
def initialize(twilio)
super
@base_url = 'https://chat.twilio.com'
@host = 'chat.twilio.com'
@port = 443
# Versions
@v1 = nil
@v2 = nil
end
##
# Version v1 of chat
def v1
@v1 ||= V1.new self
end
##
# Version v2 of chat
def v2
@v2 ||= V2.new self
end
##
# @param [String] sid The sid
# @return [Twilio::REST::Chat::V2::CredentialInstance] if sid was passed.
# @return [Twilio::REST::Chat::V2::CredentialList]
def credentials(sid=:unset)
self.v2.credentials(sid)
end
##
# @param [String] sid The sid
# @return [Twilio::REST::Chat::V2::ServiceInstance] if sid was passed.
# @return [Twilio::REST::Chat::V2::ServiceList]
def services(sid=:unset)
self.v2.services(sid)
end
##
# Provide a user friendly representation
def to_s
'#<Twilio::REST::Chat>'
end
end
end
end | Yasu31/TK_1720 | app/loverduck_app/vendor/bundle/ruby/2.4.0/gems/twilio-ruby-5.4.3/lib/twilio-ruby/rest/chat.rb | Ruby | mit | 1,229 |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.prod')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| monovertex/ygorganizer | manage.py | Python | mit | 247 |
import os
import sys
import pygame
import signal
import time
import ConfigParser
from twython import TwythonStreamer
#-----------------------------------------------------------------------------
# Import custom modules
#-----------------------------------------------------------------------------
# Add pyscope module to path
path = os.path.join(os.path.dirname(__file__), 'py_apps/pyscope')
sys.path.append(path)
# Add twit_feed module to path
path = os.path.join(os.path.dirname(__file__), '../py_apps/twit_feed')
sys.path.append(path)
import pyscope
import twit_feed
#import tf_test_02
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
MAX_ENTRIES = 1
FPS = 5
BET_TERM = ['#testing', '#blargz'] #['@Gr8AmTweetRace']
AUTH = { 'app_key': 'li8wn8Tb7xBifCnNIgyqUw',
'app_secret': 'vcwq36w4C4VXamlqWBDKM2E8etsOoangDoMhxNDU',
'oauth_token': '1969690717-rGw3VkRQ8IyL4OcPWtv5Y2CeBdVn8ndJrjGKraI',
'oauth_token_secret': 'KO7YIFMKWKaYTtz2zEyaSy044ixj5kIbWrDtZZL96ly0H'}
# Common colors
WHITE = 255,255,255
GREEN = 0,255,0
BLACK = 0,0,0
BLUE = 0,0,255
RED = 255,0,0
#-----------------------------------------------------------------------------
# Global Variables
#-----------------------------------------------------------------------------
g_terms = []
g_bet_loop = None
g_scope = None
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
# Handle graphics on the screen
def draw_starting_screen():
global g_terms
global g_scope
# Create fonts
font_mode = pygame.font.Font(None, 68)
font_title_1 = pygame.font.Font(None, 68)
font_title_2 = pygame.font.Font(None, 68)
font_instr_1 = pygame.font.Font(None, 36)
font_instr_2 = pygame.font.Font(None, 36)
font_ent_title = pygame.font.Font(None, 36)
font_ent = pygame.font.Font(None, 36)
# Create background
rect_bg = pygame.draw.rect(g_scope.screen, BLACK, \
(0, 0, 540, 960), 0)
rect_title = pygame.draw.rect(g_scope.screen, WHITE, \
(20, 20, 500, 100), 0)
rect_game_mode = pygame.draw.rect(g_scope.screen, WHITE, \
(20, 140, 500, 60), 0)
rect_instructions = pygame.draw.rect(g_scope.screen, WHITE, \
(20, 220, 500, 100), 0)
rect_tweets = pygame.draw.rect(g_scope.screen, WHITE, \
(20, 340, 500, 300), 0)
# Draw title
title1 = "The Great American"
title2 = "Tweet Race"
text_title_1 = font_title_1.render(title1,1,BLACK)
text_title_2 = font_title_2.render(title2,1,BLACK)
g_scope.screen.blit(text_title_1, (40, 25))
g_scope.screen.blit(text_title_2, (130, 70))
# Draw game mode
mode_str = font_mode.render('Starting Gate',1,BLACK)
g_scope.screen.blit(mode_str, (115, 140))
# Draw instructions
instr_str_1 = 'Send a tweet to @Gr8AmTweetRace'
instr_str_2 = 'with a #term to enter!'
instr_1 = font_instr_1.render(instr_str_1,1,BLACK)
instr_2 = font_instr_2.render(instr_str_2,1,BLACK)
g_scope.screen.blit(instr_1, (40, 240))
g_scope.screen.blit(instr_2, (40, 270))
# Draw entrants
ent_title = font_ent_title.render('Contestants',1,BLACK)
g_scope.screen.blit(ent_title, (40, 360))
ent_y = 390
for i in range(0, MAX_ENTRIES):
ent_str = ''.join([str(i + 1), ': '])
if i < len(g_terms):
ent_str = ''.join([ent_str, g_terms[i]])
ent_disp = font_ent.render(ent_str,1,BLACK)
g_scope.screen.blit(ent_disp, (40, 390 + (i * 30)))
# Test if a term is already in the term list
def is_in_terms(entry):
global g_terms
for term in g_terms:
if ''.join(['#', entry]) == term:
return True
return False
#-----------------------------------------------------------------------------
# Main
#-----------------------------------------------------------------------------
def main():
global g_bet_loop
global g_scope
global g_terms
# Setup Twitter streamer
tf = twit_feed.TwitFeed(AUTH)
#tf = tf_test_02.TwitFeed(AUTH)
# Tweet that we are accepting bets
# Start streamer to search for terms
tf.start_track_streamer(BET_TERM)
# Setup display
pygame.init()
#g_scope = pyscope.pyscope()
fps_clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
# Main game loop
g_bet_loop = False
while g_bet_loop:
# Handle game events
for event in pygame.event.get():
# End game if quit event raises
if event.type == pygame.QUIT:
g_bet_loop = False
# End game if 'q' or 'esc' key pressed
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
g_bet_loop = False
# Get entries and print them
entries = tf.get_entries()
for entry in entries:
print entry
if is_in_terms(entry) == False:
g_terms.append(''.join(['#', entry]))
print len(g_terms)
if len(g_terms) >= MAX_ENTRIES:
print 'breaking'
g_bet_loop = False
# Update screen
draw_starting_screen()
pygame.display.update()
fps_clock.tick(FPS)
# Clean up Twitter feed and pygame
print str(pygame.time.get_ticks())
tf.stop_tracking()
print str(pygame.time.get_ticks())
pygame.quit()
# Print terms
print 'Search terms: ', g_terms
# Run main
main()
| ShawnHymel/TweetRace | pytest/wager_test_01.py | Python | mit | 5,938 |
package com.martin.lolli;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition, mFromSavedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position, false);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4)
}
));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(
int position, boolean fromSavedInstanceState) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position, fromSavedInstanceState);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position, boolean fromSavedInstanceState);
}
}
| martindisch/Lolli | app/src/main/java/com/martin/lolli/NavigationDrawerFragment.java | Java | mit | 10,019 |
<?php
$id = $_GET['id'];
$link = mysqli_connect("localhost",
"root",
"lict@2",
"crud");
$query = "select * from ict_skills WHERE id = $id";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);
?>
<form action="update.php" method="post">
<input type="hidden" name="id" value="<?php echo $row['id'];?>" />
<br>
<label>Experience Category:</label>
<select name = "ecategory">
<option <?php if ($row ['ecategory']== "computer enginering") echo 'selected'; ?> value="computer enginering">Computer Enginering</option>
<option <?php if ($row ['ecategory']== "accounting") echo 'selected'; ?> value="accounting">Accounting</option>
<option <?php if ($row ['ecategory']== "bank/non-bank") echo 'selected'; ?> value="bank/non-bank">Bank/non-bank</option>
<option <?php if ($row ['ecategory']== "design/creative") echo 'selected'; ?> value="design/creative">Design/creative</option>
</select>
<br>
<label>Skills:</label>
<select name = "skills">
<option <?php if ($row ['skills']== "programming") echo 'selected'; ?> value="programming">Programming</option>
<option <?php if ($row ['skills']== "database") echo 'selected'; ?> value="database">Database</option>
<option <?php if ($row ['skills']== "xpath/xquery/xlink/xpointer") echo 'selected'; ?> value="xpath/xquery/xlink/xpointer">Xpath/Xquery/Xlink/Xpointer</option>
</select>
<br>
<label>Skill Description:</label>
<input type="text" name="sdescription" value="<?php echo $row['sdescription'];?>" />
<br>
<label> Extracurricular Activities:</label>
<input type="text" name="eactivities" value="<?php echo $row['eactivities'];?>" />
<br>
<button type="submit">Save</button>
<button type="reset">Cancel</button>
</form>
</html>
<a href="list.php">Go to list</a> | Muktaranibiswas/Assignment_crud | ict_skills/edit.php | PHP | mit | 1,875 |
(function (r) {
"use strict";
var events = r('events');
var eventEmitter = new events.EventEmitter();
var playerManager = r('../PlayerSetup/player-manager').playerManager;
var helper = r('../helpers');
var world = {
valston: r('../../World/valston/prison')
};
var time = function () {
var settings = {
tickCount: 0,
tickDuration: 45000,
ticksInDay: 48,
autoSaveTick: 300000,
sunrise: 11,
morning: 14,
midDay: 24,
afternoon: 30,
sunset: 36,
moonRise: 40,
night: 42,
midNight: 48,
twilight: 8,
hour: 0,
minute: 0
};
var recursive = function () {
eventEmitter.emit('updateTime');
eventEmitter.emit('updatePlayer', "hitpoints", "maxHitpoints", "constitution");
eventEmitter.emit('updatePlayer', "mana", "maxMana", "intelligence");
eventEmitter.emit('updatePlayer', "moves", "maxMoves", "dexterity");
eventEmitter.emit('updateRoom');
eventEmitter.emit('showPromptOnTick');
// console.log(year);
/*
* Every 45 Seconds update player health, mana, moves
* Update game clock, weather, other effects,
* trigger npc scripts?
* when to reset rooms?
* when to save world
*/
setTimeout(recursive, 50000);
}
/* Shows player prompt */
function showPromptOnTick() {
var player = playerManager.getPlayers;
playerManager.each(function (player) {
var socket = player.getSocket();
var playerPrompt = player.getPrompt(true);
helper.helpers.send(socket, playerPrompt);
});
};
/*Update Time, Day/night cycles*/
function updateTime() {
var tickCount = settings.tickCount;
var ticksInDay = settings.ticksInDay;
if (tickCount !== 0) {
if (settings.minute === 30) {
settings.hour += 1;
if (settings.hour === 24) {
settings.hour = 0;
}
}
settings.minute += 30;
if (settings.minute === 60) {
settings.minute = 0;
}
}
var hour = settings.hour;
var minute = settings.minute;
//increment tick
settings.tickCount += 1;
if (settings.tickCount === 48) {
settings.tickCount = 0;
}
function addZero(time) {
if (time.toString().length === 1) {
return "0" + time;
}
return time;
}
console.log("time " + addZero(hour) + ":" + addZero(minute));
//Shows message for day/night
//TODO: code for moon phases?
if (tickCount <= 35) {
switch (true) {
case (tickCount == 3):
// Emit event "night";
playerManager.broadcast("The moon is slowly moving west across the sky.");
break;
case (tickCount == 9):
// Emit event "Twilight";
playerManager.broadcast("The moon slowly sets in the west.");
break;
case (tickCount == 11):
// Emit event "Sunrise";
playerManager.broadcast("The sun slowly rises from the east.");
break;
case (tickCount == 13):
// Emit event "Morning";
playerManager.broadcast("The sun has risen from the east, the day has begun.");
break;
case (tickCount === 24):
// Emit event "Midday";
playerManager.broadcast("The sun is high in the sky.");
break;
case (tickCount === 29):
// Emit event "Afternoon";
playerManager.broadcast("The sun is slowly moving west across the sky.");
}
} else {
switch (true) {
case (tickCount == 36):
// Emit event "Sunset";
playerManager.broadcast("The sun slowly sets in the west.");
break;
case (tickCount == 40):
// Emit event "MoonRise";
playerManager.broadcast("The moon slowly rises in the west.");
break;
case (tickCount == 43):
// Emit event "Night";
playerManager.broadcast("The moon has risen from the east, the night has begun.");
break;
case (tickCount === 48):
// Emit event "MidNight";
playerManager.broadcast("The moon is high in the sky.");
break;
}
}
if (tickCount === ticksInDay) {
//New day reset
settings.tickCount = 0;
}
//TODO: Date update,
}
/**
Update player and mob HP,Mana,Moves.
@param {string} stat The stat to update
@param {string} maxStat The maxStat of stat to update
@param {string} statType The primary ability linked to stat
*/
function updatePlayer(stat, maxStat, statType) {
console.log(stat + " " + maxStat + " " + statType);
console.time("updatePlayer");
var player = playerManager.getPlayers;
playerManager.each(function (player) {
var playerInfo = player.getPlayerInfo();
//Update Hitpoints if player/mob is hurt
if (playerInfo.information[stat] !== playerInfo.information[maxStat]) {
var gain = playerInfo.information[stat] += playerInfo.information.stats[statType];
if (gain > playerInfo.information[maxStat]) {
gain = playerInfo.information[maxStat];
}
playerInfo.information[stat] = gain;
}
});
console.timeEnd("updatePlayer");
}
/*
* Create function to update rooms / heal mobs
* --------------------------------------------
* When player interacts with the room. (Get item, Attack mob)
* Set room clean status to false.
* This will add the room to an array.
* The update function will loop through this array and only update the dirty rooms.
* The array will check for missing items and add them back if there is no player in the room.
* It will also check / update mob health
* If there is a corpse it should be removed
* have a delay for when to do the update? Update if it's been 5 minutes? this should stop looping through a large amount of
* rooms. set a timestamp when we set dirty? then check the difference in the update? if the timestamp >= the update time. update the room
* Have a flag for when room items are clean?
* Have flag for when mobs are clean this will stop unnecessary looping through room items so we only update mob status
* once all clean, remove from modified room array
* That should cover it!!
*/
var room = [
world.valston.prison
];
var roomLength = room.length;
function updateRoom(onLoad) {
console.time("updateRoom");
/* Searches all areas */
for (var i = 0; i < roomLength; i++) {
var area = room[i];
for (var key in area) {
//Items
var defaultItems = area[key].defaults.items;
var defaultItemCount = defaultItems.length;
//Mobs
var defaultMobs = area[key].defaults.mobs;
var defaultMobsCount = defaultMobs.length;
//Update Items
for (var j = 0; j < defaultItemCount; j++) {
// If an item is missing from the room, indexOf will return -1
// so we then push it to the room items array
if (area[key].items.indexOf(defaultItems[j]) == -1) {
area[key].items.push(defaultItems[j]);
}
//If container, lets check the items
if (defaultItems[j].actions.container == true) {
var defaultContainerItems = defaultItems[j].defaults.items;
var defaultCotainerItemsCount = defaultContainerItems.length;
//update Container items
for (var k = 0; k < defaultCotainerItemsCount; k++) {
if (defaultItems[j].items.indexOf(defaultContainerItems[k]) == -1) {
defaultItems[j].items.push(defaultContainerItems[k]);
}
}
}
}
//Update Mobs
for (var l = 0; l < defaultMobsCount; l++) {
if (area[key].mobs.indexOf(defaultMobs[l]) == -1) {
area[key].mobs.push(defaultMobs[l]);
} else {
// Check Mob health
//var mob = area[key].mobs;
//var mobHP = area[key].mobs.information.hitpoints;
//var mobMaxHp = mob.information.maxHitpoints;
//var mobMana = mob.information.mana;
//var mobMaxMana = mob.information.maxMana;
//console.log(mobHP)
//if (mobHP != mobMaxHp || mobMana != mobMaxMana) {
// var gain = mob.level * 2;
// if (gain > mobMaxHp) {
// gain = mobMaxHp;
// }
// console.log(gain + " " + mobHP)
// mob.information.hitpoints = gain;
// if (gain > mobMaxMana) {
// gain = mobMaxMana;
// }
// mob.information.maxMana = gain;
//}
}
}
}
}
console.timeEnd("updateRoom");
}
eventEmitter.on('updateTime', updateTime);
eventEmitter.on('updatePlayer', updatePlayer);
eventEmitter.on('showPromptOnTick', showPromptOnTick);
eventEmitter.on('updateRoom', updateRoom);
eventEmitter.on('tickTImerStart', recursive);
eventEmitter.emit('tickTImerStart');
}
exports.time = time;
})(require); | LiamKenneth/MudDungeonJS | Game/Core/Events/time.js | JavaScript | mit | 12,168 |
require_relative '../spec_helper'
describe Expense do
describe "#new" do
subject {Expense.new(name: "water bill", amount: 100, recurrance: "annually", description: "lets me shower")}
its(:name) { should == "water bill"}
its(:amount) { should == 100}
its(:recurrance) { should == "annually"}
its(:description) { should == "lets me shower"}
end
describe "#save" do
let(:result){ Expense.connection.execute("SELECT * FROM expenses") }
let(:expense){ Expense.new(name: "water bill", amount: 100, recurrance: "annually", description: "lets me shower") }
context "with a valid expense" do
before do
expense.stub(:valid?){ true }
end
it "should only save one row to the database" do
expense.save
result.count.should == 1
end
it "should record the new id" do
expense.save
expense.id.should == result[0][0]
end
it "should actually save it to the database" do
expense.save
result[0][1].should == "water bill"
end
end
context "with an invalid expense" do
before do
expense.stub(:valid?){ false }
end
it "should not save a new expense" do
expense.save
result.count.should == 0
end
end
end
describe "#update_name" do
let(:original_expense){Expense.create(name: "foo", amount: 100, recurrance: "monthly", description: "foo description")}
let!(:original_id){original_expense.id}
context "with an invaild update" do
before do
Expense.create(name: "grille", amount: 200, recurrance: "annually", description: "grille description")
original_expense.update(name:"grille")
end
it "should not change the name" do
Expense.find_by(name:"foo").should_not be_nil
end
it "should not change the number of rows in the database" do
Expense.count.should == 2
end
it "should retain its original id" do
original_expense.id.should == original_id
end
it "should not update to an existing name" do
grille = Expense.create(name: "grille", amount: 100, recurrance: "annualy", description: "grille description")
grille.update(name:"foo")
Expense.find_by(name:"foo").id.should == original_id
end
end
context "with a valid update" do
before do
Expense.create(name:"yam", amount: 250, recurrance:"annually", description: "yam description")
Expense.create(name:"drink", amount: 2000, recurrance: "annually", description: "drink description")
original_expense.update(name: "water")
end
let(:updated_expense){Expense.find_by(name:"water")}
it "the number of rows in database should not change" do
Expense.count.should == 3
end
it "the updated expense should retain its original id" do
updated_expense.id.should == original_id
end
it "the name should not be nil" do
updated_expense.should_not be_nil
end
end
end
describe ".update_amount" do
let!(:bar){Expense.create(name:"bar", amount: 200, recurrance: "monthly", description: "bar description")}
let(:original_expense){Expense.create(name: "foo", amount: 100, recurrance: "monthly", description: "foo description")}
let!(:original_id){original_expense.id}
let(:find_original_expense){Expense.find_by(name:"foo")}
context "with a valid amount" do
it "should update the amount in database" do
original_expense.update(amount: 375)
find_original_expense.amount.should == 375
end
it "should not change the number of rows in the db" do
Expense.count.should == 2
end
it "the updated expense should retain the same id" do
original_expense.update(amount:375)
find_original_expense.id.should == original_id
end
end
context "with an invalid amount" do
it "should not update with a negative amount entered" do
original_expense.update(amount: -200)
find_original_expense.amount.should == 100
end
it "should not update with any non number characters" do
original_expense.update(amount:"abc")
find_original_expense.amount.should == 100
end
it "should not change the number of rows in the database" do
original_expense.update(amount:"abc")
Expense.count.should == 2
end
end
end
describe "#create" do
let(:result){ Expense.connection.execute("SELECT * FROM expenses") }
let(:expense){ Expense.create(name: "water bill", amount: 100, recurrance: "annually", description: "lets me shower") }
context "with a valid expense" do
before do
expense.stub(:valid?){true}
expense
end
it "should record the new id" do
expected_id = result[0][0]
expense.id.should == expected_id
end
it "should only save one row to the database" do
Expense.count.should == 1
end
it "should be found by name in the database" do
Expense.find_by(name:"water bill").name.should == "water bill"
end
it "should insert a row into database" do
result.count == 1
end
end
context "with a invalid expense" do
it "should not save it to the database" do
end
end
end
describe "#remove" do
let!(:door){Expense.create(name: "door", amount: 225, recurrance: "monthly", description: "bar description")}
let!(:grille){Expense.create(name: "grille", amount: 175, recurrance: "annually", description: "grille description")}
let!(:yam){Expense.create(name: "yam", amount: 250, recurrance: "annually", description: "yam description")}
context "with a valid delete message" do
before {grille.delete}
it "should reduce the size of the database" do
Expense.count.should == 2
end
it "should not have a name of that expense in the db" do
Expense.find_by(name: "grille").should be_nil
end
end
end
describe "#valid" do
let(:result) {Expense.connection.execute("SELECT name FROM expenses")}
let(:expense1){ Expense.new(name:"water bill", amount: 100, recurrance: "monthly", description: "lets me shower") }
let(:expense2){ Expense.new(name:"electric bill", amount: 200, recurrance: "monthly", description: "Nashville Electric Company") }
let(:expense3){ Expense.new(name:"electric bill", amount: 100, recurrance: "annually", description: "Nashville Electric Company") }
let(:expense4){ Expense.new(name:"2345", amount: 100, recurrance: "annualy", description: "Nashville Electric Company") }
it "should return true with a unique name" do
expense2.should be_valid
end
it "should return false with a name already in database" do
expense1.save
expense2.save
expense3.should_not be_valid
end
it "should return false for name with no valid characters" do
expense4.should_not be_valid
end
end
describe ".all" do
context "with no expenses in the database" do
it "should return an empty array if the db is empty" do
Expense.all.should == []
end
end
context "with multiple expenses in the database" do
before do
Expense.create(name: "water bill", amount: 100, recurrance: "annualy", description: "lets me shower")
Expense.create(name: "cable bill", amount: 100, recurrance: "annualy", description: "lets me shower")
Expense.create(name: "electric bill", amount: 100, recurrance: "annualy", description: "lets me shower")
Expense.create(name: "insurance", amount: 100, recurrance: "monthly", description: "lets me shower")
end
it "should return the correct number of rows in database" do
Expense.all.size.should == 4
end
end
end
describe ".annual_expenses_per_day" do
let(:foo){Expense.create(name:"foo", amount: 120, recurrance: "monthly", description: "foo description")}
let(:bar){Expense.create(name:"bar", amount: 95, recurrance: "monthly", description: "bar description")}
let(:grille){Expense.create(name:"grille", amount: 175, recurrance: "annually", description: "grille description")}
let(:yam){Expense.create(name:"yam", amount: 250, recurrance: "annually", description: "yam description")}
let(:drink){Expense.create(name:"drink", amount: 2000, recurrance: "annually", description: "drink description")}
context "with no annual expenses in the databse" do
it "should return zero with no expenses in database" do
Expense.annual_expenses_per_day.should == 0.00
end
it "should return zero with other expense types in database" do
foo
Expense.annual_expenses_per_day.should == 0.00
end
end
context "with one annual expense in the database" do
before {grille}
it "should return the one annual expense calc per day with no other expenses" do
Expense.annual_expenses_per_day.should == 0.48
end
it "should only return the annual expense with other types of expenses in db" do
foo
bar
Expense.annual_expenses_per_day.should == 0.48
end
end
context " with many annual expenses in the database" do
before {grille; yam; drink}
it "should return the sum of all annual expenses divided by num of days in year" do
Expense.annual_expenses_per_day.should == 6.64
end
it "should return only the sum of annual expenses with other types of expenses in db" do
foo
bar
Expense.annual_expenses_per_day.should == 6.64
end
end
end
describe ".monthly_expenses_per_day" do
let(:foo){Expense.create(name:"foo", amount:120, recurrance:"monthly", description:"foo description")}
let(:bar){Expense.create(name:"bar", amount:95, recurrance:"monthly", description:"bar description")}
let(:door){Expense.create(name:"door", amount:225, recurrance:"monthly", description:"bar description")}
let(:grille){Expense.create(name:"grille", amount:175, recurrance:"annually", description:"grille description")}
let(:yam){Expense.create(name:"yam", amount:250, recurrance:"annually", description:"yam description")}
let(:drink){Expense.create(name:"drink", amount:2000, recurrance:"annually", description:"drink description")}
context "with no monthly expenses in the databse" do
it "should return zero with no expenses in database" do
Expense.monthly_expenses_per_day.should == 0.00
end
it "should return zero with other expense types in database" do
grille
yam
Expense.monthly_expenses_per_day.should == 0.00
end
end
context "with one expense in the database" do
before{door}
it "should return the one monthly expense calc per day with no other expenses" do
Expense.monthly_expenses_per_day.should == 7.40
end
it "should only return the monthly expense with other types of expenses in db" do
grille
yam
Expense.monthly_expenses_per_day.should == 7.40
end
end
context " with many monthly expenses in the database" do
before {foo; bar; door}
it "should return monthly expenses calculated on a per day basis" do
Expense.monthly_expenses_per_day.should == 14.47
end
it "should return only monthly expenses with other types of expenses in db" do
grille
yam
drink
Expense.monthly_expenses_per_day.should == 14.47
end
end
end
describe ".total_expenses_per_day" do
let(:foo){Expense.create(name:"foo", amount:120, recurrance:"monthly", description:"foo description")}
let(:bar){Expense.create(name:"bar", amount:95, recurrance:"monthly", description:"bar description")}
let(:door){Expense.create(name:"door", amount:225, recurrance:"monthly", description:"bar description")}
let(:grille){Expense.create(name:"grille", amount:175, recurrance:"annually", description:"grille description")}
let(:yam){Expense.create(name:"yam", amount:250, recurrance:"annually", description:"yam description")}
let(:drink){Expense.create(name:"drink", amount:2000, recurrance:"annually", description:"drink description")}
context "with no expenses in database" do
it "should return zero" do
Expense.total_expenses_per_day.should == 0
end
end
context "with only one type of expense in database" do
it "should return monthly total with only monthly expenses" do
foo; bar; door;
Expense.total_expenses_per_day.should == 14.47
end
it "should return annual total with only annual expenses" do
grille; yam; drink;
Expense.total_expenses_per_day.should == 6.64
end
end
context "with both types of expenses in the database" do
it "should return total of all expenses in a per day basis" do
foo; bar; door; grille; yam; drink;
Expense.total_expenses_per_day.should == 21.11
end
end
end
describe ".last" do
context "with no expenses in the database" do
it "should return nil" do
Expense.last.should be_nil
end
end
context "with multiple expenses in the database" do
let(:water_bill){Expense.new(name:"water bill", amount:100, recurrance:"monthly", description:"lets me shower")}
before do
Expense.new(name:"electric bill", amount:100, recurrance:"monthly", description:"lets me see at night").save
Expense.new(name:"cable bill", amount:100, recurrance:"monthly", description:"lets me watch tv").save
water_bill.save
end
it "should return the last one inserted" do
Expense.last.name.should == "water bill"
end
it "should return the last one inserted with id populated" do
Expense.last.id.should == water_bill.id
end
end
end
describe ".count" do
it "should return zero with no expenses in database" do
Expense.count.should == 0
end
it "should return the correct number of rows with multiple injuries in database" do
Expense.new(name:"water bill", amount:100, recurrance:"monthly", description:"lets me shower").save
Expense.new(name:"electric bill", amount:100, recurrance:"monthly", description:"lets me see at night").save
Expense.new(name:"cable bill", amount:100, recurrance:"monthly", description:"lets me watch tv").save
Expense.count.should == 3
end
end
describe ".find_by_name" do
context "with no expenses in the database" do
it "should return nil" do
Expense.find_by(name: "Foo").should be_nil
end
end
context "with expense by that name in the database" do
let(:water_bill){Expense.new(name:"water bill", amount:100, recurrance:"monthly", description:"lets me shower")}
before do
water_bill.save
Expense.new(name:"electric bill", amount:100, recurrance:"monthly", description:"lets me see at night").save
Expense.new(name:"cable bill", amount:100, recurrance:"monthly", description:"lets me watch tv").save
end
it "should return the expense with that name" do
Expense.find_by(name:"water bill").name.should == "water bill"
end
it "should populate the id" do
Expense.find_by(name:"water bill").id.should == water_bill.id
end
end
end
end
| mknicos/dynamic-income-budget | spec/models/expense_spec.rb | Ruby | mit | 15,439 |
<?php
/**
* Created by PhpStorm.
* User: SSOMENS-022
* Date: 15/5/15
* Time: 11:13 AM
*/
class Mdl_access_rights_terminate_search_update extends CI_Model{
public function URT_SRC_errormsg_loginid($URT_SRC_source){
$URT_SRC_errorarray =array();
$USRC_arr_loginid =array();
$USRC_arr_uldid =array();
$URT_SRC_data_uld_tble=false;
$URT_SRC_customrole_array=array();
$this->db->select();
$this->db->from('USER_LOGIN_DETAILS');
$row=$this->db->count_all_results();
if($row>0){
$URT_SRC_data_uld_tble=true;
}
$this->load->model('EILIB/Mdl_eilib_common_function');
$URT_SRC_errormsg_query = "349,350,351,352,353,354,355,401,454,455,458,465";
$URT_SRC_errorarray=$this->Mdl_eilib_common_function->getErrorMessageList($URT_SRC_errormsg_query);
if(($URT_SRC_source=='URT_SRC_radio_loginterminate')||($URT_SRC_source=='URT_SRC_radio_rejoin')){
if($URT_SRC_source=='URT_SRC_radio_loginterminate'){
$this->db->select();
$this->db->from('VW_ACCESS_RIGHTS_TERMINATE_LOGINID');
$this->db->where('URC_DATA!="SUPER ADMIN"');
$this->db->order_by('ULD_LOGINID');
}
else if($URT_SRC_source=='URT_SRC_radio_rejoin'){
$this->db->select();
$this->db->from('VW_ACCESS_RIGHTS_REJOIN_LOGINID');
$this->db->order_by('ULD_LOGINID');
}
$URT_SRC_select_loginid=$this->db->get();
foreach($URT_SRC_select_loginid->result_array() as $row){
$USRC_arr_loginid[]=$row['ULD_LOGINID'];
}
}
else if($URT_SRC_source=='URT_SRC_radio_optsrcupd'){
$this->db->select();
$this->db->from('VW_ACCESS_RIGHTS_REJOIN_LOGINID');
$this->db->order_by('ULD_LOGINID');
$URT_SRC_select_loginid=$this->db->get();
foreach($URT_SRC_select_loginid->result_array() as $row)
{
$USRC_arr_loginid[]=$row['ULD_LOGINID'];
}
}
$this->db->select();
$this->db->from('ROLE_CREATION');
$this->db->order_by('RC_NAME');
$URT_SRC_select_customrole_menu=$this->db->get();
foreach($URT_SRC_select_customrole_menu->result_array() as $row){
$URT_SRC_customrole_array[]=$row["RC_NAME"];
}
$URT_SRC_result=(object)["URT_SRC_obj_errmsg"=>$URT_SRC_errorarray,"URT_SRC_obj_loginid"=>$USRC_arr_loginid,"URT_SRC_obj_source"=>$URT_SRC_source,"URT_SRC_obj_flg_login"=>$URT_SRC_data_uld_tble,"URT_SRC_customerole"=>$URT_SRC_customrole_array];
return $URT_SRC_result;
}
public function URT_SRC_func_enddate($URT_SRC_lb_loginid,$URT_SRC_recdver,$URT_SRC_flag_srcupd,$URT_SRC_flg_reverlen){
if($URT_SRC_flag_srcupd=='URT_SRC_check_enddate'){
$this->db->select( 'UA_JOIN_DATE,UA_REASON,UA_END_DATE,UA_JOIN');
$this->db->from('USER_ACCESS UA');
$this->db->where("UA.ULD_ID =(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_lb_loginid."') AND UA.UA_REC_VER=(SELECT MAX(UA_REC_VER) FROM USER_ACCESS WHERE ULD_ID=UA.ULD_ID)");
}
else if($URT_SRC_flag_srcupd=='URT_SRC_check_rejoindate'){
$this->db->select('UA_JOIN_DATE,UA_REASON,UA_END_DATE,UA_JOIN');
$this->db->from('USER_ACCESS UA');
$this->db->where("UA.ULD_ID =(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_lb_loginid."') AND UA.UA_REC_VER=(SELECT MAX(UA_REC_VER) FROM USER_ACCESS WHERE ULD_ID=UA.ULD_ID)");
}
else if($URT_SRC_flag_srcupd=='URT_SRC_srcupd'){
$this->db->select( 'UA_JOIN_DATE,UA_REASON,UA_END_DATE,UA_JOIN');
$this->db->from('USER_ACCESS UA');
$this->db->where("UA.ULD_ID =(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_lb_loginid."') AND UA.UA_REC_VER=".$URT_SRC_recdver."");
}
$URT_SRC_select_enddate=$this->db->get();
foreach($URT_SRC_select_enddate->result_array() as $row){
$URT_SRC_joindate=$row["UA_JOIN_DATE"];
$URT_SRC_reason=$row["UA_REASON"];
$URT_SRC_enddate=$row["UA_END_DATE"];
$URT_SRC_join=$row["UA_JOIN"];
}
if($URT_SRC_flg_reverlen=='URT_SRC_recvrsion_more'){
$URT_SRC_recdver=($URT_SRC_recdver)+1;
$this->db->select( 'UA_JOIN_DATE');
$this->db->from('USER_ACCESS UA');
$this->db->where("UA.ULD_ID =(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_lb_loginid."') AND UA.UA_REC_VER=".$URT_SRC_recdver."");
$URT_SRC_select_next_jdate=$this->db->get();
$row_count=$this->db->count_all_results();
if($row_count>0){
foreach($URT_SRC_select_next_jdate->result_array() as $row){
$URT_SRC_next_jdate=$row['UA_JOIN_DATE'];
}
}
else
$URT_SRC_next_jdate='URT_SRC_nomore_recver';
$URT_SRC_result=(object)["URT_SRC_obj_next_jdate"=>$URT_SRC_next_jdate,"URT_SRC_obj_joindate"=>$URT_SRC_joindate,"URT_SRC_obj_endate"=>$URT_SRC_enddate,"URT_SRC_obj_reason"=>$URT_SRC_reason,"URT_SRC_obj_srcupd"=>$URT_SRC_flag_srcupd];
}
else
$URT_SRC_result=(object)["URT_SRC_obj_joindate"=>$URT_SRC_joindate,"URT_SRC_obj_endate"=>$URT_SRC_enddate,"URT_SRC_obj_reason"=>$URT_SRC_reason,"URT_SRC_obj_srcupd"=>$URT_SRC_flag_srcupd];
return $URT_SRC_result;
}
/*-------------------------------------------FUNCTION TO GET LOGIN ID REC VER-----------------------------*/
function URT_SRC_func_recordversion($URT_SRC_lb_loginid_rec,$URT_SRC_flag_recver,$URT_SRC_recvrsion_one) {
$this->db->select( 'UA_REC_VER');
$this->db->from('USER_ACCESS UA');
$this->db->where("ULD_ID =(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_lb_loginid_rec."') AND UA_TERMINATE='X'");
$URT_SRC_select_rec=$this->db->get();
$URT_SRC_recordversion=array();
foreach($URT_SRC_select_rec->result_array() as $row){
$URT_SRC_recordversion[]=$row['UA_REC_VER'];
}
if(count($URT_SRC_recordversion)==1){
$URT_SRC_upd_val=$this->URT_SRC_func_enddate($URT_SRC_lb_loginid_rec,$URT_SRC_recordversion[0],'URT_SRC_srcupd','URT_SRC_recvrsion_one');
$URT_SRC_upd_val=(object)["URT_SRC_obj_endate"=>$URT_SRC_upd_val->URT_SRC_obj_endate,"URT_SRC_obj_reason"=>$URT_SRC_upd_val->URT_SRC_obj_reason,"URT_SRC_obj_srcupd"=>$URT_SRC_upd_val->URT_SRC_obj_srcupd,"URT_SRC_obj_recordversion"=>$URT_SRC_recordversion,"URT_SRC_obj_joindate"=>$URT_SRC_upd_val->URT_SRC_obj_joindate];
}
else{
$URT_SRC_upd_val=(object)["URT_SRC_obj_recordversion"=>$URT_SRC_recordversion,"URT_SRC_obj_srcupd"=>$URT_SRC_flag_recver];
}
return $URT_SRC_upd_val;
}
/*-------------------------------------------FUNCTION TO TERMINATE LOGIN DETAILS-----------------------------*/
function URT_SRC_func_terminate($URT_SRC_emailid,$URT_SRC_enddate,$URT_SRC_reason,$URT_SRC_flg_terminate,$UserStamp,$service){
try{
$URSRC_sharedocflag=0;$URSRC_sharecalflag=0;$URSRC_sharesiteflag=0;
$URT_SRC_enddate = date('Y-m-d',strtotime($URT_SRC_enddate));
// URT_SRC_conn.setAutoCommit(false);
$this->db->select('UA_ID,UA_REASON');
$this->db->from('USER_ACCESS');
$this->db->where(" ULD_ID=(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_emailid."') AND UA_REC_VER=(SELECT MAX(UA_REC_VER) FROM USER_ACCESS where ULD_ID=(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_emailid."'))");
$URT_SRC_select_terminate=$this->db->get();
foreach($URT_SRC_select_terminate->result_array() as $row)
{
$URT_SRC_userpro_id=$row['UA_ID'];
$URT_SRC_old_reason=$row['UA_REASON'];
}
$this->db->query('SET AUTOCOMMIT=0');
$this->db->query('START TRANSACTION');
$URT_SRC_insert_terminate ="CALL SP_LOGIN_TERMINATE_SAVE('".$URT_SRC_emailid."','".$URT_SRC_enddate."','".$URT_SRC_reason."','".$UserStamp."',@TERM_FLAG,@TEMPTBL_OUT_LOGINID,@SAVE_POINT)";
$URT_SRC_sucess_flag=0;
$this->db->query($URT_SRC_insert_terminate);
$URT_SRC_flag_lgnterminateselect="SELECT @TERM_FLAG as TERM_FLAG ,@TEMPTBL_OUT_LOGINID as TEMPTBL_OUT_LOGINID ,@SAVE_POINT as SAVE_POINT";
$URT_SRC_flag_lgnterminaters=$this->db->query($URT_SRC_flag_lgnterminateselect);
$URT_SRC_sucess_flag=$URT_SRC_flag_lgnterminaters->row()->TERM_FLAG;
$URT_SRC_terminatetemplogidtbl=$URT_SRC_flag_lgnterminaters->row()->TEMPTBL_OUT_LOGINID;
$save_point=$URT_SRC_flag_lgnterminaters->row()->SAVE_POINT;
if($URT_SRC_sucess_flag==1)
{
$this->load->model('EILIB/Mdl_eilib_common_function');
/*---------------------------------UNSHARE THE FILE & FOLDER---------------------------------------------*/
$URSRC_sharedocflag=$this->Mdl_eilib_common_function->URSRC_unshareDocuments("",$URT_SRC_emailid,$service);
if($URSRC_sharedocflag==1){
//********************** UNSHARE CALENDAR
$URSRC_sharecalflag=$this->Mdl_eilib_common_function->USRC_shareUnSharecalender($URT_SRC_emailid,'none',$service);
if($URSRC_sharecalflag==0){
$this->db->trans_savepoint_rollback($save_point);
// $this->db->trans_rollback();
$this->Mdl_eilib_common_function->URSRC_shareDocuments("",$URT_SRC_emailid,$service);
}
}
else{
$this->db->trans_savepoint_rollback($save_point);
// $this->db->trans_rollback();
$this->Mdl_eilib_common_function->URSRC_shareDocuments("",$URT_SRC_emailid,$service);
}
$this->db->trans_savepoint_release($save_point) ;
}
else{
$this->db->trans_savepoint_rollback($save_point);
}
$URT_SRC_success_flag=array();
$URT_SRC_success_flag=[$URT_SRC_flg_terminate,$URT_SRC_sucess_flag,$URSRC_sharedocflag,$URSRC_sharecalflag];
// $this->db->trans_commit();
if($URT_SRC_terminatetemplogidtbl!=null&&$URT_SRC_terminatetemplogidtbl!='undefined'){
$drop_query = "DROP TABLE ".$URT_SRC_terminatetemplogidtbl;
$this->db->query($drop_query);
}
return $URT_SRC_success_flag;
}catch(Exception $e)
{
$this->db->trans_savepoint_rollback($save_point);
// $this->db->trans_rollback();
// Logger.log("SCRIPT EXCEPTION:"+err)
// URT_SRC_conn.rollback();
// if(URT_SRC_terminatetemplogidtbl!=null&&URT_SRC_terminatetemplogidtbl!=undefined){
// eilib.DropTempTable(URT_SRC_conn,URT_SRC_terminatetemplogidtbl);}
// //********************** RESHARE CALENDAR
// if(URSRC_sharecalflag==1){
// USRC_shareUnSharecalender(URT_SRC_conn,URT_SRC_emailid,'writer');
// }
// //********************** RESHARE SITE
// if(sitermoveflag==1){
// URSRC_addViewer(URT_SRC_conn,URT_SRC_emailid);}
// //************RESHARE DOCS
// if(URSRC_sharedocflag==1){
// URSRC_shareDocuments(URT_SRC_conn,"",URT_SRC_emailid)};
// URT_SRC_conn.commit();
// URT_SRC_conn.close();
// return Logger.getLog();
}
}
/*-------------------------------------------FUNCTION TO UPDATE LOGIN DETAILS-----------------------------*/
function URT_SRC_func_update($URT_SRC_upd_loginid,$URT_SRC_upd_recver,$URT_SRC_upd_edate,$URT_SRC_upd_reason,$URT_SRC_flg_updation,$UserStamp) {
$URT_SRC_upd_enddate = date('Y-m-d',strtotime($URT_SRC_upd_edate));
$URT_SRC_sucess_flag=0;
if ($URT_SRC_upd_recver==null||$URT_SRC_upd_recver=="SELECT")
{
$URT_SRC_update_terminate =" UPDATE USER_ACCESS SET UA_END_DATE='".$URT_SRC_upd_enddate."',UA_REASON='".$URT_SRC_upd_reason."',UA_USERSTAMP='".$UserStamp."' WHERE ULD_ID=(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_upd_loginid."') AND UA_REC_VER=1";
}
else
{
$URT_SRC_update_terminate =" UPDATE USER_ACCESS SET UA_END_DATE='".$URT_SRC_upd_enddate."',UA_REASON='".$URT_SRC_upd_reason."',UA_USERSTAMP='".$UserStamp."' WHERE ULD_ID=(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_upd_loginid."') AND UA_REC_VER=".$URT_SRC_upd_recver."";
}
$this->db->query($URT_SRC_update_terminate);
if ($this->db->affected_rows() > 0) {
$URT_SRC_sucess_flag=1;
}
else {
$URT_SRC_sucess_flag=0;
}
$URT_SRC_success_flag=array();
$URT_SRC_success_flag=[$URT_SRC_flg_updation,$URT_SRC_sucess_flag];
return $URT_SRC_success_flag;
}
//
/*-------------------------------------------FUNCTION TO REJOIN LOGIN DETAILS-----------------------------*/
function URT_SRC_func_rejoin($URT_SRC_upd_emailid,$URT_SRC_upd_rejoindate,$URT_SRC_upd_customrole,$URT_SRC_flg_rejoin,$UserStamp,$service) {
try{
$URSRC_sharedocflag=0;$URSRC_sharecalflag=0;$URSRC_sharesiteflag=0;
$URT_SRC_temptable='';
// URT_SRC_conn.setAutoCommit(false);
$URT_SRC_upd_rejoindate = date('Y-m-d',strtotime($URT_SRC_upd_rejoindate));
$URT_SRC_upd_customrole=str_replace("_"," ",$URT_SRC_upd_customrole);
$URT_SRC_select_rejoin_id="SELECT UA_ID,RC_ID,MAX(UA.UA_REC_VER) as UA_REC_VER,ULD_ID FROM USER_ACCESS UA WHERE UA.ULD_ID =(SELECT ULD_ID FROM USER_LOGIN_DETAILS WHERE ULD_LOGINID='".$URT_SRC_upd_emailid."')";
$URT_SRC_rs_rejoin_id=$this->db->query($URT_SRC_select_rejoin_id);
foreach($URT_SRC_rs_rejoin_id->result_array() as $row)
{
$URT_SRC_autoinc_id=$row['UA_ID'];
$URT_SRC_userpro_maxrec=$row['UA_REC_VER'];
$URT_SRC_userpro_uldid=$row['ULD_ID'];
}
$URT_SRC_select_rc_id="SELECT RC_ID FROM ROLE_CREATION where RC_NAME='".$URT_SRC_upd_customrole."'";
$URT_SRC_rs_rc_id=$this->db->query($URT_SRC_select_rc_id);
foreach($URT_SRC_rs_rc_id->result_array() as $row){
$URT_SRC_rc_id=$row['RC_ID'];
}
$this->db->query('SET AUTOCOMMIT=0');
$this->db->query('START TRANSACTION');
$URT_SRC_select_rejoin="CALL SP_LOGIN_CREATION_INSERT('".$URT_SRC_upd_emailid."','".$URT_SRC_upd_customrole."','".$URT_SRC_upd_rejoindate."','".$UserStamp."',@TEMPTABLE,@LOGIN_CREATIONFLAG,@SAVE_POINT)";
$this->db->query($URT_SRC_select_rejoin);
$URT_SRC_flag_rejoinselect="SELECT @TEMPTABLE as TEMPTABLE,@LOGIN_CREATIONFLAG as REJOIN_FLAG,@SAVE_POINT as SAVE_POINT";
$URT_SRC_flag_rejoincrers=$this->db->query($URT_SRC_flag_rejoinselect);
$URT_SRC_flag_lgncreinsert=$URT_SRC_flag_rejoincrers->row()->REJOIN_FLAG;
$URT_SRC_temptable=$URT_SRC_flag_rejoincrers->row()->TEMPTABLE;
$save_point=$URT_SRC_flag_rejoincrers->row()->SAVE_POINT;
if($URT_SRC_flag_lgncreinsert==1){
$this->load->model('EILIB/Mdl_eilib_common_function');
$URSRC_sharedocflag= $this->Mdl_eilib_common_function->URSRC_shareDocuments($URT_SRC_upd_customrole,$URT_SRC_upd_emailid,$service);
if($URSRC_sharedocflag==1){
//URSRC_sharesiteflag=URSRC_addViewer(URSRC_conn,URSRC_loginid)
$URSRC_sharecalflag=$this->Mdl_eilib_common_function->USRC_shareUnSharecalender($URT_SRC_upd_emailid,'writer',$service);
if($URSRC_sharecalflag==0){
$this->db->trans_savepoint_rollback($save_point);
// $this->db->trans_rollback();
$this->Mdl_eilib_common_function->URSRC_unshareDocuments($URT_SRC_upd_customrole,$URT_SRC_upd_emailid,$service);
}
}
else{
$this->db->trans_savepoint_rollback($save_point);
// $this->db->trans_rollback();
$this->Mdl_eilib_common_function->URSRC_unshareDocuments($URT_SRC_upd_customrole,$URT_SRC_upd_emailid,$service);
}
$this->db->trans_savepoint_release($save_point) ;
}
else{
$this->db->trans_savepoint_rollback($save_point);
}
if($URT_SRC_temptable!='null'){
$drop_query = "DROP TABLE ".$URT_SRC_temptable;
$this->db->query($drop_query);
}
// $this->db->trans_commit();
$URT_SRC_success_flag=array();
$URT_SRC_success_flag=[$URT_SRC_flg_rejoin,$URT_SRC_flag_lgncreinsert,$URSRC_sharedocflag,$URSRC_sharecalflag];
return $URT_SRC_success_flag;
}catch(Exception $e)
{
// Logger.log("SCRIPT EXCEPTION:"+err)
$this->db->trans_savepoint_rollback($save_point);
// $this->db->trans_rollback();
// if(URT_SRC_temptable!='null'){
// eilib.DropTempTable(URT_SRC_conn,URT_SRC_temptable)
// }
// if(URSRC_sharedocflag==1)
// {
// URSRC_unshareDocuments(URT_SRC_conn,URT_SRC_upd_customrole,URT_SRC_upd_emailid)
// }
// if(URSRC_sharesiteflag==1)
// {
// URSRC_removeViewer(URT_SRC_conn,URT_SRC_upd_emailid)
// }
// if(URSRC_sharecalflag==1)
// {
// USRC_shareUnSharecalender(URT_SRC_conn,URT_SRC_upd_emailid,'none');
// }
// URT_SRC_conn.commit();
// URT_SRC_conn.close();
// return Logger.getLog();
// }
}
}
} | Rajagunasekaran/sample | application/models/ACCESS RIGHTS/Mdl_access_rights_terminate_search_update.php | PHP | mit | 17,707 |
using MomWorld.DataContexts;
using MomWorld.Entities;
using MomWorld.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MomWorld.Controllers
{
public class ChatController : Controller
{
private IdentityDb identityDb = new IdentityDb();
// GET: Chat
public ActionResult Index(string username)
{
ViewBag.CurrentUser = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name));
ViewData["ChatUsername"] = username;
return View();
}
public ActionResult ChatWith(string id)
{
return View();
}
}
} | shortgiraffe4/MomWorld | MomWorld/Controllers/ChatController.cs | C# | mit | 714 |
namespace MyApp.Core.Commands
{
using AutoMapper;
using MyApp.Core.Commands.Contracts;
using MyApp.Core.ViewModels;
using MyApp.Data;
using System.Linq;
public class EmployeePersonalInfoCommand : ICommand
{
private readonly MyAppContext context;
private readonly Mapper mapper;
public EmployeePersonalInfoCommand(MyAppContext context, Mapper mapper)
{
this.context = context;
this.mapper = mapper;
}
public string Execute(string[] inputArgs)
{
var employeeId = int.Parse(inputArgs[0]);
var employee = context.Employees
.FirstOrDefault(x => x.Id == employeeId);
var employeeInformation = this.mapper
.CreateMappedObject<EmployeePersonalInfoDto>(employee);
var result = employeeInformation.ToString();
return result;
}
}
} | Ivelin153/SoftUni | C# DB/C# DB Advanced/Automapper_/MyApp/Core/Commands/EmployeePersonalInfoCommand.cs | C# | mit | 978 |
/**
* 页面管理
* @author: SimonHao
* @date: 2015-12-19 14:24:08
*/
'use strict';
var path = require('path');
var fs = require('fs');
var extend = require('extend');
var mid = require('made-id');
var file = require('./file');
var config = require('./config');
var page_list = {};
var comm_option = config.get('comm');
var server = comm_option.server;
var base_path = comm_option.path.base;
var dist_path = comm_option.path.dist;
var page_path = path.join(dist_path, 'page');
var view_option = extend({
basedir: base_path
}, comm_option.view);
var style_option = extend({
basedir: base_path
}, comm_option.style);
var script_option = extend({
basedir: base_path
}, comm_option.script);
exports.get = function(src){
if(exports.has(src)){
return page_list[src];
}
};
exports.has = function(src){
return src in page_list;
};
exports.set = function(src){
if(exports.has(src)){
return exports.get(src);
}else{
return page_list[src] = new PageInfo(src);
}
};
function PageInfo(src){
this.info = new ModuleInfo(src);
this.deps = [];
this.external_style = {};
this.external_script = {};
this.page_style = path.dirname(this.info.view) + '.css';
this.page_script = path.dirname(this.info.view) + '.js';
this._dist = null;
this._url = null;
}
PageInfo.prototype.link_style = function(pack_name){
this.external_style[pack_name] = path.join(base_path, pack_name + '.css');
};
PageInfo.prototype.link_script = function(pack_name){
this.external_script[pack_name] = path.join(base_path, pack_name + '.js');
};
PageInfo.prototype.script_module = function(){
var script_module = [];
this.deps.forEach(function(module_info){
if(module_info.script){
script_module.push(module_info.script);
}
});
if(this.info.script){
script_module.push(this.info.script);
}
return script_module;
};
PageInfo.prototype.style_module = function(){
var style_module = [];
this.deps.forEach(function(module_info){
if(module_info.style){
style_module.push(module_info.style);
}
});
if(this.info.style){
style_module.push(this.info.style);
}
return style_module;
};
PageInfo.prototype.add_deps = function(deps){
var self = this;
deps.forEach(function(dep_info){
self.deps.push(new ModuleInfo(dep_info.filename, dep_info));
});
};
PageInfo.prototype.entry = function(){
var entry_list = [];
this.deps.filter(function(module_info){
return module_info.script;
}).forEach(function(module_info){
entry_list.push({
id: module_info.id,
options: module_info.info.options || {},
instance: module_info.info.instance
});
});
if(this.info.script){
entry_list.push({
id: this.info.id,
options: {},
instance: null
});
}
return entry_list;
};
PageInfo.prototype.dist = function(){
if(this._dist) return this._dist;
var path_dir = path.normalize(this.info.id).split(path.sep);
path_dir.splice(1,1);
return this._dist = path.join(page_path, path_dir.join(path.sep) + '.html');
};
PageInfo.prototype.url = function(){
if(this._url) return this._url
var relative_path = path.relative(page_path, this.dist());
var url = server.web_domain + server.web_path + relative_path.split(path.sep).join('/');
this._url = url;
return url;
};
/**
* Include Module Info
* @param {string} filename view filename
*/
function ModuleInfo(filename, info){
this.info = info || {};
this.view = filename;
this.id = mid.id(filename, view_option);
this.script = mid.path(this.id, script_option);
this.style = mid.path(this.id, style_option);
}
| simonhao/made-build | lib/page.js | JavaScript | mit | 3,662 |
package org.bouncycastle.asn1.cms;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.BERSequence;
import org.bouncycastle.asn1.BERTaggedObject;
public class EncryptedData
extends ASN1Object
{
private ASN1Integer version;
private EncryptedContentInfo encryptedContentInfo;
private ASN1Set unprotectedAttrs;
public static EncryptedData getInstance(Object o)
{
if (o instanceof EncryptedData)
{
return (EncryptedData)o;
}
if (o != null)
{
return new EncryptedData(ASN1Sequence.getInstance(o));
}
return null;
}
public EncryptedData(EncryptedContentInfo encInfo)
{
this(encInfo, null);
}
public EncryptedData(EncryptedContentInfo encInfo, ASN1Set unprotectedAttrs)
{
this.version = new ASN1Integer((unprotectedAttrs == null) ? 0 : 2);
this.encryptedContentInfo = encInfo;
this.unprotectedAttrs = unprotectedAttrs;
}
private EncryptedData(ASN1Sequence seq)
{
this.version = ASN1Integer.getInstance(seq.getObjectAt(0));
this.encryptedContentInfo = EncryptedContentInfo.getInstance(seq.getObjectAt(1));
if (seq.size() == 3)
{
this.unprotectedAttrs = ASN1Set.getInstance(seq.getObjectAt(2));
}
}
public ASN1Integer getVersion()
{
return version;
}
public EncryptedContentInfo getEncryptedContentInfo()
{
return encryptedContentInfo;
}
public ASN1Set getUnprotectedAttrs()
{
return unprotectedAttrs;
}
/**
* <pre>
* EncryptedData ::= SEQUENCE {
* version CMSVersion,
* encryptedContentInfo EncryptedContentInfo,
* unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
* </pre>
* @return a basic ASN.1 object representation.
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(version);
v.add(encryptedContentInfo);
if (unprotectedAttrs != null)
{
v.add(new BERTaggedObject(false, 1, unprotectedAttrs));
}
return new BERSequence(v);
}
}
| sake/bouncycastle-java | src/org/bouncycastle/asn1/cms/EncryptedData.java | Java | mit | 2,516 |
<?php
if (DEBUG_MODE) ini_set("display_errors", 1);ini_set("display_startup_errors",1);error_reporting(-1);
session_start();
require_once("Config.php");
require_once("autoload.php");
require_once('forum/SSI.php');
$uri = $_SERVER['REQUEST_URI'];
$controller = explode('/', $uri);
$controller = array_slice($controller, 1); // Delete first item, because its always empty
$router = new Router();
$page = $router->doRequest($controller, $context); // $context if smf SSI
include_once(incDir."functionInclude.php");
include_once(incDir."/header.php");
include_once(incDir."/leftbar.php");
if (isset($_REQUEST["standingsList"])) {
include_once(incDir."/rightbar.php");
} else if (isset($_REQUEST["leagues"])) {
include_once(incDir."/statisticsbar.php");
}
echo "<div id=\"content\">";
if (isset($page)) include_once($page);
include_once(incDir."/footer.php");
?> | kiuru/kiekkoliiga | index.php | PHP | mit | 893 |
//===- FindUsedTypes.cpp - Find all Types used by a module ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is used to seek out all of the types in use by the program. Note
// that this analysis explicitly does not include types only used by the symbol
// table.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/FindUsedTypes.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
char FindUsedTypes::ID = 0;
INITIALIZE_PASS(FindUsedTypes, "print-used-types",
"Find Used Types", false, true)
// IncorporateType - Incorporate one type and all of its subtypes into the
// collection of used types.
//
void FindUsedTypes::IncorporateType(Type *Ty) {
// If ty doesn't already exist in the used types map, add it now, otherwise
// return.
if (!UsedTypes.insert(Ty)) return; // Already contain Ty.
// Make sure to add any types this type references now.
//
for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
I != E; ++I)
IncorporateType(*I);
}
void FindUsedTypes::IncorporateValue(const Value *V) {
IncorporateType(V->getType());
// If this is a constant, it could be using other types...
if (const Constant *C = dyn_cast<Constant>(V)) {
if (!isa<GlobalValue>(C))
for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
OI != OE; ++OI)
IncorporateValue(*OI);
}
}
// run - This incorporates all types used by the specified module
//
bool FindUsedTypes::runOnModule(Module &m) {
UsedTypes.clear(); // reset if run multiple times...
// Loop over global variables, incorporating their types
for (Module::const_global_iterator I = m.global_begin(), E = m.global_end();
I != E; ++I) {
IncorporateType(I->getType());
if (I->hasInitializer())
IncorporateValue(I->getInitializer());
}
for (Module::iterator MI = m.begin(), ME = m.end(); MI != ME; ++MI) {
IncorporateType(MI->getType());
const Function &F = *MI;
// Loop over all of the instructions in the function, adding their return
// type as well as the types of their operands.
//
for (const_inst_iterator II = inst_begin(F), IE = inst_end(F);
II != IE; ++II) {
const Instruction &I = *II;
IncorporateType(I.getType()); // Incorporate the type of the instruction
for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
OI != OE; ++OI)
IncorporateValue(*OI); // Insert inst operand types as well
}
}
return false;
}
// Print the types found in the module. If the optional Module parameter is
// passed in, then the types are printed symbolically if possible, using the
// symbol table from the module.
//
void FindUsedTypes::print(raw_ostream &OS, const Module *M) const {
OS << "Types in use by this module:\n";
for (SetVector<Type *>::const_iterator I = UsedTypes.begin(),
E = UsedTypes.end(); I != E; ++I) {
OS << " " << **I << '\n';
}
}
| abduld/clreflect | extern/llvm/lib/Analysis/IPA/FindUsedTypes.cpp | C++ | mit | 3,524 |
require_dependency "taiwan_districts/application_controller"
module TaiwanDistricts
class DataController < ApplicationController
def show
data = TaiwanDistricts.list(params[:lang], params[:id])
render json: data, layout: nil
end
def index
end
end
end
| bugtender/TaiwanDistricts | app/controllers/taiwan_districts/data_controller.rb | Ruby | mit | 285 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Search results</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="img/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
<meta name="description" content="Your description">
<meta name="keywords" content="Your keywords">
<meta name="author" content="Your name">
<link rel="stylesheet" href="css/bootstrap.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen">
<script src="js/jquery.js"></script>
<script src="js/jquery-migrate-1.2.1.js"></script>
<script src="search/search.js"></script>
<script src="js/superfish.js"></script>
<script src="js/jquery.mobilemenu.js"></script>
<script src="js/jquery.easing.1.3.js"></script>
<script src="js/jquery.ui.totop.js"></script>
<script src="js/jquery.touchSwipe.min.js"></script>
<script src="js/jquery.equalheights.js"></script>
<!--[if lt IE 9]>
<div style='text-align:center'><a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode"><img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today." /></a></div>
<link rel="stylesheet" href="assets/tm/css/tm_docs.css" type="text/css" media="screen">
<script src="assets/assets/js/html5shiv.js"></script>
<script src="assets/assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!--==============================header=================================-->
<header id="header">
<div class="container">
<h1 class="navbar-brand navbar-brand_"><a href="index.html"><img alt="Grill point" src="img/logo.png"></a></h1>
</div>
<div class="menuheader">
<div class="container">
<nav class="navbar navbar-default navbar-static-top tm_navbar" role="navigation">
<ul class="nav sf-menu">
<li><a href="index.html">home</a>
<ul>
<li><img src="img/arrowup.png" alt=""><a href="#">info</a></li>
<li><a href="#">profile</a></li>
<li><a class="last" href="#">news</a>
<ul>
<li><a href="#">fresh</a></li>
<li><a class="last" href="#">archive</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="index-1.html">about me</a></li>
<li><a href="index-2.html">gallery</a></li>
<li><a href="index-3.html">links</a></li>
<li><a href="index-4.html">location</a></li>
</ul>
</nav>
</div>
</div>
</header>
<!--==============================content=================================-->
<section id="content">
<div class="row_11">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<h2 class="h2-pad">Search result:</h2>
<div id="search-results"></div>
</div>
</div>
</div>
</div>
</section>
<!--==============================footer=================================-->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 footercol">
<ul class="social_icons clearfix">
<li><a href="#"><img src="img/follow_icon1.png" alt=""></a></li>
<li><a href="#"><img src="img/follow_icon2.png" alt=""></a></li>
<li><a href="#"><img src="img/follow_icon3.png" alt=""></a></li>
<li><a href="#"><img src="img/follow_icon4.png" alt=""></a></li>
</ul>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 footerlogo footercol">
<a class="smalllogo2 logo" href="index.html"><img src="img/logofooter.png" alt=""></a>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 footercol">
<p class="footerpriv">© 2013 • <a class="privacylink" href="index-5.html">Privacy policy</a></p>
</div>
</div>
</div>
</footer>
<script src="js/bootstrap.min.js"></script>
<script src="js/tm-scripts.js"></script>
</body>
</html> | mfmakeup/mfmakeup.github.io | search.php | PHP | mit | 4,789 |
<?php
/**
* The Opera Framework
* Cookies.php
*
* @author Marc Heuker of Hoek <me@marchoh.com>
* @copyright 2016 - 2017 All rights reserved
* @license MIT
* @created 27-8-16
* @version 1.0
*/
namespace Opera\Component\Http;
use ArrayIterator;
use IteratorAggregate;
use Traversable;
class Cookies implements IteratorAggregate
{
protected $cookies = [];
public function add(Cookie $cookie)
{
$this->cookies[] = $cookie;
}
/**
* Retrieve an external iterator
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return Traversable An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* @since 5.0.0
*/
public function getIterator()
{
return new ArrayIterator($this->cookies);
}
} | theopera/framework | src/Component/Http/Cookies.php | PHP | mit | 823 |
export { default } from 'ember-flexberry-gis/components/flexberry-wfs-filter'; | Flexberry/ember-flexberry-gis | app/components/flexberry-wfs-filter.js | JavaScript | mit | 78 |
# Frozen-string-literal: true
# Encoding: utf-8
require 'rubygems'
require 'yaml'
module Jekyll
module LanguagePlugin
module Loaders
class BuiltinDataLoader < BaseLoader
attr_reader :data
def initialize(site)
super
@data = Hash.new
end
def loaded?(language)
@data.has_key?(language)
end
def load(language)
return true if loaded?(language)
file = File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'data', 'lang', "#{language}.yml"))
return false unless File.file?(file)
!!@data.merge!(YAML.load_file(file));
end
def get(key, language)
return nil unless loaded?(language)
traverse_hash(@data, resolve_dot_notation([language, key]))
end
end
end
end
end
Jekyll::LanguagePlugin.register_loader(Jekyll::LanguagePlugin::Loaders::BuiltinDataLoader)
| vwochnik/jekyll-language-plugin | lib/jekyll/language-plugin/loaders/builtin_data_loader.rb | Ruby | mit | 962 |
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
int main()
{
sf::RenderWindow window(sf::VideoMode(200, 200), "Donguili");
sf::Music sound;
if (!sound.openFromFile("C:/Users/Alpha/Documents/Donguili/bin/Debug/test.ogg"))
return -1; // erreur
sound.play();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
// Presse de touche
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
std::cout << "Musique en pause" << std::endl;
sound.pause();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::P))
{
std::cout << "Musique lancé" << std::endl;
sound.play();
}
// Fin Presse touche
window.clear();
window.display();
}
return 0;
}
| haaggen/Donguili | main.cpp | C++ | mit | 910 |
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by jackrosenhauer on 5/5/15.
*/
public class Main {
public static void main(String[] args){
final int DEFAULT_PORT = 8080; // For security reasons, only root can use ports < 1024.
int portNumber = args.length > 1 ? Integer.parseInt(args[0]) : DEFAULT_PORT;
ServerSocket serverSocket;
int threadsCreated = 0;
try{
serverSocket = new ServerSocket(portNumber);
while (true) {
Thread t = new Worker(serverSocket);
t.start();
threadsCreated++;
System.out.println("Threads Created & Processed: " + threadsCreated);
}
} catch (IOException e) {
System.err.println("Oops! " + e);
} catch (Exception e){
System.out.println("Something else went terribly wrong");
e.printStackTrace();
}
}
}
| jackrosenhauer/web-server | src/Main.java | Java | mit | 983 |
#include "hiscores.h"
#include "nucleo.h"
#include "galeria.h"
Hi_Scores::Hi_Scores(Nucleo *nucleo) : Widget( nucleo->screen, (SDL_Rect) {200, 50, 430, 520} )
{
this->nucleo = nucleo;
fuente = nucleo->galeria->get_fuente(CHICA2);
set_color(183, 238, 128);
refresh();
}
void Hi_Scores::refresh()
{
static Image *fondo;
fondo = nucleo->galeria->get_imagen (HI_SCORES);
fondo->imprimir(widget);
print_scores();
}
void Hi_Scores::print_scores(void)
{
for(int i = 0; i < WIN_LIST.size(); i++)
{
fuente->imprimir(widget, (char*) WIN_LIST[i].name.c_str(), 50, 100 + (20*i) );
}
}
| jion/tetrabrick | hiscores.cpp | C++ | mit | 629 |
using System;
using System.Collections.Generic;
using Content.Server.AI.Utility.Actions;
using Content.Server.AI.Utility.Actions.Combat.Melee;
using Content.Server.AI.Utility.Considerations;
using Content.Server.AI.Utility.Considerations.Combat.Melee;
using Content.Server.AI.WorldState;
using Content.Server.AI.WorldState.States;
using Content.Server.AI.WorldState.States.Inventory;
using Content.Server.GameObjects.Components.Weapon.Melee;
using Robust.Shared.IoC;
namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee
{
public sealed class EquipMeleeExp : ExpandableUtilityAction
{
public override float Bonus => UtilityAction.CombatPrepBonus;
protected override IEnumerable<Func<float>> GetCommonConsiderations(Blackboard context)
{
var considerationsManager = IoCManager.Resolve<ConsiderationsManager>();
return new[]
{
considerationsManager.Get<MeleeWeaponEquippedCon>()
.InverseBoolCurve(context),
};
}
public override IEnumerable<UtilityAction> GetActions(Blackboard context)
{
var owner = context.GetState<SelfState>().GetValue();
foreach (var entity in context.GetState<EnumerableInventoryState>().GetValue())
{
if (!entity.HasComponent<MeleeWeaponComponent>())
{
continue;
}
yield return new EquipMelee(owner, entity, Bonus);
}
}
}
}
| space-wizards/space-station-14-content | Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs | C# | mit | 1,564 |
import asyncio
from abc import ABCMeta
from collections.abc import MutableMapping
from aiohttp import web
from aiohttp.web_request import Request
from aiohttp_session import get_session
from collections.abc import Sequence
AIOLOGIN_KEY = '__aiologin__'
ON_LOGIN = 1
ON_LOGOUT = 2
ON_AUTHENTICATED = 3
ON_FORBIDDEN = 4
ON_UNAUTHORIZED = 5
class AbstractUser(MutableMapping, metaclass=ABCMeta):
def __iter__(self):
return self.__dict__.__iter__()
def __len__(self):
return len(self.__dict__)
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, value):
setattr(self, key, value)
def __delitem__(self, key):
delattr(self, key)
@property
def authenticated(self):
raise NotImplemented()
@property
def forbidden(self):
raise NotImplemented()
class AnonymousUser(AbstractUser):
@property
def authenticated(self):
return False
@property
def forbidden(self):
return False
# noinspection PyUnusedLocal
@asyncio.coroutine
def _unauthorized(*args, **kwargs):
raise web.HTTPUnauthorized()
# noinspection PyUnusedLocal
@asyncio.coroutine
def _forbidden(*args, **kwargs):
raise web.HTTPForbidden()
# noinspection PyUnusedLocal
@asyncio.coroutine
def _void(*args, **kwargs):
raise NotImplemented()
class AioLogin:
def __init__(self, request, session_name=AIOLOGIN_KEY, disabled=False,
auth_by_form=_void, auth_by_header=_void,
auth_by_session=_void, forbidden=_forbidden,
unauthorized=_unauthorized, anonymous_user=AnonymousUser,
session=get_session, signals=None):
self._request = request
self._disabled = disabled
self._session_name = session_name
self._anonymous_user = anonymous_user
self._session = session
self._auth_by_form = auth_by_form
self._auth_by_header = auth_by_header
self._auth_by_session = auth_by_session
self._unauthorized = unauthorized
self._forbidden = forbidden
self._on_login = []
self._on_logout = []
self._on_authenticated = []
self._on_forbidden = []
self._on_unauthorized = []
assert isinstance(signals, (type(None), Sequence)), \
"Excepted {!r} but received {!r}".format(Sequence, signals)
signals = [] if signals is None else signals
for sig in signals:
assert isinstance(sig, Sequence), \
"Excepted {!r} but received {!r}".format(Sequence, signals)
is_coro = asyncio.iscoroutinefunction(sig[1])
assert len(sig) == 2 and 1 <= sig[0] <= 7 and is_coro, \
"Incorrectly formatted signal argument {}".format(sig)
if sig[0] == 1:
self._on_login.append(sig[1])
elif sig[0] == 2:
self._on_logout.append(sig[1])
elif sig[0] == 3:
self._on_authenticated.append(sig[1])
elif sig[0] == 4:
self._on_forbidden.append(sig[1])
elif sig[0] == 5:
self._on_unauthorized.append(sig[1])
@asyncio.coroutine
def authenticate(self, *args, remember=False, **kwargs):
assert isinstance(remember, bool), \
"Expected {!r} but received {!r}".format(type(bool), type(remember))
user = yield from self._auth_by_form(self._request, *args, **kwargs)
if user is None:
for coro in self._on_unauthorized:
yield from coro(self._request)
raise web.HTTPUnauthorized
for coro in self._on_authenticated:
yield from coro(self._request)
yield from self.login(user, remember=remember)
@asyncio.coroutine
def login(self, user, remember):
assert isinstance(user, AbstractUser), \
"Expected {} but received {}".format(type(AbstractUser), type(user))
assert isinstance(remember, bool), \
"Expected {!r} but received {!r}".format(type(bool), type(remember))
session = yield from self._session(self._request)
try:
session.remember = remember
except:
session['_remember'] = remember
session[self._session_name] = dict(user)
for coro in self._on_login:
yield from coro(self._request)
@asyncio.coroutine
def logout(self):
session = yield from self._session(self._request)
session.invalidate()
for coro in self._on_logout:
yield from coro(self._request)
@asyncio.coroutine
def auth_by_header(self):
key = self._request.headers.get('AUTHORIZATION', None)
if key is None:
return None
return (yield from self._auth_by_header(self._request, key))
@asyncio.coroutine
def auth_by_session(self):
session = yield from self._session(self._request)
profile = session.get(self._session_name, None)
if profile is None:
return None
user = yield from self._auth_by_session(self._request, profile)
if user is None:
return None
return user
@property
def on_login(self):
return self._on_login
@property
def disabled(self):
return self._disabled
@property
def unauthorized(self):
return self._unauthorized
@property
def forbidden(self):
return self._forbidden
@property
def anonymous_user(self):
return self._anonymous_user
def setup(app, **kwargs):
app.middlewares.append(middleware_factory(**kwargs))
def middleware_factory(**options):
# noinspection PyUnusedLocal
@asyncio.coroutine
def aiologin_middleware(app, handler):
@asyncio.coroutine
def aiologin_handler(*args, **kwargs):
request = kwargs['request'] if 'request' in kwargs else args[0]
kwargs = {k: v for (k, v) in kwargs.items() if k != 'request'}
# noinspection PyTypeChecker
manager = options.get('manager', AioLogin)
request.aiologin = manager(request=request, **options)
return (yield from handler(request=request, **kwargs))
return aiologin_handler
return aiologin_middleware
def secured(func):
@asyncio.coroutine
def wrapper(*args, **kwargs):
request = kwargs['request'] if 'request' in kwargs else args[0]
kwargs = {k: v for (k, v) in kwargs.items() if k != 'request'}
if not isinstance(request, Request):
request = args[0].request
elif request not in args:
args = (request,) + args
if request.aiologin.disabled:
return (yield from func(*args, **kwargs))
user = yield from request.aiologin.auth_by_header()
if user is None:
user = yield from request.aiologin.auth_by_session()
if user is None:
user = request.aiologin.anonymous_user()
assert isinstance(user, AbstractUser), \
"Expected 'user' of type AbstractUser by got {}".format(type(user))
if not user.authenticated:
# noinspection PyProtectedMember
for coro in request.aiologin._on_unauthorized:
yield from coro(request)
return (yield from request.aiologin.unauthorized(*args, **kwargs))
if user.forbidden:
# noinspection PyProtectedMember
for coro in request.aiologin._on_forbidden:
yield from coro(request)
return (yield from request.aiologin.forbidden(*args, **kwargs))
request.current_user = user
# noinspection PyProtectedMember
for coro in request.aiologin._on_authenticated:
yield from coro(request)
return (yield from func(*args, **kwargs))
return wrapper
| trivigy/aiologin | aiologin/__init__.py | Python | mit | 7,901 |
lychee.define('Font').exports(function(lychee) {
var Class = function(spriteOrImages, settings) {
this.settings = lychee.extend({}, this.defaults, settings);
if (this.settings.kerning > this.settings.spacing) {
this.settings.kerning = this.settings.spacing;
}
this.__cache = {};
this.__images = null;
this.__sprite = null;
if (Object.prototype.toString.call(spriteOrImages) === '[object Array]') {
this.__images = spriteOrImages;
} else {
this.__sprite = spriteOrImages;
}
this.__init();
};
Class.prototype = {
defaults: {
// default charset from 32-126
charset: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
baseline: 0,
spacing: 0,
kerning: 0,
map: null
},
__init: function() {
// Single Image Mode
if (this.__images !== null) {
this.__initImages();
// Sprite Image Mode
} else if (this.__sprite !== null) {
if (Object.prototype.toString.call(this.settings.map) === '[object Array]') {
var test = this.settings.map[0];
if (Object.prototype.toString.call(test) === '[object Object]') {
this.__initSpriteXY();
} else if (typeof test === 'number') {
this.__initSpriteX();
}
}
}
},
__initImages: function() {
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var image = this.__images[c] || null;
if (image === null) continue;
var chr = {
id: this.settings.charset[c],
image: image,
width: image.width,
height: image.height,
x: 0,
y: 0
};
this.__cache[chr.id] = chr;
}
},
__initSpriteX: function() {
var offset = this.settings.spacing;
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var chr = {
id: this.settings.charset[c],
width: this.settings.map[c] + this.settings.spacing * 2,
height: this.__sprite.height,
real: this.settings.map[c],
x: offset - this.settings.spacing,
y: 0
};
offset += chr.width;
this.__cache[chr.id] = chr;
}
},
__initSpriteXY: function() {
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var frame = this.settings.map[c];
var chr = {
id: this.settings.charset[c],
width: frame.width + this.settings.spacing * 2,
height: frame.height,
real: frame.width,
x: frame.x - this.settings.spacing,
y: frame.y
};
this.__cache[chr.id] = chr;
}
},
get: function(id) {
if (this.__cache[id] !== undefined) {
return this.__cache[id];
}
return null;
},
getSettings: function() {
return this.settings;
},
getSprite: function() {
return this.__sprite;
}
};
return Class;
});
| Smotko/lycheeJS | lychee/Font.js | JavaScript | mit | 2,768 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M8 9v1.5h2.25V15h1.5v-4.5H14V9H8zM6 9H3c-.55 0-1 .45-1 1v5h1.5v-1.5h2V15H7v-5c0-.55-.45-1-1-1zm-.5 3h-2v-1.5h2V12zM21 9h-4.5c-.55 0-1 .45-1 1v5H17v-4.5h1V14h1.5v-3.51h1V15H22v-5c0-.55-.45-1-1-1z"
}), 'AtmOutlined'); | AlloyTeam/Nuclear | components/icon/esm/atm-outlined.js | JavaScript | mit | 338 |
# coding: utf-8
# pylint: disable=too-many-lines
import inspect
import sys
from typing import TypeVar, Optional, Sequence, Iterable, List, Any
from owlmixin import util
from owlmixin.errors import RequiredError, UnknownPropertiesError, InvalidTypeError
from owlmixin.owlcollections import TDict, TIterator, TList
from owlmixin.owlenum import OwlEnum, OwlObjectEnum
from owlmixin.transformers import (
DictTransformer,
JsonTransformer,
YamlTransformer,
ValueTransformer,
traverse_dict,
TOption,
)
T = TypeVar("T", bound="OwlMixin")
def _is_generic(type_):
return hasattr(type_, "__origin__")
def assert_extra(cls_properties, arg_dict, cls):
extra_keys: set = set(arg_dict.keys()) - {n for n, t in cls_properties}
if extra_keys:
raise UnknownPropertiesError(cls=cls, props=sorted(extra_keys))
def assert_none(value, type_, cls, name):
if value is None:
raise RequiredError(cls=cls, prop=name, type_=type_)
def assert_types(value, types: tuple, cls, name):
if not isinstance(value, types):
raise InvalidTypeError(cls=cls, prop=name, value=value, expected=types, actual=type(value))
def traverse(
type_, name, value, cls, force_snake_case: bool, force_cast: bool, restrict: bool
) -> Any:
# pylint: disable=too-many-return-statements,too-many-branches,too-many-arguments
if isinstance(type_, str):
type_ = sys.modules[cls.__module__].__dict__.get(type_)
if hasattr(type_, "__forward_arg__"):
# `_ForwardRef` (3.6) or `ForwardRef` (>= 3.7) includes __forward_arg__
# PEP 563 -- Postponed Evaluation of Annotations
type_ = sys.modules[cls.__module__].__dict__.get(type_.__forward_arg__)
if not _is_generic(type_):
assert_none(value, type_, cls, name)
if type_ is any:
return value
if type_ is Any:
return value
if isinstance(value, type_):
return value
if issubclass(type_, OwlMixin):
assert_types(value, (type_, dict), cls, name)
return type_.from_dict(
value, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
if issubclass(type_, ValueTransformer):
return type_.from_value(value)
if force_cast:
return type_(value)
assert_types(value, (type_,), cls, name)
return value
o_type = type_.__origin__
g_type = type_.__args__
if o_type == TList:
assert_none(value, type_, cls, name)
assert_types(value, (list,), cls, name)
return TList(
[
traverse(g_type[0], f"{name}.{i}", v, cls, force_snake_case, force_cast, restrict)
for i, v in enumerate(value)
]
)
if o_type == TIterator:
assert_none(value, type_, cls, name)
assert_types(value, (Iterable,), cls, name)
return TIterator(
traverse(g_type[0], f"{name}.{i}", v, cls, force_snake_case, force_cast, restrict)
for i, v in enumerate(value)
)
if o_type == TDict:
assert_none(value, type_, cls, name)
assert_types(value, (dict,), cls, name)
return TDict(
{
k: traverse(
g_type[0], f"{name}.{k}", v, cls, force_snake_case, force_cast, restrict
)
for k, v in value.items()
}
)
if o_type == TOption:
v = value.get() if isinstance(value, TOption) else value
# TODO: Fot `from_csvf`... need to more simple!!
if (isinstance(v, str) and v) or (not isinstance(v, str) and v is not None):
return TOption(
traverse(g_type[0], name, v, cls, force_snake_case, force_cast, restrict)
)
return TOption(None)
raise RuntimeError(f"This generics is not supported `{o_type}`")
class OwlMeta(type):
def __new__(cls, name, bases, class_dict):
ret_cls = type.__new__(cls, name, bases, class_dict)
ret_cls.__methods_dict__ = dict(inspect.getmembers(ret_cls, inspect.ismethod))
return ret_cls
class OwlMixin(DictTransformer, JsonTransformer, YamlTransformer, metaclass=OwlMeta):
@classmethod
def from_dict(
cls,
d: dict,
*,
force_snake_case: bool = True,
force_cast: bool = False,
restrict: bool = True,
) -> T:
"""From dict to instance
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human, Food, Japanese
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].name
'Apple'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
You can use default value
>>> taro: Japanese = Japanese.from_dict({
... "name": 'taro'
... }) # doctest: +NORMALIZE_WHITESPACE
>>> taro.name
'taro'
>>> taro.language
'japanese'
If you don't set `force_snake=False` explicitly, keys are transformed to snake case as following.
>>> human: Human = Human.from_dict({
... "--id": 1,
... "<name>": "Tom",
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple"}}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["en"]
'Apple'
You can allow extra parameters (like ``hogehoge``) if you set `restrict=False`.
>>> apple: Food = Food.from_dict({
... "name": "Apple",
... "hogehoge": "ooooooooooooooooooooo",
... }, restrict=False)
>>> apple.to_dict()
{'name': 'Apple'}
You can prohibit extra parameters (like ``hogehoge``) if you set `restrict=True` (which is default).
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "hogehoge1": "ooooooooooooooooooooo",
... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"],
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.UnknownPropertiesError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Unknown properties error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!!
<BLANKLINE>
* If you want to allow unknown properties, set `restrict=False`
* If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human
<BLANKLINE>
If you specify wrong type...
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "ichiro",
... "favorites": ["apple", "orange"]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.InvalidTypeError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Invalid Type error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#favorites.0 = apple` doesn't match expected types.
Expected type is one of ["<class 'owlmixin.samples.Food'>", "<class 'dict'>"], but actual type is `<class 'str'>`
<BLANKLINE>
* If you want to force cast, set `force_cast=True`
* If you don't want to force cast, specify value which has correct type
<BLANKLINE>
If you don't specify required params... (ex. name
>>> human: Human = Human.from_dict({
... "id": 1
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#name: <class 'str'>` is empty!!
<BLANKLINE>
* If `name` is certainly required, specify anything.
* If `name` is optional, change type from `<class 'str'>` to `TOption[<class 'str'>]`
<BLANKLINE>
"""
if isinstance(d, cls):
return d
instance: T = cls() # type: ignore
d = util.replace_keys(d, {"self": "_self"}, force_snake_case)
properties = cls.__annotations__.items()
if restrict:
assert_extra(properties, d, cls)
for n, t in properties:
f = cls.__methods_dict__.get(f"_{cls.__name__}___{n}") # type: ignore
arg_v = f(d.get(n)) if f else d.get(n)
def_v = getattr(instance, n, None)
setattr(
instance,
n,
traverse(
type_=t,
name=n,
value=def_v if arg_v is None else arg_v,
cls=cls,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
),
)
return instance
@classmethod
def from_optional_dict(
cls,
d: Optional[dict],
*,
force_snake_case: bool = True,
force_cast: bool = False,
restrict: bool = True,
) -> TOption[T]:
"""From dict to optional instance.
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dict(None).is_none()
True
>>> Human.from_optional_dict({}).get() # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#id: <class 'int'>` is empty!!
<BLANKLINE>
* If `id` is certainly required, specify anything.
* If `id` is optional, change type from `<class 'int'>` to `TOption[<class 'int'>]`
<BLANKLINE>
"""
return TOption(
cls.from_dict(
d, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
if d is not None
else None
)
@classmethod
def from_dicts(
cls,
ds: List[dict],
*,
force_snake_case: bool = True,
force_cast: bool = False,
restrict: bool = True,
) -> TList[T]:
"""From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_dicts([
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
"""
return TList(
[
cls.from_dict(
d, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
for d in ds
]
)
@classmethod
def from_iterable_dicts(
cls,
ds: Iterable[dict],
*,
force_snake_case: bool = True,
force_cast: bool = False,
restrict: bool = True,
) -> TIterator[T]:
"""From iterable dict to iterable instance
:param ds: Iterable dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Iterator
Usage:
>>> from owlmixin.samples import Human
>>> humans: TIterator[Human] = Human.from_iterable_dicts([
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> humans.next_at(0).get().name
'Tom'
>>> humans.next_at(0).get().name
'John'
"""
return TIterator(
cls.from_dict(
d, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
for d in ds
)
@classmethod
def from_optional_dicts(
cls,
ds: Optional[List[dict]],
*,
force_snake_case: bool = True,
force_cast: bool = False,
restrict: bool = True,
) -> TOption[TList[T]]:
"""From list of dict to optional list of instance.
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts(None).is_none()
True
>>> Human.from_optional_dicts([]).get()
[]
"""
return TOption(
cls.from_dicts(
ds, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
if ds is not None
else None
)
@classmethod
def from_optional_iterable_dicts(
cls,
ds: Optional[Iterable[dict]],
*,
force_snake_case: bool = True,
force_cast: bool = False,
restrict: bool = True,
) -> TOption[TIterator[T]]:
"""From iterable dict to optional iterable instance.
:param ds: Iterable dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Iterable instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts(None).is_none()
True
>>> Human.from_optional_dicts([]).get()
[]
"""
return TOption(
cls.from_iterable_dicts(
ds, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
if ds is not None
else None
)
@classmethod
def from_dicts_by_key(
cls,
ds: dict,
*,
force_snake_case: bool = True,
force_cast: bool = False,
restrict: bool = True,
) -> TDict[T]:
"""From dict of dict to dict of instance
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans_by_name: TDict[Human] = Human.from_dicts_by_key({
... 'Tom': {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... 'John': {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... })
>>> humans_by_name['Tom'].name
'Tom'
>>> humans_by_name['John'].name
'John'
"""
return TDict(
{
k: cls.from_dict(
v, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
for k, v in ds.items()
}
)
@classmethod
def from_optional_dicts_by_key(
cls,
ds: Optional[dict],
*,
force_snake_case=True,
force_cast: bool = False,
restrict: bool = True,
) -> TOption[TDict[T]]:
"""From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts_by_key(None).is_none()
True
>>> Human.from_optional_dicts_by_key({}).get()
{}
"""
return TOption(
cls.from_dicts_by_key(
ds, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict
)
if ds is not None
else None
)
@classmethod
def from_json(
cls, data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False
) -> T:
"""From json string to instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_json('''{
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
"""
return cls.from_dict(
util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_jsonf(
cls,
fpath: str,
encoding: str = "utf8",
*,
force_snake_case=True,
force_cast: bool = False,
restrict: bool = False,
) -> T:
"""From json file path to instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(
util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_json_to_list(
cls, data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False
) -> TList[T]:
"""From json string to list of instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_json_to_list('''[
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ]''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
"""
return cls.from_dicts(
util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_json_to_iterator(
cls, data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False
) -> TIterator[T]:
"""From json string to iterable instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Iterable instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TIterator[Human] = Human.from_json_to_iterator('''[
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ]''')
>>> humans.next_at(1).get().name
'John'
>>> humans.next_at(0).is_none()
True
"""
return cls.from_iterable_dicts(
util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_jsonf_to_list(
cls,
fpath: str,
encoding: str = "utf8",
*,
force_snake_case=True,
force_cast: bool = False,
restrict: bool = False,
) -> TList[T]:
"""From json file path to list of instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
"""
return cls.from_dicts(
util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_jsonf_to_iterator(
cls,
fpath: str,
encoding: str = "utf8",
*,
force_snake_case=True,
force_cast: bool = False,
restrict: bool = False,
) -> TIterator[T]:
"""From json file path to iterable instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Iterable instance
"""
return cls.from_iterable_dicts(
util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_yaml(
cls, data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = True
) -> T:
"""From yaml string to instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_yaml('''
... id: 1
... name: Tom
... favorites:
... - name: Apple
... names_by_lang:
... en: Apple
... de: Apfel
... - name: Orange
... ''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
"""
return cls.from_dict(
util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_yamlf(
cls,
fpath: str,
encoding: str = "utf8",
*,
force_snake_case=True,
force_cast: bool = False,
restrict: bool = True,
) -> T:
"""From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(
util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_yaml_to_list(
cls, data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = True
) -> TList[T]:
"""From yaml string to list of instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_yaml_to_list('''
... - id: 1
... name: Tom
... favorites:
... - name: Apple
... - id: 2
... name: John
... favorites:
... - name: Orange
... ''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
>>> humans[0].favorites[0].name
'Apple'
"""
return cls.from_dicts(
util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_yaml_to_iterator(
cls, data: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = True
) -> TIterator[T]:
"""From yaml string to iterable instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Iterable instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TIterator[Human] = Human.from_yaml_to_iterator('''
... - id: 1
... name: Tom
... favorites:
... - name: Apple
... - id: 2
... name: John
... favorites:
... - name: Orange
... ''')
>>> human1 = humans.next_at(1).get()
>>> human1.name
'John'
>>> humans.next_at(0).is_none()
True
>>> human1.favorites[0].name
'Orange'
"""
return cls.from_iterable_dicts(
util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_yamlf_to_list(
cls,
fpath: str,
encoding: str = "utf8",
*,
force_snake_case=True,
force_cast: bool = False,
restrict: bool = True,
) -> TList[T]:
"""From yaml file path to list of instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
"""
return cls.from_dicts(
util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_yamlf_to_iterator(
cls,
fpath: str,
encoding: str = "utf8",
*,
force_snake_case=True,
force_cast: bool = False,
restrict: bool = True,
) -> TIterator[T]:
"""From yaml file path to iterable instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Iterable instance
"""
return cls.from_iterable_dicts(
util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
@classmethod
def from_csvf_to_list(
cls,
fpath: str,
fieldnames: Optional[Sequence[str]] = None,
encoding: str = "utf8",
*,
force_snake_case: bool = True,
restrict: bool = True,
) -> TList[T]:
"""From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file
:param encoding: Csv file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param restrict: Prohibit extra parameters if True
:return: List of Instance
"""
return cls.from_dicts(
list(util.load_csvf(fpath, fieldnames, encoding)),
force_snake_case=force_snake_case,
force_cast=True,
restrict=restrict,
)
@classmethod
def from_csvf_to_iterator(
cls,
fpath: str,
fieldnames: Optional[Sequence[str]] = None,
encoding: str = "utf8",
*,
force_snake_case: bool = True,
restrict: bool = True,
) -> TIterator[T]:
"""From csv file path to iterable instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file
:param encoding: Csv file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param restrict: Prohibit extra parameters if True
:return: Iterable Instance
"""
return cls.from_iterable_dicts(
util.load_csvf(fpath, fieldnames, encoding),
force_snake_case=force_snake_case,
force_cast=True,
restrict=restrict,
)
@classmethod
def from_json_url(
cls, url: str, *, force_snake_case=True, force_cast: bool = False, restrict: bool = False
) -> T:
"""From url which returns json to instance
:param url: Url which returns json
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(
util.load_json_url(url),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict,
)
| tadashi-aikawa/owlmixin | owlmixin/__init__.py | Python | mit | 34,064 |
"""Chapter 22 Practice Questions
Answers Chapter 22 Practice Questions via Python code.
"""
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()
| JoseALermaIII/python-tutorials | pythontutorials/books/CrackingCodes/Ch22/PracticeQuestions.py | Python | mit | 1,117 |
require('mini_magick')
module Aurita
module Plugins
module Wiki
class MiniMagickRenderer
@@logger = Aurita::Log::Class_Logger.new(self)
def initialize(media_asset_instance)
@media_asset = media_asset_instance
end
def import
end
def create_variants(variants={})
end
def create_pdf_preview()
end
end
end
end
end
| fuchsto/aurita-wiki-plugin | lib/modules/mini_magick_renderer.rb | Ruby | mit | 366 |
namespace Pluton.Rust.Events
{
using Core;
using Rust;
using Rust.Objects;
using System;
using System.Collections.Generic;
public class DoorCodeEvent : Event
{
public Player Player;
public CodeLock codeLock;
public bool ForceAllow = false;
private string _entered;
public string Code {
get {
return (string) codeLock.GetFieldValue("code");
}
set {
int code;
if (value.Length == 4 && Int32.TryParse(value, out code)) {
codeLock.SetFieldValue("code", code);
}
}
}
public string Entered {
get {
return _entered;
}
set {
int code;
if (value.Length == 4 && Int32.TryParse(value, out code)) {
_entered = value;
}
}
}
public DoorCodeEvent(CodeLock doorLock, BasePlayer player, string entered)
{
codeLock = doorLock;
Player = Server.GetPlayer(player);
_entered = entered;
}
public void ClearWhitelist() => codeLock.SetFieldValue("whitelistPlayers", new List<ulong>());
public bool IsCorrect() => _entered == Code;
public void RemoveCode()
{
codeLock.SetFieldValue("code", "");
codeLock.SetFieldValue("hasCode", false);
codeLock.SetFlag(BaseEntity.Flags.Locked, false);
ForceAllow = true;
}
public void ResetLock()
{
codeLock.SetFieldValue("code", "");
codeLock.SetFieldValue("hasCode", false);
codeLock.SetFlag(BaseEntity.Flags.Locked, false);
codeLock.SetFieldValue("whitelistPlayers", new List<ulong>());
}
public void Whitelist()
{
List<ulong> whitelist = new List<ulong>();
whitelist = (List<ulong>)codeLock.GetFieldValue("whitelistPlayers");
whitelist.Add(Player.GameID);
codeLock.SetFieldValue("whitelistPlayers", whitelist);
}
}
}
| Notulp/Pluton.Rust | Events/DoorCodeEvent.cs | C# | mit | 2,204 |
var fb = "https://glaring-fire-5349.firebaseio.com";
var TodoCheck = React.createClass({displayName: "TodoCheck",
getInitialState: function() {
this.checked = false;
return {checked: this.checked};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/checked");
// Update the checked state when it changes.
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
this.checked = snap.val();
this.setState({
checked: this.checked
});
this.props.todo.setDone(this.checked);
} else {
this.ref.set(false);
this.props.todo.setDone(false);
}
}.bind(this));
},
toggleCheck: function(event) {
this.ref.set(!this.checked);
event.preventDefault();
},
render: function() {
return (
React.createElement("a", {
onClick: this.toggleCheck,
href: "#",
className: "pull-left todo-check"},
React.createElement("span", {
className: "todo-check-mark glyphicon glyphicon-ok",
"aria-hidden": "true"}
)
)
);
},
});
var TodoText = React.createClass({displayName: "TodoText",
componentWillUnmount: function() {
this.ref.off();
$("#" + this.props.todoKey + "-text").off('blur');
},
setText: function(text) {
this.text = text;
this.props.todo.setHasText(!!text);
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/text");
// Update the todo's text when it changes.
this.setText("");
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
$("#" + this.props.todoKey + "-text").text(snap.val());
this.setText(snap.val());
} else {
this.ref.set("");
}
}.bind(this));
},
onTextBlur: function(event) {
this.ref.set($(event.target).text());
},
render: function() {
setTimeout(function() {
$("#" + this.props.todoKey + "-text").text(this.text);
}.bind(this), 0);
return (
React.createElement("span", {
id: this.props.todoKey + "-text",
onBlur: this.onTextBlur,
contentEditable: "plaintext-only",
"data-ph": "Todo",
className: "todo-text"}
)
);
},
});
var TodoDelete = React.createClass({displayName: "TodoDelete",
getInitialState: function() {
return {};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/deleted");
},
onClick: function() {
this.ref.set(true);
},
render: function() {
if (this.props.isLast) {
return null;
}
return (
React.createElement("button", {
onClick: this.onClick, type: "button",
className: "close", "aria-label": "Close"},
React.createElement("span", {
"aria-hidden": "true",
dangerouslySetInnerHTML: {__html: '×'}})
)
);
},
});
var Todo = React.createClass({displayName: "Todo",
getInitialState: function() {
return {};
},
setDone: function(done) {
this.setState({
done: done
});
},
setHasText: function(hasText) {
this.setState({
hasText: hasText
});
},
render: function() {
var doneClass = this.state.done ? "todo-done" : "todo-not-done";
return (
React.createElement("li", {
id: this.props.todoKey,
className: "list-group-item todo " + doneClass},
React.createElement(TodoCheck, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoText, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoDelete, {isLast: false, todoKey: this.props.todoKey})
)
);
}
});
var TodoList = React.createClass({displayName: "TodoList",
getInitialState: function() {
this.todos = [];
return {todos: this.todos};
},
componentWillMount: function() {
this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/");
// Add an empty todo if none currently exist.
this.ref.on("value", function(snap) {
if (snap.val() === null) {
this.ref.push({
text: "",
});
return;
}
// Add a new todo if no undeleted ones exist.
var returnedTrue = snap.forEach(function(data) {
if (!data.val().deleted) {
return true;
}
});
if (!returnedTrue) {
this.ref.push({
text: "",
});
return;
}
}.bind(this));
// Add an added child to this.todos.
this.ref.on("child_added", function(childSnap) {
this.todos.push({
k: childSnap.key(),
val: childSnap.val()
});
this.replaceState({
todos: this.todos
});
}.bind(this));
this.ref.on("child_removed", function(childSnap) {
var key = childSnap.key();
var i;
for (i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
break;
}
}
this.todos.splice(i, 1);
this.replaceState({
todos: this.todos,
});
}.bind(this));
this.ref.on("child_changed", function(childSnap) {
var key = childSnap.key();
for (var i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
this.todos[i].val = childSnap.val();
this.replaceState({
todos: this.todos,
});
break;
}
}
}.bind(this));
},
componentWillUnmount: function() {
this.ref.off();
},
render: function() {
console.log(this.todos);
var todos = this.state.todos.map(function (todo) {
if (todo.val.deleted) {
return null;
}
return (
React.createElement(Todo, {todoKey: todo.k})
);
}).filter(function(todo) { return todo !== null; });
console.log(todos);
return (
React.createElement("div", null,
React.createElement("h1", {id: "list_title"}, this.props.title),
React.createElement("ul", {id: "todo-list", className: "list-group"},
todos
)
)
);
}
});
var ListPage = React.createClass({displayName: "ListPage",
render: function() {
return (
React.createElement("div", null,
React.createElement("div", {id: "list_page"},
React.createElement("a", {
onClick: this.props.app.navOnClick({page: "LISTS"}),
href: "/#/lists",
id: "lists_link",
className: "btn btn-primary"},
"Back to Lists"
)
),
React.createElement("div", {className: "page-header"},
this.props.children
)
)
);
}
});
var Nav = React.createClass({displayName: "Nav",
render: function() {
return (
React.createElement("nav", {className: "navbar navbar-default navbar-static-top"},
React.createElement("div", {className: "container"},
React.createElement("div", {className: "navbar-header"},
React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), className: "navbar-brand", href: "/#/lists"}, "Firebase Todo")
),
React.createElement("ul", {className: "nav navbar-nav"},
React.createElement("li", null, React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), href: "/#/lists"}, "Lists"))
)
)
)
);
},
});
var App = React.createClass({displayName: "App",
getInitialState: function() {
var state = this.getState();
this.setHistory(state, true);
return this.getState();
},
setHistory: function(state, replace) {
// Don't bother pushing a history entry if the latest state is
// the same.
if (_.isEqual(state, this.state)) {
return;
}
var histFunc = replace ?
history.replaceState.bind(history) :
history.pushState.bind(history);
if (state.page === "LIST") {
histFunc(state, "", "#/list/" + state.todoListKey);
} else if (state.page === "LISTS") {
histFunc(state, "", "#/lists");
} else {
console.log("Unknown page: " + state.page);
}
},
getState: function() {
var url = document.location.toString();
if (url.match(/#/)) {
var path = url.split("#")[1];
var res = path.match(/\/list\/([^\/]*)$/);
if (res) {
return {
page: "LIST",
todoListKey: res[1],
};
}
res = path.match(/lists$/);
if (res) {
return {
page: "LISTS"
}
}
}
return {
page: "LISTS"
}
},
componentWillMount: function() {
// Register history listeners.
var app = this;
window.onpopstate = function(event) {
app.replaceState(event.state);
};
},
navOnClick: function(state) {
return function(event) {
this.setHistory(state, false);
this.replaceState(state);
event.preventDefault();
}.bind(this);
},
getPage: function() {
if (this.state.page === "LIST") {
return (
React.createElement(ListPage, {app: this},
React.createElement(TodoList, {todoListKey: this.state.todoListKey})
)
);
} else if (this.state.page === "LISTS") {
return (
React.createElement("a", {onClick: this.navOnClick({page: "LIST", todoListKey: "-JjcFYgp1LyD5oDNNSe2"}), href: "/#/list/-JjcFYgp1LyD5oDNNSe2"}, "hi")
);
} else {
console.log("Unknown page: " + this.state.page);
}
},
render: function() {
return (
React.createElement("div", null,
React.createElement(Nav, {app: this}),
React.createElement("div", {className: "container", role: "main"},
this.getPage()
)
)
);
}
});
React.render(
React.createElement(App, null),
document.getElementById('content')
); | jasharpe/firebase-react-todo | build/.module-cache/55ef8d641456cf304b91346e5672f316c68f8da9.js | JavaScript | mit | 10,058 |
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Script.hpp>
# include <Siv3D/Stopwatch.hpp>
namespace s3d
{
using namespace AngelScript;
using BindType = Stopwatch;
static void Construct(BindType* self)
{
new(self) BindType();
}
static void ConstructB(bool startImmediately, BindType* self)
{
new(self) BindType(StartImmediately{ startImmediately });
}
static void ConstructDB(const Duration& time, bool startImmediately, BindType* self)
{
new(self) BindType(time, StartImmediately{ startImmediately });
}
static void Destruct(BindType* thisPointer)
{
thisPointer->~BindType();
}
static String FormatStopwatch(const String& format, const Stopwatch& stopwatch)
{
return stopwatch.format(format);
}
static int32 CompareWithDuration(const Duration& other, const Stopwatch& value)
{
const auto e = value.elapsed();
if (e == other)
{
return 0;
}
else if (e < other)
{
return -1;
}
else
{
return 1;
}
}
void RegisterStopwatch(asIScriptEngine* engine)
{
const char TypeName[] = "Stopwatch";
int32 r = 0;
r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Construct), asCALL_CDECL_OBJLAST); assert(r >= 0);
r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f(bool startImmediately) explicit", asFUNCTION(ConstructB), asCALL_CDECL_OBJLAST); assert(r >= 0);
r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f(const Duration& in, bool startImmediately = false) explicit", asFUNCTION(ConstructDB), asCALL_CDECL_OBJLAST); assert(r >= 0);
r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_DESTRUCT, "void f()", asFUNCTION(Destruct), asCALL_CDECL_OBJLAST); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "bool isStarted() const", asMETHODPR(BindType, isStarted, () const noexcept, bool), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "bool isPaused() const", asMETHODPR(BindType, isPaused, () const noexcept, bool), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "bool isRunning() const", asMETHODPR(BindType, isRunning, () const noexcept, bool), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "void start()", asMETHOD(BindType, start), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "void pause()", asMETHOD(BindType, pause), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "void resume()", asMETHOD(BindType, resume), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "void reset()", asMETHOD(BindType, reset), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "void restart()", asMETHOD(BindType, restart), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "void set(const Duration& in)", asMETHODPR(BindType, set, (const Duration&), void), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int32 d() const", asMETHODPR(BindType, d, () const, int32), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int64 d64() const", asMETHODPR(BindType, d64, () const, int64), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "double dF() const", asMETHODPR(BindType, dF, () const, double), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int32 h() const", asMETHODPR(BindType, h, () const, int32), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int64 h64() const", asMETHODPR(BindType, h64, () const, int64), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "double hF() const", asMETHODPR(BindType, hF, () const, double), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int32 min() const", asMETHODPR(BindType, min, () const, int32), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int64 min64() const", asMETHODPR(BindType, min64, () const, int64), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "double minF() const", asMETHODPR(BindType, minF, () const, double), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int32 s() const", asMETHODPR(BindType, s, () const, int32), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int64 s64() const", asMETHODPR(BindType, s64, () const, int64), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "double sF() const", asMETHODPR(BindType, sF, () const, double), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int32 ms() const", asMETHODPR(BindType, ms, () const, int32), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int64 ms64() const", asMETHODPR(BindType, ms64, () const, int64), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "double msF() const", asMETHODPR(BindType, msF, () const, double), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int64 us() const", asMETHODPR(BindType, us, () const, int64), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int64 us64() const", asMETHODPR(BindType, us64, () const, int64), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "double usF() const", asMETHODPR(BindType, usF, () const, double), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "Duration elapsed() const", asMETHODPR(BindType, elapsed, () const, Duration), asCALL_THISCALL); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "String format(const String& in format = \"H:mm:ss.xx\")", asFUNCTION(FormatStopwatch), asCALL_CDECL_OBJLAST); assert(r >= 0);
r = engine->RegisterObjectMethod(TypeName, "int32 opCmp(const Duration& in) const", asFUNCTION(CompareWithDuration), asCALL_CDECL_OBJLAST); assert(r >= 0);
}
}
| Siv3D/OpenSiv3D | Siv3D/src/Siv3D/Script/Bind/ScriptStopwatch.cpp | C++ | mit | 6,338 |
<?php
namespace Acme\StoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\StoreBundle\Entity\Product;
use Acme\StoreBundle\Form\ProductType;
class DefaultController extends Controller {
public function indexAction() {
// just setup a fresh $product object (no dummy data)
$product = new Product();
$form = $this->get('form.factory')->create(new ProductType(), $product);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
// perform some action, such as save the object to the database
return $this->redirect($this->generateUrl('store_product_success'));
}
}
return $this->render('AcmeStoreBundle:Default:index.html.twig', array(
'form' => $form->createView(),
));
}
public function successAction() {
return $this->render('AcmeStoreBundle:Default:success.html.twig');
}
}
| VelvetMirror/validation | src/Acme/StoreBundle/Controller/DefaultController.php | PHP | mit | 1,068 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
from future.utils import with_metaclass
import numpy as np
import scipy as sp
from abc import ABCMeta, abstractmethod
from scipy import integrate
import scipy.interpolate as interpolate
from . import core
from . import refstate
__all__ = ['GammaEos','GammaCalc']
#====================================================================
# Base Class
#====================================================================
def set_calculator(eos_mod, kind, kind_opts):
assert kind in kind_opts, (
kind + ' is not a valid thermal calculator. '+
'You must select one of: ' + str(kind_opts))
eos_mod._kind = kind
if kind=='GammaPowLaw':
calc = _GammaPowLaw(eos_mod)
elif kind=='GammaShiftPowLaw':
calc = _GammaShiftPowLaw(eos_mod)
elif kind=='GammaFiniteStrain':
calc = _GammaFiniteStrain(eos_mod)
else:
raise NotImplementedError(kind+' is not a valid '+
'GammaEos Calculator.')
eos_mod._add_calculator(calc, calc_type='gamma')
pass
#====================================================================
class GammaEos(with_metaclass(ABCMeta, core.Eos)):
"""
EOS model for compression dependence of Grüneisen parameter.
Parameters
----------
Thermodyn properties depend only on volume
"""
_kind_opts = ['GammaPowLaw','GammaShiftPowLaw','GammaFiniteStrain']
def __init__(self, kind='GammaPowLaw', natom=1, model_state={}):
self._pre_init(natom=natom)
set_calculator(self, kind, self._kind_opts)
ref_compress_state='P0'
ref_thermal_state='T0'
ref_energy_type = 'E0'
refstate.set_calculator(self, ref_compress_state=ref_compress_state,
ref_thermal_state=ref_thermal_state,
ref_energy_type=ref_energy_type)
# self._set_ref_state()
self._post_init(model_state=model_state)
pass
def __repr__(self):
calc = self.calculators['gamma']
return ("GammaEos(kind={kind}, natom={natom}, "
"model_state={model_state}, "
")"
.format(kind=repr(calc.name),
natom=repr(self.natom),
model_state=self.model_state
)
)
def _set_ref_state(self):
calc = self.calculators['gamma']
path_const = calc.path_const
if path_const=='S':
param_ref_names = []
param_ref_units = []
param_ref_defaults = []
param_ref_scales = []
else:
raise NotImplementedError(
'path_const '+path_const+' is not valid for ThermalEos.')
self._path_const = calc.path_const
self._param_ref_names = param_ref_names
self._param_ref_units = param_ref_units
self._param_ref_defaults = param_ref_defaults
self._param_ref_scales = param_ref_scales
pass
def gamma(self, V_a):
gamma_a = self.calculators['gamma']._calc_gamma(V_a)
return gamma_a
def gamma_deriv(self, V_a):
gamma_deriv_a = self.calculators['gamma']._calc_gamma_deriv(V_a)
return gamma_deriv_a
def temp(self, V_a, T0=None):
temp_a = self.calculators['gamma']._calc_temp(V_a, T0=T0)
return temp_a
#====================================================================
class GammaCalc(with_metaclass(ABCMeta, core.Calculator)):
"""
Abstract Equation of State class for a reference Compression Path
Path can either be isothermal (T=const) or adiabatic (S=const)
For this restricted path, thermodyn properties depend only on volume
"""
def __init__(self, eos_mod):
self._eos_mod = eos_mod
self._init_params()
self._path_const = 'S'
pass
@property
def path_const( self ):
return self._path_const
####################
# Required Methods #
####################
@abstractmethod
def _init_params( self ):
"""Initialize list of calculator parameter names."""
pass
@abstractmethod
def _calc_gamma(self, V_a):
pass
@abstractmethod
def _calc_gamma_deriv(self, V_a):
pass
@abstractmethod
def _calc_temp(self, V_a, T0=None):
pass
def _calc_theta(self, V_a):
theta0 = self.eos_mod.get_param_values(param_names=['theta0'])
theta = self._calc_temp(V_a, T0=theta0)
return theta
####################
# Optional Methods #
####################
# EOS property functions
def _calc_param_deriv(self, fname, paramname, V_a, dxfrac=1e-6):
scale_a, paramkey_a = self.get_param_scale(apply_expand_adj=True )
scale = scale_a[paramkey_a==paramname][0]
# print 'scale: ' + np.str(scale)
#if (paramname is 'E0') and (fname is 'energy'):
# return np.ones(V_a.shape)
try:
fun = getattr(self, fname)
# Note that self is implicitly included
val0_a = fun(V_a)
except:
assert False, 'That is not a valid function name ' + \
'(e.g. it should be press or energy)'
try:
param = core.get_params([paramname])[0]
dparam = scale*dxfrac
# print 'param: ' + np.str(param)
# print 'dparam: ' + np.str(dparam)
except:
assert False, 'This is not a valid parameter name'
# set param value in eos_d dict
core.set_params([paramname,], [param+dparam,])
# Note that self is implicitly included
dval_a = fun(V_a) - val0_a
# reset param to original value
core.set_params([paramname], [param])
deriv_a = dval_a/dxfrac
return deriv_a
def _calc_energy_perturb(self, V_a):
"""Returns Energy pertubation basis functions resulting from fractional changes to EOS params."""
fname = 'energy'
scale_a, paramkey_a = self.get_param_scale(
apply_expand_adj=self.expand_adj)
Eperturb_a = []
for paramname in paramkey_a:
iEperturb_a = self._calc_param_deriv(fname, paramname, V_a)
Eperturb_a.append(iEperturb_a)
Eperturb_a = np.array(Eperturb_a)
return Eperturb_a, scale_a, paramkey_a
#====================================================================
# Implementations
#====================================================================
class _GammaPowLaw(GammaCalc):
_path_opts=['S']
def __init__(self, eos_mod):
super(_GammaPowLaw, self).__init__(eos_mod)
pass
def _init_params(self):
"""Initialize list of calculator parameter names."""
V0 = 100
gamma0 = 1.0
q = 1.0
self._param_names = ['V0', 'gamma0', 'q']
self._param_units = ['ang^3', '1', '1']
self._param_defaults = [V0, gamma0, q]
self._param_scales = [V0, gamma0, q]
pass
def _calc_gamma(self, V_a):
V0, gamma0, q = self.eos_mod.get_param_values(
param_names=['V0','gamma0','q'])
gamma_a = gamma0 *(V_a/V0)**q
return gamma_a
def _calc_gamma_deriv(self, V_a):
q, = self.eos_mod.get_param_values(param_names=['q'])
gamma_a = self._calc_gamma(V_a)
gamma_deriv_a = q*gamma_a/V_a
return gamma_deriv_a
def _calc_temp(self, V_a, T0=None):
if T0 is None:
T0 = self.eos_mod.refstate.ref_temp()
# T0, = self.eos_mod.get_param_values(param_names=['T0'], overrides=[T0])
gamma0, q = self.eos_mod.get_param_values(
param_names=['gamma0','q'])
gamma_a = self._calc_gamma(V_a)
T_a = T0*np.exp(-(gamma_a - gamma0)/q)
return T_a
#====================================================================
class _GammaShiftPowLaw(GammaCalc):
"""
Shifted Power Law description of Grüneisen Parameter (Al’tshuler, 1987)
"""
_path_opts=['S']
def __init__(self, eos_mod):
super(_GammaShiftPowLaw, self).__init__(eos_mod)
pass
def _init_params(self):
"""Initialize list of calculator parameter names."""
V0 = 100
gamma0 = 1.5
gamma_inf = 2/3
beta = 1.4
T0 = 300
self._param_names = ['V0', 'gamma0', 'gamma_inf', 'beta', 'T0']
self._param_units = ['ang^3', '1', '1', '1', 'K']
self._param_defaults = [V0, gamma0, gamma_inf, beta, T0]
self._param_scales = [V0, gamma0, gamma_inf, beta, T0]
pass
def _calc_gamma(self, V_a):
V0, gamma0, gamma_inf, beta = self.eos_mod.get_param_values(
param_names=['V0','gamma0','gamma_inf','beta'])
gamma_a = gamma_inf + (gamma0-gamma_inf)*(V_a/V0)**beta
return gamma_a
def _calc_gamma_deriv(self, V_a):
gamma_inf, beta = self.eos_mod.get_param_values(
param_names=['gamma_inf','beta'])
gamma_a = self._calc_gamma(V_a)
gamma_deriv_a = beta/V_a*(gamma_a-gamma_inf)
return gamma_deriv_a
def _calc_temp(self, V_a, T0=None):
T0, = self.eos_mod.get_param_values(param_names=['T0'], overrides=[T0])
V0, gamma0, gamma_inf, beta = self.eos_mod.get_param_values(
param_names=['V0','gamma0','gamma_inf','beta'])
gamma_a = self._calc_gamma(V_a)
x = V_a/V0
T_a = T0*x**(-gamma_inf)*np.exp((gamma0-gamma_inf)/beta*(1-x**beta))
return T_a
#====================================================================
class _GammaFiniteStrain(GammaCalc):
_path_opts=['S']
def __init__(self, eos_mod):
super(_GammaFiniteStrain, self).__init__(eos_mod)
pass
def _init_params(self):
"""Initialize list of calculator parameter names."""
V0 = 100
gamma0 = 0.5
gammap0 = -2
self._param_names = ['V0', 'gamma0', 'gammap0']
self._param_units = ['ang^3', '1', '1']
self._param_defaults = [V0, gamma0, gammap0]
self._param_scales = [V0, gamma0, gammap0]
pass
def _calc_strain_coefs(self):
V0, gamma0, gammap0 = self.eos_mod.get_param_values(
param_names=['V0','gamma0','gammap0'])
a1 = 6*gamma0
a2 = -12*gamma0 +36*gamma0**2 -18*gammap0
return a1, a2
def _calc_fstrain(self, V_a, deriv=False):
V0, = self.eos_mod.get_param_values(param_names=['V0'])
x = V_a/V0
if deriv:
return -1/(3*V0)*x**(-5/3)
else:
return 1/2*(x**(-2/3)-1)
pass
def _calc_gamma(self, V_a):
a1, a2 = self._calc_strain_coefs()
fstr_a = self._calc_fstrain(V_a)
gamma_a = (2*fstr_a+1)*(a1+a2*fstr_a)/(6*(1+a1*fstr_a+0.5*a2*fstr_a**2))
return gamma_a
def _calc_gamma_deriv(self, V_a):
a1, a2 = self._calc_strain_coefs()
fstr_a = self._calc_fstrain(V_a)
fstr_deriv = self._calc_fstrain(V_a, deriv=True)
gamma_a = self._calc_gamma(V_a)
gamma_deriv_a = gamma_a*fstr_deriv*(
2/(2*fstr_a+1)+a2/(a1+a2*fstr_a)
-(a1+a2*fstr_a)/(1+a1*fstr_a+.5*a2*fstr_a**2))
return gamma_deriv_a
def _calc_temp(self, V_a, T0=None):
if T0 is None:
T0 = self.eos_mod.refstate.ref_temp()
a1, a2 = self._calc_strain_coefs()
fstr_a = self._calc_fstrain(V_a)
T_a = T0*np.sqrt(1 + a1*fstr_a + 0.5*a2*fstr_a**2)
return T_a
#====================================================================
| aswolf/xmeos | xmeos/models/gamma.py | Python | mit | 11,700 |
# encoding: utf-8
# @note Актовая запись о перемене имени в объеме справки формы32 c ЭП
class SignedActRecordToReferenceNameChange32Mapper
include XmlSchemaMapper
schema File.expand_path('../../vendor/ezags-protocols/eZAGS/public/UploadService.xsd', File.dirname(__FILE__))
type 'SignedActRecordToReferenceNameChange32'
# Запись АГС
# @return [ActRecordToReferenceNameChange32Mapper]
# minOccurs: 1, maxOccurs: 1
attr_accessor :act_record
# ЭП должностного лица органа ЗАГС
# @return [SignatureWithCommentMapper]
# minOccurs: 1, maxOccurs: 1
attr_accessor :act_record_signature
end
| webgago/ezags-xsd | app/mappers/signed_act_record_to_reference_name_change32_mapper.rb | Ruby | mit | 692 |
<?php
use yii\db\Schema;
use yii\platform\geo\models\Locations;
class m130524_200441_locations extends \yii\db\Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable(Locations::tableName(), [
'id' => Schema::TYPE_INTEGER . '(10) unsigned NOT NULL PRIMARY KEY',
'country' => Schema::TYPE_STRING . '(2) NOT NULL',
'region' => Schema::TYPE_STRING . '(2) NOT NULL DEFAULT ""',
'city' => Schema::TYPE_STRING . '(255) NOT NULL DEFAULT ""',
'postal' => Schema::TYPE_STRING . '(12) NOT NULL DEFAULT ""',
'latitude' => Schema::TYPE_DECIMAL . '(10,7) DEFAULT NULL',
'longitude' => Schema::TYPE_DECIMAL . '(10,7) DEFAULT NULL',
'create_time' => Schema::TYPE_INTEGER.' NOT NULL',
'update_time' => Schema::TYPE_INTEGER.' NOT NULL'
], $tableOptions);
}
public function down()
{
$this->dropTable(Locations::tableName());
}
}
| Filsh/yii2-platform | console/migrations/m130524_200441_locations.php | PHP | mit | 1,146 |
<?php
namespace Acme\TwigBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('acme_twig');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| gabrielnotong/noonka | src/Acme/TwigBundle/DependencyInjection/Configuration.php | PHP | mit | 873 |
import { css, ThemedStyledProps } from 'styled-components';
import { ripple } from '../../utils/animations';
import { Theme } from '../../themes/default';
import { StyleProps } from './default';
export const style = ({
theme,
main,
}: ThemedStyledProps<StyleProps, Theme>) => css`
display: flex;
flex: 0 0 1;
padding-left: 1px;
background-color: ${theme.base01};
width: 100%;
overflow: hidden;
${!main &&
`
border-top: 1px solid ${theme.base01};
border-bottom: 1px solid ${theme.base02};
`}
> div {
display: flex;
align-items: flex-end;
flex-wrap: nowrap;
button {
background-color: ${theme.base01};
color: ${theme.base07};
min-height: 30px;
padding: 0 2em;
${main && 'text-transform: uppercase;'}
cursor: pointer;
border: none;
border-bottom: 2px solid transparent;
text-align: center;
overflow: hidden;
outline: 0;
transition: all 0.5s;
&:hover,
&:focus {
border-bottom: 2px solid ${theme.base03};
color: ${theme.base04};
}
&.collapsed {
display: none;
}
${ripple(theme)}
}
> [data-selected] {
border-bottom: 2px solid ${theme.base0D};
}
}
> div:nth-child(2) {
display: block;
z-index: 10;
button {
display: block;
background: ${theme.base00};
width: 100%;
}
}
`;
| gaearon/redux-devtools | packages/devui/src/Tabs/styles/material.ts | TypeScript | mit | 1,407 |
module Ubidots
module Constants
API_URL = "http://things.ubidots.com/api/v1.6/"
end
end
| ubidots/ubidots-ruby | lib/ubidots/constants.rb | Ruby | mit | 96 |
package com.agamemnus.cordova.plugin;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.os.Bundle;
import java.util.Iterator;
import java.util.Random;
import android.provider.Settings;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.util.Log;
public class AdMob extends CordovaPlugin {
// Common tag used for logging statements.
private static final String LOGTAG = "AdMob";
private static final boolean CORDOVA_4 = Integer.valueOf(CordovaWebView.CORDOVA_VERSION.split("\\.")[0]) >= 4;
// Cordova Actions.
private static final String ACTION_SET_OPTIONS = "setOptions";
private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView";
private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView";
private static final String ACTION_REQUEST_AD = "requestAd";
private static final String ACTION_SHOW_AD = "showAd";
private static final String ACTION_CREATE_INTERSTITIAL_VIEW = "createInterstitialView";
private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd";
private static final String ACTION_SHOW_INTERSTITIAL_AD = "showInterstitialAd";
// Options.
private static final String OPT_AD_ID = "adId";
private static final String OPT_AD_SIZE = "adSize";
private static final String OPT_BANNER_AT_TOP = "bannerAtTop";
private static final String OPT_OVERLAP = "overlap";
private static final String OPT_OFFSET_TOPBAR = "offsetTopBar";
private static final String OPT_IS_TESTING = "isTesting";
private static final String OPT_AD_EXTRAS = "adExtras";
private static final String OPT_AUTO_SHOW = "autoShow";
// The adView to display to the user.
private ViewGroup parentView;
private AdView adView;
// If the user wants banner view overlap webview, we will need this layout.
private RelativeLayout adViewLayout = null;
// The interstitial ad to display to the user.
private InterstitialAd interstitialAd;
private AdSize adSize = AdSize.SMART_BANNER;
private String adId = "";
private boolean bannerAtTop = false;
private boolean bannerOverlap = false;
private boolean offsetTopBar = false;
private boolean isTesting = false;
private boolean bannerShow = true;
private boolean autoShow = true;
private boolean autoShowBanner = true;
private boolean autoShowInterstitial = true;
private boolean bannerVisible = false;
private boolean isGpsAvailable = false;
private JSONObject adExtras = null;
@Override public void initialize (CordovaInterface cordova, CordovaWebView webView) {
super.initialize (cordova, webView);
isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS);
Log.w (LOGTAG, String.format("isGooglePlayServicesAvailable: %s", isGpsAvailable ? "true" : "false"));
}
// This is the main method for the AdMob plugin. All API calls go through here.
// This method determines the action, and executes the appropriate call.
//
// @param action The action that the plugin should execute.
// @param inputs The input parameters for the action.
// @param callbackContext The callback context.
// @return A PluginResult representing the result of the provided action.
// A status of INVALID_ACTION is returned if the action is not recognized.
@Override public boolean execute (String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
PluginResult result = null;
if (ACTION_SET_OPTIONS.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeSetOptions(options, callbackContext);
} else if (ACTION_CREATE_BANNER_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateBannerView(options, callbackContext);
} else if (ACTION_CREATE_INTERSTITIAL_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateInterstitialView(options, callbackContext);
} else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) {
result = executeDestroyBannerView(callbackContext);
} else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestInterstitialAd(options, callbackContext);
} else if (ACTION_REQUEST_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestAd(options, callbackContext);
} else if (ACTION_SHOW_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowAd(show, callbackContext);
} else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowInterstitialAd(show, callbackContext);
} else {
Log.d (LOGTAG, String.format("Invalid action passed: %s", action));
result = new PluginResult(Status.INVALID_ACTION);
}
if (result != null) callbackContext.sendPluginResult (result);
return true;
}
private PluginResult executeSetOptions (JSONObject options, CallbackContext callbackContext) {
Log.w (LOGTAG, "executeSetOptions");
this.setOptions (options);
callbackContext.success ();
return null;
}
private void setOptions (JSONObject options) {
if (options == null) return;
if (options.has(OPT_AD_ID)) this.adId = options.optString (OPT_AD_ID);
if (options.has(OPT_AD_SIZE)) this.adSize = adSizeFromString (options.optString(OPT_AD_SIZE));
if (options.has(OPT_BANNER_AT_TOP)) this.bannerAtTop = options.optBoolean (OPT_BANNER_AT_TOP);
if (options.has(OPT_OVERLAP)) this.bannerOverlap = options.optBoolean (OPT_OVERLAP);
if (options.has(OPT_OFFSET_TOPBAR)) this.offsetTopBar = options.optBoolean (OPT_OFFSET_TOPBAR);
if (options.has(OPT_IS_TESTING)) this.isTesting = options.optBoolean (OPT_IS_TESTING);
if (options.has(OPT_AD_EXTRAS)) this.adExtras = options.optJSONObject (OPT_AD_EXTRAS);
if (options.has(OPT_AUTO_SHOW)) this.autoShow = options.optBoolean (OPT_AUTO_SHOW);
}
// Parses the create banner view input parameters and runs the create banner
// view action on the UI thread. If this request is successful, the developer
// should make the requestAd call to request an ad for the banner.
//
// @param inputs The JSONArray representing input parameters. This function
// expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not the banner was created successfully.
private PluginResult executeCreateBannerView (JSONObject options, final CallbackContext callbackContext) {
this.setOptions (options);
autoShowBanner = autoShow;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
boolean adViewWasNull = (adView == null);
if (adView == null) {
adView = new AdView (cordova.getActivity());
adView.setAdUnitId (adId);
adView.setAdSize (adSize);
}
if (adView.getParent() != null) ((ViewGroup)adView.getParent()).removeView(adView);
if (adViewLayout == null) {
adViewLayout = new RelativeLayout(cordova.getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
if (CORDOVA_4) {
((ViewGroup) webView.getView().getParent()).addView(adViewLayout, params);
} else {
((ViewGroup) webView).addView(adViewLayout, params);
}
}
bannerVisible = false;
adView.loadAd (buildAdRequest());
if (adViewWasNull) adView.setAdListener (new BannerListener());
if (autoShowBanner) executeShowAd (true, null);
callbackContext.success ();
}
});
return null;
}
private PluginResult executeDestroyBannerView (CallbackContext callbackContext) {
Log.w (LOGTAG, "executeDestroyBannerView");
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
if (adView != null) {
ViewGroup parentView = (ViewGroup)adView.getParent();
if (parentView != null) parentView.removeView(adView);
adView.destroy ();
adView = null;
}
bannerVisible = false;
delayCallback.success ();
}
});
return null;
}
// Parses the create interstitial view input parameters and runs the create interstitial
// view action on the UI thread. If this request is successful, the developer should make the requestAd call to request an ad for the banner.
//
// @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not the banner was created successfully.
private PluginResult executeCreateInterstitialView (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
autoShowInterstitial = autoShow;
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable(){
@Override public void run () {
interstitialAd = new InterstitialAd(cordova.getActivity());
interstitialAd.setAdUnitId (adId);
interstitialAd.loadAd (buildAdRequest());
interstitialAd.setAdListener (new InterstitialListener());
delayCallback.success ();
}
});
return null;
}
private AdRequest buildAdRequest () {
AdRequest.Builder request_builder = new AdRequest.Builder();
if (isTesting) {
// This will request test ads on the emulator and deviceby passing this hashed device ID.
String ANDROID_ID = Settings.Secure.getString(cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
String deviceId = md5(ANDROID_ID).toUpperCase();
request_builder = request_builder.addTestDevice(deviceId).addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
}
Bundle bundle = new Bundle();
bundle.putInt("cordova", 1);
if (adExtras != null) {
Iterator<String> it = adExtras.keys();
while (it.hasNext()) {
String key = it.next();
try {
bundle.putString(key, adExtras.get(key).toString());
} catch (JSONException exception) {
Log.w (LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage()));
}
}
}
AdMobExtras adextras = new AdMobExtras (bundle);
request_builder = request_builder.addNetworkExtras (adextras);
AdRequest request = request_builder.build ();
return request;
}
// Parses the request ad input parameters and runs the request ad action on
// the UI thread.
//
// @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not an ad was requested succcessfully.
// Listen for onReceiveAd() and onFailedToReceiveAd() callbacks to see if an ad was successfully retrieved.
private PluginResult executeRequestAd (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
if (adView == null) {
callbackContext.error ("adView is null, call createBannerView first");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
adView.loadAd (buildAdRequest());
delayCallback.success ();
}
});
return null;
}
private PluginResult executeRequestInterstitialAd (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
if (adView == null) {
callbackContext.error ("interstitialAd is null: call createInterstitialView first.");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
interstitialAd.loadAd (buildAdRequest());
delayCallback.success ();
}
});
return null;
}
// Parses the show ad input parameters and runs the show ad action on the UI thread.
//
// @param inputs The JSONArray representing input parameters. This function
// expects the first object in the array to be a JSONObject with the
// input parameters.
// @return A PluginResult representing whether or not an ad was requested
// succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
// callbacks to see if an ad was successfully retrieved.
private PluginResult executeShowAd (final boolean show, final CallbackContext callbackContext) {
bannerShow = show;
if (adView == null) return new PluginResult (Status.ERROR, "adView is null: call createBannerView first.");
cordova.getActivity().runOnUiThread (new Runnable(){
@Override public void run () {
if(bannerVisible == bannerShow) { // No change.
} else if (bannerShow) {
if (adView.getParent() != null) {
((ViewGroup)adView.getParent()).removeView(adView);
}
if (bannerOverlap) {
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.addRule(bannerAtTop ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.ALIGN_PARENT_BOTTOM);
adViewLayout.addView(adView, params2);
adViewLayout.bringToFront();
} else {
if (CORDOVA_4) {
ViewGroup wvParentView = (ViewGroup) webView.getView().getParent();
if (parentView == null) {
parentView = new LinearLayout(webView.getContext());
}
if (wvParentView != null && wvParentView != parentView) {
wvParentView.removeView(webView.getView());
((LinearLayout) parentView).setOrientation(LinearLayout.VERTICAL);
parentView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
webView.getView().setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0F));
parentView.addView(webView.getView());
cordova.getActivity().setContentView(parentView);
}
} else {
parentView = (ViewGroup) ((ViewGroup) webView).getParent();
}
if (bannerAtTop) {
parentView.addView (adView, 0);
} else {
parentView.addView (adView);
}
parentView.bringToFront ();
parentView.requestLayout();
}
adView.setVisibility (View.VISIBLE);
bannerVisible = true;
} else {
adView.setVisibility (View.GONE);
bannerVisible = false;
}
if (callbackContext != null) callbackContext.success ();
}
});
return null;
}
private PluginResult executeShowInterstitialAd (final boolean show, final CallbackContext callbackContext) {
if (interstitialAd == null) return new PluginResult(Status.ERROR, "interstitialAd is null: call createInterstitialView first.");
cordova.getActivity().runOnUiThread (new Runnable () {
@Override public void run () {
if (interstitialAd.isLoaded()) interstitialAd.show ();
if (callbackContext != null) callbackContext.success ();
}
});
return null;
}
// This class implements the AdMob ad listener events. It forwards the events to the JavaScript layer. To listen for these events, use:
// document.addEventListener ('onReceiveAd' , function());
// document.addEventListener ('onFailedToReceiveAd', function(data){});
// document.addEventListener ('onPresentAd' , function());
// document.addEventListener ('onDismissAd' , function());
// document.addEventListener ('onLeaveToAd' , function());
public class BasicListener extends AdListener {
@Override public void onAdFailedToLoad (int errorCode) {
webView.loadUrl (String.format(
"javascript:cordova.fireDocumentEvent('onFailedToReceiveAd', { 'error': %d, 'reason':'%s' });",
errorCode, getErrorReason(errorCode))
);
}
}
private class BannerListener extends BasicListener {
@Override public void onAdLoaded () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveAd');");}
@Override public void onAdOpened () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentAd');");}
@Override public void onAdClosed () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissAd');");}
@Override public void onAdLeftApplication () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToAd');");}
}
private class InterstitialListener extends BasicListener {
@Override public void onAdLoaded () {
Log.w ("AdMob", "InterstitialAdLoaded");
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveInterstitialAd');");
if (autoShowInterstitial) executeShowInterstitialAd (true, null);
}
@Override public void onAdOpened () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentInterstitialAd');");
}
@Override public void onAdClosed () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissInterstitialAd');");
interstitialAd = null;
}
@Override public void onAdLeftApplication () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToInterstitialAd');");
interstitialAd = null;
}
}
@Override public void onPause (boolean multitasking) {
if (adView != null) adView.pause ();
super.onPause (multitasking);
}
@Override public void onResume (boolean multitasking) {
super.onResume (multitasking);
isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS);
if (adView != null) adView.resume ();
}
@Override public void onDestroy () {
if (adView != null) {
adView.destroy ();
adView = null;
}
if (adViewLayout != null) {
ViewGroup parentView = (ViewGroup)adViewLayout.getParent();
if(parentView != null) {
parentView.removeView(adViewLayout);
}
adViewLayout = null;
}
super.onDestroy ();
}
/**
* Gets an AdSize object from the string size passed in from JavaScript.
* Returns null if an improper string is provided.
*
* @param size The string size representing an ad format constant.
* @return An AdSize object used to create a banner.
*/
public static AdSize adSizeFromString (String size) {
if ("BANNER".equals(size)) {
return AdSize.BANNER;
} else if ("IAB_MRECT".equals(size)) {
return AdSize.MEDIUM_RECTANGLE;
} else if ("IAB_BANNER".equals(size)) {
return AdSize.FULL_BANNER;
} else if ("IAB_LEADERBOARD".equals(size)) {
return AdSize.LEADERBOARD;
} else if ("SMART_BANNER".equals(size)) {
return AdSize.SMART_BANNER;
} else {
return null;
}
}
/** Gets a string error reason from an error code. */
public String getErrorReason (int errorCode) {
String errorReason = "";
switch(errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
public static final String md5 (final String s) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance ("MD5");
digest.update (s.getBytes());
byte messageDigest[] = digest.digest ();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2) h = "0" + h;
hexString.append (h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
}
return "";
}
}
| agamemnus/cordova-plugin-admob | src/android/AdMob.java | Java | mit | 20,788 |
exports.up = function (knex, Promise) {
return Promise.all([
knex.schema.createTable('locations', function (table) {
table.uuid('id').notNullable().primary()
table.string('title').notNullable().unique()
table.text('description')
table.string('address_1')
table.string('address_2')
table.string('town')
table.string('county')
table.string('zipcode')
table.string('country')
}),
knex.schema.createTable('conferences', function (table) {
table.uuid('id').notNullable().primary()
table.string('title').notNullable().unique()
table.text('description')
table.string('organiser').notNullable().unique()
table.dateTime('startTime')
table.dateTime('endTime')
table.uuid('location').references('locations.id')
})
])
}
exports.down = function (knex, Promise) {
return Promise.all([
knex.schema.dropTable('conferences'),
knex.schema.dropTable('locations')
])
}
| ztolley/conference-digital-web | src/db/migrations/20161212145712_location_conference.js | JavaScript | mit | 978 |
<?php
namespace Zeeml\DataSet\Exception;
class UnknownDataSetTypeException extends \Exception
{
}
| Zeeml/Dataset | src/Exception/UnknownDataSetTypeException.php | PHP | mit | 100 |
class Solution {
public:
vector<int> ori, cur;
random_device rd;
mt19937 g;
Solution(vector<int> nums) : ori(nums), cur(nums), g(rd()) {
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return cur = ori;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
std::shuffle(cur.begin(), cur.end(), g);
return cur;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* vector<int> param_1 = obj.reset();
* vector<int> param_2 = obj.shuffle();
*/ | llwwns/leetcode_solutions | 384#shuffle-an-array/solution.cpp | C++ | mit | 672 |
@extends('layouts.app_defect_vk')
@section('content')
<div class='col-sm-4 col-sm-offset-4'>
<h2></i> Изменить
<div class="pull-right">
{!! Form::open(['url' => '/defect/vkam/tables/ceh/' . $ceh->id, 'method' => 'DELETE']) !!}
{!! Form::submit('Удалить', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
</div>
</h2>
{!! Form::model($ceh, ['role' => 'form', 'url' => '/defect/vkam/tables/ceh/' . $ceh->id, 'method' => 'PUT']) !!}
<div class='form-group'>
{!! Form::label('ceh_id', 'Код') !!}
{!! Form::text('ceh_id', trim($ceh->ceh_id), ['placeholder' => 'Код', 'class' => 'form-control']) !!}
</div>
<div class='form-group'>
{!! Form::label('ceh_short', 'Краткое имя') !!}
{!! Form::text('ceh_short', trim($ceh->ceh_short), ['placeholder' => 'Краткое имя', 'class' => 'form-control']) !!}
</div>
<div class='form-group'>
{!! Form::label('ceh_name', 'Имя') !!}
{!! Form::text('ceh_name', trim($ceh->ceh_name), ['placeholder' => 'Имя', 'class' => 'form-control']) !!}
</div>
<div class='form-group'>
{!! Form::submit('Сохранить', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
@if ($errors->has())
@foreach ($errors->all() as $error)
<div class='bg-danger alert'>{{ $error }}</div>
@endforeach
@endif
</div>
@stop
| jips/mls-laravel | resources/views/defect/vkam/tables/ceh_edit.blade.php | PHP | mit | 1,499 |
package fi.ozzi.tapsudraft.service;
import com.google.common.collect.ImmutableMap;
import fi.ozzi.tapsudraft.model.Player;
import fi.ozzi.tapsudraft.model.Position;
import fi.ozzi.tapsudraft.repository.PlayerRepository;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PlayerFetchService {
private static final Logger LOG = LoggerFactory.getLogger(PlayerFetchService.class);
@Value("${service.playerfetch.baseUrl}")
private String baseUrl;
@NonNull
private PlayerRepository playerRepository;
@Scheduled(cron = "${service.playerfetch.cron}")
public void fetchPlayers() throws IOException {
Map<String, String> params = ImmutableMap.<String, String>builder()
.put("js", "1")
.put("rand", Float.toString(new Random().nextFloat()))
.put("player_team", "all")
.put("player_value", "all")
.put("type", "player_search")
.put("phase", "0")
.build();
String url = buildUrlFromMap(baseUrl, params);
LOG.debug(url);
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
LOG.debug("HTTP resp " + response.getStatusLine().getStatusCode());
}
Document doc = Jsoup.parse(response.getEntity().getContent(), "UTF-8", url);
Elements positionGroups = doc.getElementsByTag("tbody");
for (Element group : positionGroups) {
Elements rows = group.getElementsByTag("tr");
for (Element row : rows) {
Element nameData = row.select("td.name_data").first();
String name = nameData.text().trim();
String team = nameData.select("a.logo").first().attr("title");
team = team.substring(team.indexOf("(")+1, team.indexOf(")"));
String position = nameData.select("input[name=player_position]").first().val();
String playerUid = nameData.select("input[name=player_id]").first().val();
Player player = playerRepository.findByUid(Long.parseLong(playerUid));
if (player == null) {
playerRepository.save(
Player.builder()
.name(name)
.uid(Long.parseLong(playerUid))
.position(Position.fromCharacter(position))
.build());
}
String price = row.select("td[id~=.*_player_value]").first().text();
String points = row.select("td[title=IS Liigapörssi-pisteet]").first().text();
}
}
}
private static String buildUrlFromMap(String baseUrl, Map<String, String> params) {
String queryString = params.keySet().stream()
.map(key -> {
try {
return key + "=" + URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Error: could not URL-encode value";
}).collect(Collectors.joining("&"));
return baseUrl + "?" + queryString;
}
}
| osmoossi/tapsudraft | src/main/java/fi/ozzi/tapsudraft/service/PlayerFetchService.java | Java | mit | 3,834 |