answer
stringlengths 15
1.25M
|
|---|
require 'compiler_helper'
module Alf
class Compiler
describe Default, "join" do
subject{
compiler.call(expr)
}
let(:right){
compact(an_operand)
}
let(:expr){
join(an_operand(leaf), right)
}
<API key> "a traceable compiled"
it 'is a Join::Hash cog' do
subject.should be_a(Engine::Join::Hash)
end
it 'has the correct left sub-cog' do
subject.left.should be(leaf)
end
it 'has the correct right sub-cog' do
subject.right.should be_a(Engine::Compact)
end
end
end
end
|
@ru
<p>На сервисе <a class="link" href="https:
@en
<p>You can get €10 discount on <a class="link" href="https:
@endru
|
<?php
// somewhere in your theme.
?>
<?php if (!get_theme_mod('hide-header')) { ?>
<header class="container-fluid">
<div class="row">
<div class="banner navbar navbar-default navbar-static-top affix" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only"><?= __('Toggle navigation', 'sage'); ?></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?= esc_url(home_url('/')); ?>">
<?php
/**
* Display logo from Appearance > Customize or blog name if logo not set
*/
has_custom_logo() ? Roots\Sage\Extras\<API key>() : bloginfo('name'); ?>
</a>
</div>
<nav class="collapse navbar-collapse" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu([
'theme_location' => 'primary_navigation'
, 'walker' => new <API key>()
, 'menu_class' => 'nav navbar-nav pull-right'
]);
endif;
?>
</nav>
</div><!-- /.container -->
</div><!-- /.navbar -->
</div><!-- /.row -->
<?php
/**
* Pull in header content defined by ACF plugin
*/
if (class_exists('acf')) {
get_template_part('templates/components/header-content');
}
?>
</header><!-- /.container-fluid -->
<?php } ?>
|
<?php
namespace Test\LitGroup\Enumerable;
use LitGroup\Enumerable\Test\EnumerableTestCase;
use Test\LitGroup\Enumerable\Fixtures\AnotherColorEnum;
use Test\LitGroup\Enumerable\Fixtures\ColorEnum;
use Test\LitGroup\Enumerable\Fixtures\DuplicateIndexEnum;
use Test\LitGroup\Enumerable\Fixtures\FloatIndexedEnum;
use Test\LitGroup\Enumerable\Fixtures\<API key>;
use Test\LitGroup\Enumerable\Fixtures\<API key>;
use Test\LitGroup\Enumerable\Fixtures\SerializableEnum;
use Test\LitGroup\Enumerable\Fixtures\NonFinalEnum;
class EnumerableTest extends EnumerableTestCase
{
public function testIndex()
{
$this-><API key>([
ColorEnum::RED => ColorEnum::red(),
ColorEnum::GREEN => ColorEnum::green(),
ColorEnum::BLUE => ColorEnum::blue(),
]);
}
public function testEquality()
{
$this->assertEquals(ColorEnum::red(), ColorEnum::red());
$this->assertNotEquals(ColorEnum::red(), ColorEnum::green());
$this->assertTrue(ColorEnum::red()->equals(ColorEnum::red()));
$this->assertFalse(ColorEnum::red()->equals(ColorEnum::blue()));
}
public function <API key>()
{
$this->expectException(\<API key>::class);
ColorEnum::red()->equals(AnotherColorEnum::red());
}
public function testIdentity()
{
$this->assertSame(ColorEnum::red(), ColorEnum::red());
$this->assertNotSame(ColorEnum::red(), ColorEnum::green());
}
public function testSwitchStatement()
{
switch (ColorEnum::green()) {
case ColorEnum::green():
break;
default:
$this->fail('GREEN case had to be called.');
}
}
public function testGetValueOf()
{
$this->assertSame(ColorEnum::red(), ColorEnum::getValueOf(ColorEnum::RED));
$this->assertSame(ColorEnum::green(), ColorEnum::getValueOf(ColorEnum::GREEN));
$this->assertSame(ColorEnum::blue(), ColorEnum::getValueOf(ColorEnum::BLUE));
}
public function <API key>()
{
$this->expectException(\<API key>::class);
ColorEnum::getValueOf('incorrect_index');
}
public function testGetValues()
{
$this->assertSame(
[
ColorEnum::RED => ColorEnum::red(),
ColorEnum::GREEN => ColorEnum::green(),
ColorEnum::BLUE => ColorEnum::blue(),
],
ColorEnum::getValues()
);
}
public function <API key>()
{
$this->expectException(\LogicException::class);
$this-><API key>('Enumerable class must be final, but "Test\LitGroup\Enumerable\Fixtures\NonFinalEnum" is not final');
NonFinalEnum::getValues();
}
public function <API key>()
{
$this->expectException(\LogicException::class);
$this-><API key>('Enumerable cannot be serializable, but enum class "Test\LitGroup\Enumerable\Fixtures\SerializableEnum" implements "Serializable" interface');
SerializableEnum::getValues();
}
public function <API key>()
{
$this->expectException(\LogicException::class);
DuplicateIndexEnum::some();
}
public function <API key>()
{
$this->expectException(\<API key>::class);
FloatIndexedEnum::one();
}
public function <API key>()
{
$this->expectException(\LogicException::class);
<API key>::getValues();
}
public function <API key>()
{
$this->expectException(\LogicException::class);
<API key>::getValues();
}
public function testClone(): void
{
$red = ColorEnum::red();
$this->expectException(\<API key>::class);
$otherRed = clone $red;
}
public function testSerialize(): void
{
$red = ColorEnum::red();
$this->expectException(\<API key>::class);
serialize($red);
}
}
|
layout: ci_navbar_sidebar
title: Coding Standards
permalink: /practice/ci/coding_standards/
<div class="jumbotron">
<h1><small>Continuous Integration</small></h1>
<h1>Coding Standards Check</h1>
<p>Apply code analysis and styling checks and if unsatisfactory mark the build as a failure</p>
</div>
<div class="row">
<div id="start" class="col-md-10 col-md-offset-1" style="font-size:140%">
<h2>About</h2>
<p>Code can be written that appears to perform the required task; however, is it coded with consistency, will it crash if the data input is not 100% correct, have any TODO tags been forgotten?</p>
<p>We can run automated tests for these, and more, and then set our build result to fail if we do not get a satisfactory compliance result.</p>
<h2>Options</h2>
<p>Many packages are available; a search on the internet will return many results. Most will only perform part of the requirement. When selecting packages, try to include: code analysis, styling, open tasks and metrics. Other packages might also be required when handling the results.</p>
<h3>Python Projects</h3>
<p>The Python example below uses the following:</p>
<ul>
<li><h4>PYLINT</h4>
<p>PyLint is a static code analyser of coding standards and quality.</p>
<p>PyLint's tests include checking for docstrings, duplication, open tasks, PEP8 styling and bugs.</p>
<p>It highlights problems and gives the code a score out of 10.</p>
</li>
<li>
<h4>VIOLATIONS PLUGIN</h4>
<p>This Jenkins plugin will display the PyLint results on the Jenkins view of the project.</p>
</li>
<li>
<h4>TEXTFINDER PLUGIN</h4>
<p>This Jenkins plugin will search text files against a regular expression. The result of which can be used to set a build to pass, fail, unstable.</p>
</li>
</ul>
<h3>Java Projects</h3>
<p>TODO</p>
<h2>PyLint</h2>
<h3>Prerequisites</h3>
<h4>PYTHON PACKAGES</h4>
<p><code>pip install pylint</code></p>
<h3>Add to your Project</h3>
<p>Select <button>Add build step</button> and choose "Execute Windows batch command".</p>
<p>Enter in the Command box:</p>
<pre>pylint project_name.py --output-format=parseable | tee pylint.out</pre>
<p>You might need to drag this step to follow existing actions.</p>
<h3>Explanation of Commands</h3>
<p><code>Pylint project_name.py</code>: this starts the pylint application and tells it to analyse the specified python module.</p>
<p>For multiple files names, just add them to the list. There is no current means of specifying <i>all files</i>. Writing a python file discovery function might be worthwhile.</p>
<p>Is there a way of doing this programmatically? - <i>Under investigation.</i></p>
<p><code>--output-format=parseable</code>: the output can be in many formats, including text and html. Parseable is a format that the Violations plugin can read.</p>
<p><code>| tee pylint.out</code>: The pipe (|) is a means of redirecting the output, tee sends the output to both the screen and to a file, in this case a file named pylint.out.</p>
<p><img src="../../../images/ci/<API key>.png" alt="Screenshot of PyLint configuration in Jenkins" class = "img-thumbnail"/></p>
<h3>Example</h3>
<p>Click <a href="/practice/<API key>">here</a> for a simple example of PyLint's text output for the calculator.</p>
<p>Lint report graph</p>
<h3>Customization</h3>
<p>PyLint tests can be tailored to your requires by using the a config file (rcfile). Enter <code>pylint --help</code> in the command line for info. <code>--generate-rcfile, --rcfile=<file></code></p>
<h2>Violations Plugin</h2>
<h3>Prerequisites</h3>
<p>"Violations plugin"</p>
<h3>Add to your Project</h3>
<p>Select <button>Add post-build action</button> and choose <samp>Report Violations</samp>.</p>
<p>A long list of options will appear; we only need to complete the line for <samp>pylint</samp>. Place the file name in the box provided, e.g. <code>**/pylint.out</code></p>
<h3>Example</h3>
<p><img src="../../../images/ci/<API key>.png" alt="Screenshot of Violations report" class = "img-thumbnail"></p>
<p>Running the project a few times will provide a graph that can be drilled down to the detail.</p>
<p><img src="../../../images/ci/<API key>.png" alt="Screenshot of PyLint report" class = "img-thumbnail"></p>
<p><img src="../../../images/ci/<API key>.png" alt="Screenshot of PyLint report drill down level 1" class = "img-thumbnail"></p>
<p><img src="../../../images/ci/<API key>.png" alt="Screenshot of PyLint report drill down level 2" class = "img-thumbnail"></p>
<h2>TextFinder</h2>
<h3>Prerequisites</h3>
<p>"TextFinder plugin"</p>
<h3>Add to your Project</h3>
<p>In this example, we scan the output of PyLint for the rating. If the rating is lower than eight the build is marked as unstable.</p>
<p>Select <button>Add post-build action</button> and choose "Jenkins Text Finder".</p>
<p>Enter the file name of the PyLint output file, for example, pylint.out.</p>
<p>For the "Regular expression" enter: <code>"Your code has been rated at ([0-7]).\d*\/10"</code></p>
<p>Then tick the "Unstable if found" option.</p>
<p>Note that using "Succeed if found" will override previously obtained Fail results.</p>
<p><img src="../../../images/ci/<API key>.png" class="img-thumbnail" alt="Screenshot of TextFinder"></p>
<h3>Explanation of Regular Expression</h3>
<p>This expression checks for the string "Your code has been rated at".</p>
<p>Then it checks for 0 to 7, a decimal point, and any number of digits.</p>
<p>Then it checks for "/10" to check that the value has been scored out of ten.</p>
<p>If a rating less than 8 out of ten is present, the expression is true.</p>
<p>If a rating 8 or more out of ten is present, the expression is false.</p>
<h3>Example</h3>
<p>In the screenshot below you can see build #82 and #83 set to unstable due to a low score obtained in PyLint.</p>
<p><img src="../../../images/ci/<API key>.png" class="img-thumbnail" alt="Screenshot showing unstable build in Build History"></p>
<h2>Open Tasks</h2>
<p>The PyLint report includes Open Tasks; nevertheless, if you want the Open Tasks count on the project view screen, you need the Open Tasks Plugin.</p>
<p>If required, add the plugin and configure it with the open task keywords, such as, TODO and FIXME.</p>
<p><img src="../../../images/ci/<API key>.png" class="img-thumbnail" alt="Screenshot showing Open Tasks configuration"></p>
<p>After a build, the count will show on the project view that one can select and drill down.</p>
<p><img src="../../../images/ci/<API key>.png" class="img-thumbnail" alt="Screenshot showing Open Tasks count"></p>
<p><img src="../../../images/ci/<API key>.png" class="img-thumbnail" alt="Screenshot showing Open Tasks drill down"></p>
</div>
</div>
|
$(document).ready(function() {
$(document).on('submit', '.status-button', function(e) {
e.preventDefault();
var joinButton = e.target
$.ajax(joinButton.action, {
method: 'PATCH',
data: $(this).serialize()
})
.done(function(data) {
gameDiv = $(joinButton).parent();
gameDiv.replaceWith(data);
})
.fail(function() {
alert("Failure!");
});
});
});
|
require_relative 'spec_helper.rb'
feature "can deal cards" do
before do
<API key>("jnmandal", "bsheridan12")
end
scenario "allows you to choose amount of cards dealt" do
in_browser(:one) do
expect(page).to have_field "initial-deal-count"
end
end
scenario "deal cards button deals cards" do
in_browser(:one) do
deal_cards(4)
within "div.player-hand" do
expect(page).to have_selector ".card"
end
end
end
scenario "dealt cards viewable by other user" do
in_browser(:one) do
deal_cards(4)
end
in_browser(:two) do
within "div.player-hand" do
expect(page).to have_selector ".card"
end
end
end
scenario "does not deal cards when user enters 0" do
in_browser(:one) do
deal_cards(0)
end
in_browser(:two) do
within "div.player-hand" do
page.assert_no_selector(".card")
end
end
end
scenario "deals correct number of cards" do
in_browser(:one) do
deal_cards(5)
within "div.player-hand" do
page.assert_selector(".card", count: 5)
end
end
end
end
|
function <API key>() {
'ngInject';
// ViewModel
const vm = this;
console.log('<API key>');
}
export default {
name: '<API key>',
fn: <API key>
};
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# all copies or substantial portions of the Software.
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# 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.
from __future__ import division
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b))
def GD(PF0, PFc):
up = 0
for i in PFc:
up += min([dist(i, j) for j in PF0])
return up**0.5 / (len(PFc))
|
import React, { Component } from 'react';
import Header from './Header';
import MainSection from './MainSection';
export default class App extends Component {
render() {
return (
<div>
<Header/>
<MainSection/>
</div>
);
}
}
|
import unittest
from unittest import skip
from decimal import Decimal
from cnab240 import errors
from cnab240.bancos import itau
from tests.data import <API key>
class TestRegistro(unittest.TestCase):
def setUp(self):
itau_data = <API key>()
self.header_arquivo = itau_data['header_arquivo']
self.seg_p = itau_data['seg_p1']
self.seg_p_str = itau_data['seg_p1_str']
self.seg_q = itau_data['seg_q1']
self.seg_q_str = itau_data['seg_q1_str']
def <API key>(self):
self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00'))
def <API key>(self):
# aceitar somente tipo Decimal
with self.assertRaises(errors.TipoError):
self.seg_p.valor_titulo = 10.0
with self.assertRaises(errors.TipoError):
self.seg_p.valor_titulo = ''
# Testa se as casas decimais estao sendo verificadas
with self.assertRaises(errors.NumDecimaisError):
self.seg_p.valor_titulo = Decimal('100.2')
with self.assertRaises(errors.NumDecimaisError):
self.seg_p.valor_titulo = Decimal('1001')
with self.assertRaises(errors.NumDecimaisError):
self.seg_p.valor_titulo = Decimal('1.000')
# verifica se o numero de digitos esta sendo verificado
with self.assertRaises(errors.<API key>):
self.seg_p.valor_titulo = Decimal('10000000008100.21')
# armazemamento correto de um decimal
self.seg_p.valor_titulo = Decimal('2.13')
self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13'))
def <API key>(self):
self.assertEqual(self.header_arquivo.controle_banco, 341)
def <API key>(self):
# aceitar somente inteiros (int e long)
with self.assertRaises(errors.TipoError):
self.header_arquivo.controle_banco = 10.0
with self.assertRaises(errors.TipoError):
self.header_arquivo.controle_banco = ''
# verifica se o numero de digitos esta sendo verificado
with self.assertRaises(errors.<API key>):
self.header_arquivo.controle_banco = <API key>
with self.assertRaises(errors.<API key>):
self.header_arquivo.controle_banco = 1234
# verifica valor armazenado
self.header_arquivo.controle_banco = 5
self.assertEqual(self.header_arquivo.controle_banco, 5)
def <API key>(self):
self.assertEqual(self.header_arquivo.cedente_nome,
'TRACY TECNOLOGIA LTDA ME')
@skip
def <API key>(self):
# Testa que serao aceitos apenas unicode objects
with self.assertRaises(errors.TipoError):
self.header_arquivo.cedente_nome = 'tracy'
# Testa que strings mais longas que obj.digitos nao serao aceitas
with self.assertRaises(errors.<API key>):
self.header_arquivo.cedente_convenio = '<API key>'
# Testa que o valor atribuido foi guardado no objeto
self.header_arquivo.cedente_nome = 'tracy'
self.assertEqual(self.header_arquivo.cedente_nome, 'tracy')
def test_fromdict(self):
header_dict = self.header_arquivo.todict()
header_arquivo = itau.registros.HeaderArquivo(**header_dict)
self.assertEqual(header_arquivo.cedente_nome,
'TRACY TECNOLOGIA LTDA ME')
self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA')
def test_necessario(self):
self.assertTrue(self.seg_p)
seg_p2 = itau.registros.SegmentoP()
self.assertFalse(seg_p2.necessario())
seg_p2.controle_banco = 33
self.assertFalse(seg_p2.necessario())
seg_p2.vencimento_titulo = 10102012
self.assertTrue(seg_p2.necessario())
def test_unicode(self):
def unicode_test(seg_instance, seg_str):
seg_gen_str = str(seg_instance)
self.assertEqual(len(seg_gen_str), 240)
self.assertEqual(len(seg_str), 240)
self.assertEqual(seg_gen_str, seg_str)
unicode_test(self.seg_p, self.seg_p_str)
unicode_test(self.seg_q, self.seg_q_str)
if __name__ == '__main__':
unittest.main()
|
// Purpose: An extra interface implemented by the material system
// implementation of vgui::ISurface
// $Revision: $
// $NoKeywords: $
#ifndef IMATSYSTEMSURFACE_H
#define IMATSYSTEMSURFACE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include "vgui/ISurface.h"
// Forward declarations
class VMatrix;
class IMaterial;
struct InputEvent_t;
// Callbacks for mouse getting + setting
typedef void (*GetMouseCallback_t)(int &x, int &y);
typedef void (*SetMouseCallback_t)(int x, int y);
// Callbacks for sound playing
typedef void (*PlaySoundFunc_t)(const char *pFileName);
// An extra interface implemented by the material system implementation of vgui::ISurface
#define <API key> "MatSystemSurface008"
class IMatSystemSurface : public vgui::ISurface
{
public:
// Hook needed to get input to work.
// If the app drives the input (like the engine needs to do for VCR mode),
// it can set bLetAppDriveInput to true and call HandleInputEvent for the input events.
virtual void AttachToWindow( void *hwnd, bool bLetAppDriveInput=false ) = 0;
// Tells the surface to ignore windows messages
virtual void <API key>( bool bEnable ) = 0;
// Starts, ends 3D painting
// NOTE: These methods should only be called from within the paint()
// method of a panel.
virtual void Begin3DPaint( int iLeft, int iTop, int iRight, int iBottom, bool bRenderToTexture = true ) = 0;
virtual void End3DPaint() = 0;
// NOTE: This also should only be called from within the paint()
// method of a panel. Use it to disable clipping for the rendering
// of this panel.
virtual void DisableClipping( bool bDisable ) = 0;
virtual void GetClippingRect( int &left, int &top, int &right, int &bottom, bool &bClippingDisabled ) = 0; // <<<<< NOTE: output flag is *disabled* state, not enabled, to match the rest of the interface
virtual void SetClippingRect( int left, int top, int right, int bottom ) = 0;
// Prevents vgui from changing the cursor
virtual bool IsCursorLocked() const = 0;
// Sets the mouse get + set callbacks
virtual void SetMouseCallbacks( GetMouseCallback_t getFunc, SetMouseCallback_t setFunc ) = 0;
// Installs a function to play sounds
virtual void <API key>( PlaySoundFunc_t soundFunc ) = 0;
// Some drawing methods that cannot be accomplished under Win32
virtual void DrawColoredCircle( int centerx, int centery, float radius, int r, int g, int b, int a ) = 0;
virtual int DrawColoredText( vgui::HFont font, int x, int y, int r, int g, int b, int a, <API key> const char *fmt, ... ) = 0;
// Draws text with current font at position and wordwrapped to the rect using color values specified
virtual void DrawColoredTextRect( vgui::HFont font, int x, int y, int w, int h, int r, int g, int b, int a, <API key> const char *fmt, ... ) = 0;
virtual void DrawTextHeight( vgui::HFont font, int w, int& h, <API key> const char *fmt, ... ) = 0;
// Returns the length of the text string in pixels
virtual int DrawTextLen( vgui::HFont font, <API key> const char *fmt, ... ) = 0;
// Draws a panel in 3D space. Assumes view + projection are already set up
// Also assumes the (x,y) coordinates of the panels are defined in 640xN coords
// (N isn't necessary 480 because the panel may not be 4x3)
// The width + height specified are the size of the panel in world coordinates
virtual void DrawPanelIn3DSpace( vgui::VPANEL pRootPanel, const VMatrix &panelCenterToWorld, int nPixelWidth, int nPixelHeight, float flWorldWidth, float flWorldHeight ) = 0;
// Binds a material to a surface texture ID
virtual void <API key>( int id, IMaterial *pMaterial ) = 0;
// Handles an input event, returns true if the event should be filtered from the rest of the game
virtual bool HandleInputEvent( const InputEvent_t &event ) = 0;
virtual void <API key>( const char *pRenderTargetName ) = 0;
virtual void <API key>( void ) = 0;
// Gets a material bound to a surface texture ID
virtual IMaterial *<API key>( int id ) = 0;
virtual void <API key>( int & x, int & y, int & w, int & h, ITexture **ppRenderTarget ) = 0;
virtual void <API key>( int x, int y, int w, int h, ITexture *pRenderTarget ) = 0;
};
#endif // IMATSYSTEMSURFACE_H
|
#!/usr/bin/env python3
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# 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:
# all copies or substantial portions of the Software.
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# 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.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def <API key>(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
value = value.replace("
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=<API key>)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class <API key> extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->booting(function(){
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
/*
|
| Interfaces
|
*/
//<API key>
/*
|
| Repositories Classes
|
*/
//<API key>
/*
|
| Object Classes
|
*/
//<API key>
/*
|
| Traits
|
*/
$loader->alias('CRUDtrait', 'App\Http\Traits\CRUDtrait');
//<API key>
/*
|
| Motors
|
*/
$loader->alias('Motor', 'App\Http\Motors\Motor');
//<API key>
});
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 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.
#endregion
namespace EULex.SimpleSOAPClient.Helpers
{
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;
<summary>
Helper class with extensions for XML manipulation
</summary>
internal static class XmlHelpers
{
private static readonly <API key> <API key>;
static XmlHelpers ()
{
<API key> = new <API key> ();
<API key>.Add ("", "");
}
<summary>
Serializes the given object to a XML string
</summary>
<typeparam name="T">The object type</typeparam>
<param name="item">The item to serialize</param>
<returns>The XML string</returns>
public static string ToXmlString<T> (this T item)
{
if (item == null) return null;
using (var textWriter = new StringWriter ()) {
new XmlSerializer (item.GetType ()).Serialize (textWriter, item, <API key>);
var result = textWriter.ToString ();
return result;
}
}
<summary>
Serializes a given object to XML and returns the <see cref="XElement"/> representation.
</summary>
<typeparam name="T">The object type</typeparam>
<param name="item">The item to convert</param>
<returns>The object as a <see cref="XElement"/></returns>
public static XElement ToXElement<T> (this T item)
{
return item == null ? null : XElement.Parse (item.ToXmlString ());
}
<summary>
Deserializes a given XML string to a new object of the expected type.
If null or white spaces the default(T) will be returned;
</summary>
<typeparam name="T">The type to be deserializable</typeparam>
<param name="xml">The XML string to deserialize</param>
<returns>The deserialized object</returns>
public static T ToObject<T> (this string xml)
{
if (string.IsNullOrWhiteSpace (xml)) return default (T);
using (var textWriter = new StringReader (xml)) {
var result = (T)new XmlSerializer (typeof (T)).Deserialize (textWriter);
return result;
}
}
<summary>
Deserializes a given <see cref="XElement"/> to a new object of the expected type.
If null the default(T) will be returned.
</summary>
<typeparam name="T">The type to be deserializable</typeparam>
<param name="xml">The <see cref="XElement"/> to deserialize</param>
<returns>The deserialized object</returns>
public static T ToObject<T> (this XElement xml)
{
return xml == null ? default (T) : xml.ToString ().ToObject<T> ();
}
}
}
|
#endregion
namespace SolutionValidator.FolderStructure
{
#region using...
using System;
#endregion
public class ParseException : <API key>
{
public ParseException(string message, int lineNumber, int column)
: base(message)
{
LineNumber = lineNumber;
Column = column;
}
public int LineNumber { get; set; }
public int Column { get; set; }
}
}
|
package com.kkk.retrofitdemo;
import com.kkk.retrofitdemo.bean.Repo;
import com.kkk.retrofitdemo.bean.SearchRepoResult;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
@GET("search/repositories")
Observable<SearchRepoResult> searchRepos(@Query("q") String keyword,
@Query("sort") String sort,
@Query("order") String order);
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class <API key> extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('image_url', 768)->change();
$table->string('url', 768)->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('image_url')->change();
$table->string('url')->change();
});
}
}
|
<div class="cms-control-panel" ng-show="ctrl.isAuthenticated()">
<div class="panel-button pull-right"><i class="fa fa-2x fa-cog" ng-click="ctrl.showPanel()"></i></div>
<div class="panel-widget" ng-show="ctrl.panel">
<i class="fa fa-2x fa-save" ng-click="ctrl.save()" ng-hide="saved"></i>
<i class="fa fa-2x fa-ellipsis-h" ng-show="saved"></i>
<i class="fa fa-2x fa-undo" ng-click="ctrl.undo()"></i>
</div>
</div>
|
(function(global) {
var vwl = {};
var receivePoster;
var receiveEntry;
var receiveLoadedList;
// vwl.init - advertise VWL info and register for VWL messages
// Parameters:
// left - (optional) url of this world's initial left entry image
// right - (optional) url of this world's initial right entry image
// receivePosterFunc - (optional) function to handle poster images from other
// worlds
// receiveEntryFunc - (optional) function to handle entry images from other
// worlds
// <API key> - (optional) function to handle list of loaded worlds
vwl.init = function(left, right,
receivePosterFunc,
receiveEntryFunc,
<API key>) {
receivePoster = receivePosterFunc;
receiveEntry = receiveEntryFunc;
receiveLoadedList = <API key>;
receiveEntry && window.addEventListener('message', function(message) {
if (message.source != window || message.origin != window.location.origin)
return;
if (message.data.tabInfo) {
var left = null;
var right = null;
if (message.data.tabInfo.info && message.data.tabInfo.info.entry_image) {
left = message.data.tabInfo.info.entry_image.left_src;
right = message.data.tabInfo.info.entry_image.right_src;
}
receiveEntry(message.data.tabInfo.url, message.data.tabInfo.loaded,
left, right);
}
if (message.data.loadedList !== undefined) {
receiveLoadedList(message.data.loadedList);
}
}, false);
window.postMessage({info:{entry_image:{
left_src:left, right_src:right}}}, '*');
}
// vwl.getInfo - get info (entry image and poster image) on a specific world
// Parameters:
// url - url of worlds to get info on
// getPoster - (optional) if true get the poster image
vwl.getInfo = function(url, getPoster) {
if (receivePoster && getPoster) {
var request = new XMLHttpRequest();
var dir = url.substr(0, url.lastIndexOf('/') + 1);
request.open('GET', dir + 'vwl_info.json');
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var poster = JSON.parse(request.responseText).poster_image;
receivePoster(url,
poster.left_src ? dir + poster.left_src : null,
poster.right_src ? dir + poster.right_src : null,
poster._2d_src ? dir + poster._2d_src : null);
}
else {
receivePoster(url);
}
}
request.send(null);
}
receiveEntry && window.postMessage({getInfo:url}, '*');
}
// vwl.getLoadedList - get the list of loaded worlds
vwl.getLoadedList = function() {
window.postMessage({getLoadedList:true}, '*');
}
// vwl.open - load world
// Parameters:
// url - url of world to open
vwl.open = function(url) {
window.postMessage({open:url}, '*');
}
// vwl.navigate - navigate to a world
// Parameters:
// left - (optional) new left entry image for current world
// right - (optional) new right entry image for current world
// url - url of world to navigate to
vwl.navigate = function(left, right, url) {
var message = {navigate:url};
if (left && right) {
message.info = {entry_image:{left_src:left, right_src:right}};
}
window.postMessage(message, '*');
}
global.vwl = vwl;
}) (window);
|
# -*- coding: utf-8 -*-
"""The initialization file for the Pywikibot framework."""
from __future__ import absolute_import, unicode_literals
__release__ = '2.0b3'
__version__ = '$Id$'
__url__ = 'https:
import datetime
import math
import re
import sys
import threading
import json
if sys.version_info[0] > 2:
from queue import Queue
long = int
else:
from Queue import Queue
from warnings import warn
# Use pywikibot. prefix for all in-package imports; this is to prevent
# confusion with similarly-named modules in version 1 framework, for users
# who want to continue using both
from pywikibot import config2 as config
from pywikibot.bot import (
output, warning, error, critical, debug, stdout, exception,
input, input_choice, input_yn, inputChoice, handle_args, showHelp, ui, log,
calledModuleName, Bot, CurrentPageBot, WikidataBot,
# the following are flagged as deprecated on usage
handleArgs,
)
from pywikibot.exceptions import (
Error, InvalidTitle, BadTitle, NoPage, NoMoveTarget, SectionError,
SiteDefinitionError, NoSuchSite, UnknownSite, UnknownFamily,
UnknownExtension,
NoUsername, UserBlocked,
PageRelatedError, IsRedirectPage, IsNotRedirectPage,
<API key>, PageNotSaved, OtherPageSaveError,
LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError,
EditConflict, PageDeletedConflict, PageCreatedConflict,
ServerError, FatalServerError, Server504Error,
CaptchaError, SpamfilterError, CircularRedirect, <API key>,
WikiBaseError, <API key>,
)
from pywikibot.tools import PY2, UnicodeMixin, redirect_func
from pywikibot.i18n import translate
from pywikibot.data.api import UploadWarning
from pywikibot.diff import PatchManager
import pywikibot.textlib as textlib
import pywikibot.tools
textlib_methods = (
'unescape', 'replaceExcept', 'removeDisabledParts', 'removeHTMLParts',
'isDisabled', 'interwikiFormat', 'interwikiSort',
'getLanguageLinks', '<API key>',
'removeLanguageLinks', '<API key>',
'getCategoryLinks', 'categoryFormat', '<API key>',
'removeCategoryLinks', '<API key>',
'<API key>', 'compileLinkR', '<API key>',
'TimeStripper',
)
__all__ = (
'config', 'ui', 'UnicodeMixin', 'translate',
'Page', 'FilePage', 'Category', 'Link', 'User',
'ItemPage', 'PropertyPage', 'Claim',
'html2unicode', 'url2unicode', 'unicode2html',
'stdout', 'output', 'warning', 'error', 'critical', 'debug',
'exception', 'input_choice', 'input', 'input_yn', 'inputChoice',
'handle_args', 'handleArgs', 'showHelp', 'ui', 'log',
'calledModuleName', 'Bot', 'CurrentPageBot', 'WikidataBot',
'Error', 'InvalidTitle', 'BadTitle', 'NoPage', 'NoMoveTarget',
'SectionError',
'SiteDefinitionError', 'NoSuchSite', 'UnknownSite', 'UnknownFamily',
'UnknownExtension',
'NoUsername', 'UserBlocked', 'UserActionRefuse',
'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage',
'<API key>', 'PageNotSaved', 'OtherPageSaveError',
'LockedPage', 'CascadeLockedPage', 'LockedNoPage', 'NoCreateError',
'EditConflict', 'PageDeletedConflict', 'PageCreatedConflict',
'UploadWarning',
'ServerError', 'FatalServerError', 'Server504Error',
'CaptchaError', 'SpamfilterError', 'CircularRedirect',
'<API key>',
'WikiBaseError', '<API key>',
'<API key>',
)
__all__ += textlib_methods
if PY2:
# T111615: Python 2 requires __all__ is bytes
globals()['__all__'] = tuple(bytes(item) for item in __all__)
for _name in textlib_methods:
target = getattr(textlib, _name)
wrapped_func = redirect_func(target)
globals()[_name] = wrapped_func
deprecated = redirect_func(pywikibot.tools.deprecated)
deprecate_arg = redirect_func(pywikibot.tools.deprecate_arg)
class Timestamp(datetime.datetime):
"""Class for handling MediaWiki timestamps.
This inherits from datetime.datetime, so it can use all of the methods
and operations of a datetime object. To ensure that the results of any
operation are also a Timestamp object, be sure to use only Timestamp
objects (and datetime.timedeltas) in any operation.
Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to
create Timestamp objects from MediaWiki string formats.
As these constructors are typically used to create objects using data
passed provided by site and page methods, some of which return a Timestamp
when previously they returned a MediaWiki string representation, these
methods also accept a Timestamp object, in which case they return a clone.
Use Site.getcurrenttime() for the current time; this is more reliable
than using Timestamp.utcnow().
"""
mediawikiTSFormat = "%Y%m%d%H%M%S"
ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
def clone(self):
"""Clone this instance."""
return self.replace(microsecond=self.microsecond)
@classmethod
def fromISOformat(cls, ts):
"""Convert an ISO 8601 timestamp to a Timestamp object."""
# If inadvertantly passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
return cls.strptime(ts, cls.ISO8601Format)
@classmethod
def fromtimestampformat(cls, ts):
"""Convert a MediaWiki internal timestamp to a Timestamp object."""
# If inadvertantly passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
return cls.strptime(ts, cls.mediawikiTSFormat)
def isoformat(self):
"""
Convert object to an ISO 8601 timestamp accepted by MediaWiki.
datetime.datetime.isoformat does not postfix the ISO formatted date
with a 'Z' unless a timezone is included, which causes MediaWiki
~1.19 and earlier to fail.
"""
return self.strftime(self.ISO8601Format)
toISOformat = redirect_func(isoformat, old_name='toISOformat',
class_name='Timestamp')
def totimestampformat(self):
"""Convert object to a MediaWiki internal timestamp."""
return self.strftime(self.mediawikiTSFormat)
def __str__(self):
"""Return a string format recognized by the API."""
return self.isoformat()
def __add__(self, other):
"""Perform addition, returning a Timestamp instead of datetime."""
newdt = super(Timestamp, self).__add__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
else:
return newdt
def __sub__(self, other):
"""Perform substraction, returning a Timestamp instead of datetime."""
newdt = super(Timestamp, self).__sub__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
else:
return newdt
class Coordinate(object):
"""
Class for handling and storing Coordinates.
For now its just being used for DataSite, but
in the future we can use it for the GeoData extension.
"""
def __init__(self, lat, lon, alt=None, precision=None, globe='earth',
typ="", name="", dim=None, site=None, entity=''):
"""
Represent a geo coordinate.
@param lat: Latitude
@type lat: float
@param lon: Longitude
@type lon: float
@param alt: Altitute? TODO FIXME
@param precision: precision
@type precision: float
@param globe: Which globe the point is on
@type globe: str
@param typ: The type of coordinate point
@type typ: str
@param name: The name
@type name: str
@param dim: Dimension (in meters)
@type dim: int
@param entity: The URL entity of a Wikibase item
@type entity: str
"""
self.lat = lat
self.lon = lon
self.alt = alt
self._precision = precision
if globe:
globe = globe.lower()
self.globe = globe
self._entity = entity
self.type = typ
self.name = name
self._dim = dim
if not site:
self.site = Site().data_repository()
else:
self.site = site
def __repr__(self):
string = 'Coordinate(%s, %s' % (self.lat, self.lon)
if self.globe != 'earth':
string += ', globe="%s"' % self.globe
string += ')'
return string
@property
def entity(self):
if self._entity:
return self._entity
return self.site.globes()[self.globe]
def toWikibase(self):
"""
Export the data to a JSON object for the Wikibase API.
FIXME: Should this be in the DataSite object?
"""
if self.globe not in self.site.globes():
raise <API key>(
u"%s is not supported in Wikibase yet."
% self.globe)
return {'latitude': self.lat,
'longitude': self.lon,
'altitude': self.alt,
'globe': self.entity,
'precision': self.precision,
}
@classmethod
def fromWikibase(cls, data, site):
"""Constructor to create an object from Wikibase's JSON output."""
globes = {}
for k in site.globes():
globes[site.globes()[k]] = k
globekey = data['globe']
if globekey:
globe = globes.get(data['globe'])
else:
# Default to earth or should we use None here?
globe = 'earth'
return cls(data['latitude'], data['longitude'],
data['altitude'], data['precision'],
globe, site=site, entity=data['globe'])
@property
def precision(self):
if not self._precision:
radius = 6378137 # TODO: Support other globes
self._precision = math.degrees(
self._dim / (radius * math.cos(math.radians(self.lat))))
return self._precision
def precisionToDim(self):
"""Convert precision from Wikibase to GeoData's dim."""
raise NotImplementedError
class WbTime(object):
"""A Wikibase time representation."""
PRECISION = {'1000000000': 0,
'100000000': 1,
'10000000': 2,
'1000000': 3,
'100000': 4,
'10000': 5,
'millenia': 6,
'century': 7,
'decade': 8,
'year': 9,
'month': 10,
'day': 11,
'hour': 12,
'minute': 13,
'second': 14
}
FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
def __init__(self, year=None, month=None, day=None,
hour=None, minute=None, second=None,
precision=None, before=0, after=0,
timezone=0, calendarmodel=None, site=None):
"""
Create a new WbTime object.
The precision can be set by the Wikibase int value (0-14) or by a human
readable string, e.g., 'hour'. If no precision is given, it is set
according to the given time units.
"""
if year is None:
raise ValueError('no year given')
self.precision = self.PRECISION['second']
if second is None:
self.precision = self.PRECISION['minute']
second = 0
if minute is None:
self.precision = self.PRECISION['hour']
minute = 0
if hour is None:
self.precision = self.PRECISION['day']
hour = 0
if day is None:
self.precision = self.PRECISION['month']
day = 1
if month is None:
self.precision = self.PRECISION['year']
month = 1
self.year = long(year)
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
self.after = after
self.before = before
self.timezone = timezone
if calendarmodel is None:
if site is None:
site = Site().data_repository()
calendarmodel = site.calendarmodel()
self.calendarmodel = calendarmodel
# if precision is given it overwrites the autodetection above
if precision is not None:
if (isinstance(precision, int) and
precision in self.PRECISION.values()):
self.precision = precision
elif precision in self.PRECISION:
self.precision = self.PRECISION[precision]
else:
raise ValueError('Invalid precision: "%s"' % precision)
@classmethod
def fromTimestr(cls, datetimestr, precision=14, before=0, after=0,
timezone=0, calendarmodel=None, site=None):
match = re.match(r'([-+]?\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z',
datetimestr)
if not match:
raise ValueError(u"Invalid format: '%s'" % datetimestr)
t = match.groups()
return cls(long(t[0]), int(t[1]), int(t[2]),
int(t[3]), int(t[4]), int(t[5]),
precision, before, after, timezone, calendarmodel, site)
def toTimestr(self):
"""
Convert the data to a UTC date/time string.
@return: str
"""
return self.FORMATSTR.format(self.year, self.month, self.day,
self.hour, self.minute, self.second)
def toWikibase(self):
"""
Convert the data to a JSON object for the Wikibase API.
@return: dict
"""
json = {'time': self.toTimestr(),
'precision': self.precision,
'after': self.after,
'before': self.before,
'timezone': self.timezone,
'calendarmodel': self.calendarmodel
}
return json
@classmethod
def fromWikibase(cls, ts):
return cls.fromTimestr(ts[u'time'], ts[u'precision'],
ts[u'before'], ts[u'after'],
ts[u'timezone'], ts[u'calendarmodel'])
def __str__(self):
return json.dumps(self.toWikibase(), indent=4, sort_keys=True,
separators=(',', ': '))
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return u"WbTime(year=%(year)d, month=%(month)d, day=%(day)d, " \
u"hour=%(hour)d, minute=%(minute)d, second=%(second)d, " \
u"precision=%(precision)d, before=%(before)d, after=%(after)d, " \
u"timezone=%(timezone)d, calendarmodel='%(calendarmodel)s')" \
% self.__dict__
class WbQuantity(object):
"""A Wikibase quantity representation."""
def __init__(self, amount, unit=None, error=None):
if amount is None:
raise ValueError('no amount given')
if unit is None:
unit = '1'
self.amount = amount
self.unit = unit
upperError = lowerError = 0
if isinstance(error, tuple):
upperError, lowerError = error
elif error is not None:
upperError = lowerError = error
self.upperBound = self.amount + upperError
self.lowerBound = self.amount - lowerError
def toWikibase(self):
"""Convert the data to a JSON object for the Wikibase API."""
json = {'amount': self.amount,
'upperBound': self.upperBound,
'lowerBound': self.lowerBound,
'unit': self.unit
}
return json
@classmethod
def fromWikibase(cls, wb):
"""
Create a WbQuanity from the JSON data given by the Wikibase API.
@param wb: Wikibase JSON
"""
amount = eval(wb['amount'])
upperBound = eval(wb['upperBound'])
lowerBound = eval(wb['lowerBound'])
error = (upperBound - amount, amount - lowerBound)
return cls(amount, wb['unit'], error)
def __str__(self):
return json.dumps(self.toWikibase(), indent=4, sort_keys=True,
separators=(',', ': '))
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return (u"WbQuantity(amount=%(amount)s, upperBound=%(upperBound)s, "
u"lowerBound=%(lowerBound)s, unit=%(unit)s)" % self.__dict__)
_sites = {}
_url_cache = {} # The code/fam pair for each URL
def Site(code=None, fam=None, user=None, sysop=None, interface=None, url=None):
"""A factory method to obtain a Site object.
Site objects are cached and reused by this method.
By default rely on config settings. These defaults may all be overridden
using the method parameters.
@param code: language code (override config.mylang)
@type code: string
@param fam: family name or object (override config.family)
@type fam: string or Family
@param user: bot user name to use on this site (override config.usernames)
@type user: unicode
@param sysop: sysop user to use on this site (override config.sysopnames)
@type sysop: unicode
@param interface: site class or name of class in pywikibot.site
(override config.site_interface)
@type interface: subclass of L{pywikibot.site.BaseSite} or string
@param url: Instead of code and fam, does try to get a Site based on the
URL. Still requires that the family supporting that URL exists.
@type url: string
"""
# Either code and fam or only url
if url and (code or fam):
raise ValueError('URL to the wiki OR a pair of code and family name '
'should be provided')
_logger = "wiki"
if url:
if url not in _url_cache:
matched_sites = []
# Iterate through all families and look, which does apply to
# the given URL
for fam in config.family_files:
family = pywikibot.family.Family.load(fam)
code = family.from_url(url)
if code is not None:
matched_sites += [(code, fam)]
if matched_sites:
if len(matched_sites) > 1:
pywikibot.warning(
'Found multiple matches for URL "{0}": {1} (use first)'
.format(url, ', '.join(str(s) for s in matched_sites)))
_url_cache[url] = matched_sites[0]
else:
# TODO: As soon as AutoFamily is ready, try and use an
# AutoFamily
_url_cache[url] = None
cached = _url_cache[url]
if cached:
code = cached[0]
fam = cached[1]
else:
raise SiteDefinitionError("Unknown URL '{0}'.".format(url))
else:
# Fallback to config defaults
code = code or config.mylang
fam = fam or config.family
interface = interface or config.site_interface
# config.usernames is initialised with a dict for each family name
family_name = str(fam)
if family_name in config.usernames:
user = user or config.usernames[family_name].get(code) \
or config.usernames[family_name].get('*')
sysop = sysop or config.sysopnames[family_name].get(code) \
or config.sysopnames[family_name].get('*')
if not isinstance(interface, type):
# If it isnt a class, assume it is a string
try:
tmp = __import__('pywikibot.site', fromlist=[interface])
interface = getattr(tmp, interface)
except ImportError:
raise ValueError("Invalid interface name '%(interface)s'" % locals())
if not issubclass(interface, pywikibot.site.BaseSite):
warning('Site called with interface=%s' % interface.__name__)
user = pywikibot.tools.normalize_username(user)
key = '%s:%s:%s:%s' % (interface.__name__, fam, code, user)
if key not in _sites or not isinstance(_sites[key], interface):
_sites[key] = interface(code=code, fam=fam, user=user, sysop=sysop)
debug(u"Instantiated %s object '%s'"
% (interface.__name__, _sites[key]), _logger)
if _sites[key].code != code:
warn('Site %s instantiated using different code "%s"'
% (_sites[key], code), UserWarning, 2)
return _sites[key]
# alias for <API key>
getSite = pywikibot.tools.redirect_func(Site, old_name='getSite')
from pywikibot.page import (
Page,
FilePage,
Category,
Link,
User,
ItemPage,
PropertyPage,
Claim,
)
from pywikibot.page import html2unicode, url2unicode, unicode2html
link_regex = re.compile(r'\[\[(?P<title>[^\]|[<>{}]*)(\|.*?)?\]\]')
@pywikibot.tools.deprecated("comment parameter for page saving method")
def setAction(s):
"""Set a summary to use for changed page submissions."""
config.<API key> = s
def showDiff(oldtext, newtext, context=0):
"""
Output a string showing the differences between oldtext and newtext.
The differences are highlighted (only on compatible systems) to show which
changes were made.
"""
PatchManager(oldtext, newtext, context=context).print_hunks()
# Throttle and thread handling
stopped = False
def stopme():
"""Drop this process from the throttle log, after pending threads finish.
Can be called manually if desired, but if not, will be called automatically
at Python exit.
"""
global stopped
_logger = "wiki"
if not stopped:
debug(u"stopme() called", _logger)
def remaining():
remainingPages = page_put_queue.qsize() - 1
# -1 because we added a None element to stop the queue
remainingSeconds = datetime.timedelta(
seconds=(remainingPages * config.put_throttle))
return (remainingPages, remainingSeconds)
page_put_queue.put((None, [], {}))
stopped = True
if page_put_queue.qsize() > 1:
num, sec = remaining()
format_values = dict(num=num, sec=sec)
output(u'\03{lightblue}'
u'Waiting for %(num)i pages to be put. '
u'Estimated time remaining: %(sec)s'
u'\03{default}' % format_values)
while(_putthread.isAlive()):
try:
_putthread.join(1)
except KeyboardInterrupt:
if input_yn('There are %i pages remaining in the queue. '
'Estimated time remaining: %s\nReally exit?'
% remaining(), default=False, automatic_quit=False):
return
# only need one drop() call because all throttles use the same global pid
try:
list(_sites.values())[0].throttle.drop()
log(u"Dropped throttle(s).")
except IndexError:
pass
import atexit
atexit.register(stopme)
# Create a separate thread for asynchronous page saves (and other requests)
def async_manager():
"""Daemon; take requests from the queue and execute them in background."""
while True:
(request, args, kwargs) = page_put_queue.get()
if request is None:
break
request(*args, **kwargs)
page_put_queue.task_done()
def async_request(request, *args, **kwargs):
"""Put a request on the queue, and start the daemon if necessary."""
if not _putthread.isAlive():
try:
page_put_queue.mutex.acquire()
try:
_putthread.start()
except (AssertionError, RuntimeError):
pass
finally:
page_put_queue.mutex.release()
page_put_queue.put((request, args, kwargs))
# queue to hold pending requests
page_put_queue = Queue(config.max_queue_size)
# set up the background thread
_putthread = threading.Thread(target=async_manager)
# identification for debugging purposes
_putthread.setName('Put-Thread')
_putthread.setDaemon(True)
wrapper = pywikibot.tools.<API key>(__name__)
wrapper.<API key>('ImagePage', FilePage)
wrapper.<API key>(
'PageNotFound', pywikibot.exceptions.<API key>,
warning_message=('{0}.{1} is deprecated, and no longer '
'used by pywikibot; use http.fetch() instead.'))
wrapper.<API key>(
'UserActionRefuse', pywikibot.exceptions._EmailUserError,
warning_message='UserActionRefuse is deprecated; '
'use UserRightsError and/or NotEmailableError')
wrapper.<API key>(
'<API key>', pywikibot.bot.<API key>,
warning_message='pywikibot.<API key> is deprecated; '
'use pywikibot.bot.<API key> instead')
|
package gui;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.<API key>;
import javax.swing.UIManager;
import app.Applikation;
import javax.swing.DropMode;
import parsers.*;
import java.io.IOException;
import java.util.Random;
public class GUI {
private JFrame frmImageDownloader;
private JTextField txtInsertTagHere;
private JTextArea textArea;
private JSpinner PageSpinner;
private JComboBox<Object> comboBox;
private ImageParser parser;
private JButton Parsebtn;
private JTextField DelayField;
private BufferedImage bgImage;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblTag;
private final String FOURCHAN_THREAD = "4chan-Thread - http://boards.4chan.org/x/res/123123";
private final String FOURCHAN_BOARD = "4chan-Board - http://boards.4chan.org/x/catalog";
private final String INFINITYCHAN_THREAD = "Infinity Chan Thread - https://8chan.co/BOARD/res/THREADNR.html";
private final String INFINITYCHAN_BOARD = "Infinity Chan Board - https://8chan.co/BOARDNR/";
private final String PAHEAL = "http://rule34.paheal.net/";
private final String XXX = "http://rule34.xxx/";
private final String GELBOORU = "http://gelbooru.com/";
private final String R34HENTAI = "http://rule34hentai.net/";
private final String TUMBLR = "Tumblr Artist - http://XxXxXxX.tumblr.com";
private final String IMGUR = "Imgur-Album - http://imgur.com/a/xXxXx";
private final String GE_HENTAI_SINGLE = "http://g.e-hentai.org/ - Single Album Page";
private final String GE_HENTAI_MORE = "http://g.e-hentai.org/ - >=1 Pages";
private final String ARCHIVE_MOE_THREAD = "archive.moe/fgts.jp (Thread) - https://archive.moe/BOARD/thread/THREADNR/";
private final String ARCHIVE_MOE_BOARD = "archive-moe (Board) - https://archive.moe/BOARD/";
private final String FGTS_JP_BOARD = "fgts.jp (Board) - http://fgts.jp/BOARD/";
private boolean parsing;
public GUI() {
System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
try {
UIManager.setLookAndFeel(UIManager.<API key>());
} catch (Exception e) {
e.printStackTrace();
}
frmImageDownloader = new JFrame();
frmImageDownloader.setIconImage(Toolkit.getDefaultToolkit()
.getImage(this.getClass().getResource("/images/icon.png")));
frmImageDownloader.getContentPane().setBackground(
UIManager.getColor("Button.background"));
frmImageDownloader.setResizable(false);
frmImageDownloader.setTitle("Image Downloader v1.5.1");
frmImageDownloader.setBounds(100, 100, 761, 558);
frmImageDownloader.<API key>(JFrame.EXIT_ON_CLOSE);
frmImageDownloader.getContentPane().setLayout(null);
JLabel lblMadeByLars = new JLabel("@ berserkingyadis");
lblMadeByLars.setFont(new Font("Dialog", Font.PLAIN, 12));
lblMadeByLars.setBounds(14, 468, 157, 40);
frmImageDownloader.getContentPane().add(lblMadeByLars);
JScrollPane scrollPane = new JScrollPane();
scrollPane
.<API key>(ScrollPaneConstants.<API key>);
scrollPane.setBounds(205, 185, 542, 331);
scrollPane.setAutoscrolls(true);
frmImageDownloader.getContentPane().add(scrollPane);
try {
bgImage = ImageIO.read(Applikation.class.getResource("/images/bg" + (new Random().nextInt(4) + 1) + ".png"));
} catch (IOException e) {
appendLog("Could not get Background Image", true);
}
textArea = new BackgroundArea(bgImage);
textArea.setEditable(false);
textArea.setDropMode(DropMode.INSERT);
textArea.setColumns(2);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 11));
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
txtInsertTagHere = new JTextField();
txtInsertTagHere.setText("insert tag here");
txtInsertTagHere.setFont(new Font("Dialog", Font.PLAIN, 14));
txtInsertTagHere.setBounds(14, 208, 181, 30);
frmImageDownloader.getContentPane().add(txtInsertTagHere);
txtInsertTagHere.setColumns(10);
lblTag = new JLabel("Tag:");
lblTag.setFont(new Font("Dialog", Font.BOLD, 12));
lblTag.setBounds(12, 183, 175, 24);
frmImageDownloader.getContentPane().add(lblTag);
Parsebtn = new JButton("start parsing");
Parsebtn.setBounds(12, 372, 181, 85);
frmImageDownloader.getContentPane().add(Parsebtn);
PageSpinner = new JSpinner();
PageSpinner.setModel(new SpinnerNumberModel(new Integer(1),
new Integer(1), null, new Integer(1)));
PageSpinner.setBounds(155, 249, 40, 30);
frmImageDownloader.getContentPane().add(PageSpinner);
lblNewLabel = new JLabel("Pages to parse:");
lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 11));
lblNewLabel.setBounds(12, 249, 123, 30);
frmImageDownloader.getContentPane().add(lblNewLabel);
lblNewLabel_1 = new JLabel("1 Page = 50-60 Pictures");
lblNewLabel_1.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_1.setBounds(12, 290, 175, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_1);
comboBox = new JComboBox<Object>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
switch (comboBox.getSelectedItem().toString()) {
case GE_HENTAI_SINGLE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(false);
lblTag.setText("Page URL:");
txtInsertTagHere.setText("insert page URL here");
lblNewLabel.setEnabled(false);
break;
case GE_HENTAI_MORE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Album URL:");
txtInsertTagHere.setText("insert album URL here");
break;
case PAHEAL:
case GELBOORU:
case R34HENTAI:
case XXX:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Tag:");
txtInsertTagHere.setText("insert tag here");
lblNewLabel.setText("Pages to parse:");
break;
case FOURCHAN_THREAD:
case INFINITYCHAN_THREAD:
case ARCHIVE_MOE_THREAD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setText("Pages to parse:");
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
lblTag.setText("Thread URL:");
txtInsertTagHere.setText("insert link here");
break;
case FOURCHAN_BOARD:
case INFINITYCHAN_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Threads to parse:");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case ARCHIVE_MOE_BOARD:
case FGTS_JP_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Sites to parse(1 Site = 100 Threads):");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case TUMBLR:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Artist name:");
txtInsertTagHere.setText("insert artist name here");
lblNewLabel.setText("Pages to parse:");
break;
case IMGUR:
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
DelayField.setText("100");
lblTag.setText("Album Letters: (eg: \"Bl1QP\")");
txtInsertTagHere.setText("insert the letters here");
Parsebtn.setText("start parsing");
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setEnabled(true);
break;
}
}
});
comboBox.setModel(new <API key><Object>(
new String[]{
PAHEAL,
XXX,
R34HENTAI,
GELBOORU,
GE_HENTAI_SINGLE,
GE_HENTAI_MORE,
FOURCHAN_THREAD,
FOURCHAN_BOARD,
//ARCHIVE_MOE_THREAD,
//ARCHIVE_MOE_BOARD,
//FGTS_JP_BOARD,
INFINITYCHAN_THREAD,
INFINITYCHAN_BOARD,
TUMBLR,
IMGUR
}));
comboBox.setBounds(434, 35, 313, 24);
comboBox.setFont(new Font("Dialog", Font.PLAIN, 11));
frmImageDownloader.getContentPane().add(comboBox);
JLabel lblNewLabel_2 = new JLabel("choose the Site to parse:");
lblNewLabel_2.setFont(new Font("Dialog", Font.BOLD, 12));
lblNewLabel_2.setBounds(434, 5, 268, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel(
"<html>\nWelcome to the Image Downloader. <br>\nYour can enter the Tag of the images you are looking for below. <br>\nImgur is not supported yet. <br>\nWhen you click parse a folder with the name of the tag will be <br>\ncreated and the images will be downloaded into it. <br><br>\nI strongly advise you to not set the delay under 100 ms, <br>\nif you abuse this you will get banned from the site <br><br>\n\nhave fun :)\n\n\n</html>");
lblNewLabel_3.<API key>(SwingConstants.TOP);
lblNewLabel_3.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_3.setBounds(12, 12, 404, 195);
frmImageDownloader.getContentPane().add(lblNewLabel_3);
JLabel lblDelay = new JLabel("Delay(ms):");
lblDelay.setFont(new Font("Dialog", Font.BOLD, 12));
lblDelay.setBounds(12, 331, 85, 30);
frmImageDownloader.getContentPane().add(lblDelay);
DelayField = new JTextField();
DelayField.setText("100");
DelayField.setBounds(140, 331, 55, 30);
frmImageDownloader.getContentPane().add(DelayField);
DelayField.setColumns(10);
JLabel lblPahealSearchFor = new JLabel(
"<html>\r\npaheal: Search for Characters or Artists\r\n\t\t eg: Tifa Lockhart, Fugtrup<br>\r\nrule34.xxx: Search for things\r\n\t\teg: long hair, hand on hip<br>\r\ngelbooru: Search for what you want<br>\r\n4chan/8chan: paste the Thread URL/Boardletter in the\r\n\t\tTextfield <br>\r\ntumblr: enter the artist's name<br>imgur: enter the album id</html>");
lblPahealSearchFor.<API key>(SwingConstants.TOP);
lblPahealSearchFor.setFont(new Font("Dialog", Font.PLAIN, 11));
lblPahealSearchFor.setBounds(434, 71, 313, 109);
frmImageDownloader.getContentPane().add(lblPahealSearchFor);
Parsebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (parsing) {
parser.diePlease();
parser = null;
} else {
GUI g = getGUI();
textArea.setText("");
frmImageDownloader
.<API key>(JFrame.DO_NOTHING_ON_CLOSE);
String tag = txtInsertTagHere.getText().replace(' ', '_');
int pages = (int) PageSpinner.getValue();
String site = comboBox.getSelectedItem().toString();
int delay = Integer.parseInt(DelayField.getText());
switch (site) {
case PAHEAL:
parser = new PahealParser();
parser.setup(tag, pages, g, delay);
break;
case XXX:
parser = new XXXParser();
parser.setup(tag, pages, g, delay);
break;
case R34HENTAI:
parser = new R34HentaiParser();
parser.setup(tag, pages, g, delay);
break;
case GELBOORU:
parser = new GelBooruParser();
parser.setup(tag, pages, g, delay);
break;
case FOURCHAN_THREAD:
parser = new FourChanParser(tag, delay, g, 0);
break;
case FOURCHAN_BOARD:
parser = new FourChanParser(tag, delay, g, 1, pages);
break;
case INFINITYCHAN_THREAD:
parser = new InfinityChanParser(tag, delay, g, 0);
break;
case INFINITYCHAN_BOARD:
parser = new InfinityChanParser(tag, delay, g, 1, pages);
break;
case ARCHIVE_MOE_THREAD:
parser = new ArchiveMoeParser(tag, delay, g, 0);
break;
case ARCHIVE_MOE_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 1, pages);
break;
case FGTS_JP_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 2, pages);
break;
case TUMBLR:
parser = new TumblrParser();
parser.setup(tag, pages, g, delay);
break;
case IMGUR:
parser = new ImgurParser(tag, delay, g);
break;
case GE_HENTAI_SINGLE:
parser = new GEHentaiParser(tag, delay, g, false, pages);
break;
case GE_HENTAI_MORE:
parser = new GEHentaiParser(tag, delay, g, true, pages);
}
parser.start();
parsing = true;
Parsebtn.setText("stop parsing");
}
}
});
frmImageDownloader.setVisible(true);
parsing = false;
}
public void appendLog(String txt, boolean brk) {
textArea.append(txt);
if (brk)
textArea.append("\n");
}
private GUI getGUI() {
return this;
}
public void reportback() {
Parsebtn.setEnabled(true);
frmImageDownloader.<API key>(JFrame.EXIT_ON_CLOSE);
Parsebtn.setText("start parsing");
parsing = false;
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Slate Sample</title>
<script src="https://use.fontawesome.com/3d815f531c.js"></script>
</head>
<body>
<div id="root"></div>
<script src="bin/app.bundle.js"></script>
</body>
</html>
|
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b> </b></th><td class="std2"></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><sup class="subfont">ˋ</sup><sup class="subfont">ˋ</sup><sup class="subfont">ˋ</sup></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><font class="english_word">fù gù bù quān</font></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2">˙<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center></td></tr>
<tr><th class="std1"><b><font class="fltypefont"></font> </b></th><td class="std2"></td></tr>
</td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
|
package curveavg;
/**
* Small helper class for computing the circular arc between two points.
* @author Sebastian Weiss
*/
public class CircularArc {
private static final float EPSILON = 1e-5f;
private final Vector3f P;
private final Vector3f A;
private final Vector3f B;
private Vector3f C;
private float r;
private Vector3f N;
private Vector3f CA;
private float angle;
/**
* Computes the circular arc between the points A and B, with the point P on the
* medial axis (i.e. |A-N|==|B-N|).
* @param P the point on the medial axis, A and B are at the same distance from P
* @param A the closest point from P on the first control curve
* @param B the closest point from P on the second control curve
*/
public CircularArc(Vector3f P, Vector3f A, Vector3f B) {
this.P = P;
this.A = A;
this.B = B;
computeCenter();
}
private void computeCenter() {
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
//check for degenerated case
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
r = 0;
return; //Degenerated to a line
}
//compute directions of A,B to the center C
N.normalizeLocal();
PA.normalizeLocal();
PB.normalizeLocal();
Vector3f U = N.cross(PA);
Vector3f V = N.cross(PB);
//C is now the intersection of A+aU and B+bV
Vector3f UxV = U.cross(V);
Vector3f rhs = (B.subtract(A)).cross(V);
float a1 = rhs.x / UxV.x;
float a2 = rhs.y / UxV.y;
float a3 = rhs.z / UxV.z; //all a1,a2,a3 have to be equal
C = A.addScaled(a1, U);
//compute radius and angle
r = C.distance(A);
CA = A.subtract(C);
angle = (CA.normalize()).angleBetween((B.subtract(C).normalizeLocal()));
}
private float computeCenter_old() {
//check for degenerated case
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
return 0; //Degenerated to a line
}
//define orthonormal basis I,J,K
N.normalizeLocal();
Vector3f I = PA.normalize();
Vector3f J = N.cross(I);
Vector3f K = N;
Vector3f IxK = I.cross(K);
Vector3f JxK = J.cross(K);
//project points in the plane PAB
Vector3f PAxN = PA.cross(N);
Vector3f PBxN = PB.cross(N);
Vector2f P2 = new Vector2f(0, 0);
Vector2f A2 = new Vector2f(PA.dot(JxK)/I.dot(JxK), PA.dot(IxK)/J.dot(IxK));
Vector2f B2 = new Vector2f(PB.dot(JxK)/I.dot(JxK), PB.dot(IxK)/J.dot(IxK));
float t;
if (B2.x == A2.x) {
t = (B2.y - A2.y) / (A2.x - B2.x);
} else {
t = (B2.x - A2.x) / (A2.y - B2.y);
}
//compute C
Vector2f PArot = new Vector2f(A.y-P.y, P.x-A.x);
Vector2f C2 = P2.addLocal(PArot.multLocal(t));
//project back
C = new Vector3f(P);
C.addScaledLocal(C2.x, I);
C.addScaledLocal(C2.y, J);
//Debug
// System.out.println("A="+A+", B="+B+" P="+P+" -> I="+I+", J="+J+", K="+K+", P'="+P2+", A'="+A2+", B'="+B2+", t="+t+", C'="+C2+", C="+C);
//set radius
return C.distance(A);
}
/**
* Computes a point on the actual circular arc from A to B.
* The vectors C and the float r are the result from
* {@link #computeCenter(curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f) }.
* It interpolates from A (alpha=0) to B (alpha=1) in a circular arc.
* @param alpha
* @return
*/
public Vector3f getPointOnArc(float alpha) {
if (isDegenerated()) {
Vector3f V = new Vector3f();
return V.interpolateLocal(A, B, alpha); //degenerated case
}
//normal case, rotate
Vector3f V = rotate(alpha*angle, CA, N);
return V.addLocal(C);
}
private static Vector3f rotate(float angle, Vector3f X, Vector3f N) {
Vector3f W = N.mult(N.dot(X));
Vector3f U = X.subtract(W);
return W.add(U.mult((float) Math.cos(angle)))
.subtract(N.cross(U).mult((float) Math.sin(angle)));
}
public boolean isDegenerated() {
return r==0;
}
public Vector3f getCenter() {
return C;
}
public float getRadius() {
return r;
}
public Vector3f getNormal() {
return N;
}
public float getAngle() {
return angle;
}
@Override
public String toString() {
return "CircularArc{" + "P=" + P + ", A=" + A + ", B=" + B + " -> C=" + C + ", r=" + r + ", N=" + N + ", angle=" + angle + '}';
}
}
|
// These two object contain information about the state of Ebl
var GlobalState = Base.extend({
constructor: function() {
this.isAdmin = false;
this.authToken = null;
this.docTitle = null;
this.container = null;
// default config
this.config = {
template: 'default',
language: 'en',
postsPerPage: 5,
pageTitleFormat: "{ebl_title} | {doc_title}",
// callbacks
onBlogLoaded: null,
onPostOpened: null,
onPageChanged: null
};
}
});
var LocalState = Base.extend({
constructor: function() {
this.page = 0;
this.post = null;
this.editors = null;
}
});
var PostStatus = {
NEW: 0,
DRAFT: 1,
PUBLISHED: 2,
parse: function (s) {
if (s.toLowerCase() == "new") return 0;
if (s.toLowerCase() == "draft") return 1;
if (s.toLowerCase() == "published") return 2;
return null;
}
};
var gState = new GlobalState(); // state shared among the entire session
var lState = new LocalState(); // state of the current view
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DiveConditions.ViewModels.Manage
{
public class FactorViewModel
{
public string Purpose { get; set; }
}
}
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
namespace ApplicationInsights.OwinExtensions.Tests
{
public class <API key> : IDisposable
{
public <API key>()
{
OperationIdContext.Clear();
}
[Fact]
public void Can_Create_Context()
{
OperationIdContext.Create();
OperationIdContext.Get().Should().NotBeNullOrEmpty();
}
[Fact]
public void Can_Clear_Context()
{
OperationIdContext.Create();
OperationIdContext.Clear();
OperationIdContext.Get().Should().BeNull();
}
[Fact]
public void Can_Set_Context()
{
OperationIdContext.Set("test");
OperationIdContext.Get().Should().Be("test");
}
[Fact]
public async Task <API key>()
{
OperationIdContext.Create();
var expected = OperationIdContext.Get();
using (var client = new HttpClient())
await client.GetAsync("http://google.com");
var actual = OperationIdContext.Get();
actual.Should().NotBeNullOrEmpty();
actual.Should().Be(expected);
}
public void Dispose()
{
OperationIdContext.Clear();
}
}
}
|
// CRToast
#import <Foundation/Foundation.h>
#import "CRToastManager.h"
@import UIKit;
typedef void (^CRToastImageBlock)(UIImageView*);
@interface <API key> : NSObject
@property (nonatomic, copy) CRToastImageBlock block;
- (instancetype)initWithBlock:(CRToastImageBlock)block;
- (void)performWith:(UIImageView*)imageView;
@end
@class <API key>, <API key>;
/**
<API key> defines the types of interactions that can be injected into a <API key>.
*/
typedef NS_OPTIONS(NSInteger, <API key>) {
<API key> = 1 << 0,
<API key> = 1 << 1,
<API key> = 1 << 2,
<API key> = 1 << 3,
<API key> = 1 << 4,
<API key> = 1 << 5,
<API key> = 1 << 6,
<API key> = 1 << 7,
//An interaction responder with a <API key> interaction type will fire on all swipe interactions
<API key> = (<API key> |
<API key> |
<API key> |
<API key>),
//An interaction responder with a <API key> interaction type will fire on all tap interactions
<API key> = (<API key> |
<API key> |
<API key> |
<API key>),
//An interaction responder with a <API key> interaction type will fire on all swipe and tap interactions
<API key> = (<API key>, <API key>)
};
extern NSString *<API key>(<API key> interactionType);
/**
<API key> is a container object to configure responses to user interactions with a notification. A collection of interaction responders can be included in the
options for any given notification or in defaults.
*/
@interface <API key> : NSObject
/**
Creates an interaction responder for a given interaction type.
@param interactionType The kind of interaction that will trigger the responder
@param <API key> A BOOL indiciating if the notification should automatically be dismissed on the interaction being observed. If YES the configured notification dismisall
animation will begin immidiately upon encountering the interaction.
@param block A block of code to be called immidiately upon the interaction being encountered. The block will be provided the specific <API key> that resulted in the
block firing
*/
+ (instancetype)<API key>:(<API key>)interactionType
<API key>:(BOOL)<API key>
block:(void (^)(<API key> interactionType))block;
@end
@name Notification Option Types
/**
`CRToastType` defines the height of the notification. `<API key>` covers the status bar, `<API key>` covers the status bar
and navigation bar
*/
typedef NS_ENUM(NSInteger, CRToastType){
<API key>,
<API key>,
CRToastTypeCustom
};
/**
`<API key>` defines whether a notification will cover the contents of the status/navigation bar or whether the content will be pushed
out by the notification.
*/
typedef NS_ENUM(NSInteger, <API key>){
<API key>,
<API key>
};
/**
`<API key>` defines the direction of the notification. A direction can be specified for both notification entrance and exit.
*/
typedef NS_ENUM(NSInteger, <API key>) {
<API key>,
<API key>,
<API key>,
<API key>
};
/**
`<API key>` defines the timing function used for the notification presentation.
*/
typedef NS_ENUM(NSInteger, <API key>) {
<API key>,
<API key>,
<API key>
};
/**
`CRToastState` defines the current state of the CRToast. Used for internal state management in the manager
*/
typedef NS_ENUM(NSInteger, CRToastState){
CRToastStateWaiting,
<API key>,
<API key>,
CRToastStateExiting,
<API key>
};
/**
`<API key>` defines the alignment of the image given to the CRToast.
*/
typedef NS_ENUM(NSInteger, <API key>){
<API key>,
<API key>,
<API key>
};
@name Option Keys
/**
These are the keys that define the options that can be set for a notifaction. All primitive types mentioned should
be wrapped as `NSNumber`s or `NSValue`s
*/
/**
The notification type for the notification. Expects type `CRToastType`.
*/
extern NSString *const <API key>;
/**
The preferred height for the notificaiton, this will only be used for notifications with CRToastTypeCustom set for <API key>
*/
extern NSString *const <API key>;
/**
The presentation type for the notification. Expects type `<API key>`.
*/
extern NSString *const <API key>;
/**
Indicates whether the notification should slide under the staus bar, leaving it visible or not.
Making this YES with `<API key>` set to `<API key>` isn't sensible and will look
odd. Expects type `BOOL`.
*/
extern NSString *const <API key>;
/**
Keep toast within navigation bar border.
The standard navigation bar has a thin border on the bottom. Animations are
improved when the toast is within the border. Customized bars without the border
should have this set to NO.
Expects type `BOOL`. Defaults to YES.
*/
extern NSString *const <API key>;
/**
The animation in type for the notification. Expects type `<API key>`.
*/
extern NSString *const <API key>;
/**
The animation out type for the notification. Expects type `<API key>`.
*/
extern NSString *const <API key>;
/**
The animation in direction for the notification. Expects type `<API key>`.
*/
extern NSString *const <API key>;
/**
The animation out direction for the notification. Expects type `<API key>`.
*/
extern NSString *const <API key>;
/**
The animation in time interval for the notification. Expects type `NSTimeInterval`.
*/
extern NSString *const <API key>;
/**
The notification presentation timeinterval of type for the notification. This is how long the notification
will be on screen after its presentation but before its dismissal. Expects type `NSTimeInterval`.
*/
extern NSString *const <API key>;
/**
The animation out timeinterval for the notification. Expects type `NSTimeInterval`.
*/
extern NSString *const <API key>;
/**
The spring damping coefficient to be used when `<API key>` or `<API key>` is set to
`<API key>`. Currently you can't define separate damping for in and out. Expects type `CGFloat`.
*/
extern NSString *const <API key>;
/**
The initial velocity coefficient to be used when `<API key>` or `<API key>` is set to
`<API key>`. Currently you can't define initial velocity for in and out. Expects type `CGFloat`.
*/
extern NSString *const <API key>;
/**
The gravity magnitude coefficient to be used when `<API key>` or `<API key>` is set to
`<API key>`. Currently you can't define gravity magnitude for in and out. Expects type `CGFloat`.
*/
extern NSString *const <API key>;
/**
The main text to be shown in the notification. Expects type `NSString`.
*/
extern NSString *const kCRToastTextKey;
/**
The attributed main text to be shown in the notification. Expects type `NSAttributedString`.
*/
extern NSString *const <API key>;
/**
The font to be used for the `kCRToastTextKey` value . Expects type `UIFont`.
*/
extern NSString *const kCRToastFontKey;
/**
The text color to be used for the `kCRToastTextKey` value . Expects type `UIColor`.
*/
extern NSString *const <API key>;
/**
The text alignment to be used for the `kCRToastTextKey` value . Expects type `NSTextAlignment`.
*/
extern NSString *const <API key>;
/**
The shadow color to be used for the `kCRToastTextKey` value . Expects type `UIColor`.
*/
extern NSString *const <API key>;
/**
The shadow offset to be used for the `kCRToastTextKey` value . Expects type `CGSize`.
*/
extern NSString *const <API key>;
/**
The max number of lines to be used for the `kCRToastTextKey` value . Expects type `NSInteger`.
*/
extern NSString *const <API key>;
/**
The subtitle text to be shown in the notification. Expects type `NSString`.
*/
extern NSString *const <API key>;
/**
The attributed subtitle text to be shown in the notification. Expects type `NSAttributedString`.
*/
extern NSString *const <API key>;
/**
The font to be used for the `<API key>` value . Expects type `UIFont`.
*/
extern NSString *const <API key>;
/**
The text color to be used for the `<API key>` value . Expects type `UIColor`.
*/
extern NSString *const <API key>;
/**
The text alignment to be used for the `<API key>` value . Expects type `NSTextAlignment`.
*/
extern NSString *const <API key>;
/**
The shadow color to be used for the `<API key>` value . Expects type `UIColor`.
*/
extern NSString *const <API key>;
/**
The shadow offset to be used for the `<API key>` value . Expects type `NSInteger`.
*/
extern NSString *const <API key>;
/**
The max number of lines to be used for the `<API key>` value . Expects type `NSInteger`.
*/
extern NSString *const <API key>;
/**
The status bar style for the navigation bar. Expects type `UIStatusBarStyle`.
*/
extern NSString *const <API key>;
/**
The background color for the notification. Expects type `UIColor`.
*/
extern NSString *const <API key>;
/**
Custom view used as the background of the notification
*/
extern NSString *const <API key>;
/**
The image to be shown on the left side of the notification. Expects type `UIImage`.
*/
extern NSString *const kCRToastImageKey;
/**
The left image view size to use. Expects type CGSize.
*/
extern NSString *const <API key>;
/**
The left image corner radius. Expects type CGFloat.
*/
extern NSString *const <API key>;
/**
The left image inset. Expects type UIEdgeInset.
*/
extern NSString *const <API key>;
/**
The image content mode to use for `kCRToastImageKey` image. Exptects type `UIViewContentMode`
*/
extern NSString *const <API key>;
/**
The block that is used to set image for left toast image view. Exptects type `CRToastImageBlock`
*/
extern NSString *const <API key>;
/**
The image to be shown on the left side of the notification. Expects type `UIImage`.
*/
extern NSString *const <API key>;
/**
The left image view size to use. Expects type CGSize.
*/
extern NSString *const <API key>;
/**
The left image corner radius. Expects type CGFloat.
*/
extern NSString *const <API key>;
/**
The left image inset. Expects type UIEdgeInset.
*/
extern NSString *const <API key>;
/**
The image content mode to use for `kCRToastImageKey` image. Exptects type `UIViewContentMode`
*/
extern NSString *const <API key>;
/**
The image alignment to use. Expects type `<API key>`.
*/
extern NSString *const <API key>;
/**
BOOL setting whether the CRToast should show a loading indicator in the left image location.
*/
extern NSString *const <API key>;
/**
The activity indicator view style. Expects type `<API key>`
*/
extern NSString *const <API key>;
/**
The activity indicator alignment to use. Expects type `<API key>`.
*/
extern NSString *const <API key>;
/**
An Array of Interaction Responders for the Notification. Expects type `NSArray` full of `<API key>`
*/
extern NSString *const <API key>;
/**
BOOL setting whether the CRToast should force the user to interact with it, ignoring the `<API key>` key
*/
extern NSString *const <API key>;
/**
An BOOL setting whether the CRToast's should autorotate. Expects type `BOOL` defaults to `YES`
*/
extern NSString *const <API key>;
/**
Key for the Identifier for a notification.
*/
extern NSString *const <API key>;
/**
A BOOL setting whether the CRToast's should capture the screen behind the default UIWindow. Expects type `BOOL` defaults to `YES`
*/
extern NSString *const <API key>;
#pragma mark - CRToast Interface
@interface CRToast : NSObject <<API key>>
@property (nonatomic, strong) NSUUID *uuid;
@property (nonatomic, assign) CRToastState state;
//Top Level Properties
@property (nonatomic, strong) NSDictionary *options;
@property (nonatomic, copy) void(^completion)(void);
@property (nonatomic, copy) void(^appearance)(void);
//Interactions
@property (nonatomic, strong) NSArray *gestureRecognizers;
//Autorotate
@property (nonatomic, assign) BOOL autorotate;
//Views and Layout Data
@property (nonatomic, readonly) UIView *notificationView;
@property (nonatomic, readonly) CGRect <API key>;
@property (nonatomic, readonly) CGRect <API key>;
@property (nonatomic, readonly) UIView *statusBarView;
@property (nonatomic, readonly) CGRect <API key>;
@property (nonatomic, readonly) CGRect <API key>;
@property (nonatomic, strong) UIDynamicAnimator *animator;
//Read Only Convinence Properties Providing Default Values or Values from Options
@property (nonatomic, readonly) CRToastType notificationType;
@property (nonatomic, assign) CGFloat preferredHeight;
@property (nonatomic, readonly) <API key> presentationType;
@property (nonatomic, readonly) BOOL <API key>;
@property (nonatomic, readonly) BOOL <API key>;
@property (nonatomic, readonly) <API key> inAnimationType;
@property (nonatomic, readonly) <API key> outAnimationType;
@property (nonatomic, readonly) <API key> <API key>;
@property (nonatomic, readonly) <API key> <API key>;
@property (nonatomic, readonly) NSTimeInterval <API key>;
@property (nonatomic, readonly) NSTimeInterval timeInterval;
@property (nonatomic, readonly) NSTimeInterval <API key>;
@property (nonatomic, readonly) CGFloat <API key>;
@property (nonatomic, readonly) CGFloat <API key>;
@property (nonatomic, readonly) CGFloat <API key>;
@property (nonatomic, readonly) NSString *text;
@property (nonatomic, readonly) NSAttributedString *attributedText;
@property (nonatomic, readonly) UIFont *font;
@property (nonatomic, readonly) UIColor *textColor;
@property (nonatomic, readonly) NSTextAlignment textAlignment;
@property (nonatomic, readonly) UIColor *textShadowColor;
@property (nonatomic, readonly) CGSize textShadowOffset;
@property (nonatomic, readonly) NSInteger <API key>;
@property (nonatomic, readonly) NSString *subtitleText;
@property (nonatomic, readonly) NSAttributedString *<API key>;
@property (nonatomic, readonly) UIFont *subtitleFont;
@property (nonatomic, readonly) UIColor *subtitleTextColor;
@property (nonatomic, readonly) NSTextAlignment <API key>;
@property (nonatomic, readonly) UIColor *<API key>;
@property (nonatomic, readonly) CGSize <API key>;
@property (nonatomic, readonly) NSInteger <API key>;
@property (nonatomic, readonly) UIStatusBarStyle statusBarStyle;
@property (nonatomic, readonly) UIColor *backgroundColor;
@property (nonatomic, readonly) UIView *backgroundView;
@property (nonatomic, readonly) UIImage *image;
@property (nonatomic, readonly) UIViewContentMode imageContentMode;
@property (nonatomic, readonly) CGSize leftImageSize;
@property (nonatomic, readonly) CGFloat <API key>;
@property (nonatomic, readonly) UIEdgeInsets leftImageInsets;
@property (nonatomic, readonly) CRToastImageBlock imageBlock;
@property (nonatomic, readonly) UIImage *rightImage;
@property (nonatomic, readonly) UIViewContentMode <API key>;
@property (nonatomic, readonly) CGSize rightImageSize;
@property (nonatomic, readonly) CGFloat <API key>;
@property (nonatomic, readonly) UIEdgeInsets rightImageInsets;
@property (nonatomic, readonly) <API key> imageAlignment;
@property (nonatomic, readonly) <API key> <API key>;
@property (nonatomic, readonly) <API key> <API key>;
@property (nonatomic, readonly) BOOL <API key>;
@property (nonatomic, readonly) BOOL <API key>;
@property (nonatomic, readonly) CGVector inGravityDirection;
@property (nonatomic, readonly) CGVector outGravityDirection;
@property (nonatomic, readonly) CGPoint inCollisionPoint1;
@property (nonatomic, readonly) CGPoint inCollisionPoint2;
@property (nonatomic, readonly) CGPoint outCollisionPoint1;
@property (nonatomic, readonly) CGPoint outCollisionPoint2;
- (void)<API key>:(<API key>*)<API key>;
- (void)<API key>:(<API key>*)<API key>;
- (void)initiateAnimator:(UIView *)view;
@end
|
// This file genenerated by the Buckle tool on 2/13/2015 at 8:27 AM.
// Contains strongly typed wrappers for resources in VacuumResources.resx
namespace Vacuum {
using System;
using System.Reflection;
using System.Resources;
using System.Diagnostics;
using System.Globalization;
<summary>
Strongly typed resource wrappers generated from VacuumResources.resx.
</summary>
public class VacuumResources
{
internal static readonly ResourceManager ResourceManager = new ResourceManager(typeof(VacuumResources));
<summary>
File '{0}' does not exist
</summary>
public static string FileNotFound(object param0)
{
string format = ResourceManager.GetString("FileNotFound", CultureInfo.CurrentUICulture);
return string.Format(CultureInfo.CurrentCulture, format, param0);
}
}
}
|
# test_eng.py
# pylint: disable=C0103,C0111,C0302,E0611,R0913,R0915,W0108,W0212
# Standard library imports
import functools
import sys
import pytest
from numpy import array, ndarray
# Putil imports
import putil.eng
from putil.test import AE, AI, CS
# Global variables
DFLT = 'def'
PY2 = bool(sys.hexversion < 0x03000000)
# Helper functions
isdflt = lambda obj: bool(obj == DFLT)
h = lambda num: '100.'+('0'*num)
o = lambda num: '1.'+('0'*num)
pv = lambda py2arg, py3arg: py2arg if PY2 else py3arg
sarg = lambda msg: 'Argument `{0}` is not valid'.format(msg)
t = lambda num: '10.'+('0'*num)
def to_sci_string(number):
"""
Returns a string with the number formatted in scientific notation. This
function does not have all the configurability of the public function
<API key>, it is a convenience function to test _to_eng_tuple
"""
mant, exp = putil.eng._to_eng_tuple(number)
return '{mant}E{exp_sign}{exp}'.format(
mant=mant, exp_sign='-' if exp < 0 else '+', exp=abs(exp)
)
# Test functions
@pytest.mark.parametrize(
'text, sep, num, lstrip, rstrip, ref', [
('a, b, c, d', ',', 1, DFLT, DFLT, ('a', ' b', ' c', ' d')),
('a , b , c , d ', ',', 1, DFLT, DFLT, ('a ', ' b ', ' c ', ' d ')),
('a , b , c , d ', ',', 1, True, DFLT, ('a ', 'b ', 'c ', 'd ')),
('a , b , c , d ', ',', 1, DFLT, True, ('a', ' b', ' c', ' d')),
('a , b , c , d ', ',', 1, True, True, ('a', 'b', 'c', 'd')),
('a, b, c, d', ',', 2, DFLT, DFLT, ('a, b', ' c, d')),
('a, b, c, d', ',', 3, DFLT, DFLT, ('a, b, c', ' d')),
('a, b, c, d', ',', 4, DFLT, DFLT, ('a, b, c, d',)),
('a, b, c, d', ',', 5, DFLT, DFLT, ('a, b, c, d',)),
]
)
def test_split_every(text, sep, num, lstrip, rstrip, ref):
""" Test _split_every function behavior """
# DFLT in lstrip or rstrip means default argument values should be used
obj = putil.eng._split_every
obj = obj if isdflt(lstrip) else functools.partial(obj, lstrip=lstrip)
obj = obj if isdflt(rstrip) else functools.partial(obj, rstrip=rstrip)
assert obj(text, sep, num) == ref
@pytest.mark.parametrize(
'num, ref', [
(0.<API key>, '1.00123456789E-24'),
(0.<API key>, '1E-24'),
(0.<API key>, '10.0123456789E-24'),
(0.<API key>, '10E-24'),
(0.<API key>, '100.123456789E-24'),
(0.<API key>, '100E-24'),
(0.<API key>, '1.00123456789E-21'),
(0.<API key>, '1E-21'),
(0.<API key>, '10.0123456789E-21'),
(0.<API key>, '10E-21'),
(0.<API key>, '100.123456789E-21'),
(0.0000000000000000001, '100E-21'),
(0.<API key>, '1.00123456789E-18'),
(0.000000000000000001, '1E-18'),
(0.<API key>, '10.0123456789E-18'),
(0.00000000000000001, '10E-18'),
(0.<API key>, '100.123456789E-18'),
(0.0000000000000001, '100E-18'),
(0.<API key>, '1.00123456789E-15'),
(0.000000000000001, '1E-15'),
(0.<API key>, '10.0123456789E-15'),
(0.00000000000001, '10E-15'),
(0.<API key>, '100.123456789E-15'),
(0.0000000000001, '100E-15'),
(0.<API key>, '1.00123456789E-12'),
(0.000000000001, '1E-12'),
(0.<API key>, '10.0123456789E-12'),
(0.00000000001, '10E-12'),
(0.<API key>, '100.123456789E-12'),
(0.0000000001, '100E-12'),
(0.<API key>, '1.00123456789E-9'),
(0.000000001, '1E-9'),
(0.<API key>, '10.0123456789E-9'),
(0.00000001, '10E-9'),
(0.0000001001234567890, '100.123456789E-9'),
(0.0000001, '100E-9'),
(0.000001001234567890, '1.00123456789E-6'),
(0.000001, '1E-6'),
(0.00001001234567890, '10.0123456789E-6'),
(0.00001, '10E-6'),
(0.0001001234567890, '100.123456789E-6'),
(0.0001, '100E-6'),
(0.001001234567890, '1.00123456789E-3'),
(0.001, '1E-3'),
(0.01001234567890, '10.0123456789E-3'),
(0.01, '10E-3'),
(0.1001234567890, '100.123456789E-3'),
(0.1, '100E-3'),
(0, '0E+0'),
(1, '1E+0'),
(1.1234567890, '1.123456789E+0'),
(10, '10E+0'),
(10.1234567890, '10.123456789E+0'),
(100, '100E+0'),
(100.1234567890, '100.123456789E+0'),
(1000, '1E+3'),
(1000.1234567890, pv('1.00012345679E+3', '1.000123456789E+3')),
(10000, '10E+3'),
(10000.1234567890, pv('10.0001234568E+3', '10.000123456789E+3')),
(100000, '100E+3'),
(100000.1234567890, pv('100.000123457E+3', '100.000123456789E+3')),
(1000000, '1E+6'),
(1000000.1234567890, pv('1.00000012346E+6', '1.000000123456789E+6')),
(10000000, '10E+6'),
(10000000.1234567890, pv('10.0000001235E+6', '10.00000012345679E+6')),
(100000000, '100E+6'),
(100000000.1234567890, pv('100.000000123E+6', '100.00000012345679E+6')),
(1000000000, '1E+9'),
(1000000000.1234567890, pv('1.00000000012E+9', '1.0000000001234568E+9')),
(10000000000, '10E+9'),
(10000000000.1234567890, pv(t(9)+'1E+9', '10.000000000123457E+9')),
(100000000000, '100E+9'),
(100000000000.1234567890, pv('100E+9', '100.00000000012346E+9')),
(1000000000000, '1E+12'),
(1000000000000.1234567890, pv('1E+12', '1.0000000000001234E+12')),
(10000000000000, '10E+12'),
(10000000000000.1234567890, pv('10E+12', '10.000000000000123E+12')),
(100000000000000, '100E+12'),
(100000000000000.1234567890, pv('100E+12', '100.00000000000012E+12')),
(1000000000000000, '1E+15'),
(1000000000000000.1234567890, pv('1E+15', '1.0000000000000001E+15')),
(10000000000000000, '10E+15'),
(10000000000000000.1234567890, '10E+15'),
(100000000000000000, '100E+15'),
(100000000000000000.1234567890, '100E+15'),
(1000000000000000000, '1E+18'),
(1000000000000000000.1234567890, '1E+18'),
(<API key>, '10E+18'),
(<API key>.1234567890, '10E+18'),
(<API key>, '100E+18'),
(<API key>.1234567890, '100E+18'),
(<API key>, '1E+21'),
(<API key>.1234567890, '1E+21'),
(<API key>, '10E+21'),
(<API key>.1234567890, '10E+21'),
(<API key>, '100E+21'),
(<API key>.1234567890, pv('100E+21', h(13)+'1E+21')),
(<API key>, '1E+24'),
(<API key>.1234567890, '1E+24'),
(<API key>, '10E+24'),
(<API key>.1234567890, '10E+24'),
(<API key>, '100E+24'),
(<API key>.1234567890, '100E+24'),
(-0.<API key>, '-1.00123456789E-24'),
(-0.<API key>, '-1E-24'),
(-0.<API key>, '-10.0123456789E-24'),
(-0.<API key>, '-10E-24'),
(-0.<API key>, '-100.123456789E-24'),
(-0.<API key>, '-100E-24'),
(-0.<API key>, '-1.00123456789E-21'),
(-0.<API key>, '-1E-21'),
(-0.<API key>, '-10.0123456789E-21'),
(-0.<API key>, '-10E-21'),
(-0.<API key>, '-100.123456789E-21'),
(-0.0000000000000000001, '-100E-21'),
(-0.<API key>, '-1.00123456789E-18'),
(-0.000000000000000001, '-1E-18'),
(-0.<API key>, '-10.0123456789E-18'),
(-0.00000000000000001, '-10E-18'),
(-0.<API key>, '-100.123456789E-18'),
(-0.0000000000000001, '-100E-18'),
(-0.<API key>, '-1.00123456789E-15'),
(-0.000000000000001, '-1E-15'),
(-0.<API key>, '-10.0123456789E-15'),
(-0.00000000000001, '-10E-15'),
(-0.<API key>, '-100.123456789E-15'),
(-0.0000000000001, '-100E-15'),
(-0.<API key>, '-1.00123456789E-12'),
(-0.000000000001, '-1E-12'),
(-0.<API key>, '-10.0123456789E-12'),
(-0.00000000001, '-10E-12'),
(-0.<API key>, '-100.123456789E-12'),
(-0.0000000001, '-100E-12'),
(-0.<API key>, '-1.00123456789E-9'),
(-0.000000001, '-1E-9'),
(-0.<API key>, '-10.0123456789E-9'),
(-0.00000001, '-10E-9'),
(-0.0000001001234567890, '-100.123456789E-9'),
(-0.0000001, '-100E-9'),
(-0.000001001234567890, '-1.00123456789E-6'),
(-0.000001, '-1E-6'),
(-0.00001001234567890, '-10.0123456789E-6'),
(-0.00001, '-10E-6'),
(-0.0001001234567890, '-100.123456789E-6'),
(-0.0001, '-100E-6'),
(-0.001001234567890, '-1.00123456789E-3'),
(-0.001, '-1E-3'),
(-0.01001234567890, '-10.0123456789E-3'),
(-0.01, '-10E-3'),
(-0.1001234567890, '-100.123456789E-3'),
(-0.1, '-100E-3'),
(-1, '-1E+0'),
(-1.1234567890, '-1.123456789E+0'),
(-10, '-10E+0'),
(-10.1234567890, '-10.123456789E+0'),
(-100, '-100E+0'),
(-100.1234567890, '-100.123456789E+0'),
(-1000, '-1E+3'),
(-1000.1234567890, pv('-1.00012345679E+3', '-1.000123456789E+3')),
(-10000, '-10E+3'),
(-10000.1234567890, pv('-10.0001234568E+3', '-10.000123456789E+3')),
(-100000, '-100E+3'),
(-100000.1234567890, pv('-100.000123457E+3', '-100.000123456789E+3')),
(-1000000, '-1E+6'),
(-1000000.1234567890, pv('-1.00000012346E+6', '-1.000000123456789E+6')),
(-10000000, '-10E+6'),
(-10000000.1234567890, pv('-10.0000001235E+6', '-10.00000012345679E+6')),
(-100000000, '-100E+6'),
(-100000000.1234567890, pv('-'+h(6)+'123E+6', '-100.00000012345679E+6')),
(-1000000000, '-1E+9'),
(-1000000000.1234567890, pv('-'+o(9)+'12E+9', '-1.0000000001234568E+9')),
(-10000000000, '-10E+9'),
(-10000000000.1234567890, pv('-'+t(9)+'1E+9', '-'+t(9)+'123457E+9')),
(-100000000000, '-100E+9'),
(-100000000000.1234567890, pv('-100E+9', '-100.00000000012346E+9')),
(-1000000000000, '-1E+12'),
(-1000000000000.1234567890, pv('-1E+12', '-1.0000000000001234E+12')),
(-10000000000000, '-10E+12'),
(-10000000000000.1234567890, pv('-10E+12', '-10.000000000000123E+12')),
(-100000000000000, '-100E+12'),
(-100000000000000.1234567890, pv('-100E+12', '-100.00000000000012E+12')),
(-1000000000000000, '-1E+15'),
(-1000000000000000.1234567890, pv('-1E+15', '-1.0000000000000001E+15')),
(-10000000000000000, '-10E+15'),
(-10000000000000000.1234567890, '-10E+15'),
(-100000000000000000, '-100E+15'),
(-100000000000000000.1234567890, '-100E+15'),
(-1000000000000000000, '-1E+18'),
(-1000000000000000000.1234567890, '-1E+18'),
(-<API key>, '-10E+18'),
(-<API key>.1234567890, '-10E+18'),
(-<API key>, '-100E+18'),
(-<API key>.1234567890, '-100E+18'),
(-<API key>, '-1E+21'),
(-<API key>.1234567890, '-1E+21'),
(-<API key>, '-10E+21'),
(-<API key>.1234567890, '-10E+21'),
(-<API key>, '-100E+21'),
(-<API key>.1234567890, pv('-100E+21', '-'+h(13)+'1E+21')),
(-<API key>, '-1E+24'),
(-<API key>.1234567890, '-1E+24'),
(-<API key>, '-10E+24'),
(-<API key>.1234567890, '-10E+24'),
(-<API key>, '-100E+24'),
(-<API key>.1234567890, '-100E+24'),
('100000.1234567890', '100.000123456789E+3'),
('-100000.1234567890', '-100.000123456789E+3'),
]
)
def test_to_sci_string(num, ref):
""" Test _to_eng_string function behavior """
assert to_sci_string(num) == ref
@pytest.mark.parametrize(
'num, ref', [
(0, '0'),
(0.0, '0.0'),
(4, '4'),
(4.0, '4.0'),
(45, '45'),
(450, '450'),
(1234567, '1234567'),
(4.5, '4.5'),
(4.1234, '4.1234'),
(4123.4E4, '41234000'),
(0.1, '0.1'),
(1.43E-2, '0.0143'),
(100000000.0, '100000000.0'),
(1000000, '1000000'),
(1e3, '1000.0'),
]
)
def test_no_exp(num, ref):
""" Test no_exp function behavior """
assert putil.eng.no_exp(num) == ref
@pytest.mark.eng
def <API key>():
""" Test no_exp function exceptions """
AI(putil.eng.no_exp, 'number', number='a')
@pytest.mark.eng
@pytest.mark.parametrize(
'args, name', [
(dict(number=['5'], frac_length=3, rjust=True), 'number'),
(dict(number=5, frac_length=3.5, rjust=True), 'frac_length'),
(dict(number=5, frac_length=-2, rjust=True), 'frac_length'),
(dict(number=5, frac_length=3, rjust='a'), 'rjust')
]
)
def <API key>(args, name):
""" Test peng function exceptions """
AI(putil.eng.peng, name, **args)
@pytest.mark.parametrize(
'num, mant, rjust, ref', [
(3.0333333333, 1, False, '3.0'),
(0, 3, True, ' 0.000 '),
(0, 3, False, '0.000'),
(125.5, 0, False, '126'),
(1e-25, 3, True, ' 1.000y'),
(1e-24, 3, True, ' 1.000y'),
(1e-23, 3, True, ' 10.000y'),
(1e-22, 3, True, ' 100.000y'),
(1e-21, 3, True, ' 1.000z'),
(1e-20, 3, True, ' 10.000z'),
(1e-19, 3, True, ' 100.000z'),
(1e-18, 3, True, ' 1.000a'),
(1e-17, 3, True, ' 10.000a'),
(1e-16, 3, True, ' 100.000a'),
(1e-15, 3, True, ' 1.000f'),
(1e-14, 3, True, ' 10.000f'),
(1e-13, 3, True, ' 100.000f'),
(1e-12, 3, True, ' 1.000p'),
(1e-11, 3, True, ' 10.000p'),
(1e-10, 3, True, ' 100.000p'),
(1e-9, 3, True, ' 1.000n'),
(1e-8, 3, True, ' 10.000n'),
(1e-7, 3, True, ' 100.000n'),
(1e-6, 3, True, ' 1.000u'),
(1e-5, 3, True, ' 10.000u'),
(1e-4, 3, True, ' 100.000u'),
(1e-3, 3, True, ' 1.000m'),
(1e-2, 3, True, ' 10.000m'),
(1e-1, 3, True, ' 100.000m'),
(1e-0, 3, True, ' 1.000 '),
(1e+1, 3, True, ' 10.000 '),
(1e+2, 3, True, ' 100.000 '),
(1e+3, 3, True, ' 1.000k'),
(1e+4, 3, True, ' 10.000k'),
(1e+5, 3, True, ' 100.000k'),
(1e+6, 3, True, ' 1.000M'),
(1e+7, 3, True, ' 10.000M'),
(1e+8, 3, True, ' 100.000M'),
(1e+9, 3, True, ' 1.000G'),
(1e+10, 3, True, ' 10.000G'),
(1e+11, 3, True, ' 100.000G'),
(1e+12, 3, True, ' 1.000T'),
(1e+13, 3, True, ' 10.000T'),
(1e+14, 3, True, ' 100.000T'),
(1e+15, 3, True, ' 1.000P'),
(1e+16, 3, True, ' 10.000P'),
(1e+17, 3, True, ' 100.000P'),
(1e+18, 3, True, ' 1.000E'),
(1e+19, 3, True, ' 10.000E'),
(1e+20, 3, True, ' 100.000E'),
(1e+21, 3, True, ' 1.000Z'),
(1e+22, 3, True, ' 10.000Z'),
(1e+23, 3, True, ' 100.000Z'),
(1e+24, 3, True, ' 1.000Y'),
(1e+25, 3, True, ' 10.000Y'),
(1e+26, 3, True, ' 100.000Y'),
(1e+27, 3, True, ' 999.999Y'),
(12.45, 1, True, ' 12.5 '),
(998.999e3, 1, True, ' 999.0k'),
(998.999e3, 1, False, '999.0k'),
(999.999e3, 1, True, ' 1.0M'),
(999.999e3, 1, DFLT, ' 1.0M'),
(999.999e3, 1, False, '1.0M'),
(0.995, 0, False, '995m'),
(0.9999, 0, False, '1'),
(1.9999, 0, False, '2'),
(999.99, 0, False, '1k'),
(9.99, 1, False, '10.0'),
(5.25e3, 1, True, ' 5.3k'),
(1.05e3, 0, True, ' 1k'),
(-1e-25, 3, True, ' -1.000y'),
(-1e-24, 3, True, ' -1.000y'),
(-1e-23, 3, True, ' -10.000y'),
(-1e-22, 3, True, '-100.000y'),
(-1e-21, 3, True, ' -1.000z'),
(-1e-20, 3, True, ' -10.000z'),
(-1e-19, 3, True, '-100.000z'),
(-1e-18, 3, True, ' -1.000a'),
(-1e-17, 3, True, ' -10.000a'),
(-1e-16, 3, True, '-100.000a'),
(-1e-15, 3, True, ' -1.000f'),
(-1e-14, 3, True, ' -10.000f'),
(-1e-13, 3, True, '-100.000f'),
(-1e-12, 3, True, ' -1.000p'),
(-1e-11, 3, True, ' -10.000p'),
(-1e-10, 3, True, '-100.000p'),
(-1e-9, 3, True, ' -1.000n'),
(-1e-8, 3, True, ' -10.000n'),
(-1e-7, 3, True, '-100.000n'),
(-1e-6, 3, True, ' -1.000u'),
(-1e-5, 3, True, ' -10.000u'),
(-1e-4, 3, True, '-100.000u'),
(-1e-3, 3, True, ' -1.000m'),
(-1e-2, 3, True, ' -10.000m'),
(-1e-1, 3, True, '-100.000m'),
(-1e-0, 3, True, ' -1.000 '),
(-1e+1, 3, True, ' -10.000 '),
(-1e+2, 3, True, '-100.000 '),
(-1e+3, 3, True, ' -1.000k'),
(-1e+4, 3, True, ' -10.000k'),
(-1e+5, 3, True, '-100.000k'),
(-1e+6, 3, True, ' -1.000M'),
(-1e+7, 3, True, ' -10.000M'),
(-1e+8, 3, True, '-100.000M'),
(-1e+9, 3, True, ' -1.000G'),
(-1e+10, 3, True, ' -10.000G'),
(-1e+11, 3, True, '-100.000G'),
(-1e+12, 3, True, ' -1.000T'),
(-1e+13, 3, True, ' -10.000T'),
(-1e+14, 3, True, '-100.000T'),
(-1e+15, 3, True, ' -1.000P'),
(-1e+16, 3, True, ' -10.000P'),
(-1e+17, 3, True, '-100.000P'),
(-1e+18, 3, True, ' -1.000E'),
(-1e+19, 3, True, ' -10.000E'),
(-1e+20, 3, True, '-100.000E'),
(-1e+21, 3, True, ' -1.000Z'),
(-1e+22, 3, True, ' -10.000Z'),
(-1e+23, 3, True, '-100.000Z'),
(-1e+24, 3, True, ' -1.000Y'),
(-1e+25, 3, True, ' -10.000Y'),
(-1e+26, 3, True, '-100.000Y'),
(-1e+27, 3, True, '-999.999Y'),
(-12.45, 1, True, ' -12.5 '),
(-998.999e3, 1, True, '-999.0k'),
(-998.999e3, 1, False, '-999.0k'),
(-999.999e3, 1, True, ' -1.0M'),
(-999.999e3, 1, DFLT, ' -1.0M'),
(-999.999e3, 1, False, '-1.0M'),
(-0.995, 0, False, '-995m'),
(-0.9999, 0, False, '-1'),
(-1.9999, 0, False, '-2'),
(-999.99, 0, False, '-1k'),
(-9.99, 1, False, '-10.0'),
(-5.25e3, 1, True, ' -5.3k'),
(-1.05e3, 0, True, ' -1k')
]
)
def test_peng(num, mant, rjust, ref):
""" Test peng function behavior """
obj = putil.eng.peng
obj = obj if isdflt(rjust) else functools.partial(obj, rjust=rjust)
assert obj(num, mant) == ref
@pytest.mark.eng
@pytest.mark.parametrize('arg', [None, 5, '', ' 5x', 'a5M', '- - a5M'])
@pytest.mark.parametrize(
'func', [
putil.eng.peng_float,
putil.eng.peng_frac,
putil.eng.peng_int,
putil.eng.peng_mant,
putil.eng.peng_power,
putil.eng.peng_suffix,
]
)
def <API key>(func, arg):
"""
Test exceptions of functions that receive a string representing
a number in engineering notation
"""
AI(func, 'snum', **dict(snum=arg))
@pytest.mark.parametrize(
'arg, ref', [
(putil.eng.peng(5234.567, 3, True), 5.235e3),
(' 5.235k ', 5.235e3),
(' -5.235k ', -5.235e3),
]
)
def test_peng_float(arg, ref):
""" Test peng_float function behavior """
assert putil.eng.peng_float(arg) == ref
@pytest.mark.parametrize(
'arg, ref', [
(putil.eng.peng(5234.567, 6, True), 234567),
(putil.eng.peng(5234, 0, True), 0)
]
)
def test_peng_frac(arg, ref):
""" Test peng_frac function behavior """
assert putil.eng.peng_frac(arg) == ref
def test_peng_int():
""" Test peng_int function behavior """
assert putil.eng.peng_int(putil.eng.peng(5234.567, 6, True)) == 5
def test_peng_mant():
""" Test peng_mant function behavior """
assert putil.eng.peng_mant(putil.eng.peng(5234.567, 3, True)) == 5.235
def test_peng_power():
""" Test peng_power function behavior """
tup = putil.eng.peng_power(putil.eng.peng(1234.567, 3, True))
assert tup == ('k', 1000.0)
assert isinstance(tup[1], float)
@pytest.mark.parametrize(
'arg, ref', [
(putil.eng.peng(1, 3, True), ' '),
(putil.eng.peng(-10.5e-6, 3, False), 'u')
]
)
def test_peng_suffix(arg, ref):
""" Test peng_suffix function behavior """
assert putil.eng.peng_suffix(arg) == ref
@pytest.mark.eng
@pytest.mark.parametrize(
'args, extype, name', [
(dict(suffix='X', offset=-1), RuntimeError, 'suffix'),
(dict(suffix='M', offset='a'), RuntimeError, 'offset'),
(dict(suffix='M', offset=20), ValueError, 'offset'),
]
)
@pytest.mark.eng
def <API key>(args, extype, name):
""" Test peng_suffix_math function exceptions """
AE(putil.eng.peng_suffix_math, extype, sarg(name), **args)
@pytest.mark.parametrize('args, ref', [((' ', 3), 'G'), (('u', -2), 'p')])
def <API key>(args, ref):
""" Test peng_suffix_math function behavior """
assert putil.eng.peng_suffix_math(*args) == ref
@pytest.mark.parametrize(
'num, frac_length, exp_length, sign_always, ref', [
('5.35E+3', DFLT, DFLT, DFLT, '5.35E+3'),
(0, DFLT, DFLT, DFLT, '0E+0'),
(0.1, DFLT, DFLT, DFLT, '1E-1'),
(0.01, DFLT, DFLT, DFLT, '1E-2'),
(0.001, DFLT, DFLT, DFLT, '1E-3'),
(0.00101, DFLT, DFLT, DFLT, '1.01E-3'),
(0.123456789012, DFLT, DFLT, DFLT, '1.23456789012E-1'),
(1234567.89012, DFLT, DFLT, DFLT, '1.23456789012E+6'),
(1, DFLT, DFLT, DFLT, '1E+0'),
(20, DFLT, DFLT, DFLT, '2E+1'),
(100, DFLT, DFLT, DFLT, '1E+2'),
(200, DFLT, DFLT, DFLT, '2E+2'),
(333, DFLT, DFLT, DFLT, '3.33E+2'),
(4567, DFLT, DFLT, DFLT, '4.567E+3'),
(4567.890, DFLT, DFLT, DFLT, '4.56789E+3'),
(500, 3, DFLT, DFLT, '5.000E+2'),
(4567.890, 8, DFLT, DFLT, '4.56789000E+3'),
(99.999, 1, DFLT, DFLT, '1.0E+2'),
(4567.890, DFLT, DFLT, True, '+4.56789E+3'),
(500, 3, DFLT, True, '+5.000E+2'),
(4567.890, 8, DFLT, True, '+4.56789000E+3'),
(99.999, 1, DFLT, True, '+1.0E+2'),
(500, 3, 2, True, '+5.000E+02'),
(4567.890, 8, 3, True, '+4.56789000E+003'),
(9999999999.999, 1, 1, True, '+1.0E+10'),
(-0.1, DFLT, DFLT, DFLT, '-1E-1'),
(-0.01, DFLT, DFLT, DFLT, '-1E-2'),
(-0.001, DFLT, DFLT, DFLT, '-1E-3'),
(-0.00101, DFLT, DFLT, DFLT, '-1.01E-3'),
(-0.123456789012, DFLT, DFLT, DFLT, '-1.23456789012E-1'),
(-1234567.89012, DFLT, DFLT, DFLT, '-1.23456789012E+6'),
(-1, DFLT, DFLT, DFLT, '-1E+0'),
(-20, DFLT, DFLT, DFLT, '-2E+1'),
(-100, DFLT, DFLT, DFLT, '-1E+2'),
(-200, DFLT, DFLT, DFLT, '-2E+2'),
(-333, DFLT, DFLT, DFLT, '-3.33E+2'),
(-4567, DFLT, DFLT, DFLT, '-4.567E+3'),
(-4567.890, DFLT, DFLT, DFLT, '-4.56789E+3'),
(-500, 3, DFLT, DFLT, '-5.000E+2'),
(-4567.890, 8, DFLT, DFLT, '-4.56789000E+3'),
(-99.999, 1, DFLT, DFLT, '-1.0E+2'),
(-4567.890, DFLT, DFLT, True, '-4.56789E+3'),
(-500, 3, DFLT, True, '-5.000E+2'),
(-4567.890, 8, DFLT, True, '-4.56789000E+3'),
(-99.999, 1, DFLT, True, '-1.0E+2'),
(-500, 3, 2, True, '-5.000E+02'),
(-4567.890, 8, 3, True, '-4.56789000E+003'),
(-9999999999.999, 1, 1, True, '-1.0E+10'),
]
)
def <API key>(num, frac_length, exp_length, sign_always, ref):
""" Test _to_scientific function behavior """
fp = functools.partial
obj = putil.eng.<API key>
obj = obj if isdflt(frac_length) else fp(obj, frac_length=frac_length)
obj = obj if isdflt(exp_length) else fp(obj, exp_length=exp_length)
obj = obj if isdflt(sign_always) else fp(obj, sign_always=sign_always)
assert obj(num) == ref
CVECTOR = [-1+2j, 3+4j, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j]
@pytest.mark.parametrize(
'vector, args, ref, header', [
(
None,
DFLT,
'None',
''
),
(
[1, 2, 3, 4, 5, 6, 7, 8],
DFLT,
'[ 1, 2, 3, 4, 5, 6, 7, 8 ]',
''
),
(
[1, 2, 3, 4, 5, 6, 7, 8],
dict(indent=20),
'[ 1, 2, 3, 4, 5, 6, 7, 8 ]',
''
),
(
[1, 2, 3, 4, 5, 6, 7, 8],
dict(indent=20),
'[ 1, 2, 3, 4, 5, 6, 7, 8 ]',
''
),
(
[1, 2, 3, 4, 5, 6, 7, 8],
dict(limit=True),
'[ 1, 2, 3, ..., 6, 7, 8 ]',
''
),
(
[1, 2, 3, 4, 5, 6, 7, 8],
dict(limit=True, indent=20),
'[ 1, 2, 3, ..., 6, 7, 8 ]',
''
),
# Float and integer item #ref = (
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(eng=True),
'[ 1.000m, 20.000u, 300.000M, 4.000p,'
' 5.250k, -6.000n, 700.000 , 800.000m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(eng=True, indent=20),
'[ 1.000m, 20.000u, 300.000M, 4.000p,'
' 5.250k, -6.000n, 700.000 , 800.000m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(limit=True, eng=True),
'[ 1.000m, 20.000u, 300.000M,'
' ...,'
' -6.000n, 700.000 , 800.000m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(limit=True, eng=True, indent=20),
'[ 1.000m, 20.000u, 300.000M,'
' ...,'
' -6.000n, 700.000 , 800.000m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(eng=True, frac_length=1),
'[ 1.0m, 20.0u, 300.0M, 4.0p,'
' 5.3k, -6.0n, 700.0 , 800.0m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(eng=True, frac_length=1, indent=20),
'[ 1.0m, 20.0u, 300.0M, 4.0p,'
' 5.3k, -6.0n, 700.0 , 800.0m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(limit=True, eng=True, frac_length=1),
'[ 1.0m, 20.0u, 300.0M, ..., -6.0n, 700.0 , 800.0m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(limit=True, indent=20, eng=True, frac_length=1),
'[ 1.0m, 20.0u, 300.0M, ..., -6.0n, 700.0 , 800.0m ]',
''
),
(
[1, 2, 3, 4, 5, 6, 7, 8],
dict(width=8),
#12345678
'[ 1, 2,\n'
' 3, 4,\n'
' 5, 6,\n'
' 7, 8 ]',
''
),
(
[1, 2, 3, 4, 5, 6, 7, 8],
dict(width=10),
'[ 1, 2, 3,\n'
' 4, 5, 6,\n'
' 7, 8 ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9],
dict(width=20, eng=True, frac_length=0),
'[ 1m, 20u,\n'
' 300M, 4p,\n'
' 5k, -6n,\n'
' 700 , 8 ,\n'
' 9 ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(width=30, eng=True, frac_length=1),
'[ 1.0m, 20.0u, 300.0M,\n'
' 4.0p, 5.3k, -6.0n,\n'
' 700.0 , 800.0m ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9],
dict(width=20, eng=True, frac_length=0, limit=True),
'[ 1m,\n'
' 20u,\n'
' 300M,\n'
' ...\n'
' 700 ,\n'
' 8 ,\n'
' 9 ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9],
dict(width=30, eng=True, frac_length=1, limit=True),
'[ 1.0m, 20.0u, 300.0M,\n'
' ...\n'
' 700.0 , 8.0 , 9.0 ]',
''
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9],
dict(width=30, eng=True, frac_length=1, limit=True, indent=8),
'Vector: [ 1.0m, 20.0u, 300.0M,\n'
' ...\n'
' 700.0 , 8.0 , 9.0 ]',
'Vector: '
),
(
[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8],
dict(width=30, eng=True, frac_length=1, indent=8),
'Vector: [ 1.0m, 20.0u, 300.0M,\n'
' 4.0p, 5.3k, -6.0n,\n'
' 700.0 , 800.0m ]',
'Vector: '
),
(
[
1.23456789, 2.45678901, 3.45678901, 4.56789012,
5.67890123, 6.78901234, 7.89012345
],
dict(limit=True, width=80-22, indent=22),
'Independent variable: [ 1.23456789, 2.45678901, 3.45678901,\n'
' ...\n'
' 5.67890123, 6.78901234, 7.89012345 ]',
'Independent variable: '
),
(
[
1.23456789, 2.45678901, 3.45678901, 4.56789012,
5.67890123, 6.78901234, 7.89012345
],
dict(width=49, indent=17),
'Independent var: [ 1.23456789, 2.45678901, 3.45678901, '
'4.56789012,\n'
' 5.67890123, 6.78901234, 7.89012345 ]',
'Independent var: '
),
# Complex items
(
CVECTOR,
DFLT,
'[ -1+2j, 3+4j, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j ]',
''
),
(
CVECTOR,
dict(indent=20),
'[ -1+2j, 3+4j, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j ]',
''
),
(
CVECTOR,
dict(limit=True),
'[ -1+2j, 3+4j, 5+6j, ..., 11+12j, -13+14j, 15678-16j ]',
''
),
(
CVECTOR,
dict(limit=True, indent=20),
'[ -1+2j, 3+4j, 5+6j, ..., 11+12j, -13+14j, 15678-16j ]',
''
),
(
CVECTOR,
dict(eng=True),
'[ -1.000 + 2.000 j, 3.000 + 4.000 j,'
' 5.000 + 6.000 j,'
' 7.000 + 8.000 j, 9.000 - 10.000 j,'
' 11.000 + 12.000 j,'
' -13.000 + 14.000 j, 15.678k- 16.000 j ]',
''
),
(
CVECTOR,
dict(eng=True, indent=20),
'[ -1.000 + 2.000 j, 3.000 + 4.000 j,'
' 5.000 + 6.000 j,'
' 7.000 + 8.000 j, 9.000 - 10.000 j,'
' 11.000 + 12.000 j,'
' -13.000 + 14.000 j, 15.678k- 16.000 j ]',
''
),
(
CVECTOR,
dict(limit=True, eng=True),
'[ -1.000 + 2.000 j, 3.000 + 4.000 j,'
' 5.000 + 6.000 j,'
' ..., 11.000 + 12.000 j, -13.000 + 14.000 j,'
' 15.678k- 16.000 j ]',
''
),
(
CVECTOR,
dict(limit=True, eng=True, indent=20),
'[ -1.000 + 2.000 j, 3.000 + 4.000 j,'
' 5.000 + 6.000 j,'
' ..., 11.000 + 12.000 j, -13.000 + 14.000 j,'
' 15.678k- 16.000 j ]',
''
),
(
CVECTOR,
dict(eng=True, frac_length=1),
'[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,'
' 7.0 + 8.0 j, 9.0 - 10.0 j, 11.0 + 12.0 j,'
' -13.0 + 14.0 j, 15.7k- 16.0 j ]',
''
),
(
CVECTOR,
dict(eng=True, frac_length=1, indent=20),
'[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,'
' 7.0 + 8.0 j, 9.0 - 10.0 j, 11.0 + 12.0 j,'
' -13.0 + 14.0 j, 15.7k- 16.0 j ]',
''
),
(
CVECTOR,
dict(limit=True, eng=True, frac_length=1),
'[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,'
' ..., 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]',
''
),
(
CVECTOR,
dict(limit=True, eng=True, frac_length=1, indent=20),
'[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,'
' ..., 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]',
''
),
(
CVECTOR,
dict(width=22),
'[ -1+2j, 3+4j, 5+6j,\n'
' 7+8j, 9-10j, 11+12j,\n'
' -13+14j, 15678-16j ]',
''
),
(
CVECTOR,
dict(width=20),
'[ -1+2j, 3+4j, 5+6j,\n'
' 7+8j, 9-10j,\n'
' 11+12j, -13+14j,\n'
' 15678-16j ]',
''
),
(
CVECTOR,
dict(width=29, eng=True, frac_length=0),
'[ -1 + 2 j, 3 + 4 j,\n'
' 5 + 6 j, 7 + 8 j,\n'
' 9 - 10 j, 11 + 12 j,\n'
' -13 + 14 j, 16k- 16 j ]',
''
),
(
CVECTOR,
dict(width=37, eng=True, frac_length=1),
'[ -1.0 + 2.0 j, 3.0 + 4.0 j,\n'
' 5.0 + 6.0 j, 7.0 + 8.0 j,\n'
' 9.0 - 10.0 j, 11.0 + 12.0 j,\n'
' -13.0 + 14.0 j, 15.7k- 16.0 j ]',
''
),
(
CVECTOR,
dict(width=16, eng=True, frac_length=0),
'[ -1 + 2 j,\n'
' 3 + 4 j,\n'
' 5 + 6 j,\n'
' 7 + 8 j,\n'
' 9 - 10 j,\n'
' 11 + 12 j,\n'
' -13 + 14 j,\n'
' 16k- 16 j ]',
''
),
(
CVECTOR,
dict(width=16, eng=True, frac_length=0, limit=True),
'[ -1 + 2 j,\n'
' 3 + 4 j,\n'
' 5 + 6 j,\n'
' ...\n'
' 11 + 12 j,\n'
' -13 + 14 j,\n'
' 16k- 16 j ]',
''
),
(
CVECTOR,
dict(width=56, eng=True, frac_length=1, limit=True),
'[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,\n'
' ...\n'
' 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]',
''
),
(
CVECTOR,
dict(width=64, eng=True, frac_length=1, limit=True, indent=8),
'Vector: [ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,\n'
' ...\n'
' 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]',
'Vector: '
),
(
CVECTOR,
dict(width=20, indent=8),
'Vector: [ -1+2j, 3+4j, 5+6j,\n'
' 7+8j, 9-10j,\n'
' 11+12j, -13+14j,\n'
' 15678-16j ]',
'Vector: '
),
(
CVECTOR,
dict(width=30, indent=8, limit=True),
'Vector: [ -1+2j, 3+4j, 5+6j,\n'
' ...\n'
' 11+12j, -13+14j, 15678-16j ]',
'Vector: '
),
(
CVECTOR,
dict(width=20, indent=8, limit=True),
'Vector: [ -1+2j,\n'
' 3+4j,\n'
' 5+6j,\n'
' ...\n'
' 11+12j,\n'
' -13+14j,\n'
' 15678-16j ]',
'Vector: '
),
(
array(
[
-0.10081675027325637-0.06910517142735251j,
0.018754229185649937+0.017142783560861786j,
0+18j
]
),
DFLT,
'[ -0.100816750273-0.0691051714274j, '
'0.0187542291856+0.0171427835609j, 18j ]',
''
),
(
array(
[
-0.10081675027325637-0.06910517142735251j,
0.018754229185649937+0.017142783560861786j,
0+18j
]
),
dict(width=60, limit=True, indent=20),
'Dependent variable: [ -0.100816750273-0.0691051714274j,\n'
' 0.0187542291856+0.0171427835609j, 18j ]',
'Dependent variable: '
),
(
array(
[
-0.10081675027325637-0.06910517142735251j,
0.018754229185649937+0.017142783560861786j,
0+18j,
0.118754229185649937+0.117142783560861786j,
0.218754229185649937+0.217142783560861786j,
0+28j,
10+2j,
]
),
dict(width=60),
'[ -0.100816750273-0.0691051714274j,\n'
' 0.0187542291856+0.0171427835609j, 18j,\n'
' 0.118754229186+0.117142783561j,\n'
' 0.218754229186+0.217142783561j, 28j, 10+2j ]',
''
),
(
array(
[
-0.10081675027325637-0.06910517142735251j,
0.018754229185649937+0.017142783560861786j,
0+18j,
0.118754229185649937+0.117142783560861786j,
0.218754229185649937+0.217142783560861786j,
0+28j,
10+2j,
]
),
dict(width=60, limit=True),
'[ -0.100816750273-0.0691051714274j,\n'
' 0.0187542291856+0.0171427835609j,\n'
' 18j,\n'
' ...\n'
' 0.218754229186+0.217142783561j,\n'
' 28j,\n'
' 10+2j ]',
''
),
]
)
def test_pprint_vector(vector, args, ref, header):
""" Test pprint_vector function behavior """
obj = putil.eng.pprint_vector
obj = obj if isdflt(args) else functools.partial(obj, **args)
CS(header+obj(vector), ref)
@pytest.mark.parametrize(
'args', [
dict(
vector=[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9],
width=5, eng=True, frac_length=1, limit=True
),
dict(
vector=[-1+2j, 3, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j],
width=8, limit=True
)
]
)
@pytest.mark.eng
def <API key>(args):
""" Test pprint_vector function exceptions """
msg = 'Argument `width` is too small'
AE(putil.eng.pprint_vector, ValueError, msg, **args)
@pytest.mark.parametrize(
'num, dec, ref', [
(None, DFLT, None),
(1.3333, 2, 1.33),
(1.5555E-12, 2, 1.56E-12),
(3, 2, 3),
(array([1.3333, 2.666666]), 2, array([1.33, 2.67])),
(array([1.3333E-12, 2.666666E-12]), 2, array([1.33E-12, 2.67E-12])),
(array([1, 3]), 2, array([1, 3])),
]
)
def test_round_mantissa(num, dec, ref):
""" Test round_mantissa function behavior """
obj = putil.eng.round_mantissa
obj = obj if isdflt(dec) else functools.partial(obj, decimals=dec)
test = obj(num) == ref
assert test.all() if isinstance(num, ndarray) else test
|
<div class="commune_descr limited">
<p>
Le Caire est
un village
géographiquement positionné dans le département de l'<API key> en Provence-Alpes-Côte d'Azur. Elle comptait 70 habitants en 2008.</p>
<p>Le parc de logements, à Le Caire, se décomposait en 2011 en sept appartements et 61 maisons soit
un marché relativement équilibré.</p>
<p>À coté de Le Caire sont situées les villes de
<a href="{{VLROOT}}/immobilier/bayons_04023/">Bayons</a> située à 8 km, 257 habitants,
<a href="{{VLROOT}}/immobilier/brunet_04035/">Brunet</a> à 6 km, 249 habitants,
<a href="{{VLROOT}}/immobilier/saulce_05162/">La Saulce</a> à 7 km, 1 190 habitants,
<a href="{{VLROOT}}/immobilier/melve_04118/">Melve</a> localisée à 5 km, 109 habitants,
<a href="{{VLROOT}}/immobilier/curbans_04066/">Curbans</a> localisée à 6 km, 333 habitants,
<a href="{{VLROOT}}/immobilier/claret_04058/">Claret</a> à 8 km, 227 habitants,
entre autres. De plus, Le Caire est située à seulement 21 km de <a href="{{VLROOT}}/immobilier/gap_05061/">Gap</a>.</p>
<p>Si vous envisagez de venir habiter à Le Caire, vous pourrez facilement trouver une maison à vendre. </p>
</div>
|
<?php
include "config.php";
session_start();
if(!isset($_SESSION['username'])){
//header("location:login.php");
}
?>
<!DOCTYPE html>
<!
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>HOSPITAL MANAGMENT SYSTEM</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<link rel="stylesheet" href="dist/css/skins/skin-blue.min.css">
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!-- Main Header -->
<header class="main-header">
<!-- Logo -->
<a href="" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>H</b>MS</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>HMS</b></span>
</a>
<!-- Header Navbar -->
<nav class="navbar navbar-static-top" role="navigation">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-user"></i>
<b class="caret hidden-sm hidden-xs"></b>
<span class="notification hidden-sm hidden-xs">2</span>
<p class="hidden-lg hidden-md">
5 Notifications
<b class="caret"></b>
</p>
</a>
<ul class="dropdown-menu">
<li><a href="login.php">Logout</a></li>
<li><a href="#">change password</a></li>
</ul>
</li>
<li class="separator hidden-lg hidden-md"></li>
</ul>
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success"></span>
</a>
<ul class="dropdown-menu">
<!-- inner menu: contains the messages -->
<ul class="menu">
<li><!-- start message -->
<a href="
<div class="pull-left">
<!-- User Image -->
<i class=""></i>
</div>
</a>
</li>
<!-- end message -->
</ul>
<!-- /.menu -->
</li>
<li class="footer"><a href="#"></a></li>
</ul>
</li>
<!-- /.messages-menu -->
<!-- Notifications Menu -->
<li class="dropdown notifications-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class=""></i>
<span class="label label-warning"></span>
</a>
<ul class="dropdown-menu">
<!-- Tasks Menu -->
<li class="dropdown tasks-menu">
<!-- Menu Toggle Button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class=""></i>
<span class=""></span>
</a>
<ul class="dropdown-menu">
<li class="header"></li>
<li>
</li>
<!-- User Account Menu -->
<!-- Menu Body -->
<li class="user-body">
<!-- /.row -->
</li>
<!-- Menu Footer-->
</ul>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="#" data-toggle="control-sidebar"><i class=""></i></a>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar Menu -->
<?php
include "sidebar.php";
?>
<!-- /.sidebar-menu -->
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
</section>
<!-- Main content -->
<section class="content container-fluid">
<?php
include("xray_registration.php");
?>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- Main Footer -->
<footer class="main-footer">
<!-- To the right -->
<div class="pull-right hidden-xs">
</div>
<!-- Default to the left -->
<strong>Copyright © 2017 <a href="
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar <API key>">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified <API key>">
<li class="active"><a href="#<API key>" data-toggle="tab"><i class="fa fa-home"></i></a></li>
<li><a href="#<API key>" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane active" id="<API key>">
<h3 class="<API key>">Recent Activity</h3>
<ul class="<API key>">
<li>
<a href="javascript:;">
<i class="menu-icon fa fa-birthday-cake bg-red"></i>
<div class="menu-info">
<h4 class="<API key>">Langdon's Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
</ul>
<!-- /.<API key> -->
<h3 class="<API key>">Tasks Progress</h3>
<ul class="<API key>">
<li>
<a href="javascript:;">
<h4 class="<API key>">
Custom Template Design
<span class="<API key>">
<span class="label label-danger pull-right">70%</span>
</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-danger" style="width: 70%"></div>
</div>
</a>
</li>
</ul>
<!-- /.<API key> -->
</div>
<!-- /.tab-pane -->
<!-- Stats tab content -->
<div class="tab-pane" id="<API key>">Stats Tab Content</div>
<!-- /.tab-pane -->
<!-- Settings tab content -->
<div class="tab-pane" id="<API key>">
<form method="post">
<h3 class="<API key>">General Settings</h3>
<div class="form-group">
<label class="<API key>">
Report panel usage
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Some information about this general settings option
</p>
</div>
<!-- /.form-group -->
</form>
</div>
<!-- /.tab-pane -->
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- REQUIRED JS SCRIPTS -->
<!-- jQuery 3 -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<!-- Optionally, you can add Slimscroll and FastClick plugins.
Both of these plugins are recommended to enhance the
user experience.
</body>
</html>
|
require "pact_broker/api/resources/<API key>"
require "pact_broker/matrix/service"
module PactBroker
module Api
module Resources
describe <API key> do
include_context "stubbed services"
before do
allow(PactBroker::Deployments::EnvironmentService).to receive(:find_by_name).and_return(environment)
allow(PactBroker::Matrix::Service).to receive(:can_i_deploy).and_return([])
allow(pacticipant_service).to receive(:<API key>).and_return(pacticipant)
allow(PactBroker::Api::Decorators::MatrixDecorator).to receive(:new).and_return(decorator)
allow(version_service).to receive(:<API key>).and_return(version)
end
let(:pacticipant) { double("pacticipant") }
let(:version) { double("version") }
let(:json_response_body) { JSON.parse(subject.body, symbolize_names: true) }
let(:decorator) { double("decorator", to_json: "response_body") }
let(:selectors) { double("selectors") }
let(:options) { double("options") }
let(:environment) { double("environment") }
let(:path) { "/pacticipants/Foo/branches/main/latest-version/can-i-deploy/to-environment/dev" }
subject { get(path, nil, "Content-Type" => "application/hal+json") }
it "looks up the by branch" do
expect(version_service).to receive(:<API key>).with("Foo", "main")
subject
end
it "checks if the version can be deployed to the environment" do
expect(PactBroker::Matrix::Service).to receive(:can_i_deploy).with(anything, hash_including(environment_name: "dev"))
subject
end
it { is_expected.to <API key> }
context "when the environment does not exist" do
let(:environment) { nil }
its(:status) { is_expected.to eq 404 }
end
end
end
end
end
|
import React from 'react'
import {
Container,
Group,
TabBar,
Icon,
Badge,
amStyles,
} from 'amazeui-touch'
import {Link} from 'react-router'
class App extends React.Component{
propsType ={
children:React.PropTypes.node
}
render(){
let {
location,
params,
children,
props
} = this.props;
let transition = children.props.transition || 'sfr'
return (
<Container direction="column">
<Container
transition={transition}
>
{children}
</Container>
<TabBar
>
<TabBar.Item
component={Link}
eventKey = 'home'
active = {location.pathname === '/'}
icon = 'home'
title = ''
to='/'
/>
<TabBar.Item
component={Link}
active={location.pathname === '/class'}
eventKey="class"
icon="list"
title=""
to='/class'
/>
<TabBar.Item
active={location.pathname === '/search'}
eventKey="search"
icon="search"
title=""
/>
<TabBar.Item
component={Link}
active={location.pathname === '/me'}
eventKey="person"
icon="person"
title=""
to='/me'
/>
</TabBar>
</Container>
)
}
}
export default App
|
<?php
$<API key> = get_the_category();
$<API key> = "";
if ( ! empty( $<API key> ) ) {
$<API key> = esc_html( $<API key>[0]->name );
}
?>
<article class="su-article su-article--divider su-article--<?php echo strtolower($<API key>); ?>" id="post-<?php the_ID(); ?>">
<header class="su-header su-article__header">
<h2 class="su-heading su-heading--two su-article__title">
<a href="<?php the_permalink() ?>" rel="bookmark" class="su-heading__link">
<?php the_title() ?>
</a>
</h2>
<div class="su-article__date"><?php the_date() ?></div>
</header>
<div class="su-article__content">
<?php
the_excerpt();
?>
<a href="<?php the_permalink()?>" class="su-article__more">Continue reading <span class="<API key>"><?php the_title() ?></span></a>
</div>
<footer class="su-article__footer">
<div class="su-article-meta <API key>">
<?php sheru_entry_meta(); ?>
</div>
</footer>
</article>
|
<?php
namespace jeremykenedy\laravelusers;
use Illuminate\Support\ServiceProvider;
class <API key> extends ServiceProvider
{
private $_packageTag = 'laravelusers';
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this-><API key>(__DIR__.'/resources/lang/', $this->_packageTag);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->loadRoutesFrom(__DIR__.'/routes/web.php');
$this->loadViewsFrom(__DIR__.'/resources/views/', $this->_packageTag);
$this->mergeConfigFrom(__DIR__.'/config/'.$this->_packageTag.'.php', $this->_packageTag);
$this->publishFiles();
$this->app->make('jeremykenedy\laravelusers\App\Http\Controllers\<API key>');
$this->app->singleton(jeremykenedy\laravelusers\App\Http\Controllers\<API key>\<API key>::class, function () {
return new App\Http\Controllers\<API key>();
});
$this->app->alias(<API key>::class, 'laravelusers');
}
/**
* Publish files for the package.
*
* @return void
*/
private function publishFiles()
{
$publishTag = $this->_packageTag;
$this->publishes([
__DIR__.'/config/'.$this->_packageTag.'.php' => base_path('config/'.$this->_packageTag.'.php'),
], $publishTag);
$this->publishes([
__DIR__.'/resources/views' => resource_path('views/vendor/'.$this->_packageTag),
], $publishTag);
$this->publishes([
__DIR__.'/resources/lang' => resource_path('lang/vendor/'.$this->_packageTag),
], $publishTag);
}
}
|
<?php
namespace framework\ext;
//xml
class Xml
{
public static function decode($xml)
{
$values = array();
$index = array();
$array = array();
$parser = xml_parser_create('utf-8');
<API key>($parser, <API key>, 1);
<API key>($parser, <API key>, 0);
<API key>($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i]['tag'];
$array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
$array[$name] = self::_struct_to_array($values, $i);
return $array;
}
private static function _struct_to_array($values, &$i)
{
$child = array();
if (isset($values[$i]['value']))
array_push($child, $values[$i]['value']);
while ($i++ < count($values))
{
switch ($values[$i]['type'])
{
case 'cdata':
array_push($child, $values[$i]['value']);
break;
case 'complete':
$name = $values[$i]['tag'];
if(!empty($name))
{
$child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
if(isset($values[$i]['attributes']))
{
$child[$name] = $values[$i]['attributes'];
}
}
break;
case 'open':
$name = $values[$i]['tag'];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = self::_struct_to_array($values, $i);
break;
case 'close':
return $child;
break;
}
}
return $child;
}
}
|
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;
import java.io.IOException;
public class <API key> {
public static void main(String[] args) throws IOException {
final Mail mail = new Mail();
mail.setFrom(new Email("test@example.com", "Example User"));
mail.setSubject("Sending with Twilio SendGrid is Fun");
final Personalization personalization = new Personalization();
personalization.addTo(new Email("test1@example.com", "Example User1"));
personalization.addTo(new Email("test2@example.com", "Example User2"));
personalization.addTo(new Email("test3@example.com", "Example User3"));
mail.addPersonalization(personalization);
mail.addContent(new Content("text/plain", "and easy to do anywhere, even with Java"));
mail.addContent(new Content("text/html", "<strong>and easy to do anywhere, even with Java</strong>"));
send(mail);
}
private static void send(final Mail mail) throws IOException {
final SendGrid client = new SendGrid(System.getenv("SENDGRID_API_KEY"));
final Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
final Response response = client.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
}
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>Bombás játék: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Bombás játék
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.5 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">uivector Member List</div> </div>
</div><!--header
<div class="contents">
<p>This is the complete list of members for <a class="el" href="structuivector.html">uivector</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>allocsize</b> (defined in <a class="el" href="structuivector.html">uivector</a>)</td><td class="entry"><a class="el" href="structuivector.html">uivector</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>data</b> (defined in <a class="el" href="structuivector.html">uivector</a>)</td><td class="entry"><a class="el" href="structuivector.html">uivector</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>size</b> (defined in <a class="el" href="structuivector.html">uivector</a>)</td><td class="entry"><a class="el" href="structuivector.html">uivector</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Oct 29 2013 00:50:15 for Bombás játék by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.5
</small></address>
</body>
</html>
|
<?php
namespace BlogBundle\Document;
use Doctrine\ODM\MongoDB\DocumentRepository;
class TagRepository extends DocumentRepository
{
public function getTagByName($name = '')
{
$query = $this->createQueryBuilder()
->field('name')->equals($name);
return $query->getQuery()->getSingleResult();
}
public function getAllTags()
{
return $this->createQueryBuilder()
->hydrate(false)
->getQuery()
->toArray();
}
}
|
require "faraday"
require "faraday_middleware"
require "sqoot/version"
require "sqoot/client"
directory = File.expand_path(File.dirname(__FILE__))
module Sqoot
class << self
attr_accessor :affiliate_token, :<API key>, :api_url, :api_version
# Configure default credentials easily
# @yield [Sqoot]
def configure
load_defaults
yield self
true
end
def load_defaults
self.api_url ||= "https://api.sqoot.com"
self.api_version ||= 2
end
end
end
|
<?php
namespace Phinx\Db;
use Phinx\Db\Table\Column;
use Phinx\Db\Table\Index;
use Phinx\Db\Table\ForeignKey;
use Phinx\Db\Adapter\AdapterInterface;
class Table
{
/**
* @var string
*/
protected $name;
/**
* @var array
*/
protected $options = array();
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* @var array
*/
protected $columns = array();
/**
* @var array
*/
protected $indexes = array();
/**
* @var ForeignKey[]
*/
protected $foreignKeys = array();
/**
* Class Constuctor.
*
* @param string $name Table Name
* @param array $options Options
* @param AdapterInterface $adapter Database Adapter
* @return void
*/
public function __construct($name, $options = array(), AdapterInterface $adapter = null)
{
$this->setName($name);
$this->setOptions($options);
if (null !== $adapter) {
$this->setAdapter($adapter);
}
}
/**
* Sets the table name.
*
* @param string $name Table Name
* @return Table
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Gets the table name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Sets the table options.
*
* @param array $options
* @return Table
*/
public function setOptions($options)
{
$this->options = $options;
return $this;
}
/**
* Gets the table options.
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Sets the database adapter.
*
* @param AdapterInterface $adapter Database Adapter
* @return Table
*/
public function setAdapter(AdapterInterface $adapter)
{
$this->adapter = $adapter;
return $this;
}
/**
* Gets the database adapter.
*
* @return AdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* Does the table exist?
*
* @return boolean
*/
public function exists()
{
return $this->getAdapter()->hasTable($this->getName());
}
/**
* Drops the database table.
*
* @return void
*/
public function drop()
{
$this->getAdapter()->dropTable($this->getName());
}
/**
* Renames the database table.
*
* @param string $newTableName New Table Name
* @return Table
*/
public function rename($newTableName)
{
$this->getAdapter()->renameTable($this->getName(), $newTableName);
$this->setName($newTableName);
return $this;
}
/**
* Sets an array of columns waiting to be committed.
* Use setPendingColumns
*
* @deprecated
* @param array $columns Columns
* @return Table
*/
public function setColumns($columns)
{
$this->setPendingColumns($columns);
}
/**
* Gets an array of the table columns.
*
* @return Column[]
*/
public function getColumns()
{
return $this->getAdapter()->getColumns($this->getName());
}
/**
* Sets an array of columns waiting to be committed.
*
* @param array $columns Columns
* @return Table
*/
public function setPendingColumns($columns)
{
$this->columns = $columns;
return $this;
}
/**
* Gets an array of columns waiting to be committed.
*
* @return array
*/
public function getPendingColumns()
{
return $this->columns;
}
/**
* Sets an array of columns waiting to be indexed.
*
* @param array $indexes Indexes
* @return Table
*/
public function setIndexes($indexes)
{
$this->indexes = $indexes;
return $this;
}
/**
* Gets an array of indexes waiting to be committed.
*
* @return array
*/
public function getIndexes()
{
return $this->indexes;
}
/**
* Gets an array of foreign keys waiting to be commited.
*
* @param ForeignKey[] $foreignKeys foreign keys
* @return Table
*/
public function setForeignKeys($foreignKeys)
{
$this->foreignKeys = $foreignKeys;
return $this;
}
/**
* Gets an array of foreign keys waiting to be commited.
*
* @return array|ForeignKey[]
*/
public function getForeignKeys()
{
return $this->foreignKeys;
}
/**
* Resets all of the pending table changes.
*
* @return void
*/
public function reset()
{
$this->setPendingColumns(array());
$this->setIndexes(array());
$this->setForeignKeys(array());
}
/**
* Add a table column.
*
* Type can be: primary_key, string, text, integer, float, decimal,
* datetime, timestamp, time, date, binary, boolean.
*
* Valid options can be: limit, default, null, precision or scale.
*
* @param string|Phinx\Db\Table\Column $columnName Column Name
* @param string $type Column Type
* @param array $options Column Options
* @return Table
*/
public function addColumn($columnName, $type = null, $options = array())
{
// we need an adapter set to add a column
if (null === $this->getAdapter()) {
throw new \RuntimeException('An adapter must be specified to add a column.');
}
// create a new column object if only strings were supplied
if (!$columnName instanceof Column) {
$column = new Column();
$column->setName($columnName);
$column->setType($type);
$column->setOptions($options); // map options to column methods
} else {
$column = $columnName;
}
// check column type
if (!in_array($column->getType(), $this->getAdapter()->getColumnTypes())) {
throw new \<API key>("An invalid column type was specified: {$column->getName()}");
}
$this->columns[] = $column;
return $this;
}
/**
* Remove a table column.
*
* @param string $columnName Column Name
* @return Table
*/
public function removeColumn($columnName)
{
$this->getAdapter()->dropColumn($this->getName(), $columnName);
return $this;
}
/**
* Rename a table column.
*
* @param string $oldName Old Column Name
* @param string $newName New Column Name
* @return Table
*/
public function renameColumn($oldName, $newName)
{
$this->getAdapter()->renameColumn($this->getName(), $oldName, $newName);
return $this;
}
/**
* Change a table column type.
*
* @param string $columnName Column Name
* @param string|Column $newColumnType New Column Type
* @param array $options Options
* @return Table
*/
public function changeColumn($columnName, $newColumnType, $options = array())
{
// create a column object if one wasn't supplied
if (!$newColumnType instanceof Column) {
$newColumn = new Column();
$newColumn->setType($newColumnType);
$newColumn->setOptions($options);
} else {
$newColumn = $newColumnType;
}
// if the name was omitted use the existing column name
if (null === $newColumn->getName() || strlen($newColumn->getName()) == 0) {
$newColumn->setName($columnName);
}
$this->getAdapter()->changeColumn($this->getName(), $columnName, $newColumn);
return $this;
}
/**
* Checks to see if a column exists.
*
* @param string $columnName Column Name
* @param array $options Options
* @return boolean
*/
public function hasColumn($columnName, $options = array())
{
return $this->getAdapter()->hasColumn($this->getName(), $columnName, $options);
}
/**
* Add an index to a database table.
*
* In $options you can specific unique = true/false or name (index name).
*
* @param string|array|Index $columns Table Column(s)
* @param array $options Index Options
* @return Table
*/
public function addIndex($columns, $options = array())
{
// create a new index object if strings or an array of strings were supplied
if (!$columns instanceof Index) {
$index = new Index();
if (is_string($columns)) {
$columns = array($columns); // str to array
}
$index->setColumns($columns);
$index->setOptions($options);
} else {
$index = $columns;
}
$this->indexes[] = $index;
return $this;
}
/**
* Removes the given index from a table.
*
* @param array $columns Columns
* @param array $options Options
* @return Table
*/
public function removeIndex($columns, $options = array())
{
$this->getAdapter()->dropIndex($this->getName(), $columns, $options);
return $this;
}
/**
* Removes the given index identified by its name from a table.
*
* @param string $name Index name
* @return Table
*/
public function removeIndexByName($name)
{
$this->getAdapter()->dropIndexByName($this->getName(), $name);
return $this;
}
/**
* Checks to see if an index exists.
*
* @param string|array $columns Columns
* @param array $options Options
* @return boolean
*/
public function hasIndex($columns, $options = array())
{
return $this->getAdapter()->hasIndex($this->getName(), $columns, $options);
}
/**
* Add a foreign key to a database table.
*
* In $options you can specify on_delete|on_delete = cascade|no_action ..,
* on_update, constraint = constraint name.
*
* @param string|array $columns Columns
* @param string|Table $referencedTable Referenced Table
* @param string|array $referencedColumns Referenced Columns
* @param array $options Options
* @return Table
*/
public function addForeignKey($columns, $referencedTable, $referencedColumns = array('id'), $options = array())
{
if (is_string($referencedColumns)) {
$referencedColumns = array($referencedColumns); // str to array
}
$fk = new ForeignKey();
if ($referencedTable instanceof Table) {
$fk->setReferencedTable($referencedTable);
} else {
$fk->setReferencedTable(new Table($referencedTable, array(), $this->adapter));
}
$fk->setColumns($columns)
-><API key>($referencedColumns)
->setOptions($options);
$this->foreignKeys[] = $fk;
return $this;
}
/**
* Removes the given foreign key from the table.
*
* @param string|array $columns Column(s)
* @param null|string $constraint Constraint names
* @return Table
*/
public function dropForeignKey($columns, $constraint = null)
{
if (is_string($columns)) {
$columns = array($columns);
}
if ($constraint) {
$this->getAdapter()->dropForeignKey($this->getName(), array(), $constraint);
} else {
$this->getAdapter()->dropForeignKey($this->getName(), $columns);
}
return $this;
}
/**
* Checks to see if a foreign key exists.
*
* @param string|array $columns Column(s)
* @param null|string $constraint Constraint names
* @return boolean
*/
public function hasForeignKey($columns, $constraint = null)
{
return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint);
}
/**
* Add timestamp columns created_at and updated_at to the table.
*
* @return Table
*/
public function addTimestamps()
{
$this->addColumn('created_at', 'timestamp')
->addColumn('updated_at', 'timestamp', array(
'null' => true,
'default' => null
));
return $this;
}
/**
* Creates a table from the object instance.
*
* @return void
*/
public function create()
{
$this->getAdapter()->createTable($this);
$this->reset(); // reset pending changes
}
/**
* Updates a table from the object instance.
*
* @return void
*/
public function update()
{
if (!$this->exists()) {
throw new \RuntimeException('Cannot update a table that doesn\'t exist!');
}
// update table
foreach ($this->getPendingColumns() as $column) {
$this->getAdapter()->addColumn($this, $column);
}
foreach ($this->getIndexes() as $index) {
$this->getAdapter()->addIndex($this, $index);
}
foreach ($this->getForeignKeys() as $foreignKey) {
$this->getAdapter()->addForeignKey($this, $foreignKey);
}
$this->reset(); // reset pending changes
}
/**
* Commits the table changes.
*
* If the table doesn't exist it is created otherwise it is updated.
*
* @return void
*/
public function save()
{
if ($this->exists()) {
$this->update(); // update the table
} else {
$this->create(); // create the table
}
$this->reset(); // reset pending changes
}
}
|
<?php
namespace Forge\Log;
class File extends Writer
{
// Directory to place log files in
protected $_directory;
// Creates a new file logger. Checks that the directory exists and
// is writable.
public function __construct( $directory )
{
if ( ! is_dir($directory) OR ! is_writable($directory))
{
die('Directory ' . Debug::path( $directory ) . ' must be writable');
}
// Determine the directory path
$this->_directory = realpath($directory).DIRECTORY_SEPARATOR;
}
// Writes each of the messages into the log file. The log file will be
// appended to the `YYYY/MM/DD.log.php` file, where YYYY is the current
// year, MM is the current month, and DD is the current day.
public function write(array $messages)
{
// Set the yearly directory name
$directory = $this->_directory.date('Y');
if ( ! is_dir($directory))
{
// Create the yearly directory
mkdir($directory, 02777);
chmod($directory, 02777);
}
// Add the month to the directory
$directory .= DIRECTORY_SEPARATOR.date('m');
if ( ! is_dir($directory))
{
// Create the monthly directory
mkdir($directory, 02777);
chmod($directory, 02777);
}
// Set the name of the log file
$filename = $directory.DIRECTORY_SEPARATOR.date('d').EXT;
if ( ! file_exists($filename))
{
// Create the log file
file_put_contents($filename, Aviana::FILE_SECURITY.' ?>'.PHP_EOL);
// Allow anyone to write to log files
chmod($filename, 0666);
}
foreach ($messages as $message)
{
// Write each message into the log file
file_put_contents($filename, PHP_EOL.$message['time'].' --- '.$this->_log_levels[$message['level']].': '.$message['body'], FILE_APPEND);
}
}
}
|
# The set of languages for which implicit dependencies are needed:
set(<API key>
"CXX"
)
# The set of files for implicit dependencies of each language:
set(<API key>
"/home/sriramana/argos3-examples/controllers/<API key>/<API key>.cpp" "/home/sriramana/argos3-examples/build/controllers/<API key>/CMakeFiles/<API key>.dir/<API key>.cpp.o"
"/home/sriramana/argos3-examples/build/controllers/<API key>/<API key>.cpp" "/home/sriramana/argos3-examples/build/controllers/<API key>/CMakeFiles/<API key>.dir/<API key>.cpp.o"
)
set(<API key> "GNU")
# Preprocessor definitions for this target.
set(<API key>
"QT_CORE_LIB"
"QT_GUI_LIB"
"QT_WIDGETS_LIB"
)
# The include file search paths:
set(<API key>
"controllers/<API key>"
"../controllers/<API key>"
"/home/sriramana/anaconda2/include/qt"
"/home/sriramana/anaconda2/include/qt/QtWidgets"
"/home/sriramana/anaconda2/include/qt/QtGui"
"/home/sriramana/anaconda2/include/qt/QtCore"
"/home/sriramana/anaconda2/./mkspecs/linux-g++"
"../"
"/usr/include/lua5.2"
"../controllers"
)
# Targets to which this target links.
set(<API key>
)
# Fortran module output directory.
set(<API key> "")
|
require_relative "helper"
class HooksTest < MiniTest::Unit::TestCase
def setup
@hooked_class = Class.new do
class << self
attr_accessor :<API key>
def method_added(method)
@<API key> = true
end
end
include Harbor::Hooks
attr_accessor :before_hook_calls, :after_hook_calls, :hooked_method_calls
attr_accessor :<API key>, :<API key>, :<API key>
attr_accessor :<API key>, :<API key>, :<API key>
attr_accessor :<API key>, :<API key>
def initialize
@before_hook_calls = 0
@after_hook_calls = 0
@hooked_method_calls = 0
@<API key> = 0
@<API key> = 0
@<API key> = 0
@<API key> = 0
@<API key> = 0
@<API key> = 0
@<API key> = 0
@<API key> = 0
end
def hooked_method
@hooked_method_calls += 1
end
before :hooked_method do |reciever|
reciever.before_hook_calls += 1
end
after :hooked_method do |reciever|
reciever.after_hook_calls += 1
end
def <API key>(color, size)
@<API key> += 1
end
before :<API key> do |reciever|
reciever.<API key> += 1
end
after :<API key> do |reciever|
reciever.<API key> += 1
end
def <API key>(color, size, &block)
yield
@<API key> += 1
end
before :<API key> do |reciever|
reciever.<API key> += 1
end
after :<API key> do |reciever|
reciever.<API key> += 1
end
before :<API key> do |reciever|
reciever.<API key> += 1
end
def <API key>
@<API key> += 1
end
before :<API key> do |reciever|
throw :halt, true
end
def <API key>
false
end
end
end
def <API key>
assert_respond_to(@hooked_class, :before)
end
def <API key>
hooked_instance = @hooked_class.new
assert_equal(0, hooked_instance.before_hook_calls)
assert_equal(0, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
hooked_instance.hooked_method
assert_equal(1, hooked_instance.before_hook_calls)
assert_equal(1, hooked_instance.hooked_method_calls)
assert_equal(1, hooked_instance.after_hook_calls)
end
def <API key>
assert_respond_to(@hooked_class, :after)
end
def <API key>
assert(@hooked_class.<API key>)
end
def <API key>
hooked_instance = @hooked_class.new
assert_equal(0, hooked_instance.<API key>)
assert_equal(0, hooked_instance.<API key>)
hooked_instance.<API key>
assert_equal(1, hooked_instance.<API key>)
assert_equal(1, hooked_instance.<API key>)
end
def <API key>
hooked_instance = @hooked_class.new
assert_equal(0, hooked_instance.<API key>)
assert_equal(0, hooked_instance.<API key>)
assert_equal(0, hooked_instance.<API key>)
hooked_instance.<API key>("blue", 10)
assert_equal(1, hooked_instance.<API key>)
assert_equal(1, hooked_instance.<API key>)
assert_equal(1, hooked_instance.<API key>)
end
def <API key>
hooked_instance = @hooked_class.new
assert_equal(0, hooked_instance.<API key>)
assert_equal(0, hooked_instance.<API key>)
assert_equal(0, hooked_instance.<API key>)
@block_called = 0
hooked_instance.<API key>("blue", 10) do
@block_called += 1
end
assert_equal(1, @block_called)
assert_equal(1, hooked_instance.<API key>)
assert_equal(1, hooked_instance.<API key>)
assert_equal(1, hooked_instance.<API key>)
end
def <API key>
@hooked_class.class_eval do
def hooked_method
@hooked_method_calls = 2
end
end
hooked_instance = @hooked_class.new
assert_equal(0, hooked_instance.before_hook_calls)
assert_equal(0, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
hooked_instance.hooked_method
assert_equal(1, hooked_instance.before_hook_calls)
assert_equal(2, hooked_instance.hooked_method_calls)
assert_equal(1, hooked_instance.after_hook_calls)
end
def <API key>
subclass = Class.new(@hooked_class)
hooked_instance = subclass.new
assert_equal(0, hooked_instance.before_hook_calls)
assert_equal(0, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
hooked_instance.hooked_method
assert_equal(1, hooked_instance.before_hook_calls)
assert_equal(1, hooked_instance.hooked_method_calls)
assert_equal(1, hooked_instance.after_hook_calls)
end
def <API key>
subclass = Class.new(@hooked_class) do
before(:hooked_method) { |receiver| receiver.before_hook_calls += 1 }
end
hooked_instance = subclass.new
assert_equal(0, hooked_instance.before_hook_calls)
assert_equal(0, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
hooked_instance.hooked_method
assert_equal(2, hooked_instance.before_hook_calls)
assert_equal(1, hooked_instance.hooked_method_calls)
assert_equal(1, hooked_instance.after_hook_calls)
end
def <API key>
@hooked_class.hooks[:hooked_method].clear!
hooked_instance = @hooked_class.new
assert_equal(0, hooked_instance.before_hook_calls)
assert_equal(0, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
hooked_instance.hooked_method
assert_equal(0, hooked_instance.before_hook_calls)
assert_equal(1, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
end
def <API key>
subclass = Class.new(@hooked_class) do
hooks[:hooked_method].clear!
before(:hooked_method) { |receiver| receiver.before_hook_calls += 1 }
end
hooked_instance = subclass.new
assert_equal(0, hooked_instance.before_hook_calls)
assert_equal(0, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
hooked_instance.hooked_method
assert_equal(1, hooked_instance.before_hook_calls)
assert_equal(1, hooked_instance.hooked_method_calls)
assert_equal(0, hooked_instance.after_hook_calls)
end
def <API key>
hooked_instance = @hooked_class.new
result = hooked_instance.<API key>
assert(result)
end
end
|
/*
* @file sample.c
* @author Akagi201
* @date 2014/12/06
*/
#include <stdio.h>
#include "bytes2str.h""
int main(void) {
char in[] = {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01};
char out[32] = {0};
int olen = sizeof(out);
bytes2str(in, 6, out, &olen);
printf("out: %s, olen: %d\n", out, olen);
return 0;
}
|
const version = '1.1.3',
collection = {};
function extendUnstrap (v) {
var list;
if (!collection[v].selectors) {
collection[v].selectors = ['.' + collection[v].name];
}
collection[v].selectors.forEach(function (sel) {
list = document.querySelectorAll(sel);
for (var i = 0; i < list.length; i++) {
collection[v].extend && collection[v].extend(list.item(i));
}
})
}
function init () {
var observer = new MutationObserver(function (mut) {
mut.forEach(function (m) {
var n = m.addedNodes,
f;
for (var i=0; i<n.length; i++) {
var c = n.item(i).classList;
if (c) {
for (var j = 0; j < c.length; j++) {
if (f = collection[c.item(j)]) {
f.extend && f.extend(n.item(i));
}
}
}
}
});
});
Object.keys(collection).forEach(function (v) {
extendUnstrap(v);
})
observer.observe(document.body, {childList: true, subtree: true});
}
function register (...components) {
components.forEach((component) => {
if (component.name) {
collection[component.name] = component;
}
})
}
function unregister (...components) {
components.forEach((component) => {
delete collection[component.name];
})
}
function list () {
return Object.keys(collection).sort();
}
window.onload = init;
export default {
version,
register,
unregister,
list
}
|
// Generated by class-dump 3.5 (64 bit).
#import "NSObject.h"
@class NSArray;
@protocol <API key> <NSObject>
- (NSArray *)lineDataForBounds:(struct _DVTGraphBounds)arg1;
@end
|
<div class="modal-header">
<button type="button" class="close" ng-click="closeDialog()" aria-hidden="true">×</button>
<h4 class="modal-title">Widget hinzufügen</h4>
</div>
<div class="modal-body" class="row">
<div class="panel-group" id="accordion" role="tablist" <API key>="true">
<div class="panel panel-default" ng-repeat="(category, widgets) in categories" is-open="isopen">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
{{category}}
</a>
</h4>
</div>
<div id="#panel{{category}}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<ul class="list-group">
<li class="list-group-item" ng-repeat="(key, widget) in widgets">
<a href="" ng-click="addWidget(key)">{{widget.title}} <i class="fa fa-spinner fa-spin" ng-show="recentlyAdded.indexOf(key) > -1"></i></a>
<p>
<small ng-if="widget.description">{{widget.description}}</small>
</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="closeDialog()"><i class="fa fa-times"></i> Schließen</button>
</div>
|
<?php
/* PgGsbFraisBundle::accueilCompta.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("PgGsbFraisBundle::layout.html.twig");
$this->blocks = array(
'body' => array($this, 'block_body'),
'section' => array($this, 'block_section'),
);
}
protected function doGetParent(array $context)
{
return "PgGsbFraisBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 2
public function block_body($context, array $blocks = array())
{
// line 3
echo "<nav>
<div class=\"row\">
<div class=\"col-lg-10\">
<nav class=\"navbar navbar-default\" role=\"navigation\">
<div class=\"container-fluid\">
<div class=\"navbar-header\">
<a class=\"navbar-brand\" href=\"";
// line 9
echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_home");
echo "\">Accueil</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class=\"collapse navbar-collapse\" id=\"<API key>\">
<ul class=\"nav navbar-nav\">
<li>
<a href=\"";
// line 15
echo $this->env->getExtension('routing')->getPath("<API key>");
echo "\" title=\"Suivre fiche de frais \">Suivre fiche de frais</a>
</li>
<li>
<a href= \"";
// line 19
echo $this->env->getExtension('routing')->getPath("<API key>");
echo "\" title=\"Valider fiches de frais\">Valider fiches de frais</a>
</li>
</ul>
</div>
</nav>
</div>
<div class=\"col-lg-2\">
<nav class=\"navbar navbar-default\" role=\"deconnexion\">
<div class=\"container-fluid\">
";
// line 29
if ($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "session", array(), "any", false, true), "get", array(0 => "nom"), "method", true, true)) {
// line 30
echo " Bonjour ";
echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session"), "get", array(0 => "nom"), "method"), "html", null, true);
echo " <br />
";
}
// line 32
echo " <a href=\"";
echo $this->env->getExtension('routing')->getPath("<API key>");
echo "\" title=\"Se déconnecter\">Déconnexion</a>
</div>
</nav>
</div>
</div>
</nav>
<section>
";
// line 39
$this->displayBlock('section', $context, $blocks);
// line 41
echo "</section>
";
}
// line 39
public function block_section($context, array $blocks = array())
{
// line 40
echo " ";
}
public function getTemplateName()
{
return "PgGsbFraisBundle::accueilCompta.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 98 => 40, 95 => 39, 90 => 41, 88 => 39, 77 => 32, 71 => 30, 69 => 29, 56 => 19, 49 => 15, 40 => 9, 32 => 3, 29 => 2, 31 => 3, 28 => 2,);
}
}
|
'use strict';
const toBytes = s => [...s].map(c => c.charCodeAt(0));
const xpiZipFilename = toBytes('META-INF/mozilla.rsa');
const oxmlContentTypes = toBytes('[Content_Types].xml');
const oxmlRels = toBytes('_rels/.rels');
const fileType = input => {
const buf = input instanceof Uint8Array ? input : new Uint8Array(input);
if (!(buf && buf.length > 1)) {
return null;
}
const check = (header, options) => {
options = Object.assign({
offset: 0
}, options);
for (let i = 0; i < header.length; i++) {
// If a bitmask is set
if (options.mask) {
// If header doesn't equal `buf` with bits masked off
if (header[i] !== (options.mask[i] & buf[i + options.offset])) {
return false;
}
} else if (header[i] !== buf[i + options.offset]) {
return false;
}
}
return true;
};
const checkString = (header, options) => check(toBytes(header), options);
if (check([0xFF, 0xD8, 0xFF])) {
return {
ext: 'jpg',
mime: 'image/jpeg'
};
}
if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
return {
ext: 'png',
mime: 'image/png'
};
}
if (check([0x47, 0x49, 0x46])) {
return {
ext: 'gif',
mime: 'image/gif'
};
}
if (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) {
return {
ext: 'webp',
mime: 'image/webp'
};
}
if (check([0x46, 0x4C, 0x49, 0x46])) {
return {
ext: 'flif',
mime: 'image/flif'
};
}
// Needs to be before `tif` check
if (
(check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) &&
check([0x43, 0x52], {offset: 8})
) {
return {
ext: 'cr2',
mime: 'image/x-canon-cr2'
};
}
if (
check([0x49, 0x49, 0x2A, 0x0]) ||
check([0x4D, 0x4D, 0x0, 0x2A])
) {
return {
ext: 'tif',
mime: 'image/tiff'
};
}
if (check([0x42, 0x4D])) {
return {
ext: 'bmp',
mime: 'image/bmp'
};
}
if (check([0x49, 0x49, 0xBC])) {
return {
ext: 'jxr',
mime: 'image/vnd.ms-photo'
};
}
if (check([0x38, 0x42, 0x50, 0x53])) {
return {
ext: 'psd',
mime: 'image/vnd.adobe.photoshop'
};
}
// Zip-based file formats
// Need to be before the `zip` check
if (check([0x50, 0x4B, 0x3, 0x4])) {
if (
check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30})
) {
return {
ext: 'epub',
mime: 'application/epub+zip'
};
}
// Assumes signed `.xpi` from addons.mozilla.org
if (check(xpiZipFilename, {offset: 30})) {
return {
ext: 'xpi',
mime: 'application/x-xpinstall'
};
}
if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {offset: 30})) {
return {
ext: 'odt',
mime: 'application/vnd.oasis.opendocument.text'
};
}
if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {offset: 30})) {
return {
ext: 'ods',
mime: 'application/vnd.oasis.opendocument.spreadsheet'
};
}
if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {offset: 30})) {
return {
ext: 'odp',
mime: 'application/vnd.oasis.opendocument.presentation'
};
}
if (check(oxmlContentTypes, {offset: 30}) || check(oxmlRels, {offset: 30})) {
const sliced = buf.subarray(4, 4 + 2000);
const nextZipHeaderIndex = arr => arr.findIndex((el, i, arr) => arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4);
const header2Pos = nextZipHeaderIndex(sliced);
if (header2Pos !== -1) {
const slicedAgain = buf.subarray(header2Pos + 8, header2Pos + 8 + 1000);
const header3Pos = nextZipHeaderIndex(slicedAgain);
if (header3Pos !== -1) {
const offset = 8 + header2Pos + header3Pos + 30;
if (checkString('word/', {offset})) {
return {
ext: 'docx',
mime: 'application/vnd.<API key>.wordprocessingml.document'
};
}
if (checkString('ppt/', {offset})) {
return {
ext: 'pptx',
mime: 'application/vnd.<API key>.presentationml.presentation'
};
}
if (checkString('xl/', {offset})) {
return {
ext: 'xlsx',
mime: 'application/vnd.<API key>.spreadsheetml.sheet'
};
}
}
}
}
}
if (
check([0x50, 0x4B]) &&
(buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) &&
(buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)
) {
return {
ext: 'zip',
mime: 'application/zip'
};
}
if (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) {
return {
ext: 'tar',
mime: 'application/x-tar'
};
}
if (
check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) &&
(buf[6] === 0x0 || buf[6] === 0x1)
) {
return {
ext: 'rar',
mime: 'application/x-rar-compressed'
};
}
if (check([0x1F, 0x8B, 0x8])) {
return {
ext: 'gz',
mime: 'application/gzip'
};
}
if (check([0x42, 0x5A, 0x68])) {
return {
ext: 'bz2',
mime: 'application/x-bzip2'
};
}
if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
return {
ext: '7z',
mime: 'application/x-7z-compressed'
};
}
if (check([0x78, 0x01])) {
return {
ext: 'dmg',
mime: 'application/x-apple-diskimage'
};
}
if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5
(
check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {offset: 4}) &&
(
check([0x6D, 0x70, 0x34, 0x31], {offset: 8}) || // MP41
check([0x6D, 0x70, 0x34, 0x32], {offset: 8}) || // MP42
check([0x69, 0x73, 0x6F, 0x6D], {offset: 8}) || // ISOM
check([0x69, 0x73, 0x6F, 0x32], {offset: 8}) || // ISO2
check([0x6D, 0x6D, 0x70, 0x34], {offset: 8}) || // MMP4
check([0x4D, 0x34, 0x56], {offset: 8}) || // M4V
check([0x64, 0x61, 0x73, 0x68], {offset: 8}) // DASH
)
)) {
return {
ext: 'mp4',
mime: 'video/mp4'
};
}
if (check([0x4D, 0x54, 0x68, 0x64])) {
return {
ext: 'mid',
mime: 'audio/midi'
};
}
if (check([0x1A, 0x45, 0xDF, 0xA3])) {
const sliced = buf.subarray(4, 4 + 4096);
const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82);
if (idPos !== -1) {
const docTypePos = idPos + 3;
const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0));
if (findDocType('matroska')) {
return {
ext: 'mkv',
mime: 'video/x-matroska'
};
}
if (findDocType('webm')) {
return {
ext: 'webm',
mime: 'video/webm'
};
}
}
}
if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) ||
check([0x66, 0x72, 0x65, 0x65], {offset: 4}) ||
check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) ||
check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG
check([0x77, 0x69, 0x64, 0x65], {offset: 4})) {
return {
ext: 'mov',
mime: 'video/quicktime'
};
}
// RIFF file format which might be AVI, WAV, QCP, etc
if (check([0x52, 0x49, 0x46, 0x46])) {
if (check([0x41, 0x56, 0x49], {offset: 8})) {
return {
ext: 'avi',
mime: 'video/x-msvideo'
};
}
if (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {
return {
ext: 'wav',
mime: 'audio/x-wav'
};
}
// QLCM, QCP file
if (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {
return {
ext: 'qcp',
mime: 'audio/qcelp'
};
}
}
if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
return {
ext: 'wmv',
mime: 'video/x-ms-wmv'
};
}
if (
check([0x0, 0x0, 0x1, 0xBA]) ||
check([0x0, 0x0, 0x1, 0xB3])
) {
return {
ext: 'mpg',
mime: 'video/mpeg'
};
}
if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {offset: 4})) {
return {
ext: '3gp',
mime: 'video/3gpp'
};
}
// Check for MPEG header at different starting offsets
for (let start = 0; start < 2 && start < (buf.length - 16); start++) {
if (
check([0x49, 0x44, 0x33], {offset: start}) || // ID3 header
check([0xFF, 0xE2], {offset: start, mask: [0xFF, 0xE2]}) // MPEG 1 or 2 Layer 3 header
) {
return {
ext: 'mp3',
mime: 'audio/mpeg'
};
}
if (
check([0xFF, 0xE4], {offset: start, mask: [0xFF, 0xE4]}) // MPEG 1 or 2 Layer 2 header
) {
return {
ext: 'mp2',
mime: 'audio/mpeg'
};
}
if (
check([0xFF, 0xF8], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 2 layer 0 using ADTS
) {
return {
ext: 'mp2',
mime: 'audio/mpeg'
};
}
if (
check([0xFF, 0xF0], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 4 layer 0 using ADTS
) {
return {
ext: 'mp4',
mime: 'audio/mpeg'
};
}
}
if (
check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4}) ||
check([0x4D, 0x34, 0x41, 0x20])
) {
return {
ext: 'm4a',
mime: 'audio/m4a'
};
}
// Needs to be before `ogg` check
if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) {
return {
ext: 'opus',
mime: 'audio/opus'
};
}
// If 'OggS' in first bytes, then OGG container
if (check([0x4F, 0x67, 0x67, 0x53])) {
// This is a OGG container
// If ' theora' in header.
if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 28})) {
return {
ext: 'ogv',
mime: 'video/ogg'
};
}
// If '\x01video' in header.
if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {offset: 28})) {
return {
ext: 'ogm',
mime: 'video/ogg'
};
}
if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {offset: 28})) {
return {
ext: 'oga',
mime: 'audio/ogg'
};
}
if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {offset: 28})) {
return {
ext: 'spx',
mime: 'audio/ogg'
};
}
// If '\x01vorbis' in header
if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 28})) {
return {
ext: 'ogg',
mime: 'audio/ogg'
};
}
return {
ext: 'ogx',
mime: 'application/ogg'
};
}
if (check([0x66, 0x4C, 0x61, 0x43])) {
return {
ext: 'flac',
mime: 'audio/x-flac'
};
}
if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {
return {
ext: 'amr',
mime: 'audio/amr'
};
}
if (check([0x25, 0x50, 0x44, 0x46])) {
return {
ext: 'pdf',
mime: 'application/pdf'
};
}
if (check([0x4D, 0x5A])) {
return {
ext: 'exe',
mime: 'application/x-msdownload'
};
}
if (
(buf[0] === 0x43 || buf[0] === 0x46) &&
check([0x57, 0x53], {offset: 1})
) {
return {
ext: 'swf',
mime: 'application/x-shockwave-flash'
};
}
if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {
return {
ext: 'rtf',
mime: 'application/rtf'
};
}
if (check([0x00, 0x61, 0x73, 0x6D])) {
return {
ext: 'wasm',
mime: 'application/wasm'
};
}
if (
check([0x77, 0x4F, 0x46, 0x46]) &&
(
check([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||
check([0x4F, 0x54, 0x54, 0x4F], {offset: 4})
)
) {
return {
ext: 'woff',
mime: 'font/woff'
};
}
if (
check([0x77, 0x4F, 0x46, 0x32]) &&
(
check([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||
check([0x4F, 0x54, 0x54, 0x4F], {offset: 4})
)
) {
return {
ext: 'woff2',
mime: 'font/woff2'
};
}
if (
check([0x4C, 0x50], {offset: 34}) &&
(
check([0x00, 0x00, 0x01], {offset: 8}) ||
check([0x01, 0x00, 0x02], {offset: 8}) ||
check([0x02, 0x00, 0x02], {offset: 8})
)
) {
return {
ext: 'eot',
mime: 'application/octet-stream'
};
}
if (check([0x00, 0x01, 0x00, 0x00, 0x00])) {
return {
ext: 'ttf',
mime: 'font/ttf'
};
}
if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
return {
ext: 'otf',
mime: 'font/otf'
};
}
if (check([0x00, 0x00, 0x01, 0x00])) {
return {
ext: 'ico',
mime: 'image/x-icon'
};
}
if (check([0x00, 0x00, 0x02, 0x00])) {
return {
ext: 'cur',
mime: 'image/x-icon'
};
}
if (check([0x46, 0x4C, 0x56, 0x01])) {
return {
ext: 'flv',
mime: 'video/x-flv'
};
}
if (check([0x25, 0x21])) {
return {
ext: 'ps',
mime: 'application/postscript'
};
}
if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
return {
ext: 'xz',
mime: 'application/x-xz'
};
}
if (check([0x53, 0x51, 0x4C, 0x69])) {
return {
ext: 'sqlite',
mime: 'application/x-sqlite3'
};
}
if (check([0x4E, 0x45, 0x53, 0x1A])) {
return {
ext: 'nes',
mime: 'application/x-nintendo-nes-rom'
};
}
if (check([0x43, 0x72, 0x32, 0x34])) {
return {
ext: 'crx',
mime: 'application/<API key>'
};
}
if (
check([0x4D, 0x53, 0x43, 0x46]) ||
check([0x49, 0x53, 0x63, 0x28])
) {
return {
ext: 'cab',
mime: 'application/vnd.ms-cab-compressed'
};
}
// Needs to be before `ar` check
if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {
return {
ext: 'deb',
mime: 'application/x-deb'
};
}
if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {
return {
ext: 'ar',
mime: 'application/x-unix-archive'
};
}
if (check([0xED, 0xAB, 0xEE, 0xDB])) {
return {
ext: 'rpm',
mime: 'application/x-rpm'
};
}
if (
check([0x1F, 0xA0]) ||
check([0x1F, 0x9D])
) {
return {
ext: 'Z',
mime: 'application/x-compress'
};
}
if (check([0x4C, 0x5A, 0x49, 0x50])) {
return {
ext: 'lz',
mime: 'application/x-lzip'
};
}
if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
return {
ext: 'msi',
mime: 'application/x-msi'
};
}
if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
return {
ext: 'mxf',
mime: 'application/mxf'
};
}
if (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) {
return {
ext: 'mts',
mime: 'video/mp2t'
};
}
if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {
return {
ext: 'blend',
mime: 'application/x-blender'
};
}
if (check([0x42, 0x50, 0x47, 0xFB])) {
return {
ext: 'bpg',
mime: 'image/bpg'
};
}
if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
// JPEG-2000 family
if (check([0x6A, 0x70, 0x32, 0x20], {offset: 20})) {
return {
ext: 'jp2',
mime: 'image/jp2'
};
}
if (check([0x6A, 0x70, 0x78, 0x20], {offset: 20})) {
return {
ext: 'jpx',
mime: 'image/jpx'
};
}
if (check([0x6A, 0x70, 0x6D, 0x20], {offset: 20})) {
return {
ext: 'jpm',
mime: 'image/jpm'
};
}
if (check([0x6D, 0x6A, 0x70, 0x32], {offset: 20})) {
return {
ext: 'mj2',
mime: 'image/mj2'
};
}
}
if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) {
return {
ext: 'aif',
mime: 'audio/aiff'
};
}
if (checkString('<?xml ')) {
return {
ext: 'xml',
mime: 'application/xml'
};
}
if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) {
return {
ext: 'mobi',
mime: 'application/x-mobipocket-ebook'
};
}
if (check([0x66, 0x74, 0x79, 0x70], {offset: 4})) {
if (check([0x6D, 0x69, 0x66, 0x31], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heif'
};
}
if (check([0x6D, 0x73, 0x66, 0x31], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heif-sequence'
};
}
if (check([0x68, 0x65, 0x69, 0x63], {offset: 8}) || check([0x68, 0x65, 0x69, 0x78], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heic'
};
}
if (check([0x68, 0x65, 0x76, 0x63], {offset: 8}) || check([0x68, 0x65, 0x76, 0x78], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heic-sequence'
};
}
}
return null;
};
|
import logging
from abc import ABCMeta, abstractmethod
from collections import deque
from typing import List, Union, Iterable, Sequence
log = logging.getLogger(__name__)
class <API key>(RuntimeError):
pass
class Controller(metaclass=ABCMeta):
@abstractmethod
def run(self):
raise NotImplementedError
@abstractmethod
def enable(self):
raise NotImplementedError
@abstractmethod
def disable(self):
raise NotImplementedError
@abstractmethod
def valid(self) -> bool:
raise NotImplementedError
class InputDevice(metaclass=ABCMeta):
"""
Abstract class for input devices.
"""
def __init__(self, name):
self.name = name
self.values = ValueBuffer(name, 128)
@abstractmethod
def get_value(self) -> float:
raise NotImplementedError
class OutputDevice(metaclass=ABCMeta):
"""
Abstract class for output devices.
"""
def __init__(self, name):
self.name = name
self.values = ValueBuffer(name, 128)
def set_value(self, value: Union[int, float]):
self.values.update(value)
@abstractmethod
def apply(self):
raise NotImplementedError
@abstractmethod
def enable(self):
raise NotImplementedError
@abstractmethod
def disable(self):
raise NotImplementedError
class <API key>(Controller):
def __init__(self, inputs=Sequence[InputDevice], outputs=Sequence[OutputDevice], speeds=None):
self.inputs = list(inputs)
self.outputs = list(outputs)
def run(self):
for idx, input_reader in enumerate(self.inputs):
output = self.outputs[idx]
output.name = input_reader.name
output.values.name = input_reader.name
output.set_value(input_reader.get_value())
output.apply()
log.debug('ran loop')
def apply_candidates(self):
return self.outputs
def enable(self):
for output_dev in self.outputs:
output_dev.enable()
def disable(self):
for output_dev in self.outputs:
output_dev.disable()
def valid(self) -> bool:
return bool(self.inputs and self.outputs) and len(self.inputs) == len(self.outputs)
class DummyInput(InputDevice):
def __init__(self):
super().__init__('dummy')
self.temp = 0
def get_value(self):
return self.temp
def set_value(self, value):
self.temp = value
class DummyOutput(OutputDevice):
def __init__(self):
super().__init__('dummy')
self.speed = None
self.enabled = False
def apply(self):
if self.enabled:
self.speed = round(self.values.mean())
def enable(self):
self.enabled = True
def disable(self):
self.enabled = False
def mean(seq: Iterable) -> float:
if not isinstance(seq, Iterable):
raise ValueError('provided sequence MUST be iterable')
if not isinstance(seq, Sequence):
seq = list(seq)
if len(seq) == 1:
return float(seq[0])
if len(seq) == 0:
raise ValueError('sequence must have at least one value.')
return sum(seq) / len(seq)
def lerp(value: Union[float, int], input_min: Union[float, int], input_max: Union[float, int], output_min: Union[float, int], output_max: Union[float, int]) -> float:
if value <= input_min:
return float(output_min)
if value >= input_max:
return float(output_max)
return (output_min * (input_max - value) + output_max * (value - input_min)) / (input_max - input_min)
def lerp_range(seq: Iterable[Union[float, int]], input_min, input_max, output_min, output_max) -> List[float]:
return [lerp(val, input_min, input_max, output_min, output_max) for val in seq]
class ValueBuffer:
def __init__(self, name, default_value=0.0):
self.name = name
self.buffer = deque(maxlen=32)
self._default_value = default_value
def update(self, value: float):
self.buffer.append(value)
def mean(self) -> float:
try:
return mean(self.buffer)
except (ValueError, ZeroDivisionError):
return self._default_value
|
import { injectable, inject } from "inversify";
import { TYPES } from "../ioc/types";
const cacheKey = "<API key>";
@injectable()
export class <API key> {
constructor(
@inject(TYPES.IConfig) private _config: IConfig,
@inject(TYPES.Logger) private _logger: ILogger,
@inject(TYPES.IBasicCache) private _cache: IBasicCache,
) { }
/**
* Change to the new server
* @param name
*/
public async changeServer(name: string): Promise<void> {
const servers: IServer[] = this._config.app.aleksa.discord.servers;
const matches = servers.filter(s => s.name.indexOf(name) > -1);
const selection = matches.length > 0
? matches[0]
: servers[0];
this._logger.info(`Changing server to ${name}`);
// Ensure never expired
this._cache.set(cacheKey, JSON.stringify(selection), 0);
}
/**
* Get the current selected server
*/
public async getServer(): Promise<IServer> {
if(await this._cache.has(cacheKey)) {
return JSON.parse(await this._cache.get(cacheKey)) as IServer;
}
return this._config.app.aleksa.discord.servers[0] as IServer;
}
}
export interface IServer {
name: string;
guildId: string;
channelId: string;
userId: string;
}
|
// PS4Macro (File: Forms/MainForm.cs)
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 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.
using PS4Macro.Classes;
using PS4Macro.Classes.GlobalHooks;
using PS4Macro.Classes.Remapping;
using <API key>;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PS4Macro.Forms
{
enum ControlMode
{
Macro,
Script,
Remapper,
StatusChecker
}
public partial class MainForm : Form
{
private const string <API key> = "-";
private GlobalKeyboardHook <API key>;
private GlobalMouseHook m_GlobalMouseHook;
private MacroPlayer m_MacroPlayer;
private Remapper m_Remapper;
private StatusChecker m_StatusChecker;
private ControlMode m_ControlMode;
private PS4MacroAPI.ScriptBase m_SelectedScript;
private ScriptHost m_ScriptHost;
private SaveLoadHelper m_SaveLoadHelper;
private Process m_RemotePlayProcess;
/* Constructor */
public MainForm()
{
InitializeComponent();
// Setup global keyboard hook
<API key> = new GlobalKeyboardHook();
<API key>.KeyboardPressed += OnKeyPressed;
// Setup global mouse hook
m_GlobalMouseHook = new GlobalMouseHook();
m_GlobalMouseHook.MouseEvent += OnMouseEvent;
// Create macro player
m_MacroPlayer = new MacroPlayer();
m_MacroPlayer.Loop = true;
m_MacroPlayer.RecordShortcut = true;
m_MacroPlayer.PropertyChanged += <API key>;
// Create remapper
m_Remapper = new Remapper();
// Create status checker
m_StatusChecker = new StatusChecker();
// Set control mode
SetControlMode(ControlMode.Macro);
// Create save/load helper
m_SaveLoadHelper = new SaveLoadHelper(this, m_MacroPlayer);
m_SaveLoadHelper.PropertyChanged += <API key>;
// Initialize interceptor
InitInterceptor();
}
private void InitInterceptor()
{
// Set controller emulation based on settings
Interceptor.EmulateController = Program.Settings.EmulateController;
<API key>.Visible = Program.Settings.EmulateController;
// Enable watchdog based on settings
if (!Program.Settings.AutoInject)
{
Interceptor.InjectionMode = InjectionMode.Compatibility;
}
// Inject if not bypassed
if (!Program.Settings.BypassInjection)
{
// Attempt to inject into PS4 Remote Play
try
{
int pid = Interceptor.Inject();
m_RemotePlayProcess = Process.GetProcessById(pid);
// Set process
<API key>();
}
// Injection failed
catch (<API key> ex)
{
// Only handle when PS4 Remote Play is in used by another injection
if (ex.InnerException != null && ex.InnerException.Message.Equals("<API key>: Unknown error in injected C++ completion routine. (Code: 15)"))
{
MessageBox.Show("The process has been injected by another executable. Restart PS4 Remote Play and try again.", "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
else
{
// Handle exception if watchdog is disabled
if (!Program.Settings.AutoInject)
{
MessageBox.Show(string.Format("[{0}] - {1}", ex.GetType(), ex.Message), "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
}
}
// Start watchdog to automatically inject when possible
if (Program.Settings.AutoInject)
{
Interceptor.Watchdog.Start();
// Watchdog callbacks
Interceptor.Watchdog.OnInjectionSuccess = () =>
{
<API key>();
};
Interceptor.Watchdog.OnInjectionFailure = () =>
{
};
}
}
}
private void SetControlMode(ControlMode controlMode)
{
m_ControlMode = controlMode;
if (m_ControlMode == ControlMode.Macro)
{
// Stop script and remove
if (m_ScriptHost != null && m_ScriptHost.IsRunning)
{
m_ScriptHost.Stop();
m_ScriptHost = null;
}
// Setup callback to interceptor
Interceptor.Callback = new <API key>(m_MacroPlayer.OnReceiveData);
recordButton.Enabled = true;
<API key>.Enabled = true;
loopCheckBox.Enabled = true;
loopCheckBox.Checked = m_MacroPlayer.Loop;
<API key>.Enabled = true;
<API key>.Enabled = true;
scriptButton.Enabled = false;
<API key>.Enabled = true;
<API key>.Enabled = true;
<API key>.Enabled = true;
<API key>.Enabled = true;
}
else if (m_ControlMode == ControlMode.Script)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Setup callback to interceptor
Interceptor.Callback = new <API key>(m_ScriptHost.OnReceiveData);
recordButton.Enabled = false;
<API key>.Enabled = false;
loopCheckBox.Enabled = false;
loopCheckBox.Checked = false;
<API key>.Enabled = false;
<API key>.Enabled = false;
scriptButton.Enabled = true;
<API key>.Enabled = false;
<API key>.Enabled = false;
<API key>.Enabled = false;
<API key>.Enabled = false;
<API key>.Text = <API key>;
}
else if (m_ControlMode == ControlMode.Remapper)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Stop script
if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop();
// Setup callback to interceptor
Interceptor.Callback = new <API key>(m_Remapper.OnReceiveData);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Stop script
if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop();
// Setup callback to interceptor
Interceptor.Callback = new <API key>(m_StatusChecker.OnReceiveData);
}
}
private void <API key>(ControlMode controlMode, Action action)
{
// Store current control mode and temporarily set it
ControlMode oldControlMode = m_ControlMode;
SetControlMode(controlMode);
// Invoke action
action?.Invoke();
// Restore control mode
SetControlMode(oldControlMode);
}
private void <API key>()
{
m_Remapper.RemotePlayProcess = m_RemotePlayProcess;
m_StatusChecker.RemotePlayProcess = m_RemotePlayProcess;
}
public void LoadMacro(string path)
{
SetControlMode(ControlMode.Macro);
m_MacroPlayer.LoadFile(path);
}
public void LoadScript(string path)
{
var script = PS4MacroAPI.Internal.ScriptUtility.LoadScript(path);
m_SelectedScript = script;
m_ScriptHost = new ScriptHost(this, m_SelectedScript);
m_ScriptHost.PropertyChanged += <API key>;
SetControlMode(ControlMode.Script);
}
private void OnKeyPressed(object sender, <API key> e)
{
if (m_ControlMode == ControlMode.Remapper)
{
m_Remapper.OnKeyPressed(sender, e);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
m_StatusChecker.OnKeyPressed(sender, e);
}
}
private void OnMouseEvent(object sender, <API key> e)
{
if (m_ControlMode == ControlMode.Remapper)
{
m_Remapper.OnMouseEvent(sender, e);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
m_StatusChecker.OnMouseEvent(sender, e);
}
}
private void MainForm_Load(object sender, EventArgs e)
{
// Load startup file
if (!string.IsNullOrWhiteSpace(Program.Settings.StartupFile))
m_SaveLoadHelper.DirectLoad(Program.Settings.StartupFile);
}
/* Macro Player */
#region <API key>
private void UpdateCurrentTick()
{
BeginInvoke((MethodInvoker)delegate
{
// Invalid sequence
if (m_MacroPlayer.Sequence == null || m_MacroPlayer.Sequence.Count <= 0)
{
<API key>.Text = <API key>;
}
// Valid sequence
else
{
<API key>.Text = string.Format("{0}/{1}",
m_MacroPlayer.CurrentTick.ToString(),
m_MacroPlayer.Sequence.Count.ToString()
);
}
});
}
private void <API key>(object sender, <API key> e)
{
switch (e.PropertyName)
{
case "IsPlaying":
{
playButton.ForeColor = m_MacroPlayer.IsPlaying ? Color.Green : DefaultForeColor;
break;
}
case "IsPaused":
{
playButton.ForeColor = m_MacroPlayer.IsPaused ? DefaultForeColor : playButton.ForeColor;
break;
}
case "IsRecording":
{
recordButton.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor;
<API key>.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor;
break;
}
case "CurrentTick":
{
UpdateCurrentTick();
break;
}
case "Sequence":
{
UpdateCurrentTick();
break;
}
case "Loop":
{
loopCheckBox.Checked = m_MacroPlayer.Loop;
<API key>.Checked = m_MacroPlayer.Loop;
break;
}
case "RecordShortcut":
{
<API key>.Checked = m_MacroPlayer.RecordShortcut;
break;
}
}
}
#endregion
/* Script Host */
#region <API key>
private void <API key>(object sender, <API key> e)
{
switch (e.PropertyName)
{
case "IsRunning":
{
playButton.ForeColor = m_ScriptHost.IsRunning ? Color.Green : DefaultForeColor;
break;
}
case "IsPaused":
{
if (m_ScriptHost.IsPaused && m_ScriptHost.IsRunning)
{
playButton.ForeColor = DefaultForeColor;
}
else if (!m_ScriptHost.IsPaused && m_ScriptHost.IsRunning)
{
playButton.ForeColor = Color.Green;
}
break;
}
}
}
#endregion
/* Save/Load Helper */
#region <API key>
private void <API key>(object sender, <API key> e)
{
if (e.PropertyName == "CurrentFile")
{
if (m_SaveLoadHelper.CurrentFile == null)
{
<API key>.Text = SaveLoadHelper.DEFAULT_FILE_NAME;
<API key>.Text = <API key>;
}
else
{
<API key>.Text = System.IO.Path.GetFileName(m_SaveLoadHelper.CurrentFile);
}
}
}
#endregion
/* Playback buttons methods */
#region Playback Buttons
private void playButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Play();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Play();
}
}
private void pauseButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Pause();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Pause();
}
}
private void stopButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Stop();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Stop();
}
}
private void recordButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Record();
}
}
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Loop = loopCheckBox.Checked;
}
}
#endregion
/* Script buttons methods */
#region Script Buttons
private void scriptButton_Click(object sender, EventArgs e)
{
m_ScriptHost.ShowForm(this);
}
#endregion
/* Menu strip methods */
#region Menu Strip
#region File
private void <API key>(object sender, EventArgs e)
{
SetControlMode(ControlMode.Macro);
m_MacroPlayer.Clear();
m_SaveLoadHelper.ClearCurrentFile();
}
private void <API key>(object sender, EventArgs e)
{
m_SaveLoadHelper.Load();
}
private void <API key>(object sender, EventArgs e)
{
m_SaveLoadHelper.Save();
}
private void <API key>(object sender, EventArgs e)
{
m_SaveLoadHelper.SaveAs();
}
private void <API key>(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
#region Edit
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Clear();
}
}
private void <API key>(object sender, EventArgs e)
{
m_MacroPlayer.Stop();
var oldSequenceLength = m_MacroPlayer.Sequence.Count;
m_MacroPlayer.Sequence = MacroUtility.TrimMacro(m_MacroPlayer.Sequence);
// Show results
var difference = oldSequenceLength - m_MacroPlayer.Sequence.Count;
MessageBox.Show(
$"{difference} frames removed" + "\n\n" +
$"Before: {oldSequenceLength} frames" + "\n" +
$"After: {m_MacroPlayer.Sequence.Count} frames", "Trim Macro",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
#region Playback
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Play();
}
}
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Pause();
}
}
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Stop();
}
}
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Record();
}
}
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Loop = !<API key>.Checked;
}
}
private void <API key>(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.RecordShortcut = !<API key>.Checked;
}
}
#endregion
#region Tools
private void <API key>(object sender, EventArgs e)
{
var backgroundMode = !(ModifierKeys == Keys.Shift);
var frame = PS4MacroAPI.Internal.ScriptUtility.CaptureFrame(backgroundMode);
var folder = "screenshots";
// Create folder if not exist
Directory.CreateDirectory(folder);
if (frame != null)
{
var fileName = folder + @"\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
frame.Save(fileName);
Console.WriteLine($"{DateTime.Now.ToString()} - Screenshot saved to {Path.GetFullPath(fileName)}");
}
else
{
MessageBox.Show("Unable to capture screenshot!");
}
}
private void <API key>(object sender, EventArgs e)
{
new ImageHashForm().Show(this);
}
private void <API key>(object sender, EventArgs e)
{
new <API key>().ShowDialog(this);
}
private void <API key>(object sender, EventArgs e)
{
new MacroCompressorForm().ShowDialog(this);
}
private void <API key>(object sender, EventArgs e)
{
<API key>(ControlMode.Remapper, () =>
{
new RemapperForm(m_Remapper).ShowDialog(this);
});
}
#endregion
#region Help
private void <API key>(object sender, EventArgs e)
{
<API key>(ControlMode.StatusChecker, () =>
{
m_StatusChecker.SetActive(true);
new StatusCheckerForm(m_StatusChecker).ShowDialog(this);
m_StatusChecker.SetActive(false);
});
}
private void <API key>(object sender, EventArgs e)
{
var aboutForm = new AboutForm();
aboutForm.ShowDialog(this);
}
#endregion
#endregion
/* Status strip methods */
#region Status Strip
#endregion
}
}
|
TAG?=latest
.PHONY: build
build:
./build.sh
.PHONY: build-gateway
build-gateway:
(cd gateway; ./build.sh latest-dev)
.PHONY: test-ci
test-ci:
./contrib/ci.sh
.PHONY: ci-armhf-build
ci-armhf-build:
(cd gateway; ./build.sh $(TAG) ; cd ../auth/basic-auth ; ./build.sh $(TAG))
.PHONY: ci-armhf-push
ci-armhf-push:
(cd gateway; ./push.sh $(TAG) ; cd ../auth/basic-auth ; ./push.sh $(TAG))
.PHONY: ci-arm64-build
ci-arm64-build:
(cd gateway; ./build.sh $(TAG) ; cd ../auth/basic-auth ; ./build.sh $(TAG))
.PHONY: ci-arm64-push
ci-arm64-push:
(cd gateway; ./push.sh $(TAG) ; cd ../auth/basic-auth ; ./push.sh $(TAG))
|
let fs = require("fs");
let path = require("path");
let cp = require("child_process");
function runCommand(folder, args) {
cp.spawn("npm", args, { env: process.env, cwd: folder, stdio: "inherit" });
}
function getPackages(category) {
let folder = path.join(__dirname, category);
return fs
.readdirSync(folder)
.map(function(dir) {
let fullPath = path.join(folder, dir);
// check for a package.json file
if (!fs.existsSync(path.join(fullPath, "package.json"))) {
return;
}
return fullPath;
})
.filter(function(pkg) {
return pkg !== undefined;
});
}
function <API key>(category, args) {
let pkgs = getPackages(category);
pkgs.forEach(function(pkg) {
runCommand(pkg, args);
});
}
let CATEGORIES = ["react", "vue", "svelte", "misc"];
let category = process.argv[2];
let args = process.argv.slice(3);
if (category === "all") {
CATEGORIES.forEach(function(c) {
<API key>(c, args);
});
} else {
<API key>(category, args);
}
|
// AppDelegate.h
// wufeng_cocoapods
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <<API key>>
@property (strong, nonatomic) UIWindow *window;
@end
|
// download the contents of a url
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
res, err := http.Get("http:
if err != nil {
log.Fatal(err)
}
robots, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", robots)
}
|
# DOMHooks
Hooks functions' execution to DOM queries.
DOMHooks is an utility function meant for DOM contextual scripting. By using it you can pair a specific DOM selector (or HTML class selector) with a function which needs to be executed just on that context.
Example:
javascript
//old pattern
jQuery(document).ready(function ($) {
var $foo = $('#foo');
if ($foo.length) {
$foo.doSomething();
}
});
//with DOMHooks
$.domHooks({
//no need to wrap in a DOMReady function!
'#foo': function (selector, $foo) {
//selector === '#foo'
$foo.doSomething();
}
});
## Getting Started
Via [Bower](https://github.com/twitter/bower)...
bower install jquery.domhooks
or download the [production version][min] or the [development version][max].
[min]: https://raw.github.com/dwightjack/domhooks/master/dist/domhooks.min.js
[max]: https://raw.github.com/dwightjack/domhooks/master/dist/domhooks.js
In your web page:
html
<script src="jquery.js"></script>
<script src="/path/to/domhooks.min.js"></script>
<script>
//no need to wrap in a DOMReady function!
$.domHooks(/* args... */);
</script>
## Documentation
Usage
`$.domHooks` accepts up to three arguments:
* `type`: Type of hook, either `'ready'`, `'html'` or `'available'`. (see below for details)
* `query`: Query to execute, either a CSS selector (`'ready'` and `'available'` types) or a class name (`'html'` type)
* `callback`: Function to execute when `query` is matched. The function accepts two arguments: the `query` itself and a jQuery object referencing to it
Basic usage example:
javascript
$.domHook('ready', '#foo', function () { });
You may also pass `query` in the form of an hash `{'selector': callback}`:
javascript
//same as before but shorter
$.domHook('ready', { '#foo': function () { } });
Or you may omit the `type` argument completely, a `'ready'` hook type will always be implied:
javascript
//even shorter, but just for 'ready' hooks
$.domHook({ '#foo': function () { } });
Settings
**Breaking changes!!!**
**Up to v0.1.0b `.pollsMax` and `.pollsInterval` where called `.polls_max` and `.polls_interval`.**
`$.domHooks` exposes also two options used by the `'available'` hook type:
* `$.domHooks.settings.pollsMax`: The number of polls after which the hook gets discarted (defaults to `40`)
* `$.domHooks.settings.pollsInterval`: The interval in ms between each poll (defaults to `25`)
_Note that these settings are globals to every function call, and they may prejudice the overall performances of the page._
Query types
**ready**
hooks got parsed automatically on DOM Ready. Hooks added after DOM Ready are parsed right away. They accept CSS selector as query string.
**html**
hooks got parsed as soon as they are added, since the `html` element always exists before the DOM is ready. They accept a single class name as query string (use [.hasClass](http://api.jquery.com/hasClass/) internally).
**available**
hooks got parsed as soon as they are added and try to match a DOM element _BEFORE_ the DOM is ready. They work very similarly to the [available event in YUI](http://yuilibrary.com/yui/docs/event/domready.html#available), by polling the DOM for a given element at regular intervals. If the query isn't matched they fail silently. _Since these hooks are expensive in terms of performances, use them sparingly._
## Release History
* 0.1.2 Added [Bower](https://github.com/twitter/bower) support
* 0.1.1 Bugfixes
* 0.1.0b Initial release
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ColorPickerModule } from '<API key>';
// components
import { ShellComponent } from './components/shell';
import { HelloComponent } from './components/hello';
import { OpenFolderComponent } from './components/folder';
import { SettingsComponent } from './components/settings';
import { AboutComponent } from './components/about';
// pipes
import { SVGPipe } from './pipes/SVGPipe';
// services
import { IpcRendererService } from './services/ipcRender';
import { StorageService } from './services/storage';
import { ComponentService } from './services/componentService';
// directives
import { WebviewDirective } from './directives/webview';
// routes
import { appRoutes } from './routes';
@NgModule({
imports: [
BrowserModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
ColorPickerModule,
RouterModule.forRoot(appRoutes)
],
declarations: [
ShellComponent,
HelloComponent,
OpenFolderComponent,
SettingsComponent,
AboutComponent,
SVGPipe,
WebviewDirective
],
bootstrap: [ShellComponent],
providers: [IpcRendererService, StorageService, ComponentService]
})
export class Module { }
|
<?php
$_pluginInfo=array(
'name'=>'Inet',
'version'=>'1.0.3',
'description'=>"Get the contacts from a Inet account",
'base_version'=>'1.8.0',
'type'=>'email',
'check_url'=>'http://inet.ua/index.php',
'requirement'=>'email',
'allowed_domains'=>array('/(inet.ua)/i','/(fm.com.ua)/i'),
);
/**
* Inet Plugin
*
* Imports user's contacts from Inet AddressBook
*
* @author OpenInviter
* @version 1.0.0
*/
class inet extends openinviter_base
{
private $login_ok=false;
public $showContacts=true;
public $internalError=false;
protected $timeout=30;
public $debug_array=array(
'initial_get'=>'login_username',
'login_post'=>'frame',
'url_redirect'=>'passport',
'url_export'=>'FORENAME',
);
/**
* Login function
*
* Makes all the necessary requests to authenticate
* the current user to the server.
*
* @param string $user The current user.
* @param string $pass The password for the current user.
* @return bool TRUE if the current user was authenticated successfully, FALSE otherwise.
*/
public function login($user,$pass)
{
$this->resetDebugger();
$this->service='inet';
$this->service_user=$user;
$this->service_password=$pass;
if (!$this->init()) return false;
$res=$this->get("http://inet.ua/index.php");
if ($this->checkResponse("initial_get",$res))
$this->updateDebugBuffer('initial_get',"http://inet.ua/index.php",'GET');
else
{
$this->updateDebugBuffer('initial_get',"http://inet.ua/index.php",'GET',false);
$this->debugRequest();
$this->stopPlugin();
return false;
}
$user_array=explode('@',$user);$username=$user_array[0];
$form_action="http://newmail.inet.ua/login.php";
$post_elements=array('username'=>$username,'password'=>$pass,'server_id'=>0,'template'=>'v-webmail','language'=>'ru','login_username'=>$username,'servname'=>'inet.ua','login_password'=>$pass,'version'=>1,'x'=>rand(1,100),'y'=>rand(1,100));
$res=$this->post($form_action,$post_elements,true);
if ($this->checkResponse('login_post',$res))
$this->updateDebugBuffer('login_post',$form_action,'POST',true,$post_elements);
else
{
$this->updateDebugBuffer('login_post',$form_action,'POST',false,$post_elements);
$this->debugRequest();
$this->stopPlugin();
return false;
}
$this->login_ok="http://newmail.inet.ua/download.php?act=process_export&method=csv&addresses=all";
return true;
}
/**
* Get the current user's contacts
*
* Makes all the necesarry requests to import
* the current user's contacts
*
* @return mixed The array if contacts if importing was successful, FALSE otherwise.
*/
public function getMyContacts()
{
if (!$this->login_ok)
{
$this->debugRequest();
$this->stopPlugin();
return false;
}
else $url=$this->login_ok;
$res=$this->get($url);
if ($this->checkResponse("url_export",$res))
$this->updateDebugBuffer('url_export',$url,'GET');
else
{
$this->updateDebugBuffer('url_export',$url,'GET',false);
$this->debugRequest();
$this->stopPlugin();
return false;
}
$tempFile=explode(PHP_EOL,$res);$contacts=array();unset($tempFile[0]);
foreach ($tempFile as $valuesTemp)
{
$values=explode('~',$valuesTemp);
if (!empty($values[3]))
$contacts[$values[3]]=array('first_name'=>(!empty($values[1])?$values[1]:false),
'middle_name'=>(!empty($values[2])?$values[2]:false),
'last_name'=>false,
'nickname'=>false,
'email_1'=>(!empty($values[3])?$values[3]:false),
'email_2'=>(!empty($values[4])?$values[4]:false),
'email_3'=>(!empty($values[5])?$values[5]:false),
'organization'=>false,
'phone_mobile'=>(!empty($values[8])?$values[8]:false),
'phone_home'=>(!empty($values[6])?$values[6]:false),
'pager'=>false,
'address_home'=>false,
'address_city'=>(!empty($values[11])?$values[11]:false),
'address_state'=>(!empty($values[12])?$values[12]:false),
'address_country'=>(!empty($values[14])?$values[14]:false),
'postcode_home'=>(!empty($values[13])?$values[13]:false),
'company_work'=>false,
'address_work'=>false,
'address_work_city'=>false,
'<API key>'=>false,
'address_work_state'=>false,
'<API key>'=>false,
'fax_work'=>false,
'phone_work'=>(!empty($values[7])?$values[7]:false),
'website'=>false,
'isq_messenger'=>false,
'skype_essenger'=>false,
'yahoo_essenger'=>false,
'msn_messenger'=>false,
'aol_messenger'=>false,
'other_messenger'=>false,
);
}
foreach ($contacts as $email=>$name) if (!$this->isEmail($email)) unset($contacts[$email]);
return $this->returnContacts($contacts);
}
/**
* Terminate session
*
* Terminates the current user's session,
* debugs the request and reset's the internal
* debudder.
*
* @return bool TRUE if the session was terminated successfully, FALSE otherwise.
*/
public function logout()
{
if (!$this->checkSession()) return false;
$res=$this->get('http://newmail.inet.ua/logout.php?vwebmailsession=',true);
$this->debugRequest();
$this->resetDebugger();
$this->stopPlugin();
return true;
}
}
?>
|
package org.workcraft.plugins.circuit;
import org.workcraft.annotations.DisplayName;
import org.workcraft.annotations.Hotkey;
import org.workcraft.annotations.SVGIcon;
import org.workcraft.dom.Node;
import org.workcraft.dom.visual.BoundingBoxHelper;
import org.workcraft.dom.visual.DrawRequest;
import org.workcraft.formula.BooleanFormula;
import org.workcraft.formula.visitors.<API key>;
import org.workcraft.formula.visitors.FormulaToGraphics;
import org.workcraft.gui.tools.Decoration;
import org.workcraft.observation.<API key>;
import org.workcraft.observation.StateEvent;
import org.workcraft.observation.StateObserver;
import org.workcraft.plugins.circuit.renderers.<API key>.RenderType;
import org.workcraft.serialisation.NoAutoSerialisation;
import org.workcraft.utils.ColorUtils;
import org.workcraft.utils.Hierarchy;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.*;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
@DisplayName("Input/output port")
@Hotkey(KeyEvent.VK_P)
@SVGIcon("images/circuit-node-port.svg")
public class <API key> extends VisualContact implements StateObserver {
private static final double size = 0.3;
private static FontRenderContext context = new FontRenderContext(AffineTransform.getScaleInstance(1000.0, 1000.0), true, true);
private static Font functionFont;
private <API key> renderedSetFunction = null;
private <API key> <API key> = null;
private static double functionFontSize = CircuitSettings.getFunctionFontSize();
static {
try {
functionFont = Font.createFont(Font.TYPE1_FONT, ClassLoader.<API key>("fonts/eurm10.pfb"));
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
}
public <API key>(FunctionContact contact) {
super(contact);
}
@Override
public FunctionContact <API key>() {
return (FunctionContact) super.<API key>();
}
@NoAutoSerialisation
public BooleanFormula getSetFunction() {
return <API key>().getSetFunction();
}
@NoAutoSerialisation
public void setSetFunction(BooleanFormula setFunction) {
if (getParent() instanceof <API key>) {
<API key> p = (<API key>) getParent();
p.<API key>();
}
renderedSetFunction = null;
<API key>().setSetFunction(setFunction);
}
@NoAutoSerialisation
public BooleanFormula getResetFunction() {
return <API key>().getResetFunction();
}
@NoAutoSerialisation
public void setForcedInit(boolean value) {
<API key>().setForcedInit(value);
}
@NoAutoSerialisation
public boolean getForcedInit() {
return <API key>().getForcedInit();
}
@NoAutoSerialisation
public void setInitToOne(boolean value) {
<API key>().setInitToOne(value);
}
@NoAutoSerialisation
public boolean getInitToOne() {
return <API key>().getInitToOne();
}
@NoAutoSerialisation
public void setResetFunction(BooleanFormula resetFunction) {
if (getParent() instanceof <API key>) {
<API key> p = (<API key>) getParent();
p.<API key>();
}
<API key> = null;
<API key>().setResetFunction(resetFunction);
}
public void <API key>() {
renderedSetFunction = null;
<API key> = null;
}
private Font getFunctionFont() {
return functionFont.deriveFont((float) CircuitSettings.getFunctionFontSize());
}
private <API key> <API key>() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
renderedSetFunction = null;
}
BooleanFormula setFunction = <API key>().getSetFunction();
if (setFunction == null) {
renderedSetFunction = null;
} else if (renderedSetFunction == null) {
renderedSetFunction = FormulaToGraphics.render(setFunction, context, getFunctionFont());
}
return renderedSetFunction;
}
private Point2D getSetFormulaOffset() {
double xOffset = size;
double yOffset = -size / 2;
<API key> renderingResult = <API key>();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof <API key>)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getSetBoundingBox() {
Rectangle2D bb = null;
<API key> setRenderingResult = <API key>();
if (setRenderingResult != null) {
bb = BoundingBoxHelper.move(setRenderingResult.boundingBox, getSetFormulaOffset());
Direction dir = getDirection();
if (!(getParent() instanceof <API key>)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private <API key> <API key>() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
<API key> = null;
}
BooleanFormula resetFunction = <API key>().getResetFunction();
if (resetFunction == null) {
<API key> = null;
} else if (<API key> == null) {
<API key> = FormulaToGraphics.render(resetFunction, context, getFunctionFont());
}
return <API key>;
}
private Point2D <API key>() {
double xOffset = size;
double yOffset = size / 2;
<API key> renderingResult = <API key>();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof <API key>)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
yOffset = size / 2 + renderingResult.boundingBox.getHeight();
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getResetBoundingBox() {
Rectangle2D bb = null;
<API key> renderingResult = <API key>();
if (renderingResult != null) {
bb = BoundingBoxHelper.move(renderingResult.boundingBox, <API key>());
Direction dir = getDirection();
if (!(getParent() instanceof <API key>)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private void drawArrow(Graphics2D g, int arrowType, double arrX, double arrY) {
double s = CircuitSettings.getFunctionFontSize();
g.setStroke(new BasicStroke((float) s / 25));
double s1 = 0.75 * s;
double s2 = 0.45 * s;
double s3 = 0.30 * s;
if (arrowType == 1) {
// arrow down
Line2D line = new Line2D.Double(arrX, arrY - s1, arrX, arrY - s3);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s3);
path.lineTo(arrX + 0.05, arrY - s3);
path.lineTo(arrX, arrY);
path.closePath();
g.fill(path);
g.draw(line);
} else if (arrowType == 2) {
// arrow up
Line2D line = new Line2D.Double(arrX, arrY, arrX, arrY - s2);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s2);
path.lineTo(arrX + 0.05, arrY - s2);
path.lineTo(arrX, arrY - s1);
path.closePath();
g.fill(path);
g.draw(line);
}
}
private void drawFormula(Graphics2D g, int arrowType, Point2D offset, <API key> renderingResult) {
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof <API key>)) {
dir = dir.flip();
}
AffineTransform savedTransform = g.getTransform();
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
g.transform(rotateTransform);
}
double dXArrow = -0.15;
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
dXArrow = renderingResult.boundingBox.getWidth() + 0.15;
}
drawArrow(g, arrowType, offset.getX() + dXArrow, offset.getY());
g.translate(offset.getX(), offset.getY());
renderingResult.draw(g);
g.setTransform(savedTransform);
}
}
@Override
public void draw(DrawRequest r) {
if (needsFormulas()) {
Graphics2D g = r.getGraphics();
Decoration d = r.getDecoration();
g.setColor(ColorUtils.colorise(getForegroundColor(), d.getColorisation()));
<API key> renderingResult;
renderingResult = <API key>();
if (renderingResult != null) {
Point2D offset = getSetFormulaOffset();
drawFormula(g, 2, offset, renderingResult);
}
renderingResult = <API key>();
if (renderingResult != null) {
Point2D offset = <API key>();
drawFormula(g, 1, offset, renderingResult);
}
}
super.draw(r);
}
private boolean needsFormulas() {
boolean result = false;
Node parent = getParent();
if (parent != null) {
// Primary input port
if (!(parent instanceof <API key>) && isInput()) {
result = true;
}
// Output port of a BOX-rendered component
if ((parent instanceof <API key>) && isOutput()) {
<API key> component = (<API key>) parent;
if (component.getRenderType() == RenderType.BOX) {
result = true;
}
}
}
return result;
}
@Override
public Rectangle2D <API key>() {
Rectangle2D bb = super.<API key>();
if (needsFormulas()) {
bb = BoundingBoxHelper.union(bb, getSetBoundingBox());
bb = BoundingBoxHelper.union(bb, getResetBoundingBox());
}
return bb;
}
private Collection<<API key>> getAllContacts() {
HashSet<<API key>> result = new HashSet<>();
Node root = Hierarchy.getRoot(this);
if (root != null) {
result.addAll(Hierarchy.<API key>(root, <API key>.class));
}
return result;
}
@Override
public void notify(StateEvent e) {
if (e instanceof <API key>) {
<API key> pc = (<API key>) e;
String propertyName = pc.getPropertyName();
if (propertyName.equals(FunctionContact.<API key>) || propertyName.equals(FunctionContact.<API key>)) {
<API key>();
}
if (propertyName.equals(Contact.PROPERTY_NAME)) {
for (<API key> vc : getAllContacts()) {
vc.<API key>();
}
}
}
super.notify(e);
}
}
|
#ifndef _SMT_ARITH_H_
#define _SMT_ARITH_H_
#include"ast.h"
#include"smt_solver_types.h"
#include"params.h"
#include"statistics.h"
class model;
namespace smt {
class arith {
struct imp;
imp * m_imp;
params_ref m_params;
public:
arith(ast_manager & m, params_ref const & p);
~arith();
void updt_params(params_ref const & p);
void assert_axiom(expr * t, bool neg);
void mk_atom(expr * t, atom_id id);
void asserted(atom_id id, bool is_true);
bool inconsistent() const;
void push();
void pop(unsigned num_scopes);
void set_cancel(bool f);
void simplify();
void display(std::ostream & out) const;
void reset();
void preprocess();
void collect_statistics(statistics & st) const;
void reset_statistics();
lbool check();
void mk_model(model * md);
};
};
#endif
|
from core.himesis import Himesis, <API key>
import uuid
class <API key>(<API key>):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model <API key>
"""
# Flag this instance as compiled now
self.is_compiled = True
super(<API key>, self).__init__(name='<API key>', num_nodes=0, edges=[])
# Add the edges
self.add_edges([])
# Set the graph attributes
self["mm__"] = ['<API key>', 'MoTifRule']
self["MT_constraint__"] = """return True"""
self["name"] =
self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'<API key>')
self["equations"] = []
# Set the node attributes
# match class Family(Fam) node
self.add_node()
self.vs[0]["MT_pre__attr1"] = """return True"""
self.vs[0]["MT_label__"] =
self.vs[0]["mm__"] = """MT_pre__Family"""
self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam')
# match class Child(Child) node
self.add_node()
self.vs[1]["MT_pre__attr1"] = """return True"""
self.vs[1]["MT_label__"] =
self.vs[1]["mm__"] = """MT_pre__Child"""
self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child')
# match association null--daughters-->nullnode
self.add_node()
self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """
self.vs[2]["MT_label__"] =
self.vs[2]["mm__"] = """<API key>"""
self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child')
# Add the edges
self.add_edges([
(0,2), # match class null(Fam) -> association daughters
(2,1), # association null -> match class null(Child)
])
# define evaluation methods for each match class.
def eval_attr11(self, attr_value, this):
return True
def eval_attr12(self, attr_value, this):
return True
# define evaluation methods for each match association.
def eval_attr13(self, attr_value, this):
return attr_value == "daughters"
def constraint(self, PreNode, graph):
return True
|
layout: post
title: iOS Localization
date: 2014-10-25
categories: iOS
This post contains some of my thoughts and experiences from localizing iOS applications.
##Format specifiers
After many mistakes when localizing and having to change stuff later I've arrived at the conclusion that you should use the string format specifier (`%@`) for *everything*.
The following example should give you an idea of why.
{% highlight objc %}
NSString *format = NSLocalizedString(@"I have %d red candies.", nil);
NSString *result = [NSString stringWithFormat:format, 5];
// "I have 5 red candies".
{% endhighlight %}
There are two problems with using integer format (`%d`) here:
1. Sooner or later we might want to put something other than an integer in there, like spelling out "five" or using a fractional number like 5.5.
2. Some languages don't use decimal integers like we do. A language could theoretically use base 4, or use [different characters](http://en.wikipedia.org/wiki/<API key>) for numbers. I'll explain how to deal with the number formatting in a second.
Had we used `%@` instead of `%d`, both of the above problems could be solved without ordering new, specific translations.
##Combining strings
Combining different localized strings is something I've seen happen every now and then.
For instance, if we already have localizations for the strings `@"Eat"` and `@"Candy"`, it could be very tempting to do something like this to reduce translation costs:
{% highlight objc %}
NSString *eat = NSLocalizedString(@"Eat", nil);
NSString *candy = NSLocalizedString(@"Candy", nil);
NSString *consumeButtonText = [NSString stringWithFormat:@"%@ %@", eat, candy];
// "Eat Candy"
{% endhighlight %}
The problem is that in some languages, the order of words will be inverted. It only gets worse if we combine several words or sentences. I recommend that you spend some more resources on adding all the possible sentences to your localization files, and the translations will be more correct.
##Formatting numbers
Each and every number presented in the UI should be formatted. This guarantees that the application displays numbers correctly even if different locales use different characters or number systems.
{% highlight objc %}
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.numberStyle = <API key>;
NSInteger aNumber = 74679;
NSString *formattedNumber = [formatter stringFromNumber:@(aNumber)];
{% endhighlight %}
`formattedNumber` will differ depending on the current locale:
{% highlight objc %}
"74,679"
"74 679"
"٧٤٬٦٧٩"
{% endhighlight %}
Since `NSNumberFormatter` is heavy to initialize, I usually keep a few static formatters in a utility class configured for different format styles.
Formatting numbers also have other benefits, for example, not having to write code to round floats or display percentages. If you give a formatter with `<API key>` a float like `0.53467`, it will nicely output `53%`for you. (Or whatever a percentage number should look like in the current locale).
`NSNumberFormatter` really is an amazing class, and I recommend everyone to at least skim through its documentation.
##Autolayout
Autolayout is a great tool to aid us in our quests for perfect localizations. Different languages use different amount of characters to express the same things, and having UI elements automatically make room for text is a real time saver.
It's especially helpful for supporting right-to-left (RTL) languages. Every view that layouts using leading or trailing attributes will be properly laid out together with labels containing right-to-left text.
Most of the time, Autolayout takes care of everything we need for supporting RTL languages. But when something comes up that needs to be done manually (or if we don't use Autolayout at all), we can always branch code like this:
{% highlight objc %}
<API key> layoutDirection = [UIApplication sharedApplication].<API key>;
if (layoutDirection == <API key>) {
// Code to handle RTL language
}
{% endhighlight %}
|
module Lib where
import Data.Function (on)
import Data.List (findIndices, minimumBy, transpose)
import Data.Maybe (isJust, isNothing)
data Shape = Nought | Cross
deriving (Read, Show, Eq)
type Cell = Maybe Shape
type Board = [Cell]
boardSize = 3
emptyBoard = replicate (boardSize * boardSize) Nothing
makeBoard :: String -> Board
makeBoard = map charToCell . take (boardSize * boardSize)
where
charToCell 'o' = Just Nought
charToCell 'x' = Just Cross
charToCell _ = Nothing
nextMove :: Board -> Shape -> Board
nextMove brd shp = minimumBy (compare `on` opponentScore) (nextBoards brd shp)
where
opponentScore brd' = scoreFor brd' (opponent shp)
isWinFor :: Board -> Shape -> Bool
isWinFor brd shp = any winningSlice allSlices
where
winningSlice = all (== Just shp)
allSlices = rows brd ++ cols brd ++ diagonals brd
isLossFor :: Board -> Shape -> Bool
isLossFor brd shp = isWinFor brd (opponent shp)
isDraw :: Board -> Bool
isDraw brd = isFull brd && noWin Nought && noWin Cross
where
noWin = not . isWinFor brd
isFull :: Board -> Bool
isFull = all isJust
nextBoards :: Board -> Shape -> [Board]
nextBoards brd shp = map makeMove emptyIdxs
where
makeMove n = fillCell brd n (Just shp)
emptyIdxs = findIndices isNothing brd
fillCell :: Board -> Int -> Cell -> Board
fillCell brd n cell
| n >= (boardSize * boardSize) = brd
| otherwise = before ++ [cell] ++ (drop 1 after)
where
(before, after) = splitAt n brd
scoreFor :: Board -> Shape -> Int
scoreFor brd shp
| isWinFor brd shp = 1
| isLossFor brd shp = -1
| isDraw brd = 0
| otherwise = -(minimum $ map opponentScore (nextBoards brd shp))
where
opponentScore brd' = scoreFor brd' (opponent shp)
rows :: Board -> [[Cell]]
rows brd = map row [0..boardSize-1]
where
row n = take boardSize . drop (n * boardSize) $ brd
cols :: Board -> [[Cell]]
cols = transpose . rows
diagonals :: Board -> [[Cell]]
diagonals brd = map extract [topLeft, topRight]
where
extract = map (brd !!)
topLeft = map (\n -> n * (boardSize + 1)) [0..boardSize-1]
topRight = map (\n -> (n + 1) * (boardSize - 1)) [0..boardSize-1]
opponent :: Shape -> Shape
opponent Nought = Cross
opponent Cross = Nought
|
<?php
/* TwigBundle:Exception:traces.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div class=\"block\">
";
// line 2
if (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) > 0)) {
// line 3
echo " <h2>
<span><small>[";
// line 4
echo twig_escape_filter($this->env, (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) - (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position"))) + 1), "html", null, true);
echo "/";
echo twig_escape_filter($this->env, ((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) + 1), "html", null, true);
echo "]</small></span>
";
// line 5
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class", array()));
echo ": ";
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message", array()), "html", null, true)));
echo "
";
// line 6
ob_start();
// line 7
echo " <a href=\"#\" onclick=\"toggle('traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "', 'traces'); switchIcons('icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open', 'icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close'); return false;\">
<img class=\"toggle\" id=\"icon-traces-";
// line 8
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close\" alt=\"-\" src=\"data:image/gif;base64,<API key>+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/<API key>+<API key>=\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("inline") : ("none"));
echo "\" />
<img class=\"toggle\" id=\"icon-traces-";
// line 9
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open\" alt=\"+\" src=\"data:image/gif;base64,<API key>/v+<API key>+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/<API key>\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("none") : ("inline"));
echo "\" />
</a>
";
echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
// line 12
echo " </h2>
";
} else {
// line 14
echo " <h2>Stack Trace</h2>
";
}
// line 16
echo "
<a id=\"traces-link-";
// line 17
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\"></a>
<ol class=\"traces list-exception\" id=\"traces-";
// line 18
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("block") : ("none"));
echo "\">
";
// line 19
$context['_parent'] = $context;
$context['_seq'] = <API key>($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()));
foreach ($context['_seq'] as $context["i"] => $context["trace"]) {
// line 20
echo " <li>
";
// line 21
$this->loadTemplate("TwigBundle:Exception:trace.html.twig", "TwigBundle:Exception:traces.html.twig", 21)->display(array("prefix" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "i" => $context["i"], "trace" => $context["trace"]));
// line 22
echo " </li>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 24
echo " </ol>
</div>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 101 => 24, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 39 => 6, 33 => 5, 27 => 4, 24 => 3, 22 => 2, 19 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("<div class=\"block\">
{% if count > 0 %}
<h2>
<span><small>[{{ count - position + 1 }}/{{ count + 1 }}]</small></span>
{{ exception.class|abbr_class }}: {{ exception.message|nl2br|<API key> }}
{% spaceless %}
<a href=\"#\" onclick=\"toggle('traces-{{ position }}', 'traces'); switchIcons('icon-traces-{{ position }}-open', 'icon-traces-{{ position }}-close'); return false;\">
<img class=\"toggle\" id=\"icon-traces-{{ position }}-close\" alt=\"-\" src=\"data:image/gif;base64,<API key>+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/<API key>+<API key>=\" style=\"display: {{ 0 == count ? 'inline' : 'none' }}\" />
<img class=\"toggle\" id=\"icon-traces-{{ position }}-open\" alt=\"+\" src=\"data:image/gif;base64,<API key>/v+<API key>+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/<API key>\" style=\"display: {{ 0 == count ? 'none' : 'inline' }}\" />
</a>
{% endspaceless %}
</h2>
{% else %}
<h2>Stack Trace</h2>
{% endif %}
<a id=\"traces-link-{{ position }}\"></a>
<ol class=\"traces list-exception\" id=\"traces-{{ position }}\" style=\"display: {{ 0 == count ? 'block' : 'none' }}\">
{% for i, trace in exception.trace %}
<li>
{% include 'TwigBundle:Exception:trace.html.twig' with { 'prefix': position, 'i': i, 'trace': trace } only %}
</li>
{% endfor %}
</ol>
</div>
", "TwigBundle:Exception:traces.html.twig", "C:\\inetpub\\wwwroot\\Cupon1\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle/Resources/views/Exception/traces.html.twig");
}
}
|
Polaris::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.<API key> = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use <API key>, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.<API key> = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Mailer settings
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'mail.google.com',
authentication: 'plain',
<API key>: true,
user_name: 'contato@codepolaris.com',
password: 'CodePolaris'
}
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
|
var models=require('../models/models.js');
// Autoload :id de comentarios
exports.load=function (req,res,next,commentId) {
models.Comment.find({
where:{
id:Number(commentId)
}
}).then(function (comment) {
if(comment){
req.comment=comment;
next();
}else{
next(new Error('No existe commentId=' +commentId))
}
}).catch(function (error) {
next(error);
});
};
//GET /quizes/:quizId/comments/new
exports.new=function (req,res) {
res.render('comments/new.ejs',{quizid:req.params.quizId, errors:[]});
};
//POST /quizes/:quizId/comments
exports.create=function (req,res) {
var comment =models.Comment.build(
{
texto:req.body.comment.texto,
QuizId:req.params.quizId,
});
comment
.validate()
.then(
function (err) {
if(err){
res.render('comments/new.ejs',
{comment:comment,quizid:req.params.quizId,errors:err.errors});
}else{
comment //save :guarda en DB campo texto
.save()
.then(function () {
res.redirect('/quizes/'+req.params.quizId);
});
}
}
).catch(function (error) {
next(error);
});
};
//GET /quizes/:quizId/comments/:commentId/publish
exports.publish=function (req,res) {
req.comment.publicado=true;
req.comment.save({fields:["publicado"]}).then(
function () {
res.redirect('/quizes/'+req.params.quizId);
}).catch(function (error) {
next(error);
});
};
|
package net.dirtyfilthy.bouncycastle.asn1.nist;
import net.dirtyfilthy.bouncycastle.asn1.DERObjectIdentifier;
import net.dirtyfilthy.bouncycastle.asn1.sec.SECNamedCurves;
import net.dirtyfilthy.bouncycastle.asn1.sec.<API key>;
import net.dirtyfilthy.bouncycastle.asn1.x9.X9ECParameters;
import net.dirtyfilthy.bouncycastle.util.Strings;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2
*/
public class NISTNamedCurves
{
static final Hashtable objIds = new Hashtable();
static final Hashtable names = new Hashtable();
static void defineCurve(String name, DERObjectIdentifier oid)
{
objIds.put(name, oid);
names.put(oid, name);
}
static
{
// TODO Missing the "K-" curves
defineCurve("B-571", <API key>.sect571r1);
defineCurve("B-409", <API key>.sect409r1);
defineCurve("B-283", <API key>.sect283r1);
defineCurve("B-233", <API key>.sect233r1);
defineCurve("B-163", <API key>.sect163r2);
defineCurve("P-521", <API key>.secp521r1);
defineCurve("P-384", <API key>.secp384r1);
defineCurve("P-256", <API key>.secp256r1);
defineCurve("P-224", <API key>.secp224r1);
defineCurve("P-192", <API key>.secp192r1);
}
public static X9ECParameters getByName(
String name)
{
DERObjectIdentifier oid = (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
if (oid != null)
{
return getByOID(oid);
}
return null;
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters getByOID(
DERObjectIdentifier oid)
{
return SECNamedCurves.getByOID(oid);
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DERObjectIdentifier getOID(
String name)
{
return (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
}
/**
* return the named curve name represented by the given object identifier.
*/
public static String getName(
DERObjectIdentifier oid)
{
return (String)names.get(oid);
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static Enumeration getNames()
{
return objIds.keys();
}
}
|
<?php
// Include the API
require '../../lastfmapi/lastfmapi.php';
// Get the session auth data
$file = fopen('../auth.txt', 'r');
// Put the auth data into an array
$authVars = array(
'apiKey' => trim(fgets($file)),
'secret' => trim(fgets($file)),
'username' => trim(fgets($file)),
'sessionKey' => trim(fgets($file)),
'subscriber' => trim(fgets($file))
);
$config = array(
'enabled' => true,
'path' => '../../lastfmapi/',
'cache_length' => 1800
);
// Pass the array to the auth class to eturn a valid auth
$auth = new lastfmApiAuth('setsession', $authVars);
$apiClass = new lastfmApi();
$tagClass = $apiClass->getPackage($auth, 'tag', $config);
// Setup the variables
$methodVars = array(
'tag' => 'Emo'
);
if ( $albums = $tagClass->getTopAlbums($methodVars) ) {
echo '<b>Data Returned</b>';
echo '<pre>';
print_r($albums);
echo '</pre>';
}
else {
die('<b>Error '.$tagClass->error['code'].' - </b><i>'.$tagClass->error['desc'].'</i>');
}
?>
|
BuildTearDown {
throw "forced error"
}
Task default -depends Compile,Test,Deploy
Task Compile {
"Compiling;"
}
Task Test -depends Compile {
"Testing;"
}
Task Deploy -depends Test {
"Deploying;"
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<link href='https://fonts.googleapis.com/css?family=Chivo:900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/pygment_trac.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]
<title>Davidstrada.GitHub.io by DavidStrada</title>
</head>
<body>
<div id="container">
<div class="inner">
<header>
<h1>Davidstrada.GitHub.io</h1>
<h2></h2>
</header>
<section id="downloads" class="clearfix">
<a href="https://github.com/DavidStrada" id="view-on-github" class="button"><span>View on GitHub</span></a>
</section>
<hr>
<section id="main_content">
<h3>
<a id="<API key>" class="anchor" href="#<API key>" aria-hidden="true"><span class="octicon octicon-link"></span></a>Welcome to GitHub Pages.</h3>
<p>This automatic page generator is the easiest way to create beautiful pages for all of your projects. Author your page content here using GitHub Flavored Markdown, select a template crafted by a designer, and publish. After your page is generated, you can check out the new branch:</p>
<pre><code>$ cd your_repo_root/repo_name
$ git fetch origin
$ git checkout gh-pages
</code></pre>
<p>If you're using the GitHub for Mac, simply sync your repository and you'll see the new branch.</p>
<h3>
<a id="designer-templates" class="anchor" href="#designer-templates" aria-hidden="true"><span class="octicon octicon-link"></span></a>Designer Templates</h3>
<p>We've crafted some handsome templates for you to use. Go ahead and continue to layouts to browse through them. You can easily go back to edit your page before publishing. After publishing your page, you can revisit the page generator and switch to another theme. Your Page content will be preserved if it remained markdown format.</p>
<h3>
<a id="rather-drive-stick" class="anchor" href="#rather-drive-stick" aria-hidden="true"><span class="octicon octicon-link"></span></a>Rather Drive Stick?</h3>
<p>If you prefer to not use the automatic generator, push a branch named <code>gh-pages</code> to your repository to create a page manually. In addition to supporting regular HTML content, GitHub Pages support Jekyll, a simple, blog aware static site generator written by our own Tom Preston-Werner. Jekyll makes it easy to create site-wide headers and footers without having to copy them across every page. It also offers intelligent blog support and other advanced templating features.</p>
<h3>
<a id="<API key> class="anchor" href="#<API key> aria-hidden="true"><span class="octicon octicon-link"></span></a>Authors and Contributors</h3>
<p>You can <a href="https:
<h3>
<a id="support-or-contact" class="anchor" href="#support-or-contact" aria-hidden="true"><span class="octicon octicon-link"></span></a>Support or Contact</h3>
<p>Having trouble with Pages? Check out the documentation at <a href="https:
</section>
<footer>
This page was generated by <a href="http:
</footer>
</div>
</div>
</body>
</html>
|
package com.cosmos.kafka.client.producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
import java.util.Random;
import static org.apache.kafka.clients.producer.ProducerConfig.*;
/**
* Producer using multiple partition
*/
public class <API key> implements Runnable {
private KafkaProducer<Integer, String> producer;
private String topic;
public <API key>(String topic) {
final Properties props = new Properties();
props.put(<API key>, "localhost:9092,localhost:9093,localhost:9094");
props.put(<API key>, "org.apache.kafka.common.serialization.IntegerSerializer");
props.put(<API key>, "org.apache.kafka.common.serialization.StringSerializer");
props.put(<API key>, "org.apache.kafka.clients.producer.internals.DefaultPartitioner");
props.put(ACKS_CONFIG, "1");
this.producer = new KafkaProducer<>(props);
this.topic = topic;
}
@Override
public void run() {
System.out.println("Sending 1000 messages");
Random rnd = new Random();
int i = 1;
while (i <= 1000) {
int key = rnd.nextInt(255);
String message = String.format("Message for key - [%d]: %d", key, i);
System.out.printf("Send: %s\n", message);
this.producer.send(new ProducerRecord<>(this.topic, key, message));
i++;
try {
Thread.sleep(3);
} catch (<API key> e) {
e.printStackTrace();
}
}
producer.close();
}
}
|
// FAQViewController.h
// AKG
#import <UIKit/UIKit.h>
@interface FAQViewController : UIViewController
@end
|
#David Hickox
#Feb 15 17
#Squares (counter update)
#descriptions, description, much descripticve
#variables
# limit, where it stops
# num, sentry variable
#creates array if needbe
#array = [[0 for x in range(h)] for y in range(w)]
#imports date time and curency handeling because i hate string formating (this takes the place of #$%.2f"%)
import locale
locale.setlocale( locale.LC_ALL, '' )
#use locale.currency() for currency formating
print("Welcome to the (insert name here bumbblefack) Program\n")
limit = float(input("How many squares do you want? "))
num = 1
print("number\tnumber^2")
while num <= limit:
#prints the number and squares it then seperates by a tab
print (num,num**2,sep='\t')
#increments
num += 1
input("\nPress Enter to Exit")
|
<?php
namespace Minsal\GinecologiaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SrgTipoConsultaPf
*
* @ORM\Table(name="<API key>")
* @ORM\Entity
*/
class SrgTipoConsultaPf
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="SEQUENCE")
* @ORM\SequenceGenerator(sequenceName="<API key>", allocationSize=1, initialValue=1)
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="tipo_consulta_pf", type="string", length=20, nullable=true)
*/
private $tipoConsultaPf;
/**
* @ORM\OneToMany(targetEntity="<API key>", mappedBy="idTipoConsultaPf", cascade={"all"}, orphanRemoval=true))
**/
private $<API key>;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tipoConsultaPf
*
* @param string $tipoConsultaPf
* @return SrgTipoConsultaPf
*/
public function setTipoConsultaPf($tipoConsultaPf)
{
$this->tipoConsultaPf = $tipoConsultaPf;
return $this;
}
/**
* Get tipoConsultaPf
*
* @return string
*/
public function getTipoConsultaPf()
{
return $this->tipoConsultaPf;
}
/**
* Constructor
*/
public function __construct()
{
$this-><API key> = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add <API key>
*
* @param \Minsal\GinecologiaBundle\Entity\<API key> $<API key>
* @return SrgTipoConsultaPf
*/
public function <API key>(\Minsal\GinecologiaBundle\Entity\<API key> $<API key>)
{
$this-><API key>[] = $<API key>;
return $this;
}
/**
* Remove <API key>
*
* @param \Minsal\GinecologiaBundle\Entity\<API key> $<API key>
*/
public function <API key>(\Minsal\GinecologiaBundle\Entity\<API key> $<API key>)
{
$this-><API key>->removeElement($<API key>);
}
/**
* Get <API key>
*
* @return \Doctrine\Common\Collections\Collection
*/
public function <API key>()
{
return $this-><API key>;
}
public function __toString() {
return $this->id? (string) $this->id: '';
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jprover: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / jprover - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
jprover
<small>
8.6.0
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-02-04 18:52:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-04 18:52:19 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/jprover"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/JProver"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [
"keyword: decision procedure"
"keyword: first-order logic"
"keyword: intuitionistic logic"
"keyword: theorem proving"
"keyword: proof search"
"category: Miscellaneous/Coq Extensions"
"category: Computer Science/Decision Procedures and Certified Algorithms/Decision procedures"
"date: 2002-04 (contribution since January 2009)"
]
authors: [ "Huang Guan-Shieng" ]
bug-reports: "https://github.com/coq-contribs/jprover/issues"
dev-repo: "git+https://github.com/coq-contribs/jprover.git"
synopsis: "A theorem prover for first-order intuitionistic logic"
description: """
JProver is a theorem prover for first-order intuitionistic logic.
It is originally implemented by Stephan Schmitt and then integrated into
MetaPRL by Aleksey Nogin. After this, Huang Guan-Shieng extracted the
necessary ML-codes from MetaPRL and then adapted it to Coq."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/jprover/archive/v8.6.0.tar.gz"
checksum: "md5=<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-jprover.8.6.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-jprover -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-jprover.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>icharate: 41 s</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.1 / icharate - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
icharate
<small>
8.9.0
<span class="label label-success">41 s</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-24 17:47:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-24 17:47:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.12 <API key> of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.9.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https:
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Icharate"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: Multimodal Categorial Grammars"
"keyword: Syntax/Semantics Interface"
"keyword: Higher Order Logic"
"keyword: Meta-Linguistics"
"category: Computer Science/Formal Languages Theory and Automata"
"date: 2003-2006"
]
authors: [
"Houda Anoun <anoun@labri.fr>"
"Pierre Casteran <casteran@labri.fr>"
]
bug-reports: "https://github.com/coq-contribs/icharate/issues"
dev-repo: "git+https://github.com/coq-contribs/icharate.git"
synopsis: "Icharate: A logical Toolkit for Multimodal Categorial Grammars"
description: """
The logical toolkit ICHARATE is built upon a formalization of
multimodal categorial grammars in Coq proof assistant.
This toolkit aims at facilitating the study of these
complicated formalisms by allowing users to build interactively the
syntactic derivations of different sentences, compute their
semantic interpretations and also prove universal properties of entire
classes of grammars using a collection of already established derived
rules. Several tactics are defined to ease the interaction with users."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/icharate/archive/v8.9.0.tar.gz"
checksum: "md5=<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-icharate.8.9.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-icharate.8.9.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>5 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-icharate.8.9.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>41 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 5 M</p>
<ul>
<li>1 M <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_bruijn.vo</code></li>
<li>657 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/basics.vo</code></li>
<li>257 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/apply_rule_props.vo</code></li>
<li>234 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/derivedRulesNatDed.vo</code></li>
<li>195 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_ex.vo</code></li>
<li>183 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsDed.vo</code></li>
<li>126 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/basics.glob</code></li>
<li>123 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_reduction.vo</code></li>
<li>112 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/apply_rule_props.glob</code></li>
<li>108 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_ex.glob</code></li>
<li>104 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/derivedRulesNatDed.glob</code></li>
<li>91 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_bruijn.glob</code></li>
<li>83 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/final_sem.vo</code></li>
<li>79 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/listAux.vo</code></li>
<li>76 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/permutation.vo</code></li>
<li>71 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_coq.vo</code></li>
<li>68 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_reduction.glob</code></li>
<li>66 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsDed.glob</code></li>
<li>60 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/derivSem.vo</code></li>
<li>58 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1s.vo</code></li>
<li>58 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unaries.vo</code></li>
<li>54 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_props.vo</code></li>
<li>52 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDed.vo</code></li>
<li>51 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/polarity.vo</code></li>
<li>50 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/seqNatDed.vo</code></li>
<li>50 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/crossDep.vo</code></li>
<li>49 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1.vo</code></li>
<li>48 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/polEx.vo</code></li>
<li>47 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/dep_ex.vo</code></li>
<li>46 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/medialEx.vo</code></li>
<li>45 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/sequent.vo</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/semLex.vo</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDedGram.vo</code></li>
<li>39 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/medialExtraction.vo</code></li>
<li>38 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unbounDep.vo</code></li>
<li>37 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/struct_tacs.vo</code></li>
<li>37 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/basics.v</code></li>
<li>33 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/polTac.vo</code></li>
<li>33 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/listAux.glob</code></li>
<li>32 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/permutation.glob</code></li>
<li>30 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/interp_coq.vo</code></li>
<li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex3.vo</code></li>
<li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/logic_const.vo</code></li>
<li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsDed.v</code></li>
<li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/notations.vo</code></li>
<li>27 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_bruijn.v</code></li>
<li>27 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/apply_rule_props.v</code></li>
<li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDed.glob</code></li>
<li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/derivedRulesNatDed.v</code></li>
<li>22 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_reduction.v</code></li>
<li>21 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_ex.v</code></li>
<li>21 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/polarity.glob</code></li>
<li>19 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/sequent.glob</code></li>
<li>18 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_props.glob</code></li>
<li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_coq.glob</code></li>
<li>14 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1s.glob</code></li>
<li>14 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unaries.glob</code></li>
<li>13 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/crossDep.glob</code></li>
<li>12 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/semLex.glob</code></li>
<li>12 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/derivSem.glob</code></li>
<li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/listAux.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/final_sem.glob</code></li>
<li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDedGram.glob</code></li>
<li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Lib/permutation.v</code></li>
<li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/polEx.glob</code></li>
<li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/seqNatDed.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/medialEx.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unbounDep.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/dep_ex.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1.glob</code></li>
<li>7 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/lambda_coq.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/polarity.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/medialExtraction.glob</code></li>
<li>5 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDed.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/interp_coq.glob</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unaries.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/derivSem.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/struct_props.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/struct_tacs.glob</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/crossDep.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/seqNatDed.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/final_sem.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/semLex.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/sequent.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/struct_tacs.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/logic_const.glob</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1s.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/natDedGram.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex1.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/unbounDep.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/polTac.glob</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Meta/medialExtraction.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/dep_ex.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/polEx.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/medialEx.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex3.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsSeq.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/notations.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/notations.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/polTac.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/interp_coq.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Kernel/logic_const.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsSeq.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Examples/ex3.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Icharate/Tacs/tacticsSeq.glob</code></li>
</ul>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-icharate.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
using System;
using AppStudio.Uwp;
namespace DJNanoShow.ViewModels
{
public class PrivacyViewModel : ObservableBase
{
public Uri Url
{
get
{
return new Uri(UrlText, UriKind.RelativeOrAbsolute);
}
}
public string UrlText
{
get
{
return "http://1drv.ms/1llJOkM";
}
}
}
}
|
import React, { PropTypes } from 'react';
import TodoItem from './TodoItem';
const TodoList = ({todos}) => (
<ul className="todo-list">
{todos.map(todo =>
<TodoItem key={todo.id} {...todo} />
)}
</ul>
);
TodoList.propTypes = {
todos: PropTypes.array.isRequired
}
export default TodoList;
|
<?php
namespace Podlove\Settings\Dashboard;
use Podlove\Model;
class FileValidation
{
public static function content()
{
global $wpdb;
$sql = '
SELECT
p.post_status,
mf.episode_id,
mf.episode_asset_id,
mf.size,
mf.id media_file_id
FROM
`'.Model\MediaFile::table_name().'` mf
JOIN `'.Model\Episode::table_name().'` e ON e.id = mf.`episode_id`
JOIN `'.$wpdb->posts."` p ON e.`post_id` = p.`ID`
WHERE
p.`post_type` = 'podcast'
AND p.post_status in ('private', 'draft', 'publish', 'pending', 'future')
";
$rows = $wpdb->get_results($sql, ARRAY_A);
$media_files = [];
foreach ($rows as $row) {
if (!isset($media_files[$row['episode_id']])) {
$media_files[$row['episode_id']] = ['post_status' => $row['post_status']];
}
$media_files[$row['episode_id']][$row['episode_asset_id']] = [
'size' => $row['size'],
'media_file_id' => $row['media_file_id'],
];
}
$podcast = Model\Podcast::get();
$episodes = $podcast->episodes(['post_status' => ['private', 'draft', 'publish', 'pending', 'future']]);
$assets = Model\EpisodeAsset::all();
$header = [__('Episode', '<API key>')];
foreach ($assets as $asset) {
$header[] = $asset->title;
}
$header[] = __('Status', '<API key>');
\Podlove\load_template('settings/dashboard/file_validation', [
'episodes' => $episodes,
'assets' => $assets,
'media_files' => $media_files,
'header' => $header,
]);
}
}
|
package de.mpg.mpdl.labcam.code.common.widget;
public class Constants {
public static final String STATUS_SUCCESS = "SUCCESS";
public static final String KEY_CLASS_NAME = "key_class_name";
public static final String SHARED_PREFERENCES = "myPref"; // name of shared preferences
public static final String API_KEY = "apiKey";
public static final String USER_ID = "userId";
public static final String USER_NAME = "username";
public static final String FAMILY_NAME = "familyName";
public static final String GIVEN_NAME = "givenName";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String SERVER_NAME = "serverName";
public static final String OTHER_SERVER = "otherServer";
public static final String COLLECTION_ID = "collectionID";
public static final String OCR_IS_ON = "ocrIsOn";
public static final String IS_ALBUM = "isAlbum";
}
|
const process = require("process");
const path = require("upath");
const semver = require("semver");
const fs = qx.tool.utils.Promisify.fs;
/**
* Installs a package
*/
qx.Class.define("qx.tool.cli.commands.package.Migrate", {
extend: qx.tool.cli.commands.Package,
statics: {
/**
* Flag to prevent recursive call to process()
*/
migrationInProcess: false,
/**
* Return the Yargs configuration object
* @return {{}}
*/
getYargsCommand: function() {
return {
command: "migrate",
describe: "migrates the package system to a newer version.",
builder: {
"verbose": {
alias: "v",
describe: "Verbose logging"
},
"quiet": {
alias: "q",
describe: "No output"
}
}
};
}
},
members: {
/**
* Announces or applies a migration
* @param {Boolean} announceOnly If true, announce the migration without
* applying it.
*/
process: async function(announceOnly=false) {
const self = qx.tool.cli.commands.package.Migrate;
if (self.migrationInProcess) {
return;
}
self.migrationInProcess = true;
let needFix = false;
// do not call this.base(arguments) here!
let pkg = qx.tool.cli.commands.Package;
let cwd = process.cwd();
let migrateFiles = [
[
path.join(cwd, pkg.lockfile.filename),
path.join(cwd, pkg.lockfile.legacy_filename)
],
[
path.join(cwd, pkg.cache_dir),
path.join(cwd, pkg.legacy_cache_dir)
],
[
path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.package_cache_name),
path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.<API key>)
]
];
if (this.checkFilesToRename(migrateFiles).length) {
let replaceInFiles = [{
files: path.join(cwd, ".gitignore"),
from: pkg.legacy_cache_dir + "/",
to: pkg.cache_dir + "/"
}];
await this.migrate(migrateFiles, replaceInFiles, announceOnly);
if (announceOnly) {
needFix = true;
} else {
if (!this.argv.quiet) {
qx.tool.compiler.Console.info("Fixing path names in the lockfile...");
}
this.argv.reinstall = true;
await (new qx.tool.cli.commands.package.Upgrade(this.argv)).process();
}
}
// Migrate all manifest in a package
const registryModel = qx.tool.config.Registry.getInstance();
let manifestModels =[];
if (await registryModel.exists()) {
// we have a qooxdoo.json index file containing the paths of libraries in the repository
await registryModel.load();
let libraries = registryModel.getLibraries();
for (let library of libraries) {
manifestModels.push((new qx.tool.config.Abstract(qx.tool.config.Manifest.config)).set({baseDir: path.join(cwd, library.path)}));
}
} else if (fs.existsSync(qx.tool.config.Manifest.config.fileName)) {
manifestModels.push(qx.tool.config.Manifest.getInstance());
}
for (const manifestModel of manifestModels) {
await manifestModel.set({warnOnly: true}).load();
manifestModel.setValidate(false);
needFix = false;
let s = "";
if (!qx.lang.Type.isArray(manifestModel.getValue("info.authors"))) {
needFix = true;
s += " missing info.authors\n";
}
if (!semver.valid(manifestModel.getValue("info.version"))) {
needFix = true;
s += " missing or invalid info.version\n";
}
let obj = {
"info.qooxdoo-versions": null,
"info.qooxdoo-range": null,
"provides.type": null,
"requires.qxcompiler": null,
"requires.qooxdoo-sdk": null,
"requires.qooxdoo-compiler": null
};
if (manifestModel.keyExists(obj)) {
needFix = true;
s += " obsolete entry:\n";
for (let key in obj) {
if (obj[key]) {
s += " " + key + "\n";
}
}
}
if (needFix) {
if (announceOnly) {
qx.tool.compiler.Console.warn("*** Manifest(s) need to be updated:\n" + s);
} else {
manifestModel
.transform("info.authors", authors => {
if (authors === "") {
return [];
} else if (qx.lang.Type.isString(authors)) {
return [{name: authors}];
} else if (qx.lang.Type.isObject(authors)) {
return [{
name: authors.name,
email: authors.email
}];
} else if (qx.lang.Type.isArray(authors)) {
return authors.map(r =>
qx.lang.Type.isObject(r) ? {
name: r.name,
email: r.email } :
{
name: r
}
);
}
return [];
})
.transform("info.version", version => {
let coerced = semver.coerce(version);
if (coerced === null) {
qx.tool.compiler.Console.warn(`*** Version string '${version}' could not be interpreted as semver, changing to 1.0.0`);
return "1.0.0";
}
return String(coerced);
})
.unset("info.qooxdoo-versions")
.unset("info.qooxdoo-range")
.unset("provides.type")
.unset("requires.qxcompiler")
.unset("requires.qooxdoo-compiler")
.unset("requires.qooxdoo-sdk");
await manifestModel.save();
if (!this.argv.quiet) {
qx.tool.compiler.Console.info(`Updated settings in ${manifestModel.getRelativeDataPath()}.`);
}
}
}
// check framework and compiler dependencies
// if none are given in the Manifest, use the present framework and compiler
const compiler_version = qx.tool.compiler.Version.VERSION;
const compiler_range = manifestModel.getValue("requires.@qooxdoo/compiler") || compiler_version;
const framework_version = await this.getLibraryVersion(await this.getGlobalQxPath());
const framework_range = manifestModel.getValue("requires.@qooxdoo/framework") || framework_version;
if (
!semver.satisfies(compiler_version, compiler_range) ||
!semver.satisfies(framework_version, framework_range)) {
needFix = true;
if (announceOnly) {
qx.tool.compiler.Console.warn(`*** Mismatch between installed framework version (${framework_version}) and/or compiler version (${compiler_version}) and the declared dependencies in the Manifest.`);
} else {
manifestModel
.setValue("requires.@qooxdoo/compiler", "^" + compiler_version)
.setValue("requires.@qooxdoo/framework", "^" + framework_version);
manifestModel.setWarnOnly(false);
// now model should validate
await manifestModel.save();
if (!this.argv.quiet) {
qx.tool.compiler.Console.info(`Updated dependencies in ${manifestModel.getRelativeDataPath()}.`);
}
}
}
manifestModel.setValidate(true);
}
if (!announceOnly) {
let compileJsonFilename = path.join(process.cwd(), "compile.json");
let replaceInFiles = [{
files: compileJsonFilename,
from: "\"qx/browser\"",
to: "\"@qooxdoo/qx/browser\""
}];
await this.migrate([compileJsonFilename], replaceInFiles);
}
let compileJsFilename = path.join(process.cwd(), "compile.js");
if (await fs.existsAsync(compileJsFilename)) {
let data = await fs.readFileAsync(compileJsFilename, "utf8");
if (data.indexOf("module.exports") < 0) {
qx.tool.compiler.Console.warn("*** Your compile.js appears to be missing a `module.exports` statement - please see https://git.io/fjBqU for more details");
}
}
self.migrationInProcess = false;
if (needFix) {
if (announceOnly) {
qx.tool.compiler.Console.error(`*** Try executing 'qx package migrate' to apply the changes. Alternatively, upgrade or downgrade framework and/or compiler to match the library dependencies.`);
process.exit(1);
}
qx.tool.compiler.Console.info("Migration completed.");
} else if (!announceOnly && !this.argv.quiet) {
qx.tool.compiler.Console.info("Everything is up-to-date. No migration necessary.");
}
}
}
});
|
#ifndef __FTCharmap__
#define __FTCharmap__
#include <XMFreeType/ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include <FTGL/ftgles.h>
#include "<API key>.h"
/**
* FTCharmap takes care of specifying the encoding for a font and mapping
* character codes to glyph indices.
*
* It doesn't preprocess all indices, only on an as needed basis. This may
* seem like a performance penalty but it is quicker than using the 'raw'
* freetype calls and will save significant amounts of memory when dealing
* with unicode encoding
*
* @see "Freetype 2 Documentation"
*
*/
class FTFace;
class FTCharmap
{
public:
/**
* Constructor
*/
FTCharmap(FTFace* face);
/**
* Destructor
*/
virtual ~FTCharmap();
/**
* Queries for the current character map code.
*
* @return The current character map code.
*/
FT_Encoding Encoding() const { return ftEncoding; }
/**
* Sets the character map for the face. If an error occurs the object is not modified.
* Valid encodings as at Freetype 2.0.4
* ft_encoding_none
* ft_encoding_symbol
* ft_encoding_unicode
* ft_encoding_latin_2
* ft_encoding_sjis
* ft_encoding_gb2312
* ft_encoding_big5
* ft_encoding_wansung
* ft_encoding_johab
* <API key>
* <API key>
* <API key>
* <API key>
*
* @param encoding the Freetype encoding symbol. See above.
* @return <code>true</code> if charmap was valid and set
* correctly.
*/
bool CharMap(FT_Encoding encoding);
/**
* Get the FTGlyphContainer index of the input character.
*
* @param characterCode The character code of the requested glyph in
* the current encoding eg apple roman.
* @return The FTGlyphContainer index for the character or zero
* if it wasn't found
*/
unsigned int GlyphListIndex(const unsigned int characterCode);
/**
* Get the font glyph index of the input character.
*
* @param characterCode The character code of the requested glyph in
* the current encoding eg apple roman.
* @return The glyph index for the character.
*/
unsigned int FontIndex(const unsigned int characterCode);
/**
* Set the FTGlyphContainer index of the character code.
*
* @param characterCode The character code of the requested glyph in
* the current encoding eg apple roman.
* @param containerIndex The index into the FTGlyphContainer of the
* character code.
*/
void InsertIndex(const unsigned int characterCode,
const size_t containerIndex);
/**
* Queries for errors.
*
* @return The current error code. Zero means no error.
*/
FT_Error Error() const { return err; }
private:
/**
* Current character map code.
*/
FT_Encoding ftEncoding;
/**
* The current Freetype face.
*/
const FT_Face ftFace;
/**
* A structure that maps glyph indices to character codes
*
* < character code, face glyph index>
*/
typedef <API key> CharacterMap;
CharacterMap charMap;
/**
* Precomputed font indices.
*/
static const unsigned int MAX_PRECOMPUTED = 128;
unsigned int charIndexCache[MAX_PRECOMPUTED];
/**
* Current error code.
*/
FT_Error err;
};
#endif // __FTCharmap__
|
package gavilan.irc;
import java.util.Set;
import javax.annotation.PreDestroy;
import org.pircbotx.PircBotX;
public interface TwitchCore {
void doGreet(ChatMessage cm);
Set<String> getPendings();
void message(String channel, String message);
void onMessage(ChatMessage cm);
@PreDestroy
void shutdown();
void startAll(PircBotX pircBotX);
}
|
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Documento
*
* @ORM\Table(name="documentos")
* @ORM\Entity
*/
class Documento
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var text
*
* @ORM\Column(name="descripcion", type="text",nullable=true)
*/
private $descripcion;
/**
* @var \DateTime
*
* @ORM\Column(name="fecha_ingreso", type="date")
*/
private $fechaIngreso;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Expediente",inversedBy="documentos")
* @ORM\JoinColumn(name="expediente_id", <API key>="id")
*/
private $expediente;
/**
* @ORM\ManyToOne(targetEntity="<API key>",inversedBy="documentos")
* @ORM\JoinColumn(name="<API key>", <API key>="id")
*/
private $<API key>;
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Hoja", mappedBy="documento",cascade={"persist", "remove"})
* @ORM\OrderBy({"numero" = "ASC"})
*/
private $hojas;
/**
* @var datetime $creado
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(name="creado", type="datetime")
*/
private $creado;
/**
* @var datetime $actualizado
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(name="actualizado",type="datetime")
*/
private $actualizado;
/**
* @var integer $creadoPor
*
* @Gedmo\Blameable(on="create")
* @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario")
* @ORM\JoinColumn(name="creado_por", <API key>="id", nullable=true)
*/
private $creadoPor;
/**
* @var integer $actualizadoPor
*
* @Gedmo\Blameable(on="update")
* @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario")
* @ORM\JoinColumn(name="actualizado_por", <API key>="id", nullable=true)
*/
private $actualizadoPor;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set descripcion
*
* @param string $descripcion
*
* @return Documento
*/
public function setDescripcion($descripcion)
{
$this->descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* @return string
*/
public function getDescripcion()
{
return $this->descripcion;
}
/**
* Set fechaIngreso
*
* @param \DateTime $fechaIngreso
*
* @return Documento
*/
public function setFechaIngreso($fechaIngreso)
{
$this->fechaIngreso = $fechaIngreso;
return $this;
}
/**
* Get fechaIngreso
*
* @return \DateTime
*/
public function getFechaIngreso()
{
return $this->fechaIngreso;
}
/**
* Set orden
*
* @param integer $orden
*
* @return Documento
*/
public function setOrden($orden)
{
$this->orden = $orden;
return $this;
}
/**
* Get orden
*
* @return integer
*/
public function getOrden()
{
return $this->orden;
}
/**
* Constructor
*/
public function __construct()
{
$this->hojas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set creado
*
* @param \DateTime $creado
*
* @return Documento
*/
public function setCreado($creado)
{
$this->creado = $creado;
return $this;
}
/**
* Get creado
*
* @return \DateTime
*/
public function getCreado()
{
return $this->creado;
}
/**
* Set actualizado
*
* @param \DateTime $actualizado
*
* @return Documento
*/
public function setActualizado($actualizado)
{
$this->actualizado = $actualizado;
return $this;
}
/**
* Get actualizado
*
* @return \DateTime
*/
public function getActualizado()
{
return $this->actualizado;
}
/**
* Set expediente
*
* @param \AppBundle\Entity\Expediente $expediente
*
* @return Documento
*/
public function setExpediente(\AppBundle\Entity\Expediente $expediente = null)
{
$this->expediente = $expediente;
return $this;
}
/**
* Get expediente
*
* @return \AppBundle\Entity\Expediente
*/
public function getExpediente()
{
return $this->expediente;
}
/**
* Add hoja
*
* @param \AppBundle\Entity\Hoja $hoja
*
* @return Documento
*/
public function addHoja(\AppBundle\Entity\Hoja $hoja)
{
$this->hojas[] = $hoja;
return $this;
}
/**
* Remove hoja
*
* @param \AppBundle\Entity\Hoja $hoja
*/
public function removeHoja(\AppBundle\Entity\Hoja $hoja)
{
$this->hojas->removeElement($hoja);
}
/**
* Get hojas
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getHojas()
{
return $this->hojas;
}
/**
* Set creadoPor
*
* @param \UsuariosBundle\Entity\Usuario $creadoPor
*
* @return Documento
*/
public function setCreadoPor(\UsuariosBundle\Entity\Usuario $creadoPor = null)
{
$this->creadoPor = $creadoPor;
return $this;
}
/**
* Get creadoPor
*
* @return \UsuariosBundle\Entity\Usuario
*/
public function getCreadoPor()
{
return $this->creadoPor;
}
/**
* Set actualizadoPor
*
* @param \UsuariosBundle\Entity\Usuario $actualizadoPor
*
* @return Documento
*/
public function setActualizadoPor(\UsuariosBundle\Entity\Usuario $actualizadoPor = null)
{
$this->actualizadoPor = $actualizadoPor;
return $this;
}
/**
* Get actualizadoPor
*
* @return \UsuariosBundle\Entity\Usuario
*/
public function getActualizadoPor()
{
return $this->actualizadoPor;
}
/**
* Set <API key>
*
* @param \AppBundle\Entity\<API key> $<API key>
*
* @return Documento
*/
public function <API key>(\AppBundle\Entity\<API key> $<API key> = null)
{
$this-><API key> = $<API key>;
return $this;
}
/**
* Get <API key>
*
* @return \AppBundle\Entity\<API key>
*/
public function <API key>()
{
return $this-><API key>;
}
}
|
package com.github.visgeek.utils.collections;
import java.util.Iterator;
class LinqConcateIterator<T> implements Iterator<T> {
public LinqConcateIterator(Iterable<T> source, Iterable<? extends T> second) {
this.second = second;
this.itr = source.iterator();
this.isSwitched = false;
}
private final Iterable<? extends T> second;
private Iterator<? extends T> itr;
private boolean isSwitched;
@Override
public boolean hasNext() {
boolean result = false;
result = this.itr.hasNext();
if (!this.isSwitched) {
if (!result) {
this.itr = this.second.iterator();
result = this.itr.hasNext();
this.isSwitched = true;
}
}
return result;
}
@Override
public T next() {
return this.itr.next();
}
}
|
package de.csmath.QT;
import java.util.Collection;
import java.util.List;
/**
* This class builds a FTypeAtom from given parameters.
* @author lpfeiler
*/
public class FTypeAtomBuilder extends QTAtomBuilder {
/**
* @see FTypeAtom#majBrand
*/
private int majBrand = 0;
/**
* @see FTypeAtom#minVersion
*/
private int minVersion = 0;
/**
* @see FTypeAtom#compBrands
*/
private Collection<Integer> compBrands;
/**
* Constructs a FTypeAtomBuilder.
* @param size the size of the FTypeAtom in the file
* @param type the type of the atom, should be set to 'ftyp'
*/
public FTypeAtomBuilder(int size, int type) {
super(size, type);
}
/**
* Returns a new FTypeAtom.
* @return a new FTypeAtom
*/
public FTypeAtom build() {
return new FTypeAtom(size,type,majBrand,minVersion,compBrands);
}
/**
* Sets the major brand.
* @see FTypeAtom#majBrand
* @param majBrand the major brand
* @return a reference to this object
*/
public FTypeAtomBuilder withMajBrand(int majBrand) {
this.majBrand = majBrand;
return this;
}
/**
* Sets the minor version.
* @see FTypeAtom#minVersion
* @param minVersion the minor version
* @return a reference to this object
*/
public FTypeAtomBuilder withMinVersion(int minVersion) {
this.minVersion = minVersion;
return this;
}
/**
* Sets the compatible brands.
* @param compBrands a collection of compatible brands
* @return a reference to this object
*/
public FTypeAtomBuilder withCompBrands(Collection<Integer> compBrands) {
this.compBrands = compBrands;
return this;
}
}
|
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Workweek Template: Tyler Kirkham Andrews</title>
<meta name="description" content="Workweek lets you build your own portfolio with built-in invoicing and payment processing. ">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/stylesheet.css">
<link rel="stylesheet" href="codrops/css/component.css">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Stylesheet for Lightbox plugin -->
<link rel="stylesheet" href="js/<API key>/css/css.css">
</head>
<body>
<!-- needed for facebook like button -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.<API key>(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]
<!-- Add your site or application content here -->
<!-- HEADER -->
<div class="header sidebar">
<div class="logo">
<!-- <img src="" alt="Anna James Photography Logo" width="200"> -->
<h1><a href="index.html">Tyler Andrews</a></h1>
</div>
<div class="nav">
<div class="nav-menu">
<ul class="reset">
<li>
<a href="index.html">Work</a>
</li>
<li>
<a href="index-about.html">About</a>
</li>
<li>
<a href="http://hellotylo.tumblr.com/">Blog</a>
</li>
<li>
<a href="contact.html">Contact</a>
</li>
</ul>
<div class="social-icons">
<a href="http://instagram.com/hellotylo">
<i class="fa fa-instagram"></i>
</a>
<a href="http://twitter.com/workweekhq">
<i class="fa fa-twitter"></i>
</a>
</div>
</div>
</div>
</div>
<!-- MAIN BODY -->
<div class="main">
<!-- BEGIN new slider thing -->
<!-- PORTFOLIO -->
<div class="section portfolio">
<div class="gallery">
<a href="img/10.jpg" class="gallery__item">
<img src="img/10.jpg" alt="" class="gallery__item-img" data-id="0" data-title="Neue Wall">
<i class="gallery__item-cover"></i>
</a>
<a href="img/7.jpg" class="gallery__item">
<img src="img/7.jpg" alt="" class="gallery__item-img" data-id="1" data-title="Exhibit Cards">
<i class="gallery__item-cover"></i>
</a>
<a href="img/8.jpg" class="gallery__item">
<img src="img/8.jpg" alt="" class="gallery__item-img" data-id="2" data-title="Neue Poster 1">
<i class="gallery__item-cover"></i>
</a>
<a href="img/9.jpg" class="gallery__item">
<img src="img/9.jpg" alt="" class="gallery__item-img" data-id="3" data-title="Neue Poster 2">
<i class="gallery__item-cover"></i>
</a>
<hr>
</div>
<!-- SLIDER -->
<div class="slider" style="display: none;">
<table class="slider__table">
<tr>
<td class="slider__table-td">
<!-- <div class="<API key>">
</div>
<div class="<API key>">
<img src="img/0.jpg" alt="" class="slider__cur-img">
</div>
<div class="<API key>">
</div>
</td>
</tr>
</table>
<a href="#prev" class="slider__btn slider__btn_prev"></a>
<a href="#next" class="slider__btn slider__btn_next"></a>
<i class="slider__btn_close"></i>
</div>
<!-- NEW PORTFOLIO with just thumbs -- adding to bottom of each project page. for easy navigation -->
<div class="section portfolio">
<div class="row">
<div class="four columns">
<a href="project-1.html" class="thumbnail" style="background-image: url(img/2-1.jpg)"></a>
</div>
<div class="four columns">
<a href="project-2.html" class="thumbnail" style="background-image: url(img/10.jpg)"></a>
</div>
<div class="four columns">
<a href="project-3.html" class="thumbnail" style="background-image: url(img/11.jpg)"></a>
</div>
</div>
<div class="row">
<div class="four columns">
<a href="project-4.html" class="thumbnail" style="background-image: url(img/14.jpg)"></a>
</div>
<div class="four columns">
<a href="project-5.html" class="thumbnail" style="background-image: url(img/16.jpg)"></a>
</div>
<div class="four columns">
<a href="project-6.html" class="thumbnail" style="background-image: url(img/19.jpg)"></a>
</div>
</div>
<div class="row">
<div class="four columns">
<a href="project-7.html" class="thumbnail" style="background-image: url(img/3.jpg)"></a>
</div>
<div class="four columns">
<a href="project-8.html" class="thumbnail" style="background-image: url(http://static1.squarespace.com/static/<API key>/<API key>/<API key>/1396488997535/2.jpg?format=1000w)"></a>
</div>
<div class="four columns">
<a href="project-9.html" class="thumbnail" style="background-image: url(img/20.jpg)"></a>
</div>
</div>
</div>
</div>
</div>
<!-- FOOTER -->
<div class="footer">
</div>
<!-- Scripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!-- Gallery Lightbox plugin -->
<script src="js/<API key>/js/js.js"></script>
<!-- Google Analytics -->
<script>
(function(b,o,i,l,e,r){b.<API key>=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.<API key>(i)[0];
e.src='https:
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXX-XXXX','auto');ga('send','pageview');
</script>
</body>
</html>
|
package personifiler.cluster;
import static org.junit.Assert.*;
import org.junit.Test;
import personifiler.util.TestUtils;
/**
* Tests for {@link RandIndex}
*
* @author Allen Cheng
*/
public class TestRandIndex
{
/**
* Tests that the rand index of a cluster is between 0.0 and 1.0
*/
@Test
public void testRandIndex()
{
ClusterPeople cluster = new ClusterPeople(TestUtils.<API key>());
double randIndex = cluster.randIndex(TestUtils.<API key>());
assertTrue(randIndex >= 0.0 && randIndex <= 1.0);
}
}
|
namespace Azure.Security.Attestation
{
public partial class <API key> : System.IDisposable
{
protected <API key>() { }
public <API key>(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
public <API key>(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Security.Attestation.<API key> options) { }
public System.Uri Endpoint { get { throw null; } }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.<API key>> <API key>(System.Security.Cryptography.X509Certificates.X509Certificate2 <API key>, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.<API key>>> <API key>(System.Security.Cryptography.X509Certificates.X509Certificate2 <API key>, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual Azure.Security.Attestation.AttestationResponse<string> GetPolicy(Azure.Security.Attestation.AttestationType attestationType, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<string>> GetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.<API key>> <API key>(System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.<API key>>> <API key>(System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.<API key>> <API key>(System.Security.Cryptography.X509Certificates.X509Certificate2 certificateToRemove, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.<API key>>> <API key>(System.Security.Cryptography.X509Certificates.X509Certificate2 certificateToRemove, Azure.Security.Attestation.TokenSigningKey existingSigningKey, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult> ResetPolicy(Azure.Security.Attestation.AttestationType attestationType, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult>> ResetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult> SetPolicy(Azure.Security.Attestation.AttestationType attestationType, string policyToSet, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.PolicyResult>> SetPolicyAsync(Azure.Security.Attestation.AttestationType attestationType, string policyToSet, Azure.Security.Attestation.TokenSigningKey signingKey = null, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class AttestationClient : System.IDisposable
{
protected AttestationClient() { }
public AttestationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
public AttestationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Security.Attestation.<API key> options) { }
public System.Uri Endpoint { get { throw null; } }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult> AttestOpenEnclave(System.ReadOnlyMemory<byte> report, System.BinaryData initTimeData, bool <API key>, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult>> <API key>(System.ReadOnlyMemory<byte> report, System.BinaryData initTimeData, bool <API key>, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult> AttestSgxEnclave(System.ReadOnlyMemory<byte> quote, System.BinaryData initTimeData, bool <API key>, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Security.Attestation.AttestationResponse<Azure.Security.Attestation.AttestationResult>> <API key>(System.ReadOnlyMemory<byte> quote, System.BinaryData initTimeData, bool <API key>, System.BinaryData runTimeData, bool runTimeDataIsObject, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<System.BinaryData> AttestTpm(System.BinaryData request, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.BinaryData>> AttestTpmAsync(System.BinaryData request, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner>> <API key>(System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner>>> <API key>(System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class <API key> : Azure.Core.ClientOptions
{
public <API key>(Azure.Security.Attestation.<API key>.ServiceVersion version = Azure.Security.Attestation.<API key>.ServiceVersion.V2020_10_01, Azure.Security.Attestation.<API key> tokenOptions = null) { }
public enum ServiceVersion
{
V2020_10_01 = 1,
}
}
public partial class AttestationResponse<T> : Azure.Response<T> where T : class
{
internal AttestationResponse() { }
public Azure.Security.Attestation.AttestationToken Token { get { throw null; } }
public override T Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
}
public partial class AttestationResult
{
internal AttestationResult() { }
public object Confirmation { get { throw null; } }
public byte[] <API key> { get { throw null; } }
public byte[] <API key> { get { throw null; } }
public bool? <API key> { get { throw null; } }
public string DeprecatedMrEnclave { get { throw null; } }
public string DeprecatedMrSigner { get { throw null; } }
public byte[] <API key> { get { throw null; } }
public float? DeprecatedProductId { get { throw null; } }
public string DeprecatedRpData { get { throw null; } }
public object <API key> { get { throw null; } }
public float? DeprecatedSvn { get { throw null; } }
public string DeprecatedTee { get { throw null; } }
public string DeprecatedVersion { get { throw null; } }
public byte[] EnclaveHeldData { get { throw null; } }
public System.DateTimeOffset Expiration { get { throw null; } }
public object InittimeClaims { get { throw null; } }
public bool? IsDebuggable { get { throw null; } }
public System.DateTimeOffset IssuedAt { get { throw null; } }
public System.Uri Issuer { get { throw null; } }
public string MrEnclave { get { throw null; } }
public string MrSigner { get { throw null; } }
public string Nonce { get { throw null; } }
public System.DateTimeOffset NotBefore { get { throw null; } }
public object PolicyClaims { get { throw null; } }
public byte[] PolicyHash { get { throw null; } }
public float? ProductId { get { throw null; } }
public object RuntimeClaims { get { throw null; } }
public object SgxCollateral { get { throw null; } }
public float? Svn { get { throw null; } }
public string UniqueIdentifier { get { throw null; } }
public string VerifierType { get { throw null; } }
public string Version { get { throw null; } }
}
public partial class AttestationSigner
{
public AttestationSigner(System.Security.Cryptography.X509Certificates.X509Certificate2[] signingCertificates, string certificateKeyId) { }
public string CertificateKeyId { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<System.Security.Cryptography.X509Certificates.X509Certificate2> SigningCertificates { get { throw null; } }
}
public partial class AttestationToken
{
protected AttestationToken() { }
public AttestationToken(Azure.Security.Attestation.TokenSigningKey signingKey) { }
public AttestationToken(object body) { }
public AttestationToken(object body, Azure.Security.Attestation.TokenSigningKey signingKey) { }
[System.ComponentModel.<API key>(System.ComponentModel.<API key>.Never)]
protected internal AttestationToken(string token) { }
public virtual string Algorithm { get { throw null; } }
public virtual string <API key> { get { throw null; } }
public virtual string ContentType { get { throw null; } }
public virtual bool? Critical { get { throw null; } }
public virtual System.DateTimeOffset? ExpirationTime { get { throw null; } }
public virtual System.DateTimeOffset? IssuedAtTime { get { throw null; } }
public virtual string Issuer { get { throw null; } }
public virtual string KeyId { get { throw null; } }
public virtual System.Uri KeyUrl { get { throw null; } }
public virtual System.DateTimeOffset? NotBeforeTime { get { throw null; } }
public virtual Azure.Security.Attestation.AttestationSigner SigningCertificate { get { throw null; } }
public virtual string TokenBody { get { throw null; } }
public virtual System.ReadOnlyMemory<byte> TokenBodyBytes { get { throw null; } }
public virtual string TokenHeader { get { throw null; } }
public virtual System.ReadOnlyMemory<byte> TokenHeaderBytes { get { throw null; } }
public virtual System.ReadOnlyMemory<byte> TokenSignatureBytes { get { throw null; } }
public virtual string Type { get { throw null; } }
public virtual System.Security.Cryptography.X509Certificates.X509Certificate2[] <API key> { get { throw null; } }
public virtual string <API key> { get { throw null; } }
public virtual string <API key> { get { throw null; } }
public virtual System.Uri X509Url { get { throw null; } }
public virtual T GetBody<T>() where T : class { throw null; }
public override string ToString() { throw null; }
public virtual bool ValidateToken(Azure.Security.Attestation.<API key> options, System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner> <API key>, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<bool> ValidateTokenAsync(Azure.Security.Attestation.<API key> options, System.Collections.Generic.IReadOnlyList<Azure.Security.Attestation.AttestationSigner> <API key>, System.Threading.Cancellation<API key> = default(System.Threading.CancellationToken)) { throw null; }
}
[System.Runtime.InteropServices.<API key>(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct AttestationType : System.IEquatable<Azure.Security.Attestation.AttestationType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public AttestationType(string value) { throw null; }
public static Azure.Security.Attestation.AttestationType OpenEnclave { get { throw null; } }
public static Azure.Security.Attestation.AttestationType SgxEnclave { get { throw null; } }
public static Azure.Security.Attestation.AttestationType Tpm { get { throw null; } }
public bool Equals(Azure.Security.Attestation.AttestationType other) { throw null; }
[System.ComponentModel.<API key>(System.ComponentModel.<API key>.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.<API key>(System.ComponentModel.<API key>.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Security.Attestation.AttestationType left, Azure.Security.Attestation.AttestationType right) { throw null; }
public static implicit operator Azure.Security.Attestation.AttestationType (string value) { throw null; }
public static bool operator !=(Azure.Security.Attestation.AttestationType left, Azure.Security.Attestation.AttestationType right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.<API key>(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct <API key> : System.IEquatable<Azure.Security.Attestation.<API key>>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public <API key>(string value) { throw null; }
public static Azure.Security.Attestation.<API key> IsAbsent { get { throw null; } }
public static Azure.Security.Attestation.<API key> IsPresent { get { throw null; } }
public bool Equals(Azure.Security.Attestation.<API key> other) { throw null; }
[System.ComponentModel.<API key>(System.ComponentModel.<API key>.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.<API key>(System.ComponentModel.<API key>.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Security.Attestation.<API key> left, Azure.Security.Attestation.<API key> right) { throw null; }
public static implicit operator Azure.Security.Attestation.<API key> (string value) { throw null; }
public static bool operator !=(Azure.Security.Attestation.<API key> left, Azure.Security.Attestation.<API key> right) { throw null; }
public override string ToString() { throw null; }
}
public partial class <API key>
{
internal <API key>() { }
public Azure.Security.Attestation.<API key>? <API key> { get { throw null; } }
public string <API key> { get { throw null; } }
}
public partial class <API key>
{
public <API key>() { }
public System.Collections.Generic.IReadOnlyList<System.Security.Cryptography.X509Certificates.X509Certificate2> <API key>() { throw null; }
}
[System.Runtime.InteropServices.<API key>(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct PolicyModification : System.IEquatable<Azure.Security.Attestation.PolicyModification>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public PolicyModification(string value) { throw null; }
public static Azure.Security.Attestation.PolicyModification Removed { get { throw null; } }
public static Azure.Security.Attestation.PolicyModification Updated { get { throw null; } }
public bool Equals(Azure.Security.Attestation.PolicyModification other) { throw null; }
[System.ComponentModel.<API key>(System.ComponentModel.<API key>.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.<API key>(System.ComponentModel.<API key>.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Security.Attestation.PolicyModification left, Azure.Security.Attestation.PolicyModification right) { throw null; }
public static implicit operator Azure.Security.Attestation.PolicyModification (string value) { throw null; }
public static bool operator !=(Azure.Security.Attestation.PolicyModification left, Azure.Security.Attestation.PolicyModification right) { throw null; }
public override string ToString() { throw null; }
}
public partial class PolicyResult
{
public PolicyResult() { }
public Azure.Security.Attestation.PolicyModification PolicyResolution { get { throw null; } }
public Azure.Security.Attestation.AttestationSigner PolicySigner { get { throw null; } }
public byte[] PolicyTokenHash { get { throw null; } }
}
public partial class <API key>
{
public <API key>() { }
public string AttestationPolicy { get { throw null; } set { } }
}
public partial class TokenSigningKey
{
public TokenSigningKey(System.Security.Cryptography.AsymmetricAlgorithm signer, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public TokenSigningKey(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } }
public System.Security.Cryptography.AsymmetricAlgorithm Signer { get { throw null; } }
}
public partial class <API key>
{
public <API key>(bool validateToken = true, bool <API key> = true, bool <API key> = true, bool validateIssuer = false, string expectedIssuer = null, int timeValidationSlack = 0, System.Func<Azure.Security.Attestation.AttestationToken, Azure.Security.Attestation.AttestationSigner, bool> validationCallback = null) { }
public string ExpectedIssuer { get { throw null; } }
public long TimeValidationSlack { get { throw null; } }
public bool <API key> { get { throw null; } }
public bool ValidateIssuer { get { throw null; } }
public bool <API key> { get { throw null; } }
public bool ValidateToken { get { throw null; } }
public System.Func<Azure.Security.Attestation.AttestationToken, Azure.Security.Attestation.AttestationSigner, bool> ValidationCallback { get { throw null; } }
}
public partial class <API key>
{
public <API key>() { }
public System.ReadOnlyMemory<byte> Data { get { throw null; } set { } }
}
public partial class <API key>
{
internal <API key>() { }
public System.ReadOnlyMemory<byte> Data { get { throw null; } }
}
}
|
const daggy = require('daggy')
const compose = (f, g) => x => f(g(x))
const id = x => x
// create constructor with props 'x' and 'f'
// 'x' is our value, 'f' is a function
const Coyoneda = daggy.tagged('x', 'f')
// map composes the function
Coyoneda.prototype.map = function(f) {
return Coyoneda(this.x, compose(f, this.f))
}
Coyoneda.prototype.lower = function() {
return this.x.map(this.f)
}
// lift starts off Coyoneda with the 'id' function
Coyoneda.lift = x => Coyoneda(x, id)
// Set does not have a 'map' method
const set = new Set([1, 1, 2, 3, 3, 4])
console.log("Set([1, 1, 2, 3, 3, 4]) : ", set)
// Wrap set into Coyoneda with 'id' function
const coyoResult = Coyoneda.lift(set)
.map(x => x + 1)
.map(x => `${x}!`)
console.log(
"Coyoneda.lift(set).map(x => x + 1).map(x => `${x}!`): ",
coyoResult
)
// equivalent to buildUpFn = coyoResult.f, ourSet = coyoResult.x
const {f: builtUpFn, x: ourSet} = coyoResult
console.log("builtUpFn is: ", builtUpFn, "; ourSet is: ", ourSet)
ourSet
.forEach(n => console.log(builtUpFn(n)))
console.log(
`Coyoneda.lift([1,2,3]).map(x => x * 2).map(x => x - 1).lower() : `,
Coyoneda.lift([1,2,3])
.map(x => x * 2)
.map(x => x - 1)
.lower()
)
// [ 1, 3, 5 ]
// Any object becomes a functor when placed in Coyoneda
const Container = daggy.tagged('x')
const tunacan = Container("tuna")
const res = Coyoneda.lift(tunacan)
.map(x => x.toUpperCase())
.map(x => x + '!')
const {f: fn, x: can} = res
console.log(fn(can.x))
// TUNA!
|
package org.coursera.androidcapstone.symptomchecker.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.<API key>;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface PatientRepository extends <API key><Patient, Long> {
@Query("From Patient p where :doctor member p.doctors")
public Page<Patient> findByDoctor(@Param("doctor") Doctor doctor, Pageable page);
@Query("From Patient p where :doctor member p.doctors AND UPPER(fullName)=:fullName")
public List<Patient> <API key>(@Param("doctor") Doctor doctor, @Param("fullName") String fullName);
}
|
var map, boroughSearch = [],
theaterSearch = [],
museumSearch = [];
/* Basemap Layers */
var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png");
var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png");
var mbTerrainReg = L.tileLayer("https://{s}.tiles.mapbox.com/v3/aj.um7z9lus/{z}/{x}/{y}.png");
var mapquestOAM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", {
maxZoom: 19,
});
var mapquestHYB = L.layerGroup([L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", {
maxZoom: 19,
}), L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/hyb/{z}/{x}/{y}.png", {
maxZoom: 19,
subdomains: ["oatile1", "oatile2", "oatile3", "oatile4"],
})]);
map = L.map("map", {
zoom: 5,
center: [39, -95],
layers: [mapquestOSM]
});
/* Larger screens get expanded layer control */
if (document.body.clientWidth <= 767) {
var isCollapsed = true;
} else {
var isCollapsed = false;
}
var baseLayers = {
"Street Map": mapquestOSM,
"Aerial Imagery": mapquestOAM,
"Imagery with Streets": mapquestHYB
};
var overlays = {};
var layerControl = L.control.layers(baseLayers, {}, {
collapsed: isCollapsed
}).addTo(map);
/* Add overlay layers to map after defining layer control to preserver order */
var sidebar = L.control.sidebar("sidebar", {
closeButton: true,
position: "left"
}).addTo(map);
sidebar.toggle();
/* Highlight search box text on click */
$("#searchbox").click(function () {
$(this).select();
});
/* Placeholder hack for IE */
if (navigator.appName == "Microsoft Internet Explorer") {
$("input").each(function () {
if ($(this).val() === "" && $(this).attr("placeholder") !== "") {
$(this).val($(this).attr("placeholder"));
$(this).focus(function () {
if ($(this).val() === $(this).attr("placeholder")) $(this).val("");
});
$(this).blur(function () {
if ($(this).val() === "") $(this).val($(this).attr("placeholder"));
});
}
});
}
$(function(){
var popup = {
init : function() {
// position popup
windowW = $(window).width();
$("#map").on("mousemove", function(e) {
var x = e.pageX + 20;
var y = e.pageY;
var windowH = $(window).height();
if (y > (windowH - 100)) {
var y = e.pageY - 100;
} else {
var y = e.pageY - 20;
}
$("#info").css({
"left": x,
"top": y
});
});
}
};
popup.init();
})
|
# Jirabot
A Slack bot that watches any channel it's invited to for mentions of JIRA issues. If it sees one, it responds with a message consisting of:
ISSUE-1223: Issue summary
https://yourlocation.jira.com/browse/ISSUE-1223
Issue Status (Issue Type)
## Setup
You'll need to configure a bot on Slack (fixme: Add setup link) and get your API token. Once you have that, set a new environmental variable `SLACK_API_TOKEN`. Additionally, you'll need to supply JIRA credentials and your JIRA enpoint address. This is because JIRA cloud doesn't support app tokens. Yeah, in 2016 you have to use basic auth if your app doesn't run through a browser.
For local development, you can do this with a `.env` file, which we've helpfully left out of this repo.
# ENV Sample
SLACK_API_<API key>
JIRA_USER=jirauser_notemail
JIRA_PASS=jirapassword
JIRA_PREFIX=https://yourcompany.jira.com/
## Running Locally
foreman start
This will open your connection to the Slack API, and your bot will be online. You can connect to it and chat with it directly (it'll behave the same way).
|
# <API key>: true
require 'spec_helper'
describe ErrorTracking::<API key> do
include <API key>
set(:project) { create(:project) }
subject { create(:<API key>, project: project) }
describe 'Associations' do
it { is_expected.to belong_to(:project) }
end
describe 'Validations' do
context 'when api_url is over 255 chars' do
before do
subject.api_url = 'https://' + 'a' * 250
end
it 'fails validation' do
expect(subject).not_to be_valid
expect(subject.errors.messages[:api_url]).to include('is too long (maximum is 255 characters)')
end
end
context 'With unsafe url' do
it 'fails validation' do
subject.api_url = "https://replaceme.com/'><script>alert(document.cookie)</script>"
expect(subject).not_to be_valid
end
end
context 'presence validations' do
using RSpec::Parameterized::TableSyntax
valid_api_url = 'http://example.com/api/0/projects/org-slug/proj-slug/'
valid_token = 'token'
where(:enabled, :token, :api_url, :valid?) do
true | nil | nil | false
true | nil | valid_api_url | false
true | valid_token | nil | false
true | valid_token | valid_api_url | true
false | nil | nil | true
false | nil | valid_api_url | true
false | valid_token | nil | true
false | valid_token | valid_api_url | true
end
with_them do
before do
subject.enabled = enabled
subject.token = token
subject.api_url = api_url
end
it { expect(subject.valid?).to eq(valid?) }
end
end
context 'URL path' do
it 'fails validation with wrong path' do
subject.api_url = 'http://gitlab.com/project1/something'
expect(subject).not_to be_valid
expect(subject.errors.messages[:api_url]).to include('path needs to start with /api/0/projects')
end
it 'passes validation with correct path' do
subject.api_url = 'http://gitlab.com/api/0/projects/project1/something'
expect(subject).to be_valid
end
end
context 'non ascii chars in api_url' do
before do
subject.api_url = 'http:
end
it 'fails validation' do
expect(subject).not_to be_valid
end
end
end
describe '#sentry_external_url' do
let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' }
before do
subject.api_url = sentry_url
end
it 'returns the correct url' do
expect(subject.class).to receive(:<API key>).with(sentry_url).and_call_original
result = subject.sentry_external_url
expect(result).to eq('https://sentrytest.gitlab.com/sentry-org/sentry-project')
end
end
describe '#sentry_client' do
it 'returns sentry client' do
expect(subject.sentry_client).to be_a(Sentry::Client)
end
end
describe '#list_sentry_issues' do
let(:issues) { [:list, :of, :issues] }
let(:opts) do
{ issue_status: 'unresolved', limit: 10 }
end
let(:result) do
subject.list_sentry_issues(**opts)
end
context 'when cached' do
let(:sentry_client) { spy(:sentry_client) }
before do
stub_reactive_cache(subject, issues, opts)
<API key>(subject)
expect(subject).to receive(:sentry_client).and_return(sentry_client)
end
it 'returns cached issues' do
expect(sentry_client).to receive(:list_issues).with(opts)
.and_return(issues)
expect(result).to eq(issues: issues)
end
end
context 'when not cached' do
it 'returns nil' do
expect(subject).not_to receive(:sentry_client)
expect(result).to be_nil
end
end
end
describe '#<API key>' do
let(:projects) { [:list, :of, :projects] }
let(:sentry_client) { spy(:sentry_client) }
it 'calls sentry client' do
expect(subject).to receive(:sentry_client).and_return(sentry_client)
expect(sentry_client).to receive(:list_projects).and_return(projects)
result = subject.<API key>
expect(result).to eq(projects: projects)
end
end
context 'slugs' do
shared_examples_for 'slug from api_url' do |method, slug|
context 'when api_url is correct' do
before do
subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug/'
end
it 'returns slug' do
expect(subject.public_send(method)).to eq(slug)
end
end
context 'when api_url is blank' do
before do
subject.api_url = nil
end
it 'returns nil' do
expect(subject.public_send(method)).to be_nil
end
end
end
it_behaves_like 'slug from api_url', :project_slug, 'project-slug'
it_behaves_like 'slug from api_url', :organization_slug, 'org-slug'
end
context 'names from api_url' do
shared_examples_for 'name from api_url' do |name, titleized_slug|
context 'name is present in DB' do
it 'returns name from DB' do
subject[name] = 'Sentry name'
subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug'
expect(subject.public_send(name)).to eq('Sentry name')
end
end
context 'name is null in DB' do
it 'titleizes and returns slug from api_url' do
subject[name] = nil
subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug'
expect(subject.public_send(name)).to eq(titleized_slug)
end
it 'returns nil when api_url is incorrect' do
subject[name] = nil
subject.api_url = 'http://gitlab.com/api/0/projects/'
expect(subject.public_send(name)).to be_nil
end
it 'returns nil when api_url is blank' do
subject[name] = nil
subject.api_url = nil
expect(subject.public_send(name)).to be_nil
end
end
end
it_behaves_like 'name from api_url', :organization_name, 'Org Slug'
it_behaves_like 'name from api_url', :project_name, 'Project Slug'
end
describe '.build_api_url_from' do
it 'correctly builds api_url with slugs' do
api_url = described_class.build_api_url_from(
api_host: 'http://sentry.com/',
organization_slug: 'org-slug',
project_slug: 'proj-slug'
)
expect(api_url).to eq('http://sentry.com/api/0/projects/org-slug/proj-slug/')
end
it 'correctly builds api_url without slugs' do
api_url = described_class.build_api_url_from(
api_host: 'http://sentry.com/',
organization_slug: nil,
project_slug: nil
)
expect(api_url).to eq('http://sentry.com/api/0/projects/')
end
it 'does not raise exception with invalid url' do
api_url = described_class.build_api_url_from(
api_host: ':::',
organization_slug: 'org-slug',
project_slug: 'proj-slug'
)
expect(api_url).to eq(':::')
end
end
describe '#api_host' do
context 'when api_url exists' do
before do
subject.api_url = 'https://example.com/api/0/projects/org-slug/proj-slug/'
end
it 'extracts the api_host from api_url' do
expect(subject.api_host).to eq('https://example.com/')
end
end
context 'when api_url is nil' do
before do
subject.api_url = nil
end
it 'returns nil' do
expect(subject.api_url).to eq(nil)
end
end
end
end
|
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('commentator', 'Unit | Model | commentator', {
// Specify the other units that are required for this test.
needs: []
});
test('it exists', function(assert) {
let model = this.subject();
// let store = this.store();
assert.ok(!!model);
});
|
<?php
class Xform_model extends CI_Model
{
/**
* Table name for xform definitions
*
* @var string
*/
private static $xform_table_name = "xforms"; //default value
/**
* Table name for archived/deleted xforms
*
* @var string
*/
private static $<API key> = "archive_xformx"; //default value
public function __construct()
{
$this->initialize_table();
}
/**
* Initializes table names from configuration files
*/
private function initialize_table()
{
if ($this->config->item("table_xform"))
self::$xform_table_name = $this->config->item("table_xform");
if ($this->config->item("table_archive_xform"))
self::$<API key> = $this->config->item("table_archive_xform");
}
/**
* @param $statement
* @return bool
*/
public function create_table($statement)
{
if ($this->db->simple_query($statement)) {
log_message("debug", "Success!");
return TRUE;
} else {
$error = $this->db->error(); // Has keys 'code' and 'message'
log_message("debug", $statement . ", error " . json_encode($error));
return FALSE;
}
}
/**
* @param $statement
* @return bool
*/
public function insert_data($statement)
{
if ($this->db->simple_query($statement)) {
log_message("debug", "Success!");
return TRUE;
} else {
$error = $this->db->error(); // Has keys 'code' and 'message'
log_message("debug", $statement . ", error " . json_encode($error));
}
}
/**
* @param $form_details an array of form details with keys match db field names
* @return id for the created form
*/
public function create_xform($form_details)
{
$this->db->insert(self::$xform_table_name, $form_details);
return $this->db->insert_id();
}
/**
* @param int xform_id the row that needs to be updated
* @param string form_id
* @return bool
*/
public function update_form_id($xform_id, $form_id)
{
$data = array('form_id' => $form_id);
$this->db->where('id', $xform_id);
return $this->db->update(self::$xform_table_name, $data);
}
/**
* @param $form_id
* @param $form_details
* @return mixed
*/
public function update_form($form_id, $form_details)
{
$this->db->where('id', $form_id);
return $this->db->update(self::$xform_table_name, $form_details);
}
/**
* @param null $user_id
* @param int $limit
* @param int $offset
* @return mixed returns list of forms available.
*/
public function get_form_list($user_id = NULL, $limit = 30, $offset = 0)
{
if ($user_id != NULL)
$this->db->where("user_id", $user_id);
$this->db->limit($limit, $offset);
return $this->db->get(self::$xform_table_name)->result();
}
/**
* Finds a table field with point data type
*
* @param $table_name
* @return field name or FALSE
*/
public function get_point_field($table_name)
{
$sql = " SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS ";
$sql .= " WHERE table_name = '{$table_name}' ";
$sql .= " AND DATA_TYPE = 'point'";
$query = $this->db->query($sql);
return ($query->num_rows() == 1) ? $query->row(1)->COLUMN_NAME : FALSE;
}
/**
* @param $form_id
* @return mixed
*/
public function find_by_id($form_id)
{
$this->db->where("id", $form_id);
return $this->db->get(self::$xform_table_name)->row();
}
/**
* @param $xform_id
* @return mixed
*/
public function delete_form($xform_id)
{
$this->db->limit(1);
$this->db->where("id", $xform_id);
return $this->db->delete(self::$xform_table_name);
}
/**
* @param $xform_archive_data
* @return mixed
*/
public function create_archive($xform_archive_data)
{
return $this->db->insert(self::$<API key>, $xform_archive_data);
}
public function find_form_data($table_name, $limit = 30, $offset = 0)
{
$this->db->limit($limit, $offset);
return $this->db->get($table_name)->result();
}
/**
* @param $table_name
* @return mixed return an object of fields of the specified table
*/
public function find_table_columns($table_name)
{
return $this->db->list_fields($table_name);
}
/**
* @param $table_name
* @return mixed returns table fields/columns with metadata object
*/
public function <API key>($table_name)
{
return $this->db->field_data($table_name);
}
public function get_graph_data($table_name, $x_axis_column, $y_axis_column, $y_axis_action = "COUNT")
{
if ($y_axis_action == "COUNT") {
$this->db->select("`" . $y_axis_column . "`, COUNT(" . $y_axis_column . ") AS `" . strtolower($y_axis_action) . "`");
$this->db->group_by($x_axis_column);
}
if ($y_axis_action == "SUM") {
$this->db->select("`" . $y_axis_column . "`, SUM(" . $y_axis_column . ") AS `" . strtolower($y_axis_action) . "`");
$this->db->group_by($x_axis_column);
}
$this->db->from($table_name);
return $this->db->get()->result();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.